@mistriwork/engine 1.0.0-rc.52 → 1.0.0-rc.53

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.
@@ -24,18 +24,25 @@ export declare function postgresDescriptionCounts(): Readonly<{
24
24
  * An adapter on the manager every adapter of `url` with this `shape` shares (sharedPgConnections): its own catalog,
25
25
  * lanes and stores, the pools of its neighbors. Closing it lets its share go; the pools close with the last one.
26
26
  */
27
- export declare function sharedPostgresAdapter(url: string, label: string, shape?: SharedPoolShape): PostgresAdapter;
27
+ export declare function sharedPostgresAdapter(url: string, label: string, shape?: SharedPoolShape, options?: PostgresAdapterOptions): PostgresAdapter;
28
28
  /** What an adapter is built with beyond its connection. */
29
29
  export interface PostgresAdapterOptions {
30
30
  /**
31
31
  * The database's own tenant backstop (row security): the role this adapter's connections run as, which every
32
32
  * tenant table's one row policy names. With it, a scoped transaction and a read snapshot given a tenant set
33
33
  * `mistri.tenant` for the policy to read, the scope catalog accepts exactly that policy (postgresScopeCatalog.ts),
34
- * and an autocommit scoped read, which no tenant rides with, refuses. Without it, nothing the adapter sends changes.
34
+ * and an autocommit scoped read, which no tenant rides with, refuses. A scoped transaction or snapshot asked with no
35
+ * tenant at all refuses too, so a path that forgot its tenant is an error rather than an empty answer; `null` is the
36
+ * deliberate none (a store's or the catalog's own read). Without it, nothing the adapter sends changes.
37
+ *
38
+ * `bypass`: this adapter connects as the tables' owner, which the policy (`TO` the runtime `role`) does not bind —
39
+ * the paths that cross tenants by design. Its catalogs accept the same one policy, and nothing else changes: no
40
+ * tenant is asked for or set, and autocommit scoped reads stay.
35
41
  */
36
42
  readonly rowSecurity?: {
37
43
  readonly role: string;
38
44
  readonly force?: boolean;
45
+ readonly bypass?: boolean;
39
46
  };
40
47
  }
41
48
  export declare class PostgresAdapter implements Adapter {
@@ -327,9 +334,10 @@ export declare class PostgresAdapter implements Adapter {
327
334
  * discarded rather than reused. Everything else did not commit.
328
335
  */
329
336
  scopeTransaction<T>(input: RowScope, run: (tx: WriteTransaction, catalog: DatabaseSchema) => Promise<T>, triggers?: TriggerAcceptance,
330
- /** `tenant`: what the row policy reads, under the backstop (PostgresAdapterOptions.rowSecurity); ignored without it. */
337
+ /** `tenant`: what the row policy reads, under the backstop (PostgresAdapterOptions.rowSecurity), where it must be
338
+ * given (`null`: deliberately none); ignored without it. */
331
339
  options?: {
332
- readonly tenant?: string;
340
+ readonly tenant?: string | null;
333
341
  }): Promise<T>;
334
342
  /**
335
343
  * Private source-owner boundary, deliberately absent from Adapter: the
@@ -348,7 +356,7 @@ export declare class PostgresAdapter implements Adapter {
348
356
  scopeVerifiedTransaction<T>(input: RowScope, verify: PostgresTransactionVerifier, run: (tx: WriteTransaction, catalog: DatabaseSchema) => Promise<T>,
349
357
  /** As scopeTransaction's. */
350
358
  options?: {
351
- readonly tenant?: string;
359
+ readonly tenant?: string | null;
352
360
  }): Promise<T>;
353
361
  /**
354
362
  * Private source-owner boundary, deliberately absent from Adapter: one
@@ -363,8 +371,9 @@ export declare class PostgresAdapter implements Adapter {
363
371
  * client rather than returning it to the pool.
364
372
  */
365
373
  readSnapshot<T>(run: (snapshot: PostgresReadSnapshot) => Promise<T>, observeCheckout?: boolean, prologue?: string, ahead?: boolean, whole?: boolean,
366
- /** What the row policy reads, under the backstop (PostgresAdapterOptions.rowSecurity); ignored without it. */
367
- tenant?: string): Promise<T>;
374
+ /** What the row policy reads, under the backstop (PostgresAdapterOptions.rowSecurity), where it must be given
375
+ * (`null`: deliberately none); ignored without it. */
376
+ tenant?: string | null): Promise<T>;
368
377
  private tenantSet;
369
378
  /** Private source-shape owner, not an authorization proof or generic Adapter
370
379
  * capability. Only this actual adapter's native snapshot runner is used. */
@@ -81,8 +81,8 @@ export function postgresDescriptionCounts() {
81
81
  * An adapter on the manager every adapter of `url` with this `shape` shares (sharedPgConnections): its own catalog,
82
82
  * lanes and stores, the pools of its neighbors. Closing it lets its share go; the pools close with the last one.
83
83
  */
84
- export function sharedPostgresAdapter(url, label, shape = {}) {
85
- return new PostgresAdapter(url, label, [], sharedPgConnections(url, shape, keepDatesAsText));
84
+ export function sharedPostgresAdapter(url, label, shape = {}, options = {}) {
85
+ return new PostgresAdapter(url, label, [], sharedPgConnections(url, shape, keepDatesAsText), undefined, options);
86
86
  }
87
87
  /**
88
88
  * Whether a statement sent ahead behind a write's BEGIN (writeAhead.ts) failed, so the transaction must begin again
@@ -141,9 +141,12 @@ export class PostgresAdapter {
141
141
  this.schemas = schemas;
142
142
  const security = options.rowSecurity;
143
143
  if (security !== undefined &&
144
- (typeof security.role !== 'string' || !security.role || (security.force !== undefined && typeof security.force !== 'boolean')))
144
+ (typeof security.role !== 'string' ||
145
+ !security.role ||
146
+ (security.force !== undefined && typeof security.force !== 'boolean') ||
147
+ (security.bypass !== undefined && typeof security.bypass !== 'boolean')))
145
148
  throw new TypeError('A row-security role is a role name.');
146
- this.rowSecurity = security && Object.freeze({ role: security.role, force: security.force === true });
149
+ this.rowSecurity = security && Object.freeze({ role: security.role, force: security.force === true, bypass: security.bypass === true });
147
150
  this.connections = connections ?? new PgConnectionManager(connectionString, keepDatesAsText, undefined, pool);
148
151
  this.describes = `${connectionString}\0${schemas.join('\0')}`;
149
152
  this.database = connectionString;
@@ -158,7 +161,8 @@ export class PostgresAdapter {
158
161
  attestedStore: (client, store, read) => this.attestedStore(client, store, read),
159
162
  verifiedSource: () => this.verifiedSource(),
160
163
  journalTransaction: (journal, run, options) => this.journalTransaction(journal, run, options),
161
- readSnapshot: (run) => this.readSnapshot(run, true),
164
+ // A store's tables carry no tenant policy: its snapshot is deliberately no tenant's.
165
+ readSnapshot: (run) => this.readSnapshot(run, true, undefined, false, false, null),
162
166
  hasReplicas: () => this.connections.hasReplicas(),
163
167
  onHealthyReplicas: (work) => this.connections.onHealthyReplicas(work),
164
168
  });
@@ -494,7 +498,7 @@ export class PostgresAdapter {
494
498
  async scopeReads(input) {
495
499
  /* Each read here is its own autocommit statement, with no transaction for a tenant to be set in: under the
496
500
  backstop it would see nothing, and an empty answer would read as an empty tenant. Loud instead. */
497
- if (this.rowSecurity)
501
+ if (this.rowSecurity && !this.rowSecurity.bypass)
498
502
  throw new Refusal('Autocommit scoped reads are unavailable under row security; read in a snapshot.');
499
503
  // Capture before metadata I/O: callers cannot change an in-flight policy.
500
504
  const scope = captureRowScope(input);
@@ -1241,10 +1245,11 @@ export class PostgresAdapter {
1241
1245
  * discarded rather than reused. Everything else did not commit.
1242
1246
  */
1243
1247
  async scopeTransaction(input, run, triggers,
1244
- /** `tenant`: what the row policy reads, under the backstop (PostgresAdapterOptions.rowSecurity); ignored without it. */
1248
+ /** `tenant`: what the row policy reads, under the backstop (PostgresAdapterOptions.rowSecurity), where it must be
1249
+ * given (`null`: deliberately none); ignored without it. */
1245
1250
  options = {}) {
1246
1251
  const scope = captureRowScope(input);
1247
- return this.scopedTransact(scope, undefined, (tx, _journal, catalog) => run(tx, catalog), undefined, undefined, triggers, options.tenant);
1252
+ return this.scopedTransact(scope, undefined, (tx, _journal, catalog) => run(tx, catalog), undefined, undefined, triggers, options.tenant, 'scopeTransaction');
1248
1253
  }
1249
1254
  /**
1250
1255
  * Private source-owner boundary, deliberately absent from Adapter: the
@@ -1266,7 +1271,7 @@ export class PostgresAdapter {
1266
1271
  const scope = captureRowScope(input);
1267
1272
  if (typeof verify !== 'function' || typeof run !== 'function' || Object.keys(scope).some(isRuntimeRelation))
1268
1273
  throw new Refusal('This verified transaction is unavailable.');
1269
- return this.scopedTransact(scope, undefined, (tx, _journal, catalog) => run(tx, catalog), verify, undefined, undefined, options.tenant);
1274
+ return this.scopedTransact(scope, undefined, (tx, _journal, catalog) => run(tx, catalog), verify, undefined, undefined, options.tenant, 'scopeVerifiedTransaction');
1270
1275
  }
1271
1276
  /**
1272
1277
  * Private source-owner boundary, deliberately absent from Adapter: one
@@ -1284,14 +1289,22 @@ export class PostgresAdapter {
1284
1289
  /* The prologue is the snapshot's whole question (a membership fence): BEGIN, the prologue and COMMIT in one
1285
1290
  round trip where they were two. `run` is handed its answers and nothing it can ask. */
1286
1291
  whole = false,
1287
- /** What the row policy reads, under the backstop (PostgresAdapterOptions.rowSecurity); ignored without it. */
1292
+ /** What the row policy reads, under the backstop (PostgresAdapterOptions.rowSecurity), where it must be given
1293
+ * (`null`: deliberately none); ignored without it. */
1288
1294
  tenant) {
1289
- return readSnapshotOn(this.connections, (db, checkout) => (checkout ? PostgresAdapter.prototype.describe.call(this, db) : this.describeSnapshot(db)), run, observeCheckout, prologue, ahead, whole, this.tenantSet(tenant));
1295
+ return readSnapshotOn(this.connections, (db, checkout) => (checkout ? PostgresAdapter.prototype.describe.call(this, db) : this.describeSnapshot(db)), run, observeCheckout, prologue, ahead, whole, this.tenantSet(tenant, 'readSnapshot'));
1290
1296
  }
1291
1297
  /* The tenant's SET in a BEGIN's message (tenantSession), under the backstop alone: without it a tenant passed
1292
- changes nothing sent. Under it, a transaction given none sets none, and the policy then admits no row. */
1293
- tenantSet(tenant) {
1294
- return this.rowSecurity && tenant !== undefined ? tenantSession(tenant) : '';
1298
+ changes nothing sent, and the owner's adapter (`bypass`) is not bound by the policy. Under it, `null` sets none,
1299
+ and the policy then admits no row; no tenant at all is a caller that forgot it, refused before anything is sent
1300
+ rather than answered with an empty tenant. */
1301
+ tenantSet(tenant, method) {
1302
+ const security = this.rowSecurity;
1303
+ if (!security || security.bypass)
1304
+ return '';
1305
+ if (tenant === undefined)
1306
+ throw new Error(`${method} was asked without a tenant under the row-security backstop; pass the tenant, or null where none is meant.`);
1307
+ return tenant === null ? '' : tenantSession(tenant);
1295
1308
  }
1296
1309
  /** Private source-shape owner, not an authorization proof or generic Adapter
1297
1310
  * capability. Only this actual adapter's native snapshot runner is used. */
@@ -1311,7 +1324,8 @@ export class PostgresAdapter {
1311
1324
  nativeCurrent();
1312
1325
  return createPinnedPostgresReadOwner((run) => {
1313
1326
  nativeCurrent();
1314
- return (PostgresAdapter.prototype.readSnapshot).call(this, run, true);
1327
+ // Its pinned catalog refuses a table under row security: no tenant's rows are read here.
1328
+ return (PostgresAdapter.prototype.readSnapshot).call(this, run, true, undefined, false, false, null);
1315
1329
  }, dependencies, () => {
1316
1330
  nativeCurrent();
1317
1331
  assertCurrent();
@@ -1321,9 +1335,9 @@ export class PostgresAdapter {
1321
1335
  /* Scoped records and, for a command, the durable journal and fresh catalog
1322
1336
  evidence in one transaction. The journal is attested before the catalog
1323
1337
  is read, so an unmigrated layout refuses before any lock is taken. */
1324
- async scopedTransact(scope, journal, run, verify, bound, triggers, tenant) {
1338
+ async scopedTransact(scope, journal, run, verify, bound, triggers, tenant, method = 'journalTransaction') {
1325
1339
  // Said before the transaction is queued: a tenant that cannot be set refuses with nothing begun.
1326
- const session = SCOPED_SESSION + this.tenantSet(tenant);
1340
+ const session = SCOPED_SESSION + this.tenantSet(tenant, method);
1327
1341
  /* The proof is loaded where a transaction accepts triggers, not at startup; and awaited in the transaction's turn,
1328
1342
  not before it is queued: a write asked after this one would otherwise take its turn while the module loads. */
1329
1343
  const loading = triggers && !journal?.fixedRecords ? import('./scoped/triggerProof.js') : undefined;
@@ -15,6 +15,15 @@ export declare function withPostgresMaintenanceTransaction<T>(url: string, run:
15
15
  * Returns whether this call created it.
16
16
  */
17
17
  export declare function ensurePostgresRuntimeSchema(client: PgQuery): Promise<boolean>;
18
+ /**
19
+ * Under the tenant row-security backstop, the App connects as `runtime` and its stores belong to `owner`, which
20
+ * migrated them. Declared once the startup attestation has proved the pair (two roles, the runtime neither
21
+ * superuser, BYPASSRLS nor a member of the owner): from then on a store attestation on either role's connection
22
+ * takes the owner's view of ownership and allows the runtime its DML (postgresRuntimeSchemaProblems). A runtime paired with a second, different owner is refused: a store has one owner.
23
+ */
24
+ export declare function declareBackstopRoles(runtime: string, owner: string): void;
25
+ /** Forget every declared pair: a process's tenant pools closing (tenantConnections.forgetTenantPools). */
26
+ export declare function forgetBackstopRoles(): void;
18
27
  /**
19
28
  * What makes a store's part of the runtime schema not this role's alone, as
20
29
  * sentences; empty when it is. The schema: owned by this role (or, for a
@@ -92,6 +92,32 @@ export async function ensurePostgresRuntimeSchema(client) {
92
92
  await client.query(`REVOKE ALL ON SCHEMA ${RUNTIME_SCHEMA} FROM PUBLIC`);
93
93
  return true;
94
94
  }
95
+ /* The tenant backstop's role pairs, runtime to owner (declareBackstopRoles), once a tenant App's startup has
96
+ attested them: none without the backstop, and then every statement below is the one it was. */
97
+ const backstopRoles = new Map();
98
+ /**
99
+ * Under the tenant row-security backstop, the App connects as `runtime` and its stores belong to `owner`, which
100
+ * migrated them. Declared once the startup attestation has proved the pair (two roles, the runtime neither
101
+ * superuser, BYPASSRLS nor a member of the owner): from then on a store attestation on either role's connection
102
+ * takes the owner's view of ownership and allows the runtime its DML (postgresRuntimeSchemaProblems). A runtime paired with a second, different owner is refused: a store has one owner.
103
+ */
104
+ export function declareBackstopRoles(runtime, owner) {
105
+ if (typeof runtime !== 'string' || !runtime || typeof owner !== 'string' || !owner || runtime === owner)
106
+ throw new TypeError('A backstop pairs two role names.');
107
+ const held = backstopRoles.get(runtime);
108
+ if (held !== undefined && held !== owner)
109
+ throw new Refusal(`The role "${runtime}" already runs as the runtime of another owner.`);
110
+ backstopRoles.set(runtime, owner);
111
+ }
112
+ /** Forget every declared pair: a process's tenant pools closing (tenantConnections.forgetTenantPools). */
113
+ export function forgetBackstopRoles() {
114
+ backstopRoles.clear();
115
+ }
116
+ /* The pair the connecting role belongs to, as SQL over two text-array parameters at `at`: a CTE `bk(rt, owner)`
117
+ holding it, or nothing. */
118
+ const backstopPair = (at) => `bk AS (SELECT p.rt, p.owner FROM pg_catalog.unnest($${at}::text[], $${at + 1}::text[]) AS p(rt, owner)
119
+ WHERE CURRENT_USER IN (p.rt, p.owner) LIMIT 1)`;
120
+ const backstopValues = () => [[...backstopRoles.keys()], [...backstopRoles.values()]];
95
121
  /* A role the store may belong to: the connecting role itself, or a role
96
122
  whose privileges it inherits, so a deployment can migrate as one member
97
123
  of an owning group and run as another. A superuser is an implicit member
@@ -124,8 +150,16 @@ export async function postgresRuntimeSchemaProblems(client, prefix, options = {}
124
150
  throw new TypeError('A runtime role is a role name.');
125
151
  /* `rt.oid` is null without a runtime role, so nothing, PUBLIC included, is the runtime's and every grant counts as before. */
126
152
  const runtime = (grantee, privilege, kinds) => `COALESCE(${grantee} = rt.oid AND ${privilege} IN (${kinds}), false)`;
127
- const row = (await client.query(`WITH me AS (SELECT r.oid, r.rolsuper FROM pg_catalog.pg_roles r WHERE r.rolname = CURRENT_USER),
128
- rt AS (SELECT (SELECT r.oid FROM pg_catalog.pg_roles r WHERE r.rolname = $6::text) AS oid),
153
+ /* Under a declared backstop pair (declareBackstopRoles) the checks take the owner's view, on either role's
154
+ connection, and the runtime is the pair's unless the caller named one. */
155
+ const paired = backstopRoles.size > 0;
156
+ const roles = paired
157
+ ? `${backstopPair(7)},
158
+ me AS (SELECT r.oid, r.rolsuper FROM pg_catalog.pg_roles r WHERE r.rolname = COALESCE((SELECT owner FROM bk), CURRENT_USER)),
159
+ rt AS (SELECT (SELECT r.oid FROM pg_catalog.pg_roles r WHERE r.rolname = COALESCE($6::text, (SELECT bk.rt FROM bk))) AS oid),`
160
+ : `me AS (SELECT r.oid, r.rolsuper FROM pg_catalog.pg_roles r WHERE r.rolname = CURRENT_USER),
161
+ rt AS (SELECT (SELECT r.oid FROM pg_catalog.pg_roles r WHERE r.rolname = $6::text) AS oid),`;
162
+ const row = (await client.query(`WITH ${roles}
129
163
  ns AS (SELECT n.oid, n.nspowner, n.nspacl FROM pg_catalog.pg_namespace n WHERE n.nspname = $1),
130
164
  acl AS (SELECT a.grantee, a.privilege_type FROM ns, pg_catalog.aclexplode(COALESCE(ns.nspacl, pg_catalog.acldefault('n', ns.nspowner))) a),
131
165
  control AS (SELECT DISTINCT c.relowner AS role FROM ns, pg_catalog.pg_class c
@@ -170,6 +204,7 @@ export async function postgresRuntimeSchemaProblems(client, prefix, options = {}
170
204
  RUNTIME_CONTROL_PREFIXES.map((each) => `${each.replaceAll('_', '\\_')}%`),
171
205
  RUNTIME_SCHEMA_FUNCTIONS,
172
206
  options.runtime ?? null,
207
+ ...(paired ? backstopValues() : []),
173
208
  ])).rows[0];
174
209
  if (!row)
175
210
  return ['its catalog could not be read'];
@@ -75,8 +75,9 @@ export interface JournalTransactionOptions<V> {
75
75
  readonly ordinaryVerify?: () => unknown;
76
76
  /** A scoped transaction's triggers the App accepts, by physical table (scoped/triggerProof.ts). */
77
77
  readonly triggers?: TriggerAcceptance;
78
- /** A scoped transaction's tenant, for the row policy under PostgreSQL's backstop (PostgresAdapterOptions.rowSecurity); SQLite has none. */
79
- readonly tenant?: string;
78
+ /** A scoped transaction's tenant, for the row policy under PostgreSQL's backstop (PostgresAdapterOptions.rowSecurity),
79
+ * where it must be given (`null`: deliberately none); SQLite has none. */
80
+ readonly tenant?: string | null;
80
81
  }
81
82
  /** The callback: the records, the journal, and a scoped transaction's catalog evidence (absent in an ordinary one). */
82
83
  export type JournalRun<J, T> = (records: WriteTransaction, journal: J, catalog?: DatabaseSchema) => Promise<T>;
@@ -103,6 +103,8 @@ export async function readStartupConfig(opts, registry, given) {
103
103
  ...(c.replicas ? { replicas: c.replicas } : {}),
104
104
  // A direct URL for LISTEN behind a pooler, checked by loadConfig.
105
105
  ...(c.listen ? { listen: c.listen } : {}),
106
+ // The row-level security backstop and its owner's URL, checked by loadConfig.
107
+ ...(c.backstop ? { backstop: c.backstop, ...(c.owner ? { owner: c.owner } : {}) } : {}),
106
108
  // An API's base URL, description and auth, checked by loadConfig.
107
109
  http: c.http,
108
110
  // Where its migrations are (tablewalk migrate), checked by loadConfig.
@@ -88,6 +88,14 @@ export interface ConnectionConfig {
88
88
  * listening session (packages/mistri/src/adapters/events/postgresCommandEventWake.ts).
89
89
  */
90
90
  listen?: string;
91
+ /**
92
+ * `"rls"`: the database's row-level security stands behind the tenant scope (docs/postgresql.md). `url` and
93
+ * `replicas` then name the runtime role, which owns no table and reads under the pinned policy; `owner` names
94
+ * the role that owns the tables. A tenant App only; checked by backstopOf.
95
+ */
96
+ backstop?: 'rls';
97
+ /** The owner role's URL under `backstop`, resolved as `url` is: what crosses tenants by design runs on it. */
98
+ owner?: string;
91
99
  /**
92
100
  * Present for an API read through its description (`"kind": "http"` in the
93
101
  * config file); `url` is then the API's base URL. It holds no secret:
@@ -299,6 +307,10 @@ interface ConfigFile {
299
307
  replicas?: unknown;
300
308
  /** A direct URL for LISTEN behind a pooler, checked by listenOf. */
301
309
  listen?: unknown;
310
+ /** `"rls"` with `owner`, checked by backstopOf. */
311
+ backstop?: unknown;
312
+ /** The owner role's URL under `backstop`, checked by backstopOf. */
313
+ owner?: unknown;
302
314
  /** `"http"` for an API, `"cache"`, `"webhook"`, … for a service (serviceConnections.ts); absent for a database. */
303
315
  kind?: 'http' | ServiceKind;
304
316
  /** A description file relative to this one, or the description itself. */
@@ -319,12 +331,14 @@ interface ConfigFile {
319
331
  export interface LoadedConfig {
320
332
  path: string;
321
333
  /** As written — a SQLite path located against the file (`writtenUrl` keeps the spelling) — plus an HTTP connection's fields checked and its description resolved against the file, and a checked pool. */
322
- connections: Array<Omit<ConfigFile['connections'][number], 'pool' | 'replicas' | 'listen'> & {
334
+ connections: Array<Omit<ConfigFile['connections'][number], 'pool' | 'replicas' | 'listen' | 'backstop' | 'owner'> & {
323
335
  writtenUrl?: string;
324
336
  http?: HttpConnectionConfig;
325
337
  pool?: PoolSize;
326
338
  replicas?: string[];
327
339
  listen?: string;
340
+ backstop?: 'rls';
341
+ owner?: string;
328
342
  }>;
329
343
  /** The services the file names beside its databases, checked; never databases, never listed as connections. */
330
344
  services: ServiceConfig[];
@@ -31,7 +31,7 @@ import { httpConnectionOf, openHttp } from './httpConnection.js';
31
31
  import { checkServices, isServiceKind, isUrlless, keptUnread, parseConfigSections, serviceConnectionOf, serviceEntry, } from './configSections.js';
32
32
  import { CACHE_SECTIONS, openCache } from './cacheService.js';
33
33
  import { MemoryCacheStore, scopedCache } from '../adapters/cache/cacheStore.js';
34
- import { listenOf, poolOf, replicaEngine, replicasOf } from './poolConfig.js';
34
+ import { backstopOf, listenOf, poolOf, replicaEngine, replicasOf } from './poolConfig.js';
35
35
  import { slug } from '../shared/slug.js';
36
36
  import { sqliteTargetFrom } from './configPaths.js';
37
37
  import { product } from './product.js';
@@ -826,7 +826,8 @@ export async function loadConfig(explicit, sections) {
826
826
  const pool = poolOf(c, http !== undefined, path);
827
827
  const replicas = replicasOf(c, http !== undefined, path);
828
828
  const listen = listenOf(c, http !== undefined, path);
829
- const { pool: _written, replicas: _listed, listen: _direct, ...entry } = c;
829
+ const backstop = backstopOf(c, http !== undefined, path);
830
+ const { pool: _written, replicas: _listed, listen: _direct, backstop: _wall, owner: _owner, ...entry } = c;
830
831
  const located = http ? c.url : sqliteTargetFrom(c.url, dirname(resolve(path)));
831
832
  return [
832
833
  {
@@ -836,6 +837,7 @@ export async function loadConfig(explicit, sections) {
836
837
  ...(pool ? { pool } : {}),
837
838
  ...(replicas ? { replicas } : {}),
838
839
  ...(listen ? { listen } : {}),
840
+ ...(backstop ?? {}),
839
841
  },
840
842
  ];
841
843
  });
@@ -30,5 +30,17 @@ export declare function replicasOf(entry: Record<string, unknown>, http: boolean
30
30
  * anything but PostgreSQL rather than ignored: a wake that is not happening is a 30-second wait nobody chose.
31
31
  */
32
32
  export declare function listenOf(entry: Record<string, unknown>, http: boolean, path: string): string | undefined;
33
+ /**
34
+ * A connection's `"backstop": "rls"` and its `"owner"`: the database's row-level security as a second wall behind
35
+ * the tenant scope (docs/postgresql.md). `url` and `replicas` then name the runtime role, which owns nothing and
36
+ * reads under the pinned policy; `owner` names the role that owns the tables and serves what crosses tenants by
37
+ * design. Both or neither: a backstop with no owner has nobody to resolve a public address or run the jobs that
38
+ * read every tenant, and an owner with no backstop is a second pool doing what `url` does. Refused for HTTP and
39
+ * SQLite, which have no roles to separate.
40
+ */
41
+ export declare function backstopOf(entry: Record<string, unknown>, http: boolean, path: string): {
42
+ owner: string;
43
+ backstop: 'rls';
44
+ } | undefined;
33
45
  /** Which engine a URL names, for a replica's agreement with its primary; undefined for anything else. */
34
46
  export declare function replicaEngine(url: string): 'PostgreSQL' | undefined;
@@ -106,6 +106,40 @@ export function listenOf(entry, http, path) {
106
106
  throw new Error(`${where} is not a PostgreSQL connection, so it has nothing to listen on. Remove "listen".`);
107
107
  return listen;
108
108
  }
109
+ /**
110
+ * A connection's `"backstop": "rls"` and its `"owner"`: the database's row-level security as a second wall behind
111
+ * the tenant scope (docs/postgresql.md). `url` and `replicas` then name the runtime role, which owns nothing and
112
+ * reads under the pinned policy; `owner` names the role that owns the tables and serves what crosses tenants by
113
+ * design. Both or neither: a backstop with no owner has nobody to resolve a public address or run the jobs that
114
+ * read every tenant, and an owner with no backstop is a second pool doing what `url` does. Refused for HTTP and
115
+ * SQLite, which have no roles to separate.
116
+ */
117
+ export function backstopOf(entry, http, path) {
118
+ const { owner, backstop } = entry;
119
+ if (owner === undefined && backstop === undefined)
120
+ return undefined;
121
+ const where = `${path}: connection "${String(entry.name)}"`;
122
+ if (http)
123
+ throw new Error(`${where} is an HTTP connection; "backstop" and "owner" separate database roles. Remove them.`);
124
+ if (backstop === undefined) {
125
+ throw new Error(`${where} has "owner" without "backstop". The owner's URL is only used under "backstop": "rls"; add it, or remove "owner".`);
126
+ }
127
+ if (backstop !== 'rls')
128
+ throw new Error(`${where} has "backstop": ${JSON.stringify(backstop)}. The one backstop is "rls".`);
129
+ if (owner === undefined) {
130
+ throw new Error(`${where} has "backstop": "rls" without "owner". Add "owner": the URL of the role that owns the tables, such as "\${OWNER_URL}".`);
131
+ }
132
+ if (typeof owner !== 'string' || !owner.trim()) {
133
+ throw new Error(`${where} has "owner": ${JSON.stringify(owner)}. It must be a PostgreSQL URL, such as "postgres://owner@db:5432/app".`);
134
+ }
135
+ const written = owner.trim();
136
+ if (!written.includes('$') && replicaEngine(written) !== 'PostgreSQL')
137
+ throw new Error(`${where} has an "owner" that is not a PostgreSQL URL; the backstop is PostgreSQL's row-level security.`);
138
+ const url = String(entry.url);
139
+ if (!url.includes('$') && replicaEngine(url) !== 'PostgreSQL')
140
+ throw new Error(`${where} is not a PostgreSQL connection; SQLite has no roles or row-level security. Remove "backstop" and "owner".`);
141
+ return { owner: written, backstop: 'rls' };
142
+ }
109
143
  /** Which engine a URL names, for a replica's agreement with its primary; undefined for anything else. */
110
144
  export function replicaEngine(url) {
111
145
  if (/^postgres(ql)?:\/\//i.test(url))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mistriwork/engine",
3
- "version": "1.0.0-rc.52",
3
+ "version": "1.0.0-rc.53",
4
4
  "description": "The engine both products stand on: the adapters (SQLite, Postgres), the catalog, the query language, keyset pages, the HTTP kit and the shared rules. No React.",
5
5
  "homepage": "https://mistriwork.dev",
6
6
  "bugs": {