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

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 (65) hide show
  1. package/bootstrap.json +29 -29
  2. package/dist/admin/outbox-dead.service.js +133 -120
  3. package/dist/background/store.js +78 -67
  4. package/dist/background/tasks.service.d.ts +6 -0
  5. package/dist/background/tasks.service.js +3 -0
  6. package/dist/catalog/marketplaces.service.d.ts +1 -1
  7. package/dist/catalog/plugin-import.js +45 -40
  8. package/dist/catalog/scope-sync-workers.js +3 -0
  9. package/dist/channels/inbound.d.ts +6 -1
  10. package/dist/channels/inbound.js +18 -1
  11. package/dist/client/client-reports.service.js +9 -6
  12. package/dist/config/schema.d.ts +5 -0
  13. package/dist/config/schema.js +6 -0
  14. package/dist/conversations/attachments.service.js +101 -96
  15. package/dist/conversations/events.d.ts +7 -0
  16. package/dist/conversations/events.js +9 -0
  17. package/dist/ctx/bus.js +5 -3
  18. package/dist/ctx/queue.js +4 -2
  19. package/dist/db/pool.d.ts +6 -0
  20. package/dist/db/pool.js +3 -2
  21. package/dist/devices/legacy-cleanup.job.js +73 -70
  22. package/dist/dial-in/gateway.d.ts +8 -0
  23. package/dist/dial-in/gateway.js +22 -2
  24. package/dist/extensions/admin-ops.js +22 -19
  25. package/dist/extensions/lifecycle-hooks.js +3 -1
  26. package/dist/http/app.js +3 -1
  27. package/dist/http/plugin-dispatch.js +8 -0
  28. package/dist/identity/auth.guard.js +13 -3
  29. package/dist/index.d.ts +2 -0
  30. package/dist/index.js +1 -0
  31. package/dist/infra/database/database.module.js +1 -0
  32. package/dist/infra/database/org-scope.d.ts +59 -0
  33. package/dist/infra/database/org-scope.js +68 -0
  34. package/dist/infra/database/rls-role.d.ts +11 -0
  35. package/dist/infra/database/rls-role.js +33 -0
  36. package/dist/infra/database/scoped-dialect.d.ts +18 -0
  37. package/dist/infra/database/scoped-dialect.js +245 -0
  38. package/dist/infra/outbox/outbox.dispatcher.js +98 -90
  39. package/dist/infra/outbox/outbox.service.js +29 -26
  40. package/dist/infra/queue/run-job.d.ts +8 -2
  41. package/dist/infra/queue/run-job.js +16 -3
  42. package/dist/infra/schedule/locked-tick.js +12 -4
  43. package/dist/infra/schedule/scheduled-runs.js +3 -1
  44. package/dist/lifecycle/kernel-lifecycle.d.ts +1 -0
  45. package/dist/lifecycle/kernel-lifecycle.js +16 -1
  46. package/dist/orgs/org.guard.js +4 -0
  47. package/dist/platform/sealed-reveals.js +9 -6
  48. package/dist/runtime/maintenance.js +6 -1
  49. package/dist/runtime/run-execution.d.ts +1 -0
  50. package/dist/runtime/run-execution.js +5 -0
  51. package/dist/runtime/run-orphan-check.job.js +20 -15
  52. package/dist/sandbox/legacy-retirement.js +438 -397
  53. package/dist/sandbox/modes.d.ts +10 -0
  54. package/dist/sandbox/modes.js +23 -0
  55. package/dist/sandbox/operation-reconcile.job.d.ts +14 -1
  56. package/dist/sandbox/operation-reconcile.job.js +35 -3
  57. package/dist/sandbox/permission-config-publication.js +83 -77
  58. package/dist/sandbox/sandbox.service.d.ts +24 -0
  59. package/dist/sandbox/sandbox.service.js +159 -62
  60. package/dist/schedules/store.js +17 -14
  61. package/dist/tools/builtins/sandbox/bash.js +16 -1
  62. package/dist/tools/drift.js +31 -24
  63. package/dist/tools/outputs.js +20 -17
  64. package/package.json +2 -2
  65. package/src/migrations/0182_rls_policies.sql +202 -0
