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

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.
@@ -25,6 +25,19 @@ export declare function postgresDescriptionCounts(): Readonly<{
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
27
  export declare function sharedPostgresAdapter(url: string, label: string, shape?: SharedPoolShape): PostgresAdapter;
28
+ /** What an adapter is built with beyond its connection. */
29
+ export interface PostgresAdapterOptions {
30
+ /**
31
+ * The database's own tenant backstop (row security): the role this adapter's connections run as, which every
32
+ * tenant table's one row policy names. With it, a scoped transaction and a read snapshot given a tenant set
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.
35
+ */
36
+ readonly rowSecurity?: {
37
+ readonly role: string;
38
+ readonly force?: boolean;
39
+ };
40
+ }
28
41
  export declare class PostgresAdapter implements Adapter {
29
42
  private label;
30
43
  /** Restrict to these schemas. Empty means every non-system schema. */
@@ -38,13 +51,14 @@ export declare class PostgresAdapter implements Adapter {
38
51
  /** The epoch each open write transaction read, by the handle it runs on. */
39
52
  private readonly txEpochs;
40
53
  private epochStore;
54
+ private readonly rowSecurity;
41
55
  /** `work`, forgetting the kept catalog if it dies on a table or column that is gone: what was kept is wrong. */
42
56
  private watched;
43
57
  constructor(connectionString: string, label?: string,
44
58
  /** Restrict to these schemas. Empty means every non-system schema. */
45
59
  schemas?: string[], connections?: PgConnectionManager,
46
60
  /** The reader count the connection's config names; the process defaults fill the rest. */
47
- pool?: PgConnectionOptions);
61
+ pool?: PgConnectionOptions, options?: PostgresAdapterOptions);
48
62
  private verifiedSource;
49
63
  /** The pools' meters, for the operator surface. */
50
64
  poolStats(): readonly PoolRoleStats[];
@@ -312,7 +326,11 @@ export declare class PostgresAdapter implements Adapter {
312
326
  * rollback that was not acknowledged, is unknown, and the client is
313
327
  * discarded rather than reused. Everything else did not commit.
314
328
  */
315
- scopeTransaction<T>(input: RowScope, run: (tx: WriteTransaction, catalog: DatabaseSchema) => Promise<T>, triggers?: TriggerAcceptance): Promise<T>;
329
+ 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. */
331
+ options?: {
332
+ readonly tenant?: string;
333
+ }): Promise<T>;
316
334
  /**
317
335
  * Private source-owner boundary, deliberately absent from Adapter: the
318
336
  * PostgreSQL counterpart of `SqliteAdapter.scopeVerifiedTransaction`. The
@@ -327,7 +345,11 @@ export declare class PostgresAdapter implements Adapter {
327
345
  * because its fence is a snapshot check; here the fence is row locks held
328
346
  * to the end of the transaction, so the two checks bound its lifetime.
329
347
  */
330
- scopeVerifiedTransaction<T>(input: RowScope, verify: PostgresTransactionVerifier, run: (tx: WriteTransaction, catalog: DatabaseSchema) => Promise<T>): Promise<T>;
348
+ scopeVerifiedTransaction<T>(input: RowScope, verify: PostgresTransactionVerifier, run: (tx: WriteTransaction, catalog: DatabaseSchema) => Promise<T>,
349
+ /** As scopeTransaction's. */
350
+ options?: {
351
+ readonly tenant?: string;
352
+ }): Promise<T>;
331
353
  /**
332
354
  * Private source-owner boundary, deliberately absent from Adapter: one
333
355
  * `REPEATABLE READ, READ ONLY` transaction on a leased reader, for trusted
@@ -340,7 +362,10 @@ export declare class PostgresAdapter implements Adapter {
340
362
  * fails surfaces as TransactionOutcomeUnknown; any failure discards the
341
363
  * client rather than returning it to the pool.
342
364
  */
343
- readSnapshot<T>(run: (snapshot: PostgresReadSnapshot) => Promise<T>, observeCheckout?: boolean, prologue?: string, ahead?: boolean, whole?: boolean): Promise<T>;
365
+ 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>;
368
+ private tenantSet;
344
369
  /** Private source-shape owner, not an authorization proof or generic Adapter
345
370
  * capability. Only this actual adapter's native snapshot runner is used. */
346
371
  capturePinnedReadSnapshot(dependencies: readonly PostgresReadDependency[], assertCurrent: () => void): Promise<PinnedPostgresReadOwner>;
@@ -29,7 +29,7 @@ import { compileBreakdown, compileBreakdownCount } from '../shared/breakdown.js'
29
29
  import { PgConnectionManager, sharedPgConnections } from './postgresPool.js';
30
30
  import { aheadReport, beforeCommit, behindWrite, generationOf, heldAhead, redoWithoutAhead, sendsAhead, waitsAhead, RolledBackAtCommit, transactionHandle, attestedOn, keepAttestedOn, forgetAttestations, noteCatalogVersion, readsCatalogVersion, suspectsStores, } from './postgresTransactionHandle.js';
31
31
  import { snapshotRead, withoutSnapshotRead } from './snapshotRead.js';
32
- import { SCOPED_SESSION, beginOf, snapshotHandles, verifierPin } from './postgresTransactionOpening.js';
32
+ import { SCOPED_SESSION, beginOf, snapshotHandles, tenantSession, verifierPin, } from './postgresTransactionOpening.js';
33
33
  import { withoutWriteAhead, writeAhead } from './writeAhead.js';
34
34
  import { KeyRows } from './scoped/keyRows.js';
35
35
  import { PLAIN_SCOPE, catalogId, heldLocks, heldRows, lockKey, plainStatement, plainTable, reportWriteAhead, rowLockKey, rowLockStatement, scopedStatement, sendPlainAhead, sendWriteAhead, } from './postgresWriteAhead.js';
@@ -120,6 +120,8 @@ export class PostgresAdapter {
120
120
  /* Whether the database holds the epoch store: learned from the first
121
121
  write transaction; absent, every transaction reads the digest as before. */
122
122
  epochStore;
123
+ /* The tenant backstop this adapter runs under (PostgresAdapterOptions.rowSecurity), copied at construction. */
124
+ rowSecurity;
123
125
  /** `work`, forgetting the kept catalog if it dies on a table or column that is gone: what was kept is wrong. */
124
126
  watched(work) {
125
127
  return work.catch((error) => {
@@ -134,9 +136,14 @@ export class PostgresAdapter {
134
136
  /** Restrict to these schemas. Empty means every non-system schema. */
135
137
  schemas = [], connections,
136
138
  /** The reader count the connection's config names; the process defaults fill the rest. */
137
- pool) {
139
+ pool, options = {}) {
138
140
  this.label = label;
139
141
  this.schemas = schemas;
142
+ const security = options.rowSecurity;
143
+ if (security !== undefined &&
144
+ (typeof security.role !== 'string' || !security.role || (security.force !== undefined && typeof security.force !== 'boolean')))
145
+ throw new TypeError('A row-security role is a role name.');
146
+ this.rowSecurity = security && Object.freeze({ role: security.role, force: security.force === true });
140
147
  this.connections = connections ?? new PgConnectionManager(connectionString, keepDatesAsText, undefined, pool);
141
148
  this.describes = `${connectionString}\0${schemas.join('\0')}`;
142
149
  this.database = connectionString;
@@ -266,13 +273,13 @@ export class PostgresAdapter {
266
273
  .withWriteClient(async (write) => {
267
274
  await write.query('BEGIN');
268
275
  try {
269
- return await effectCatalogFacts(write, tables);
276
+ return await effectCatalogFacts(write, tables, this.rowSecurity);
270
277
  }
271
278
  finally {
272
279
  await write.query('ROLLBACK');
273
280
  }
274
281
  })
275
- .catch(() => primaryReads(async () => effectCatalogFacts(await this.conn(), tables)));
282
+ .catch(() => primaryReads(async () => effectCatalogFacts(await this.conn(), tables, this.rowSecurity)));
276
283
  }
277
284
  /** The catalog as one handle sees it, read by postgresCatalog.ts: the
278
285
  * reader on connect, or the leased writer inside a scoped transaction,
@@ -485,6 +492,10 @@ export class PostgresAdapter {
485
492
  return this.queryOn(request, await this.conn(), true);
486
493
  }
487
494
  async scopeReads(input) {
495
+ /* Each read here is its own autocommit statement, with no transaction for a tenant to be set in: under the
496
+ backstop it would see nothing, and an empty answer would read as an empty tenant. Loud instead. */
497
+ if (this.rowSecurity)
498
+ throw new Refusal('Autocommit scoped reads are unavailable under row security; read in a snapshot.');
488
499
  // Capture before metadata I/O: callers cannot change an in-flight policy.
489
500
  const scope = captureRowScope(input);
490
501
  const schema = await this.schema();
@@ -1120,7 +1131,7 @@ export class PostgresAdapter {
1120
1131
  const verify = options.ordinaryVerify;
1121
1132
  return this.ordinaryJournalTransaction(journal, run, verify && (async () => void (await verify())));
1122
1133
  }
1123
- return this.scopedTransact(options.scope, journal, run, options.verify, options.bound, options.triggers);
1134
+ return this.scopedTransact(options.scope, journal, run, options.verify, options.bound, options.triggers, options.tenant);
1124
1135
  }
1125
1136
  async ordinaryJournalTransaction(journal, run, verify) {
1126
1137
  /* The command host supplies target and receipt lanes through inWriteLanes.
@@ -1229,9 +1240,11 @@ export class PostgresAdapter {
1229
1240
  * rollback that was not acknowledged, is unknown, and the client is
1230
1241
  * discarded rather than reused. Everything else did not commit.
1231
1242
  */
1232
- async scopeTransaction(input, run, triggers) {
1243
+ async scopeTransaction(input, run, triggers,
1244
+ /** `tenant`: what the row policy reads, under the backstop (PostgresAdapterOptions.rowSecurity); ignored without it. */
1245
+ options = {}) {
1233
1246
  const scope = captureRowScope(input);
1234
- return this.scopedTransact(scope, undefined, (tx, _journal, catalog) => run(tx, catalog), undefined, undefined, triggers);
1247
+ return this.scopedTransact(scope, undefined, (tx, _journal, catalog) => run(tx, catalog), undefined, undefined, triggers, options.tenant);
1235
1248
  }
1236
1249
  /**
1237
1250
  * Private source-owner boundary, deliberately absent from Adapter: the
@@ -1247,11 +1260,13 @@ export class PostgresAdapter {
1247
1260
  * because its fence is a snapshot check; here the fence is row locks held
1248
1261
  * to the end of the transaction, so the two checks bound its lifetime.
1249
1262
  */
1250
- async scopeVerifiedTransaction(input, verify, run) {
1263
+ async scopeVerifiedTransaction(input, verify, run,
1264
+ /** As scopeTransaction's. */
1265
+ options = {}) {
1251
1266
  const scope = captureRowScope(input);
1252
1267
  if (typeof verify !== 'function' || typeof run !== 'function' || Object.keys(scope).some(isRuntimeRelation))
1253
1268
  throw new Refusal('This verified transaction is unavailable.');
1254
- return this.scopedTransact(scope, undefined, (tx, _journal, catalog) => run(tx, catalog), verify);
1269
+ return this.scopedTransact(scope, undefined, (tx, _journal, catalog) => run(tx, catalog), verify, undefined, undefined, options.tenant);
1255
1270
  }
1256
1271
  /**
1257
1272
  * Private source-owner boundary, deliberately absent from Adapter: one
@@ -1268,8 +1283,15 @@ export class PostgresAdapter {
1268
1283
  async readSnapshot(run, observeCheckout = false, prologue, ahead = false,
1269
1284
  /* The prologue is the snapshot's whole question (a membership fence): BEGIN, the prologue and COMMIT in one
1270
1285
  round trip where they were two. `run` is handed its answers and nothing it can ask. */
1271
- whole = false) {
1272
- return readSnapshotOn(this.connections, (db, checkout) => (checkout ? PostgresAdapter.prototype.describe.call(this, db) : this.describeSnapshot(db)), run, observeCheckout, prologue, ahead, whole);
1286
+ whole = false,
1287
+ /** What the row policy reads, under the backstop (PostgresAdapterOptions.rowSecurity); ignored without it. */
1288
+ 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));
1290
+ }
1291
+ /* 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) : '';
1273
1295
  }
1274
1296
  /** Private source-shape owner, not an authorization proof or generic Adapter
1275
1297
  * capability. Only this actual adapter's native snapshot runner is used. */
@@ -1299,7 +1321,9 @@ export class PostgresAdapter {
1299
1321
  /* Scoped records and, for a command, the durable journal and fresh catalog
1300
1322
  evidence in one transaction. The journal is attested before the catalog
1301
1323
  is read, so an unmigrated layout refuses before any lock is taken. */
1302
- async scopedTransact(scope, journal, run, verify, bound, triggers) {
1324
+ async scopedTransact(scope, journal, run, verify, bound, triggers, tenant) {
1325
+ // Said before the transaction is queued: a tenant that cannot be set refuses with nothing begun.
1326
+ const session = SCOPED_SESSION + this.tenantSet(tenant);
1303
1327
  /* The proof is loaded where a transaction accepts triggers, not at startup; and awaited in the transaction's turn,
1304
1328
  not before it is queued: a write asked after this one would otherwise take its turn while the module loads. */
1305
1329
  const loading = triggers && !journal?.fixedRecords ? import('./scoped/triggerProof.js') : undefined;
@@ -1338,7 +1362,7 @@ export class PostgresAdapter {
1338
1362
  // The rows whose locks were sent ahead, held from the moment their answers came back (sendWriteAhead), with what each lock said.
1339
1363
  const lockedAhead = new Map();
1340
1364
  let aheads = [];
1341
- const opening = { lock: pinned, pin, digest: true, session: SCOPED_SESSION };
1365
+ const opening = { lock: pinned, pin, digest: true, session };
1342
1366
  let opened = await this.openWrite(write, {
1343
1367
  ...opening,
1344
1368
  sent: () => void (aheads = sendWriteAhead(this, write, scope, peeked, keyRows, journal, verify, hint, lockedAhead)),
@@ -1359,7 +1383,7 @@ export class PostgresAdapter {
1359
1383
  if (journal)
1360
1384
  await this.attestJournal(write, journal);
1361
1385
  const catalog = this.catalogCache.get(opened.epoch, scopeKey) ??
1362
- this.catalogCache.set(opened.epoch, scopeKey, await readPostgresScopeCatalog(write, scope, (db) => this.describeScoped(db)));
1386
+ this.catalogCache.set(opened.epoch, scopeKey, await readPostgresScopeCatalog(write, scope, (db) => this.describeScoped(db), this.rowSecurity));
1363
1387
  // Rows read under another epoch's catalog answer nothing: the statements sent ahead were built from it.
1364
1388
  if (catalog !== peeked) {
1365
1389
  keyRows.forget();
@@ -27,7 +27,14 @@ export declare function ensurePostgresRuntimeSchema(client: PgQuery): Promise<bo
27
27
  * the ones named under `prefix`: owned by this role, with no privilege held on
28
28
  * them or their columns by any other. A grant on `public`, a reporting role's
29
29
  * `SELECT ON ALL TABLES IN SCHEMA public`, reaches none of this.
30
+ *
31
+ * `runtime`, under the tenant row-security backstop: the role the App runs
32
+ * as, which is not this one and needs the store too. It alone may hold USAGE
33
+ * on the schema and SELECT, INSERT, UPDATE, DELETE or a sequence's USAGE on
34
+ * the store's relations and columns, never with GRANT OPTION — never CREATE,
35
+ * never ownership, and PUBLIC and every other role are refused as before.
30
36
  */
31
37
  export declare function postgresRuntimeSchemaProblems(client: PgQuery, prefix: string, options?: {
32
38
  delegated?: boolean;
39
+ runtime?: string;
33
40
  }): Promise<string[]>;
@@ -97,6 +97,8 @@ export async function ensurePostgresRuntimeSchema(client) {
97
97
  of an owning group and run as another. A superuser is an implicit member
98
98
  of every role, which would make every owner pass, so for a superuser
99
99
  only itself counts. PUBLIC (grantee 0) is never ours. */
100
+ /* What the runtime role may hold on a store's relation or column: reading and writing its rows, and a sequence's nextval. */
101
+ const DML = `'SELECT', 'INSERT', 'UPDATE', 'DELETE', 'USAGE'`;
100
102
  const ours = (role) => `COALESCE(${role} = me.oid OR (NOT me.rolsuper AND ${role} <> 0 AND pg_catalog.pg_has_role(me.oid, ${role}, 'USAGE')), false)`;
101
103
  /**
102
104
  * What makes a store's part of the runtime schema not this role's alone, as
@@ -110,9 +112,20 @@ const ours = (role) => `COALESCE(${role} = me.oid OR (NOT me.rolsuper AND ${role
110
112
  * the ones named under `prefix`: owned by this role, with no privilege held on
111
113
  * them or their columns by any other. A grant on `public`, a reporting role's
112
114
  * `SELECT ON ALL TABLES IN SCHEMA public`, reaches none of this.
115
+ *
116
+ * `runtime`, under the tenant row-security backstop: the role the App runs
117
+ * as, which is not this one and needs the store too. It alone may hold USAGE
118
+ * on the schema and SELECT, INSERT, UPDATE, DELETE or a sequence's USAGE on
119
+ * the store's relations and columns, never with GRANT OPTION — never CREATE,
120
+ * never ownership, and PUBLIC and every other role are refused as before.
113
121
  */
114
122
  export async function postgresRuntimeSchemaProblems(client, prefix, options = {}) {
123
+ if (options.runtime !== undefined && (typeof options.runtime !== 'string' || !options.runtime))
124
+ throw new TypeError('A runtime role is a role name.');
125
+ /* `rt.oid` is null without a runtime role, so nothing, PUBLIC included, is the runtime's and every grant counts as before. */
126
+ const runtime = (grantee, privilege, kinds) => `COALESCE(${grantee} = rt.oid AND ${privilege} IN (${kinds}), false)`;
115
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),
116
129
  ns AS (SELECT n.oid, n.nspowner, n.nspacl FROM pg_catalog.pg_namespace n WHERE n.nspname = $1),
117
130
  acl AS (SELECT a.grantee, a.privilege_type FROM ns, pg_catalog.aclexplode(COALESCE(ns.nspacl, pg_catalog.acldefault('n', ns.nspowner))) a),
118
131
  control AS (SELECT DISTINCT c.relowner AS role FROM ns, pg_catalog.pg_class c
@@ -124,12 +137,15 @@ export async function postgresRuntimeSchemaProblems(client, prefix, options = {}
124
137
  COALESCE((SELECT pg_catalog.has_schema_privilege(ns.oid, 'CREATE') AND pg_catalog.has_schema_privilege(ns.oid, 'USAGE') FROM ns), false) AS granted,
125
138
  EXISTS (SELECT 1 FROM acl, ns, me WHERE acl.privilege_type = 'CREATE' AND acl.grantee <> ns.nspowner AND NOT ${ours('acl.grantee')}
126
139
  AND acl.grantee NOT IN (SELECT role FROM control)) AS "foreignCreate",
127
- EXISTS (SELECT 1 FROM acl, ns, me WHERE acl.grantee <> ns.nspowner AND NOT ${ours('acl.grantee')}
128
- AND acl.grantee NOT IN (SELECT role FROM control)) AS "foreignUsage",
140
+ EXISTS (SELECT 1 FROM acl, ns, me, rt WHERE acl.grantee <> ns.nspowner AND NOT ${ours('acl.grantee')}
141
+ AND acl.grantee NOT IN (SELECT role FROM control)
142
+ AND NOT ${runtime('acl.grantee', 'acl.privilege_type', "'USAGE'")}) AS "foreignUsage",
129
143
  EXISTS (SELECT 1 FROM rel, me WHERE NOT ${ours('rel.relowner')}) AS "foreignOwner",
130
- EXISTS (SELECT 1 FROM rel, me, pg_catalog.aclexplode(rel.relacl) a WHERE NOT ${ours('a.grantee')})
131
- OR EXISTS (SELECT 1 FROM rel, me, pg_catalog.pg_attribute t, pg_catalog.aclexplode(t.attacl) a
132
- WHERE t.attrelid = rel.oid AND NOT ${ours('a.grantee')}) AS "foreignGrant",
144
+ EXISTS (SELECT 1 FROM rel, me, rt, pg_catalog.aclexplode(rel.relacl) a WHERE NOT ${ours('a.grantee')}
145
+ AND NOT (${runtime('a.grantee', 'a.privilege_type', DML)} AND NOT a.is_grantable))
146
+ OR EXISTS (SELECT 1 FROM rel, me, rt, pg_catalog.pg_attribute t, pg_catalog.aclexplode(t.attacl) a
147
+ WHERE t.attrelid = rel.oid AND NOT ${ours('a.grantee')}
148
+ AND NOT (${runtime('a.grantee', 'a.privilege_type', DML)} AND NOT a.is_grantable)) AS "foreignGrant",
133
149
  COALESCE((SELECT (SELECT count(*) FROM pg_catalog.pg_proc WHERE pronamespace = ns.oid AND proname <> ALL ($5::text[]))
134
150
  + (SELECT count(*) FROM pg_catalog.pg_operator WHERE oprnamespace = ns.oid)
135
151
  + (SELECT count(*) FROM pg_catalog.pg_type t WHERE t.typnamespace = ns.oid AND t.typrelid = 0
@@ -153,6 +169,7 @@ export async function postgresRuntimeSchemaProblems(client, prefix, options = {}
153
169
  prefix.length,
154
170
  RUNTIME_CONTROL_PREFIXES.map((each) => `${each.replaceAll('_', '\\_')}%`),
155
171
  RUNTIME_SCHEMA_FUNCTIONS,
172
+ options.runtime ?? null,
156
173
  ])).rows[0];
157
174
  if (!row)
158
175
  return ['its catalog could not be read'];
@@ -43,4 +43,4 @@ export interface PostgresReadSnapshot {
43
43
  * Run `run` in a snapshot on `connections`' reader. `describe` is the adapter's own introspection on the leased
44
44
  * client; `onCheckout` says it is a pinned owner's, whose introspection is the class's and not an instance's.
45
45
  */
46
- export declare function readSnapshotOn<T>(connections: PgConnectionManager, describe: (db: PgQuery, checkout: boolean) => Promise<DatabaseSchema>, run: (snapshot: PostgresReadSnapshot) => Promise<T>, observeCheckout: boolean, prologue: string | undefined, ahead: boolean, whole: boolean): Promise<T>;
46
+ export declare function readSnapshotOn<T>(connections: PgConnectionManager, describe: (db: PgQuery, checkout: boolean) => Promise<DatabaseSchema>, run: (snapshot: PostgresReadSnapshot) => Promise<T>, observeCheckout: boolean, prologue: string | undefined, ahead: boolean, whole: boolean, session?: string): Promise<T>;
@@ -12,11 +12,12 @@ const BEGIN_SNAPSHOT = 'BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY';
12
12
  * Run `run` in a snapshot on `connections`' reader. `describe` is the adapter's own introspection on the leased
13
13
  * client; `onCheckout` says it is a pinned owner's, whose introspection is the class's and not an instance's.
14
14
  */
15
- export async function readSnapshotOn(connections, describe, run, observeCheckout, prologue, ahead, whole) {
15
+ export async function readSnapshotOn(connections, describe, run, observeCheckout, prologue, ahead, whole, session = '') {
16
16
  if (typeof run !== 'function' ||
17
17
  (prologue !== undefined && (typeof prologue !== 'string' || !prologue.trim())) ||
18
18
  (ahead && (observeCheckout || prologue === undefined)) ||
19
- (whole && (observeCheckout || ahead || prologue === undefined))) {
19
+ (whole && (observeCheckout || ahead || prologue === undefined)) ||
20
+ typeof session !== 'string') {
20
21
  throw new Refusal('This read snapshot is unavailable.');
21
22
  }
22
23
  /* The answer is final once `run` returns: a read-only transaction's
@@ -27,6 +28,9 @@ export async function readSnapshotOn(connections, describe, run, observeCheckout
27
28
  observed checkout: its owner hands its response off inside the
28
29
  snapshot (postgresReadCatalog.ts), so a COMMIT it never heard
29
30
  acknowledged is an uncertain outcome it must be told of. */
31
+ /* The tenant a row policy reads (postgresTransactionOpening.ts tenantSession), set in every BEGIN this snapshot
32
+ sends: its one answer is the engine's to drop, so an owner counts its own results as it did without one. */
33
+ const set = session ? 1 : 0;
30
34
  let deliver;
31
35
  const answered = new Promise((resolve) => {
32
36
  deliver = resolve;
@@ -50,9 +54,9 @@ export async function readSnapshotOn(connections, describe, run, observeCheckout
50
54
  BEGIN and each of them were one each. The owner waits on the BEGIN's
51
55
  answer before it trusts anything; a BEGIN that failed fails what was
52
56
  sent behind it, and the owner hears the BEGIN's failure first. */
53
- const begun = client.query(prologue === undefined ? BEGIN_SNAPSHOT : `${BEGIN_SNAPSHOT}; ${prologue}${whole ? '; COMMIT' : ''}`).then((opened) => Object.freeze(prologue === undefined
57
+ const begun = client.query(prologue === undefined ? `${BEGIN_SNAPSHOT}${session}` : `${BEGIN_SNAPSHOT}${session}; ${prologue}${whole ? '; COMMIT' : ''}`).then((opened) => Object.freeze(prologue === undefined
54
58
  ? []
55
- : (Array.isArray(opened) ? opened : [opened]).slice(1, whole ? -1 : undefined)));
59
+ : (Array.isArray(opened) ? opened : [opened]).slice(1 + set, whole ? -1 : undefined)));
56
60
  let results;
57
61
  if (ahead)
58
62
  void begun.catch(() => { });
@@ -74,8 +78,8 @@ export async function readSnapshotOn(connections, describe, run, observeCheckout
74
78
  ended = true;
75
79
  if (ahead)
76
80
  await begun;
77
- const closed = (await client.query(`COMMIT; ${BEGIN_SNAPSHOT}; ${next}; COMMIT`));
78
- return Object.freeze((Array.isArray(closed) ? closed : [closed]).slice(2, -1));
81
+ const closed = (await client.query(`COMMIT; ${BEGIN_SNAPSHOT}${session}; ${next}; COMMIT`));
82
+ return Object.freeze((Array.isArray(closed) ? closed : [closed]).slice(2 + set, -1));
79
83
  };
80
84
  try {
81
85
  out = await run(Object.freeze({
@@ -1,8 +1,3 @@
1
- /**
2
- * How a Postgres scoped transaction opens: the verifier a trusted host hands it, the pin that rides in its BEGIN, the
3
- * isolation a snapshot read begins with, and the session text its BEGIN sets. Pure parts of the adapter's opening, kept
4
- * apart from the connection and the writes that use them (postgres.ts).
5
- */
6
1
  import type { DatabaseSchema } from '../shared/schema.js';
7
2
  import type { PgQuery } from './postgresPool.js';
8
3
  import type { PostgresScopeCatalog } from './scoped/postgresScopeCatalog.js';
@@ -37,3 +32,4 @@ export declare function verifierPin(verify: PostgresTransactionVerifier | undefi
37
32
  export declare const snapshotHandles: WeakSet<PgQuery>;
38
33
  export declare const beginOf: (write: PgQuery) => "BEGIN" | "BEGIN ISOLATION LEVEL REPEATABLE READ";
39
34
  export declare const SCOPED_SESSION = "; SET LOCAL DateStyle = ISO; SET LOCAL IntervalStyle = postgres; SET LOCAL extra_float_digits = 3";
35
+ export declare function tenantSession(id: string): string;
@@ -1,3 +1,9 @@
1
+ /**
2
+ * How a Postgres scoped transaction opens: the verifier a trusted host hands it, the pin that rides in its BEGIN, the
3
+ * isolation a snapshot read begins with, and the session text its BEGIN sets. Pure parts of the adapter's opening, kept
4
+ * apart from the connection and the writes that use them (postgres.ts).
5
+ */
6
+ import { Refusal } from './adapter.js';
1
7
  /** A verifier's pin, when it is only LOCK statements with no parameters (it rides in the simple-protocol message).
2
8
  Anything else is not taken: the transaction then runs as it would without one, and its verifier attests in full. */
3
9
  export function verifierPin(verify) {
@@ -14,3 +20,13 @@ export const beginOf = (write) => (snapshotHandles.has(write) ? 'BEGIN ISOLATION
14
20
  field order, which decides how a person's own 01/02/2026 is read, stays the database's. The float and interval
15
21
  text, which no key is (keyTypes.ts), is pinned as well, so a value a trigger's proof compares reads as stored. */
16
22
  export const SCOPED_SESSION = '; SET LOCAL DateStyle = ISO; SET LOCAL IntervalStyle = postgres; SET LOCAL extra_float_digits = 3';
23
+ /* The tenant a row policy reads (`current_setting('mistri.tenant', true)`), said in the BEGIN's own message as the
24
+ session above is: SET LOCAL ends with the transaction, so a pooled connection never carries one tenant's setting
25
+ into another's. SET takes no parameter, so the value is a literal; it is a tenant id (tenantMembership.ts
26
+ parseTenantSelector) and a quote is doubled all the same. NUL cannot be sent at all, and a backslash would be an
27
+ escape under `standard_conforming_strings = off`, so either refuses rather than being said some other way. */
28
+ export function tenantSession(id) {
29
+ if (typeof id !== 'string' || !id || id.includes('\0') || id.includes('\\'))
30
+ throw new Refusal('This tenant cannot be set on the transaction.');
31
+ return `; SET LOCAL mistri.tenant = '${id.replaceAll("'", "''")}'`;
32
+ }
@@ -13,7 +13,25 @@ export interface PostgresScopeCatalog extends ScopeCatalog {
13
13
  /** Each table in `triggered`, what its triggers' proof was read from (postgresTriggers.ts triggerVersion): read
14
14
  * again before COMMIT by a transaction that relied on it (attestPostgresTriggers). */
15
15
  triggerVersions?: ReadonlyMap<string, string>;
16
+ /** Under row security (PostgresAdapterOptions.rowSecurity): each table carrying mistri's tenant policy, and the
17
+ * column that policy compares. Which column a table's policy must be on, and which tables must carry one, is the
18
+ * App's ownership to say (mistri's tenantPostgresCatalog.ts); the engine says only that the shape is exactly this. */
19
+ tenantPolicies?: ReadonlyMap<string, string>;
16
20
  }
21
+ /** Row security as the adapter runs under it: the role a policy names, and whether FORCE ROW LEVEL SECURITY may be on. */
22
+ type RowSecurityShape = Readonly<{
23
+ role: string;
24
+ force: boolean;
25
+ }>;
26
+ /** The only policy a scoped write accepts under row security, by name. */
27
+ export declare const TENANT_POLICY = "mistri_tenant";
28
+ /**
29
+ * What follows the column in the policy's expression as `pg_get_expr` deparses it (PostgreSQL 16.15): a text column
30
+ * reads `(tenant = NULLIF(current_setting('mistri.tenant'::text, true), ''::text))`, a varchar one
31
+ * `((tenant)::text = NULLIF(…))`. Compared as text so that any other expression — `USING (true)`, another setting, an
32
+ * OR — is not mistri's policy, whatever it would filter.
33
+ */
34
+ export declare const TENANT_POLICY_TAIL = " = NULLIF(current_setting('mistri.tenant'::text, true), ''::text))";
17
35
  /**
18
36
  * Before COMMIT, in a transaction that let a write fire a trigger the catalog proved validation-only: the proof's
19
37
  * sources read again. A table's triggers cannot change under its pin, but the function a trigger runs, and the
@@ -48,8 +66,9 @@ export declare function joinedHierarchy(error: unknown): ScopeRefusal | undefine
48
66
  * (readPostgresScopeCatalog), read on `client` outside a write: the keys, the tables in a partition or inheritance
49
67
  * hierarchy, and the tables a scoped write cannot target for row security, a rule, or the role's privileges.
50
68
  */
51
- export declare function effectCatalogFacts(client: PgQuery, given: readonly string[]): Promise<TriggerKeyFacts>;
69
+ export declare function effectCatalogFacts(client: PgQuery, given: readonly string[], backstop?: RowSecurityShape): Promise<TriggerKeyFacts>;
52
70
  /** Call only on the leased writer inside its transaction, before any read of
53
71
  * user data. The describe callback is the adapter's own introspection so the
54
72
  * evidence has the same shape as the catalog the permissions were bound to. */
55
- export declare function readPostgresScopeCatalog(client: PgQuery, scope: RowScope, describe: (client: PgQuery) => Promise<DatabaseSchema>): Promise<PostgresScopeCatalog>;
73
+ export declare function readPostgresScopeCatalog(client: PgQuery, scope: RowScope, describe: (client: PgQuery) => Promise<DatabaseSchema>, backstop?: RowSecurityShape): Promise<PostgresScopeCatalog>;
74
+ export {};
@@ -32,6 +32,15 @@ import { recordRefusalCause } from '../../shared/refusal.js';
32
32
  import { baseType, CATALOG_OPERATORS, defaultBtreeClass, postgresTreeTriggerNames, postgresTriggerAnalyzer, postgresTriggersByTable, postgresTriggerStatement, postgresTriggerVersions, readPostgresTableCode, } from './postgresTriggers.js';
33
33
  import { keyTypeRefusal, postgresKeyType } from './keyTypes.js';
34
34
  const { EQ, GT, LT, NE, PLUS } = CATALOG_OPERATORS;
35
+ /** The only policy a scoped write accepts under row security, by name. */
36
+ export const TENANT_POLICY = 'mistri_tenant';
37
+ /**
38
+ * What follows the column in the policy's expression as `pg_get_expr` deparses it (PostgreSQL 16.15): a text column
39
+ * reads `(tenant = NULLIF(current_setting('mistri.tenant'::text, true), ''::text))`, a varchar one
40
+ * `((tenant)::text = NULLIF(…))`. Compared as text so that any other expression — `USING (true)`, another setting, an
41
+ * OR — is not mistri's policy, whatever it would filter.
42
+ */
43
+ export const TENANT_POLICY_TAIL = " = NULLIF(current_setting('mistri.tenant'::text, true), ''::text))";
35
44
  const refuse = () => {
36
45
  throw new Refusal('PostgreSQL scoped transactions require a complete catalog and an ordinary table the writer may update.');
37
46
  };
@@ -47,10 +56,36 @@ const saidType = (type, typmod, base, basemod) => `pg_catalog.format_type(${type
47
56
  /** Everything that decides whether a write to a relation means what the
48
57
  * scope assumes: its kind, row security, and the presence of triggers,
49
58
  * rules and policies — and whether this role may update it at all. */
50
- async function facts(client, targets) {
59
+ async function facts(client, targets, backstop) {
51
60
  const result = new Map();
52
61
  if (!targets.length)
53
62
  return result;
63
+ /* Under row security only, so a deployment without it asks the statement it always did. The policy is matched in
64
+ full here — its name, command, permissiveness, its one role, and both expressions as deparsed against a column of
65
+ the table — and anything else is a policy that is not mistri's (tenantShape). */
66
+ const policy = backstop
67
+ ? {
68
+ columns: `,
69
+ c.relforcerowsecurity AS force,
70
+ (SELECT pg_catalog.count(*) FROM pg_catalog.pg_policy p WHERE p.polrelid ${EQ} c.oid)::pg_catalog.int4 AS policy_count,
71
+ tenant.name AS tenant_column`,
72
+ join: `
73
+ LEFT JOIN LATERAL (SELECT a.attname::pg_catalog.text AS name
74
+ FROM pg_catalog.pg_policy p
75
+ JOIN pg_catalog.pg_attribute a ON a.attrelid ${EQ} c.oid AND a.attnum ${GT} 0 AND NOT a.attisdropped
76
+ CROSS JOIN LATERAL (SELECT CASE a.atttypid
77
+ WHEN 25::pg_catalog.oid THEN '(' ${CONCAT} pg_catalog.quote_ident(a.attname::pg_catalog.text) ${CONCAT} $4::pg_catalog.text
78
+ WHEN 1043::pg_catalog.oid THEN '((' ${CONCAT} pg_catalog.quote_ident(a.attname::pg_catalog.text) ${CONCAT} ')::text' ${CONCAT} $4::pg_catalog.text
79
+ END AS said) AS expected
80
+ WHERE p.polrelid ${EQ} c.oid AND p.polname ${EQ} '${TENANT_POLICY}' AND p.polcmd ${EQ} '*' AND p.polpermissive
81
+ AND pg_catalog.cardinality(p.polroles) ${EQ} 1
82
+ AND p.polroles[1] ${EQ} (SELECT r.oid FROM pg_catalog.pg_roles r WHERE r.rolname::pg_catalog.text ${EQ} $3::pg_catalog.text)
83
+ AND pg_catalog.pg_get_expr(p.polqual, p.polrelid) ${EQ} expected.said
84
+ AND pg_catalog.pg_get_expr(p.polwithcheck, p.polrelid) ${EQ} expected.said
85
+ LIMIT 1) AS tenant ON true`,
86
+ values: [backstop.role, TENANT_POLICY_TAIL],
87
+ }
88
+ : { columns: '', join: '', values: [] };
54
89
  const rows = await client.query(
55
90
  /* Every function and operator named in pg_catalog (postgresTriggers.ts CAT): with `cardinality` found through the
56
91
  search_path, `public.cardinality(text[])` answered 0 for every table, which read as no triggers at all. */
@@ -62,7 +97,7 @@ async function facts(client, targets) {
62
97
  c.relkind ${EQ} 'p' OR EXISTS (SELECT 1 FROM pg_catalog.pg_inherits i WHERE i.inhrelid ${EQ} c.oid OR i.inhparent ${EQ} c.oid)
63
98
  AS hierarchy,
64
99
  c.relkind ${EQ} 'r' AND EXISTS (SELECT 1 FROM pg_catalog.pg_inherits i WHERE i.inhparent ${EQ} c.oid) AS inherited,
65
- unkeyed.name AS unkeyed_column, unkeyed.said AS unkeyed_type
100
+ unkeyed.name AS unkeyed_column, unkeyed.said AS unkeyed_type${policy.columns}
66
101
  FROM ${WANTED}
67
102
  -- A key column whose type is not on the list (keyTypes.ts), its domains unwrapped: no scoped write targets the table.
68
103
  LEFT JOIN LATERAL (SELECT a.attname::pg_catalog.text AS name, ${saidType('a.atttypid', 'a.atttypmod', 'b.type', 'b.typmod')} AS said
@@ -71,7 +106,7 @@ async function facts(client, targets) {
71
106
  WHERE i.indrelid ${EQ} c.oid AND i.indisprimary AND NOT ${postgresKeyType('b.type')}
72
107
  ORDER BY a.attnum LIMIT 1) AS unkeyed ON true
73
108
  -- Its partitions' and inheritance children's too: a write through it reaches their rows and fires theirs.
74
- CROSS JOIN LATERAL (SELECT ${postgresTreeTriggerNames('c.oid')} AS names) AS fired`, [targets.map((target) => target.schema), targets.map((target) => target.name)]);
109
+ CROSS JOIN LATERAL (SELECT ${postgresTreeTriggerNames('c.oid')} AS names) AS fired${policy.join}`, [targets.map((target) => target.schema), targets.map((target) => target.name), ...policy.values]);
75
110
  for (const row of rows.rows) {
76
111
  if (typeof row.schema !== 'string' ||
77
112
  typeof row.name !== 'string' ||
@@ -81,6 +116,10 @@ async function facts(client, targets) {
81
116
  row.trigger_names.some((name) => typeof name !== 'string') ||
82
117
  (row.unkeyed_column !== null && typeof row.unkeyed_column !== 'string') ||
83
118
  (row.unkeyed_type !== null && typeof row.unkeyed_type !== 'string') ||
119
+ (backstop &&
120
+ (typeof row.force !== 'boolean' ||
121
+ !Number.isInteger(row.policy_count) ||
122
+ (row.tenant_column !== null && typeof row.tenant_column !== 'string'))) ||
84
123
  result.has(key(row)))
85
124
  return refuse();
86
125
  result.set(key(row), row);
@@ -88,9 +127,24 @@ async function facts(client, targets) {
88
127
  return result;
89
128
  }
90
129
  const lockable = (fact) => fact !== undefined && ['r', 'p'].includes(fact.kind) && fact.updatable;
91
- const clean = (fact) => !fact.rls && !fact.triggers && !fact.rules && !fact.policies;
130
+ /**
131
+ * Under row security, the one shape of row security a scoped write accepts: enabled, FORCE off unless the deployment
132
+ * allows it, and exactly one policy, mistri's (facts). Anything else — a second policy, a RESTRICTIVE one, `USING
133
+ * (true)`, another role — refuses as it always did, named as a policy that is not mistri's.
134
+ */
135
+ const tenantShape = (fact, backstop) => backstop !== undefined &&
136
+ fact.rls &&
137
+ fact.policies &&
138
+ (!fact.force || backstop.force) &&
139
+ fact.policy_count === 1 &&
140
+ typeof fact.tenant_column === 'string';
141
+ /** Row security a scoped write does not take as given: none at all is clean, and under row security mistri's own is. */
142
+ const secured = (fact, backstop) => (fact.rls || fact.policies) && !tenantShape(fact, backstop);
143
+ const clean = (fact, backstop) => !secured(fact, backstop) && !fact.triggers && !fact.rules;
92
144
  /** Clean but for its triggers: each write is then judged by the triggers it fires (scopedTransaction.ts target). */
93
- const cleanButTriggers = (fact) => fact.triggers && !fact.rls && !fact.rules && !fact.policies;
145
+ const cleanButTriggers = (fact, backstop) => fact.triggers && !secured(fact, backstop) && !fact.rules;
146
+ /** Row security as a refusal names it: under row security, any that is not mistri's tenant policy. */
147
+ const securityNamed = (backstop) => backstop ? "a row policy that is not mistri's tenant policy" : 'row-level security';
94
148
  /** The rows of the triggers of `tables`, read on the writer. */
95
149
  async function triggerRows(client, tables) {
96
150
  const result = await client.query(postgresTriggerStatement(true), [
@@ -389,51 +443,55 @@ async function foreignKeyComparisons(client, schema) {
389
443
  return comparisons;
390
444
  }
391
445
  /** What blocks a scoped write to a table beyond its triggers, as a refusal names it; undefined where nothing does. */
392
- const blockerOf = (fact) => !['r', 'p'].includes(fact.kind)
446
+ const blockerOf = (fact, backstop) => !['r', 'p'].includes(fact.kind)
393
447
  ? 'a kind a scoped write cannot target'
394
448
  : !fact.updatable
395
449
  ? 'no UPDATE privilege for the role that writes'
396
- : fact.rls || fact.rules || fact.policies
397
- ? [fact.rules ? 'a rule' : '', fact.policies || fact.rls ? 'row-level security' : ''].filter(Boolean).join(' and ')
450
+ : fact.rules || secured(fact, backstop)
451
+ ? [fact.rules ? 'a rule' : '', secured(fact, backstop) ? securityNamed(backstop) : ''].filter(Boolean).join(' and ')
398
452
  : undefined;
399
453
  /**
400
454
  * For `mistri check`: what a write's own catalog reads about `ids` to judge a trigger's effects
401
455
  * (readPostgresScopeCatalog), read on `client` outside a write: the keys, the tables in a partition or inheritance
402
456
  * hierarchy, and the tables a scoped write cannot target for row security, a rule, or the role's privileges.
403
457
  */
404
- export async function effectCatalogFacts(client, given) {
458
+ export async function effectCatalogFacts(client, given, backstop) {
405
459
  const ids = [...new Set(given)];
406
- const read = await facts(client, ids.map(located));
460
+ const read = await facts(client, ids.map(located), backstop);
407
461
  const blocked = new Map();
408
462
  const hierarchy = new Set();
409
463
  for (const id of ids) {
410
464
  const fact = read.get(key(located(id)));
411
465
  if (fact?.hierarchy)
412
466
  hierarchy.add(id);
413
- const blocker = fact && blockerOf(fact);
467
+ const blocker = fact && blockerOf(fact, backstop);
414
468
  if (blocker)
415
469
  blocked.set(id, blocker);
416
470
  }
417
471
  return { ...(await effectKeyFacts(client, ids)), hierarchy, blocked };
418
472
  }
419
473
  /** What makes a table unclean, as a refusal names it. */
420
- const unclean = (fact) => [fact.triggers ? triggerNames(fact.trigger_names) : '', fact.rules ? 'a rule' : '', fact.policies || fact.rls ? 'row-level security' : '']
474
+ const unclean = (fact, backstop) => [
475
+ fact.triggers ? triggerNames(fact.trigger_names) : '',
476
+ fact.rules ? 'a rule' : '',
477
+ secured(fact, backstop) ? securityNamed(backstop) : '',
478
+ ]
421
479
  .filter(Boolean)
422
480
  .join(' and ');
423
481
  /** Call only on the leased writer inside its transaction, before any read of
424
482
  * user data. The describe callback is the adapter's own introspection so the
425
483
  * evidence has the same shape as the catalog the permissions were bound to. */
426
- export async function readPostgresScopeCatalog(client, scope, describe) {
484
+ export async function readPostgresScopeCatalog(client, scope, describe, backstop) {
427
485
  try {
428
486
  const wanted = Object.keys(scope).map(located);
429
- const before = await facts(client, wanted);
487
+ const before = await facts(client, wanted, backstop);
430
488
  const pinned = wanted.filter((target) => lockable(before.get(key(target))));
431
489
  const relations = pinned.map((target) => `${POSTGRES_STYLE.quote(target.schema)}.${POSTGRES_STYLE.quote(target.name)}`);
432
490
  if (pinned.length)
433
491
  await client.query(`LOCK TABLE ${relations.join(', ')} IN ROW EXCLUSIVE MODE`);
434
492
  const described = await describe(client);
435
493
  const schema = captureScopeCatalog({ ...described, label: 'PostgreSQL scoped transaction', readAt: new Date().toISOString() });
436
- const after = facts(client, schema.tables.map((table) => ({ schema: table.schema, name: table.name })));
494
+ const after = facts(client, schema.tables.map((table) => ({ schema: table.schema, name: table.name })), backstop);
437
495
  const held = new Set(pinned.map(key));
438
496
  const writable = new Set();
439
497
  const blockedBy = new Map();
@@ -442,6 +500,7 @@ export async function readPostgresScopeCatalog(client, scope, describe) {
442
500
  const inheritanceParents = new Set();
443
501
  const locks = new Set();
444
502
  const withTriggers = [];
503
+ const tenantPolicies = new Map();
445
504
  for (const table of schema.tables) {
446
505
  const fact = (await after).get(key(table));
447
506
  // A relation the catalog listed a moment ago and cannot describe now
@@ -455,6 +514,8 @@ export async function readPostgresScopeCatalog(client, scope, describe) {
455
514
  hierarchy.add(table.id);
456
515
  if (fact.inherited)
457
516
  inheritanceParents.add(table.id);
517
+ if (tenantShape(fact, backstop))
518
+ tenantPolicies.set(table.id, fact.tenant_column);
458
519
  if (!lockable(fact))
459
520
  continue;
460
521
  locks.add(table.id);
@@ -463,12 +524,12 @@ export async function readPostgresScopeCatalog(client, scope, describe) {
463
524
  // Writable means pinned: a table that became clean after the pin
464
525
  // decision could be dirtied again before COMMIT, so it stays read-only.
465
526
  const ordinary = held.has(table.id) && !table.isView && table.columns.some((column) => column.primaryKey);
466
- if (ordinary && clean(fact))
527
+ if (ordinary && clean(fact, backstop))
467
528
  writable.add(table.id);
468
- else if (ordinary && cleanButTriggers(fact))
529
+ else if (ordinary && cleanButTriggers(fact, backstop))
469
530
  withTriggers.push({ id: table.id, schema: table.schema, name: table.name });
470
- else if (!clean(fact))
471
- blockedBy.set(table.id, unclean(fact));
531
+ else if (!clean(fact, backstop))
532
+ blockedBy.set(table.id, unclean(fact, backstop));
472
533
  }
473
534
  /* Read only where a table has triggers: a database without them asks nothing more than it did. */
474
535
  const read = withTriggers.length ? await readTriggers(client, withTriggers) : undefined;
@@ -507,6 +568,7 @@ export async function readPostgresScopeCatalog(client, scope, describe) {
507
568
  ...(hierarchy.size ? { hierarchy } : {}),
508
569
  ...(inheritanceParents.size ? { inheritanceParents } : {}),
509
570
  ...(triggered.size ? { triggered, triggerVersions } : {}),
571
+ ...(tenantPolicies.size ? { tenantPolicies } : {}),
510
572
  lockable: locks,
511
573
  pinned: relations,
512
574
  };
@@ -75,6 +75,8 @@ 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
80
  }
79
81
  /** The callback: the records, the journal, and a scoped transaction's catalog evidence (absent in an ordinary one). */
80
82
  export type JournalRun<J, T> = (records: WriteTransaction, journal: J, catalog?: DatabaseSchema) => Promise<T>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mistriwork/engine",
3
- "version": "1.0.0-rc.51",
3
+ "version": "1.0.0-rc.52",
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": {