@capybara-hq/kernel 0.1.0-rc.80 → 0.1.0-rc.81

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 (64) hide show
  1. package/dist/admin/outbox-dead.service.js +133 -120
  2. package/dist/background/store.js +78 -67
  3. package/dist/background/tasks.service.d.ts +6 -0
  4. package/dist/background/tasks.service.js +3 -0
  5. package/dist/catalog/marketplaces.service.d.ts +1 -1
  6. package/dist/catalog/plugin-import.js +45 -40
  7. package/dist/catalog/scope-sync-workers.js +3 -0
  8. package/dist/channels/inbound.d.ts +6 -1
  9. package/dist/channels/inbound.js +18 -1
  10. package/dist/client/client-reports.service.js +9 -6
  11. package/dist/config/schema.d.ts +5 -0
  12. package/dist/config/schema.js +6 -0
  13. package/dist/conversations/attachments.service.js +101 -96
  14. package/dist/conversations/events.d.ts +7 -0
  15. package/dist/conversations/events.js +9 -0
  16. package/dist/ctx/bus.js +5 -3
  17. package/dist/ctx/queue.js +4 -2
  18. package/dist/db/pool.d.ts +6 -0
  19. package/dist/db/pool.js +3 -2
  20. package/dist/devices/legacy-cleanup.job.js +73 -70
  21. package/dist/dial-in/gateway.d.ts +8 -0
  22. package/dist/dial-in/gateway.js +22 -2
  23. package/dist/extensions/admin-ops.js +22 -19
  24. package/dist/extensions/lifecycle-hooks.js +3 -1
  25. package/dist/http/app.js +3 -1
  26. package/dist/http/plugin-dispatch.js +8 -0
  27. package/dist/identity/auth.guard.js +13 -3
  28. package/dist/index.d.ts +2 -0
  29. package/dist/index.js +1 -0
  30. package/dist/infra/database/database.module.js +1 -0
  31. package/dist/infra/database/org-scope.d.ts +59 -0
  32. package/dist/infra/database/org-scope.js +68 -0
  33. package/dist/infra/database/rls-role.d.ts +11 -0
  34. package/dist/infra/database/rls-role.js +33 -0
  35. package/dist/infra/database/scoped-dialect.d.ts +18 -0
  36. package/dist/infra/database/scoped-dialect.js +245 -0
  37. package/dist/infra/outbox/outbox.dispatcher.js +98 -90
  38. package/dist/infra/outbox/outbox.service.js +29 -26
  39. package/dist/infra/queue/run-job.d.ts +8 -2
  40. package/dist/infra/queue/run-job.js +16 -3
  41. package/dist/infra/schedule/locked-tick.js +12 -4
  42. package/dist/infra/schedule/scheduled-runs.js +3 -1
  43. package/dist/lifecycle/kernel-lifecycle.d.ts +1 -0
  44. package/dist/lifecycle/kernel-lifecycle.js +16 -1
  45. package/dist/orgs/org.guard.js +4 -0
  46. package/dist/platform/sealed-reveals.js +9 -6
  47. package/dist/runtime/maintenance.js +6 -1
  48. package/dist/runtime/run-execution.d.ts +1 -0
  49. package/dist/runtime/run-execution.js +5 -0
  50. package/dist/runtime/run-orphan-check.job.js +20 -15
  51. package/dist/sandbox/legacy-retirement.js +438 -397
  52. package/dist/sandbox/modes.d.ts +10 -0
  53. package/dist/sandbox/modes.js +23 -0
  54. package/dist/sandbox/operation-reconcile.job.d.ts +14 -1
  55. package/dist/sandbox/operation-reconcile.job.js +35 -3
  56. package/dist/sandbox/permission-config-publication.js +83 -77
  57. package/dist/sandbox/sandbox.service.d.ts +24 -0
  58. package/dist/sandbox/sandbox.service.js +159 -62
  59. package/dist/schedules/store.js +17 -14
  60. package/dist/tools/builtins/sandbox/bash.js +16 -1
  61. package/dist/tools/drift.js +31 -24
  62. package/dist/tools/outputs.js +20 -17
  63. package/package.json +2 -2
  64. package/src/migrations/0182_rls_policies.sql +202 -0
@@ -10,6 +10,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
10
10
  import { Inject, Injectable } from "@nestjs/common";
11
11
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
12
12
  import { KernelDb } from "../infra/database/kernel-db.js";
13
+ import { asPlatform } from "../infra/database/org-scope.js";
13
14
  import { LockService } from "../infra/lock/lock.service.js";
14
15
  import { LockedInterval } from "../infra/schedule/locked-interval.js";
15
16
  import { KERNEL_LOGGER } from "../infra/tokens.js";