@@ -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
+ }
@@ -0,0 +1,245 @@
1
+ import { CompiledQuery, PostgresDialect, } from "kysely";
2
+ 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]);
10
+ }
11
+ /** Tables of the `capybara` schema with an `org_id` column (for the unscoped-query check). */
12
+ const ORG_TABLES_SQL = "select table_name from information_schema.columns " +
13
+ "where table_schema = 'capybara' and column_name = 'org_id'";
14
+ const TABLE_REF = /"capybara"\."([a-z0-9_]+)"|\bcapybara\.([a-z0-9_]+)/g;
15
+ /**
16
+ * One checkout of a pool connection. Before a query runs, the scope of the caller's async context
17
+ * is put on the connection unless it is already there: session-level (`set_config(…, false)`)
18
+ * outside a transaction, transaction-local (`true`) inside one, the first right after `BEGIN`.
19
+ * A fresh checkout knows nothing about the session's values, so its first query always sets all
20
+ * three: whatever an earlier holder left on the connection is overwritten before it can be read,
21
+ * and a returned connection carries no scope into its next user. Queries on one checkout run one
22
+ * after another (as pg runs them anyway), so a scope change and the query it precedes are never
23
+ * split by another query of the same transaction.
24
+ */
25
+ class ScopedConnection {
26
+ inner;
27
+ rls;
28
+ orgTables;
29
+ /** The scope key now on the connection; undefined when unknown (fresh, or after a commit). */
30
+ applied;
31
+ inTransaction = false;
32
+ tail = Promise.resolve();
33
+ constructor(inner, rls, orgTables) {
34
+ this.inner = inner;
35
+ this.rls = rls;
36
+ this.orgTables = orgTables;
37
+ }
38
+ // cancellation (an aborted query) goes to the inner connection, which knows the backend; the
39
+ // kernel passes no abort signal to queries, so terminating a whole session is never asked for
40
+ cancelQuery(provider) {
41
+ return this.inner.cancelQuery?.(provider) ?? Promise.resolve();
42
+ }
43
+ collectSessionInfo() {
44
+ return this.inner.collectSessionInfo?.() ?? Promise.resolve();
45
+ }
46
+ /** Runs `fn` after every earlier operation of this checkout settled. */
47
+ serial(fn) {
48
+ const run = this.tail.then(fn, fn);
49
+ this.tail = run.catch(() => { });
50
+ return run;
51
+ }
52
+ async ensure(scope) {
53
+ const key = scopeKey(scope);
54
+ if (this.applied === key)
55
+ return;
56
+ this.applied = undefined;
57
+ await this.inner.executeQuery(setScopeQuery(scope, this.rls, this.inTransaction));
58
+ this.applied = key;
59
+ }
60
+ async check(scope, sql) {
61
+ const check = unscopedQueryCheck();
62
+ if (!check || scope)
63
+ return;
64
+ const tables = await this.orgTables(this.inner);
65
+ for (const m of sql.matchAll(TABLE_REF)) {
66
+ const table = m[1] ?? m[2];
67
+ if (table && tables.has(table))
68
+ check(table, sql);
69
+ }
70
+ }
71
+ executeQuery(query) {
72
+ const scope = currentScope();
73
+ return this.serial(async () => {
74
+ await this.check(scope, query.sql);
75
+ await this.ensure(scope);
76
+ return this.inner.executeQuery(query);
77
+ });
78
+ }
79
+ /**
80
+ * A cursor holds this checkout until it is closed: the scope is set and the stream read inside
81
+ * one serial step, so no query of another scope runs in between.
82
+ */
83
+ async *streamQuery(query, chunkSize) {
84
+ const scope = currentScope();
85
+ let release = () => { };
86
+ const held = new Promise((resolve) => {
87
+ release = resolve;
88
+ });
89
+ let ready = () => { };
90
+ const started = new Promise((resolve, reject) => {
91
+ ready = (error) => (error === undefined ? resolve() : reject(error));
92
+ });
93
+ void this.serial(async () => {
94
+ try {
95
+ await this.check(scope, query.sql);
96
+ await this.ensure(scope);
97
+ }
98
+ catch (error) {
99
+ ready(error ?? new Error("scope setup failed"));
100
+ return;
101
+ }
102
+ ready();
103
+ await held;
104
+ });
105
+ try {
106
+ await started;
107
+ yield* this.inner.streamQuery(query, chunkSize);
108
+ }
109
+ finally {
110
+ release();
111
+ }
112
+ }
113
+ /** `BEGIN`, then the scope of the caller transaction-local, as the transaction's first statement. */
114
+ begin(driver, settings) {
115
+ const scope = currentScope();
116
+ return this.serial(async () => {
117
+ await driver.beginTransaction(this.inner, settings);
118
+ this.inTransaction = true;
119
+ this.applied = undefined;
120
+ try {
121
+ await this.ensure(scope);
122
+ }
123
+ catch (error) {
124
+ // Kysely rolls back only a transaction whose begin resolved: end this one here, or the
125
+ // connection would return to the pool inside it (best effort; the error is the caller's)
126
+ await driver.rollbackTransaction(this.inner).catch(() => { });
127
+ this.inTransaction = false;
128
+ this.applied = undefined;
129
+ throw error;
130
+ }
131
+ });
132
+ }
133
+ /** `COMMIT` / `ROLLBACK`: the local values end, the session's (unknown here) apply again. */
134
+ end(fn) {
135
+ return this.serial(async () => {
136
+ try {
137
+ await fn();
138
+ }
139
+ finally {
140
+ this.inTransaction = false;
141
+ this.applied = undefined;
142
+ }
143
+ });
144
+ }
145
+ /**
146
+ * A savepoint statement, in order with the queries. A rollback to a savepoint also undoes a
147
+ * scope set after it, so the scope on the connection is unknown again.
148
+ */
149
+ step(fn, rollsBack = false) {
150
+ return this.serial(async () => {
151
+ try {
152
+ await fn();
153
+ }
154
+ finally {
155
+ if (rollsBack)
156
+ this.applied = undefined;
157
+ }
158
+ });
159
+ }
160
+ }
161
+ /**
162
+ * Wraps Kysely's Postgres driver so every connection carries the caller's org scope
163
+ * ({@link ScopedConnection}). Everything else (pooling, cancellation, savepoints) is the inner
164
+ * driver's.
165
+ */
166
+ class ScopedDriver {
167
+ inner;
168
+ rls;
169
+ tables;
170
+ constructor(inner, rls) {
171
+ this.inner = inner;
172
+ this.rls = rls;
173
+ }
174
+ init() {
175
+ return this.inner.init();
176
+ }
177
+ /**
178
+ * The org-scoped tables, read once (on the connection of the query that first needs them, so the
179
+ * check never waits for a second pool connection).
180
+ */
181
+ orgTables = (conn) => {
182
+ this.tables ??= conn
183
+ .executeQuery(CompiledQuery.raw(ORG_TABLES_SQL))
184
+ .then((r) => new Set(r.rows.map((row) => row.table_name)));
185
+ this.tables.catch(() => {
186
+ this.tables = undefined;
187
+ });
188
+ return this.tables;
189
+ };
190
+ async acquireConnection() {
191
+ const inner = await this.inner.acquireConnection();
192
+ return new ScopedConnection(inner, this.rls, this.orgTables);
193
+ }
194
+ beginTransaction(conn, settings) {
195
+ return scoped(conn).begin(this.inner, settings);
196
+ }
197
+ commitTransaction(conn) {
198
+ const c = scoped(conn);
199
+ return c.end(() => this.inner.commitTransaction(c.inner));
200
+ }
201
+ rollbackTransaction(conn) {
202
+ const c = scoped(conn);
203
+ return c.end(() => this.inner.rollbackTransaction(c.inner));
204
+ }
205
+ async savepoint(conn, name, compile) {
206
+ const c = scoped(conn);
207
+ await c.step(async () => this.inner.savepoint?.(c.inner, name, compile));
208
+ }
209
+ async rollbackToSavepoint(conn, name, compile) {
210
+ const c = scoped(conn);
211
+ await c.step(async () => this.inner.rollbackToSavepoint?.(c.inner, name, compile), true);
212
+ }
213
+ async releaseSavepoint(conn, name, compile) {
214
+ const c = scoped(conn);
215
+ await c.step(async () => this.inner.releaseSavepoint?.(c.inner, name, compile));
216
+ }
217
+ releaseConnection(conn) {
218
+ return this.inner.releaseConnection(scoped(conn).inner);
219
+ }
220
+ destroy() {
221
+ return this.inner.destroy();
222
+ }
223
+ }
224
+ function scoped(conn) {
225
+ if (!(conn instanceof ScopedConnection))
226
+ throw new Error("Not a scoped pool connection");
227
+ return conn;
228
+ }
229
+ /**
230
+ * The kernel pool's dialect: Kysely's Postgres dialect, with {@link ScopedDriver} unless `rls` is
231
+ * `off` (then nothing changes, not even a round trip).
232
+ */
233
+ export class ScopedPostgresDialect extends PostgresDialect {
234
+ rls;
235
+ constructor(config, rls) {
236
+ super(config);
237
+ this.rls = rls;
238
+ }
239
+ createDriver() {
240
+ const inner = super.createDriver();
241
+ if (this.rls === "off")
242
+ return inner;
243
+ return new ScopedDriver(inner, this.rls === "enforce" ? "enforce" : "off");
244
+ }
245
+ }