@@ -55,79 +56,81 @@ let LegacySandboxCleanupJob = class LegacySandboxCleanupJob {
55
56
  // org-filter: deployment-wide sweep of the legacy sandboxes table across all orgs
56
57
  // (LockedInterval), each row keyed by its own conversation id
57
58
  async runOnce(now = new Date(), signal) {
58
- const any = await this.db
59
- .selectFrom("sandboxes")
60
- .select("conversation_id")
61
- .limit(1)
62
- .executeTakeFirst();
63
- if (any === undefined)
64
- return { destroyed: 0, kept: 0 };
65
- const byProvider = await this.db
66
- .selectFrom("sandboxes")
67
- .select(["provider", (eb) => eb.fn.countAll().as("n")])
68
- .groupBy("provider")
69
- .execute();
70
- const loaded = byProvider.filter((p) => this.providers.forDevice(p.provider) !== undefined);
71
- const unloaded = byProvider.filter((p) => this.providers.forDevice(p.provider) === undefined);
72
- const kept = unloaded.reduce((sum, p) => sum + Number(p.n), 0);
73
- if (unloaded.length > 0 && now.getTime() % 3_600_000 < PERIOD_MS) {
74
- this.log.warn("legacy sandboxes kept: their provider is not loaded", {
75
- providers: unloaded.map((p) => p.provider),
76
- count: kept,
77
- });
78
- }
79
- if (loaded.length === 0)
80
- return { destroyed: 0, kept };
81
- const rows = await this.db
82
- .selectFrom("sandboxes")
83
- .select(["conversation_id", "provider", "prev_provider"])
84
- .where("provider", "in", loaded.map((p) => p.provider))
85
- .orderBy("sweep_failed_at", (o) => o.asc().nullsFirst())
86
- .orderBy("conversation_id")
87
- .limit(BATCH)
88
- .execute();
89
- let destroyed = 0;
90
- for (const row of rows) {
91
- if (signal?.aborted)
92
- break;
93
- const name = `cap-${row.conversation_id}`;
94
- const impl = this.providers.forDevice(row.provider)?.impl;
95
- if (impl === undefined)
96
- continue; // unloaded since the query: kept for a later tick
97
- const callSignal = () => signal
98
- ? AbortSignal.any([signal, AbortSignal.timeout(CALL_TIMEOUT_MS)])
99
- : AbortSignal.timeout(CALL_TIMEOUT_MS);
100
- try {
101
- // no device lease holds a legacy row: nothing to fence the destroy with
102
- await impl.destroyByName(name, callSignal(), null);
103
- await impl.destroyFileSystemByName(name, callSignal());
104
- if (row.prev_provider !== null && row.prev_provider !== row.provider) {
105
- const prev = this.providers.forDevice(row.prev_provider)?.impl;
106
- if (prev !== undefined)
107
- await prev.destroyByName(name, callSignal(), null);
108
- else {
109
- this.log.warn("legacy sandbox of a replaced provider left: provider not loaded", {
110
- name,
111
- provider: row.prev_provider,
112
- });
59
+ return asPlatform("deployment-wide sweep of the legacy sandboxes table across all orgs", async () => {
60
+ const any = await this.db
61
+ .selectFrom("sandboxes")
62
+ .select("conversation_id")
63
+ .limit(1)
64
+ .executeTakeFirst();
65
+ if (any === undefined)
66
+ return { destroyed: 0, kept: 0 };
67
+ const byProvider = await this.db
68
+ .selectFrom("sandboxes")
69
+ .select(["provider", (eb) => eb.fn.countAll().as("n")])
70
+ .groupBy("provider")
71
+ .execute();
72
+ const loaded = byProvider.filter((p) => this.providers.forDevice(p.provider) !== undefined);
73
+ const unloaded = byProvider.filter((p) => this.providers.forDevice(p.provider) === undefined);
74
+ const kept = unloaded.reduce((sum, p) => sum + Number(p.n), 0);
75
+ if (unloaded.length > 0 && now.getTime() % 3_600_000 < PERIOD_MS) {
76
+ this.log.warn("legacy sandboxes kept: their provider is not loaded", {
77
+ providers: unloaded.map((p) => p.provider),
78
+ count: kept,
79
+ });
80
+ }
81
+ if (loaded.length === 0)
82
+ return { destroyed: 0, kept };
83
+ const rows = await this.db
84
+ .selectFrom("sandboxes")
85
+ .select(["conversation_id", "provider", "prev_provider"])
86
+ .where("provider", "in", loaded.map((p) => p.provider))
87
+ .orderBy("sweep_failed_at", (o) => o.asc().nullsFirst())
88
+ .orderBy("conversation_id")
89
+ .limit(BATCH)
90
+ .execute();
91
+ let destroyed = 0;
92
+ for (const row of rows) {
93
+ if (signal?.aborted)
94
+ break;
95
+ const name = `cap-${row.conversation_id}`;
96
+ const impl = this.providers.forDevice(row.provider)?.impl;
97
+ if (impl === undefined)
98
+ continue; // unloaded since the query: kept for a later tick
99
+ const callSignal = () => signal
100
+ ? AbortSignal.any([signal, AbortSignal.timeout(CALL_TIMEOUT_MS)])
101
+ : AbortSignal.timeout(CALL_TIMEOUT_MS);
102
+ try {
103
+ // no device lease holds a legacy row: nothing to fence the destroy with
104
+ await impl.destroyByName(name, callSignal(), null);
105
+ await impl.destroyFileSystemByName(name, callSignal());
106
+ if (row.prev_provider !== null && row.prev_provider !== row.provider) {
107
+ const prev = this.providers.forDevice(row.prev_provider)?.impl;
108
+ if (prev !== undefined)
109
+ await prev.destroyByName(name, callSignal(), null);
110
+ else {
111
+ this.log.warn("legacy sandbox of a replaced provider left: provider not loaded", {
112
+ name,
113
+ provider: row.prev_provider,
114
+ });
115
+ }
113
116
  }
117
+ await this.db
118
+ .deleteFrom("sandboxes")
119
+ .where("conversation_id", "=", row.conversation_id)
120
+ .execute();
121
+ destroyed++;
122
+ }
123
+ catch (err) {
124
+ this.log.warn("cannot destroy legacy sandbox; will retry", { name, err });
125
+ await this.db
126
+ .updateTable("sandboxes")
127
+ .set({ sweep_failed_at: now })
128
+ .where("conversation_id", "=", row.conversation_id)
129
+ .execute();
114
130
  }
115
- await this.db
116
- .deleteFrom("sandboxes")
117
- .where("conversation_id", "=", row.conversation_id)
118
- .execute();
119
- destroyed++;
120
- }
121
- catch (err) {
122
- this.log.warn("cannot destroy legacy sandbox; will retry", { name, err });
123
- await this.db
124
- .updateTable("sandboxes")
125
- .set({ sweep_failed_at: now })
126
- .where("conversation_id", "=", row.conversation_id)
127
- .execute();
128
131
  }
129
- }
130
- return { destroyed, kept };
132
+ return { destroyed, kept };
133
+ });
131
134
  }
132
135
  };
133
136
  __decorate([
@@ -94,7 +94,14 @@ declare class DeviceConnection {
94
94
  private publishFailures;
95
95
  private publishCapacity;
96
96
  get deviceId(): string;
97
+ /**
98
+ * Runs `fn` in the device's org (RLS spec §5.3: per-event work of a long connection enters the
99
+ * org its credential resolved). Socket listeners run in the emitter's async context, not the
100
+ * one that registered them, so each enters it again.
101
+ */
102
+ private inOrg;
97
103
  start(): void;
104
+ private arm;
98
105
  private onFrame;
99
106
  /**
100
107
  * The accepted hello: claims the lease, records the program facts, then asks the provider
@@ -195,6 +202,7 @@ export declare class DialInGateway {
195
202
  * before the upgrade): null for an unknown or revoked credential.
196
203
  */
197
204
  admit(credential: string): Promise<DialInAdmission>;
205
+ private admitted;
198
206
  /**
199
207
  * Serves one upgraded socket of a machine until it closes, speaking `protocol` (the route
200
208
  * admitted it). The credential and the provider are checked again here, with the socket paused,
@@ -11,6 +11,7 @@ import { randomUUID } from "node:crypto";
11
11
  import { DIAL_IN_PROTOCOL_RE, parseDialInMachineFrame, } from "@capybara-hq/plugin-sdk";
12
12
  import { Inject, Injectable } from "@nestjs/common";
13
13
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
14
+ import { asPlatform, withOrgScope, withoutOrgScope } from "../infra/database/org-scope.js";
14
15
  import { LockService } from "../infra/lock/lock.service.js";
15
16
  import { KERNEL_BUS, KERNEL_LOGGER, REDIS } from "../infra/tokens.js";
16
17
  import { storedResult, wireFrameOf } from "./envelope.js";
@@ -185,7 +186,22 @@ class DeviceConnection {
185
186
  get deviceId() {
186
187
  return this.identity.deviceId;
187
188
  }
189
+ /**
190
+ * Runs `fn` in the device's org (RLS spec §5.3: per-event work of a long connection enters the
191
+ * org its credential resolved). Socket listeners run in the emitter's async context, not the
192
+ * one that registered them, so each enters it again.
193
+ */
194
+ inOrg(fn) {
195
+ // never throw inside a socket listener: a device without an org (impossible by the schema)
196
+ // runs unscoped, which fails closed
197
+ const { orgId } = this.identity;
198
+ return orgId ? withOrgScope(orgId, fn) : withoutOrgScope(fn);
199
+ }
188
200
  start() {
201
+ // the timers armed here keep this scope (timers carry their creator's async context)
202
+ this.inOrg(() => this.arm());
203
+ }
204
+ arm() {
189
205
  const { socket } = this;
190
206
  this.helloTimer = setTimeout(() => this.close(DEVICE_CLOSE.protocol, "hello expected"), HELLO_TIMEOUT_MS);
191
207
  this.schedulePing();
@@ -206,10 +222,10 @@ class DeviceConnection {
206
222
  : Buffer.isBuffer(data)
207
223
  ? data.toString("utf8")
208
224
  : Buffer.from(data).toString("utf8");
209
- void this.onFrame(text);
225
+ void this.inOrg(() => this.onFrame(text));
210
226
  });
211
227
  socket.on("close", () => {
212
- void this.shutdown();
228
+ void this.inOrg(() => this.shutdown());
213
229
  });
214
230
  }
215
231
  async onFrame(text) {
@@ -785,6 +801,10 @@ let DialInGateway = class DialInGateway {
785
801
  * before the upgrade): null for an unknown or revoked credential.
786
802
  */
787
803
  async admit(credential) {
804
+ // the credential names the device and its org: looked up before any org is known
805
+ return asPlatform("dial-in credential lookup", () => this.admitted(credential));
806
+ }
807
+ async admitted(credential) {
788
808
  const identity = await this.machines.authenticate(credential);
789
809
  if (identity === null)
790
810
  return null;
@@ -20,6 +20,7 @@ import { SuperAdminLock } from "../identity/super-admin.js";
20
20
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
21
21
  import { afterCommit } from "../infra/database/after-commit.js";
22
22
  import { KernelDb } from "../infra/database/kernel-db.js";
23
+ import { asPlatform } from "../infra/database/org-scope.js";
23
24
  import { TransactionHost } from "../infra/database/transaction-host.js";
24
25
  import { Transactional } from "../infra/database/transactional.decorator.js";
25
26
  import { OutboxService } from "../infra/outbox/outbox.service.js";
@@ -560,25 +561,27 @@ function fallbackView(name, known, err) {
560
561
  }
561
562
  /** 插件名已留下的数据:权限快照、部署配置、任一组织的配置,或插件 schema(`plugin_<name>`)。 */
562
563
  async function hasRetainedData(db, name) {
563
- const schema = await sql `SELECT 1 AS x FROM pg_namespace WHERE nspname = ${pluginSchemaName(name)}`.execute(db);
564
- if (schema.rows.length > 0)
565
- return true;
566
- // org-filter: whether any org kept config for the plugin name (a deployment-wide existence check)
567
- const hit = await db
568
- .selectFrom("extension_permission_snapshots")
569
- .select(sql `1`.as("x"))
570
- .where("plugin", "=", name)
571
- .union(db
572
- .selectFrom("extension_deployment_configs")
573
- .select(sql `1`.as("x"))
574
- .where("plugin", "=", name))
575
- .union(db
576
- .selectFrom("extension_org_configs")
577
- .select(sql `1`.as("x"))
578
- .where("plugin", "=", name))
579
- .limit(1)
580
- .executeTakeFirst();
581
- return hit !== undefined;
564
+ return asPlatform("whether any org kept config for a plugin", async () => {
565
+ const schema = await sql `SELECT 1 AS x FROM pg_namespace WHERE nspname = ${pluginSchemaName(name)}`.execute(db);
566
+ if (schema.rows.length > 0)
567
+ return true;
568
+ // org-filter: whether any org kept config for the plugin name (a deployment-wide existence check)
569
+ const hit = await db
570
+ .selectFrom("extension_permission_snapshots")
571
+ .select(sql `1`.as("x"))
572
+ .where("plugin", "=", name)
573
+ .union(db
574
+ .selectFrom("extension_deployment_configs")
575
+ .select(sql `1`.as("x"))
576
+ .where("plugin", "=", name))
577
+ .union(db
578
+ .selectFrom("extension_org_configs")
579
+ .select(sql `1`.as("x"))
580
+ .where("plugin", "=", name))
581
+ .limit(1)
582
+ .executeTakeFirst();
583
+ return hit !== undefined;
584
+ });
582
585
  }
583
586
  const required = (name) => new ApiError("extension.required", `Extension ${name} is required by this deployment (a bootstrap plugin): it is enabled in every organization and cannot be disabled or uninstalled; a super admin can upgrade it`);
584
587
  const notFound = (name) => new ApiError("extension.not_found", `Extension ${name} is not installed in this deployment`);
@@ -217,7 +217,9 @@ let LifecycleHooksProcessor = class LifecycleHooksProcessor extends WorkerHost {
217
217
  this.log = log;
218
218
  }
219
219
  process(job) {
220
- return runJob(LIFECYCLE_QUEUE, job, () => this.hooks.process(job.data, this.stopping.signal));
220
+ return runJob(LIFECYCLE_QUEUE, job, () => this.hooks.process(job.data, this.stopping.signal), {
221
+ platform: "extension lifecycle hook (deployment-wide)",
222
+ });
221
223
  }
222
224
  /** Starts consuming (worker role, after the extensions loaded). */
223
225
  start() {
package/dist/http/app.js CHANGED
@@ -7,6 +7,7 @@ import { ApiTokenService } from "../identity/api-tokens.js";
7
7
  import { authenticateOrgUploader, authorizeSuperAdmin, } from "../identity/auth.guard.js";
8
8
  import { SessionService } from "../identity/sessions.js";
9
9
  import { KernelDb } from "../infra/database/kernel-db.js";
10
+ import { withRequestScopeSlot } from "../infra/database/org-scope.js";
10
11
  import { withLogContext } from "../log-context.js";
11
12
  import { authorizeOrgAction } from "../orgs/org.guard.js";
12
13
  import { redactPath } from "./error.filter.js";
@@ -68,7 +69,8 @@ function registerRequestLog(fastify, log) {
68
69
  };
69
70
  reply.raw.once("finish", accessLine);
70
71
  reply.raw.once("close", accessLine);
71
- withLogContext({ reqId: req.id }, done);
72
+ // an empty org scope slot the guards bind (RLS spec §5.1), then the log context
73
+ withRequestScopeSlot(() => withLogContext({ reqId: req.id }, done));
72
74
  });
73
75
  }
74
76
  /** 允许较大请求体的路由(Fastify 路由模板,只读常量表)及其上限。 */
@@ -2,6 +2,7 @@ import { Readable } from "node:stream";
2
2
  import FindMyWay from "find-my-way";
3
3
  import { ApiError, ERROR_CODES, errorBody } from "../errors.js";
4
4
  import { ACCESS_COOKIE, REFRESH_COOKIE } from "../identity/cookies.js";
5
+ import { bindRequestScope } from "../infra/database/org-scope.js";
5
6
  import { codeForStatus, redactPath } from "./error.filter.js";
6
7
  /** Every extension route lives under this prefix (`ctx.http.route` adds `/plugins/<name>`). */
7
8
  export const PLUGIN_PREFIX = "/plugins/";
@@ -139,6 +140,13 @@ export async function registerPluginDispatch(fastify, getTable, log, access) {
139
140
  if (!entry)
140
141
  return reply.code(500).send(errorBody("internal", "Internal error"));
141
142
  const { route, caller } = entry;
143
+ // the org scope of everything the handler runs (RLS spec §5.1): its caller's org, platform
144
+ // for a super admin's embed, none for a public route until the extension acts for an org
145
+ if ("orgId" in caller && caller.orgId)
146
+ bindRequestScope({ kind: "org", orgId: caller.orgId });
147
+ else if (caller.access === "embed" && caller.scope === "platform") {
148
+ bindRequestScope({ kind: "platform", reason: "super admin embed route" });
149
+ }
142
150
  // Abort `req.signal` only when the connection closes before the response is written (the
143
151
  // client disconnected): long-lived handlers (SSE) unsubscribe on it. A close after a finished
144
152
  // response does not abort (writableFinished is true).
@@ -10,6 +10,8 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
10
10
  import { Inject, Injectable } from "@nestjs/common";
11
11
  import { Reflector } from "@nestjs/core";
12
12
  import { ApiError } from "../errors.js";
13
+ import { asPlatform, bindRequestScope } from "../infra/database/org-scope.js";
14
+ import { ORG_ACTION_KEY } from "../orgs/org.guard.js";
13
15
  import { AccountsService } from "./accounts.js";
14
16
  import { ApiTokenService } from "./api-tokens.js";
15
17
  import { ACCESS_COOKIE } from "./cookies.js";
@@ -34,7 +36,8 @@ async function resolveBearer(req, s) {
34
36
  const bearer = BEARER_RE.exec(req.headers.authorization ?? "")?.[1];
35
37
  if (bearer === undefined)
36
38
  return undefined;
37
- const rec = await s.tokens.authenticate(bearer);
39
+ // looked up by token hash before any org is known: personal tokens have no org (RLS spec §9.4)
40
+ const rec = await asPlatform("api token lookup by hash", () => s.tokens.authenticate(bearer));
38
41
  if (!rec)
39
42
  throw new ApiError("auth.required", "Authentication required");
40
43
  if (rec.kind === "service") {
@@ -195,8 +198,15 @@ let AuthGuard = class AuthGuard {
195
198
  if (p.kind === "user" && p.account.mustChangePassword && !flag(PASSWORD_CHANGE_KEY)) {
196
199
  throw passwordChangeRequired();
197
200
  }
198
- if (flag(SUPER_ADMIN_KEY) && !(p.kind === "user" && p.account.isSuperAdmin)) {
199
- throw new ApiError("forbidden", "Super admin required");
201
+ if (flag(SUPER_ADMIN_KEY)) {
202
+ if (!(p.kind === "user" && p.account.isSuperAdmin)) {
203
+ throw new ApiError("forbidden", "Super admin required");
204
+ }
205
+ // a super admin's route works across the deployment (RLS spec §5.1); one that also acts
206
+ // in an org (`@OrgAction`) is scoped to that org by OrgGuard instead
207
+ const orgRoute = this.reflector.getAllAndOverride(ORG_ACTION_KEY, targets);
208
+ if (!orgRoute)
209
+ bindRequestScope({ kind: "platform", reason: "super admin route" });
200
210
  }
201
211
  return true;
202
212
  }
package/dist/index.d.ts CHANGED
@@ -60,6 +60,8 @@ export { DEPLOYMENT_SETTINGS, type DeploymentSettings, SettingsService, } from "
60
60
  export { type KernelCliOptions, openKernelCli, openKernelCliOverPool, } from "./infra/cli/kernel-cli.module.js";
61
61
  export { rewrapMasterKeys } from "./infra/cli/master-key-rewrap.js";
62
62
  export { type CutoverReplica, type PermissionCutoverReport, permissionCutoverFreeze, permissionCutoverReport, permissionCutoverSnapshot, } from "./infra/cli/permission-cutover.js";
63
+ export { asPlatform, currentScope, type OrgScope, setUnscopedQueryCheck, type UnscopedQueryCheck, withOrgScope, } from "./infra/database/org-scope.js";
64
+ export type { RlsMode } from "./infra/database/scoped-dialect.js";
63
65
  export { onProcessFault } from "./infra/health/process-fault.js";
64
66
  export { GUARD_CIRCUIT_LIMIT, GUARD_CIRCUIT_WINDOW_MS, installProcessGuards, type ProcessGuardDeps, } from "./infra/lifecycle/process-guards.js";
65
67
  export { handleShutdownSignals, type ShutdownSignalHandle, type ShutdownSignalOptions, } from "./infra/lifecycle/shutdown-signals.js";
package/dist/index.js CHANGED
@@ -58,6 +58,7 @@ export { DEPLOYMENT_SETTINGS, SettingsService, } from "./identity/settings.js";
58
58
  export { openKernelCli, openKernelCliOverPool, } from "./infra/cli/kernel-cli.module.js";
59
59
  export { rewrapMasterKeys } from "./infra/cli/master-key-rewrap.js";
60
60
  export { permissionCutoverFreeze, permissionCutoverReport, permissionCutoverSnapshot, } from "./infra/cli/permission-cutover.js";
61
+ export { asPlatform, currentScope, setUnscopedQueryCheck, withOrgScope, } from "./infra/database/org-scope.js";
61
62
  export { onProcessFault } from "./infra/health/process-fault.js";
62
63
  export { GUARD_CIRCUIT_LIMIT, GUARD_CIRCUIT_WINDOW_MS, installProcessGuards, } from "./infra/lifecycle/process-guards.js";
63
64
  export { handleShutdownSignals, } from "./infra/lifecycle/shutdown-signals.js";
@@ -68,6 +68,7 @@ let DatabaseModule = class DatabaseModule {
68
68
  connectTimeoutMs: db.connectTimeoutMs,
69
69
  idleTimeoutMs: db.idleTimeoutMs,
70
70
  onClientError: (err) => log.warn("pg client error", { err }),
71
+ rls: db.rls,
71
72
  });
72
73
  },
73
74
  },
@@ -0,0 +1,59 @@
1
+ /**
2
+ * The org scope of the current async context (Postgres RLS spec §5.1,
3
+ * docs/superpowers/specs/2026-11-23-postgres-rls-design.md): the org whose rows the queries of this
4
+ * call chain may see, or the platform scope for deployment-wide work. The scoped pool
5
+ * (`scoped-dialect.ts`) copies it onto every connection a query runs on (`capybara.org_id`,
6
+ * `capybara.scope`), where the row level security policies read it once enforced (`db.rls`).
7
+ *
8
+ * It is set only at entry points, never inside domain services: the org guard of an HTTP request,
9
+ * `runJob` from the job's org, a run's claim, the gateway once a connection or an event resolved
10
+ * its org, the cron ticks, the start sequence and the CLI (platform). A sweep that walks every org
11
+ * and the queries marked `// org-filter: deployment-wide …` run inside {@link asPlatform}.
12
+ */
13
+ export type OrgScope = {
14
+ readonly kind: "org";
15
+ readonly orgId: string;
16
+ } | {
17
+ readonly kind: "platform";
18
+ readonly reason: string;
19
+ };
20
+ /** The scope of the current async context, or undefined outside any (unscoped). */
21
+ export declare function currentScope(): OrgScope | undefined;
22
+ /** Runs `fn` scoped to `orgId`: its queries see that org's rows once RLS is enforced. */
23
+ export declare function withOrgScope<T>(orgId: string, fn: () => T): T;
24
+ /**
25
+ * Runs `fn` in the platform scope: deployment-wide work (sweeps over every org, relays, super-admin
26
+ * services, lookups made before any org is known). `reason` says why, for review and logs.
27
+ */
28
+ export declare function asPlatform<T>(reason: string, fn: () => T): T;
29
+ /**
30
+ * Runs `fn` with no scope, whatever the caller had: a callback that outlives its registrant (the
31
+ * bus subscriber's shared connection, a job with no org) must not inherit the scope of whoever
32
+ * happened to create it. Fails closed once RLS is enforced.
33
+ */
34
+ export declare function withoutOrgScope<T>(fn: () => T): T;
35
+ /**
36
+ * Runs `fn` (an HTTP request, from the Fastify `onRequest` hook) with an empty, bindable slot: no
37
+ * scope until a guard binds one with {@link bindRequestScope}.
38
+ */
39
+ export declare function withRequestScopeSlot<T>(fn: () => T): T;
40
+ /**
41
+ * Binds the scope of the current HTTP request (the org guard: the guarded org; the super-admin
42
+ * check: platform; an extension route: its caller's org). Everything the request runs afterwards,
43
+ * the handler included, sees it. Binding the same scope twice is allowed; binding a different one
44
+ * is a programming error (a route both platform and org guarded) and throws. Outside a request
45
+ * slot it does nothing.
46
+ */
47
+ export declare function bindRequestScope(scope: OrgScope): void;
48
+ /** A comparable key: `org:<id>`, `platform` or `none`. */
49
+ export declare function scopeKey(scope: OrgScope | undefined): string;
50
+ /**
51
+ * Test seam for RLS phase 4 (spec §7): called by the scoped pool for each query that runs with no
52
+ * scope and names an org-scoped table, with that table and the SQL. A test setup installs one that
53
+ * throws to find unscoped paths; undefined (the default) checks nothing. Only the scoped pool
54
+ * (`db.rls` `scoped` or `enforce`) calls it.
55
+ */
56
+ export type UnscopedQueryCheck = (table: string, sql: string) => void;
57
+ export declare function setUnscopedQueryCheck(check: UnscopedQueryCheck | undefined): void;
58
+ /** @internal the installed check (read by the scoped pool). */
59
+ export declare function unscopedQueryCheck(): UnscopedQueryCheck | undefined;
@@ -0,0 +1,68 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ const storage = new AsyncLocalStorage();
3
+ /** The scope of the current async context, or undefined outside any (unscoped). */
4
+ export function currentScope() {
5
+ return storage.getStore()?.scope;
6
+ }
7
+ /** Runs `fn` scoped to `orgId`: its queries see that org's rows once RLS is enforced. */
8
+ export function withOrgScope(orgId, fn) {
9
+ if (!orgId)
10
+ throw new Error("withOrgScope needs an org id");
11
+ return storage.run({ scope: { kind: "org", orgId }, bindable: false }, fn);
12
+ }
13
+ /**
14
+ * Runs `fn` in the platform scope: deployment-wide work (sweeps over every org, relays, super-admin
15
+ * services, lookups made before any org is known). `reason` says why, for review and logs.
16
+ */
17
+ export function asPlatform(reason, fn) {
18
+ if (!reason.trim())
19
+ throw new Error("asPlatform needs a reason");
20
+ return storage.run({ scope: { kind: "platform", reason }, bindable: false }, fn);
21
+ }
22
+ /**
23
+ * Runs `fn` with no scope, whatever the caller had: a callback that outlives its registrant (the
24
+ * bus subscriber's shared connection, a job with no org) must not inherit the scope of whoever
25
+ * happened to create it. Fails closed once RLS is enforced.
26
+ */
27
+ export function withoutOrgScope(fn) {
28
+ return storage.run({ scope: undefined, bindable: false }, fn);
29
+ }
30
+ /**
31
+ * Runs `fn` (an HTTP request, from the Fastify `onRequest` hook) with an empty, bindable slot: no
32
+ * scope until a guard binds one with {@link bindRequestScope}.
33
+ */
34
+ export function withRequestScopeSlot(fn) {
35
+ return storage.run({ scope: undefined, bindable: true }, fn);
36
+ }
37
+ /**
38
+ * Binds the scope of the current HTTP request (the org guard: the guarded org; the super-admin
39
+ * check: platform; an extension route: its caller's org). Everything the request runs afterwards,
40
+ * the handler included, sees it. Binding the same scope twice is allowed; binding a different one
41
+ * is a programming error (a route both platform and org guarded) and throws. Outside a request
42
+ * slot it does nothing.
43
+ */
44
+ export function bindRequestScope(scope) {
45
+ const slot = storage.getStore();
46
+ // outside a request slot (or inside a fixed scope a caller entered) there is nothing to bind:
47
+ // the context stays as it is, which fails closed once RLS is enforced
48
+ if (!slot?.bindable)
49
+ return;
50
+ if (slot.scope && scopeKey(slot.scope) !== scopeKey(scope)) {
51
+ throw new Error(`The request is already scoped to ${scopeKey(slot.scope)}; refusing ${scopeKey(scope)}`);
52
+ }
53
+ slot.scope = scope;
54
+ }
55
+ /** A comparable key: `org:<id>`, `platform` or `none`. */
56
+ export function scopeKey(scope) {
57
+ if (!scope)
58
+ return "none";
59
+ return scope.kind === "org" ? `org:${scope.orgId}` : "platform";
60
+ }
61
+ let unscopedCheck;
62
+ export function setUnscopedQueryCheck(check) {
63
+ unscopedCheck = check;
64
+ }
65
+ /** @internal the installed check (read by the scoped pool). */
66
+ export function unscopedQueryCheck() {
67
+ return unscopedCheck;
68
+ }
@@ -0,0 +1,11 @@
1
+ import { type Kysely } from "kysely";
2
+ /**
3
+ * Why `db.rls: enforce` would filter nothing on this pool, or undefined when it can work (RLS spec
4
+ * §10):
5
+ * - PostgreSQL never applies a row level security policy to a superuser or a role with BYPASSRLS,
6
+ * even on a table that forces RLS. The official compose file's `POSTGRES_USER` is a superuser, so
7
+ * such a deployment needs a role of its own before enforcing;
8
+ * - the policies ship dark: migration 0182 creates them without `ENABLE` / `FORCE ROW LEVEL
9
+ * SECURITY`, which a later migration (phase 5) runs. Until then no org-scoped table applies them.
10
+ */
11
+ export declare function rlsEnforceProblem(pool: Kysely<any>): Promise<string | undefined>;
@@ -0,0 +1,33 @@
1
+ import { sql } from "kysely";
2
+ /**
3
+ * Why `db.rls: enforce` would filter nothing on this pool, or undefined when it can work (RLS spec
4
+ * §10):
5
+ * - PostgreSQL never applies a row level security policy to a superuser or a role with BYPASSRLS,
6
+ * even on a table that forces RLS. The official compose file's `POSTGRES_USER` is a superuser, so
7
+ * such a deployment needs a role of its own before enforcing;
8
+ * - the policies ship dark: migration 0182 creates them without `ENABLE` / `FORCE ROW LEVEL
9
+ * SECURITY`, which a later migration (phase 5) runs. Until then no org-scoped table applies them.
10
+ */
11
+ // biome-ignore lint/suspicious/noExplicitAny: the pool carries no schema types
12
+ export async function rlsEnforceProblem(pool) {
13
+ const role = await sql `
14
+ select rolsuper as superuser, rolbypassrls as bypass from pg_roles
15
+ where rolname = current_user`.execute(pool);
16
+ const row = role.rows[0];
17
+ if (row?.superuser)
18
+ return "the database role is a superuser";
19
+ if (row?.bypass)
20
+ return "the database role has BYPASSRLS";
21
+ const off = await sql `
22
+ select c.relname as table from pg_class c
23
+ join pg_namespace n on n.oid = c.relnamespace and n.nspname = 'capybara'
24
+ where c.relkind = 'r' and not (c.relrowsecurity and c.relforcerowsecurity)
25
+ and exists (select 1 from pg_attribute a
26
+ where a.attrelid = c.oid and a.attname = 'org_id' and not a.attisdropped)
27
+ order by 1`.execute(pool);
28
+ if (off.rows.length > 0) {
29
+ const first = off.rows[0]?.table;
30
+ return `row level security is not enabled and forced on ${off.rows.length} org-scoped table(s) (${first}, …; RLS spec phase 5 enables them)`;
31
+ }
32
+ return undefined;
33
+ }
@@ -0,0 +1,18 @@
1
+ import { type Driver, PostgresDialect, type PostgresDialectConfig } from "kysely";
2
+ /**
3
+ * `db.rls`: how the kernel pool carries the org scope to Postgres (RLS spec §5.2, §7).
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
6
+ * every row; for measuring the round-trip cost (§8) and for the unscoped-query check.
7
+ * - `enforce`: the same with `capybara.rls = enforce`: the policies filter by the scope.
8
+ */
9
+ export type RlsMode = "off" | "scoped" | "enforce";
10
+ /**
11
+ * The kernel pool's dialect: Kysely's Postgres dialect, with {@link ScopedDriver} unless `rls` is
12
+ * `off` (then nothing changes, not even a round trip).
13
+ */
14
+ export declare class ScopedPostgresDialect extends PostgresDialect {
15
+ private readonly rls;
16
+ constructor(config: PostgresDialectConfig, rls: RlsMode);
17
+ createDriver(): Driver;
18
+ }