@aria-framework/db-worker 0.29.0 → 0.30.0

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.
package/README.md CHANGED
@@ -700,8 +700,81 @@ replaces its own copy with the package's. Each was checked against the app copie
700
700
  | `aria-tenancy` | New; nothing runs until the app adds `aria.tenancy.json` and the command to its suite. The wall app passes `partnerIdType: "INTEGER"` and its `moveRows` exception; the hub passes `requireUpdateCascade: true`; the four apps that freeze every existing file need no compatibility rule. | See "Adopting `aria-tenancy`" above. |
701
701
  | The tenant filter (`TENANT_EXPR`, and `createTenantSettings`' reads) | The CASE form. The hub's `lib/sql.js` and `models/Settings.js` still use the older COALESCE form. | The hub switches when it adopts, with a measured query plan (`EXPLAIN (ANALYZE, BUFFERS)` before and after) in its pull request. |
702
702
 
703
+ ## The customer pin (0.30.0)
704
+
705
+ A third level under the tenant context's two: work done for ONE customer of ONE partner (a customer's own people, a
706
+ device of one customer). It holds at two locks, both in this package; the lists stay the app's.
707
+
708
+ ```js
709
+ // main thread
710
+ const db = new DbClient({ workerPath, logger, customerPin: true });
711
+ runWithTenant({ scope: 'partner', partnerId: 7 },
712
+ () => runPinned({ partnerId: 7, customerId: 'c_123', contactId: 'p_9' }, () => db.invoke('Media', 'list')));
713
+ // (@aria-framework/tenancy's asCustomer(partnerId, customerId, fn, { contactId }) does both)
714
+
715
+ // worker entry
716
+ runWorker({ init, customerScope: (models) => createCustomerScope({ safe: CUSTOMER_SAFE, models }) });
717
+ ```
718
+
719
+ | Export | What it does | What it refuses |
720
+ |---|---|---|
721
+ | `runPinned({ partnerId, customerId, contactId }, fn)` | runs `fn` pinned (AsyncLocalStorage; restored after `fn` returns or throws) | a partner that is not a positive whole number (a number or a digit string; not `true`, `'7.0'`, `' 7'`); a customer or contact id that is not a letter or digit then letters, digits, `_`, `-` (at most 64) |
722
+ | `currentPin()` | the pin in force, frozen, or null | |
723
+ | `activePin()` | the pin to apply to an invoke made NOW: the pin, only while the tenant in force is `'partner'` scope at the pin's own partner | |
724
+ | `pinnedCustomer()`, `pinClause(col)` | the model-layer half: the pinned customer, or ` AND <col> = ?` and its params (nothing outside a pin) | `pinClause`: a `col` that is not a column name |
725
+ | `runUnpinnedFor({ partnerId, customerId }, fn)` | leaves the pin for the app's own follow-up about that same pair | a pin in force for any other pair |
726
+ | `createCustomerScope({ safe, models, customerId?, contactId? })` | the worker's lock: under a pin only a listed method runs. It only DECIDES; the worker runs the method from its own registry, by the same dispatch as an unpinned call, so a scope built over another object cannot change what runs | a list naming anything but a registered model's OWN function property (so never `constructor`, `toString`, `hasOwnProperty`, `valueOf`, `__proto__`); with a pin: a method that is not the model's own in the worker's registry, an unlisted method, every method when the list is `{}`, an `outsideTransaction` method, a tenant that is not partner scope at the pin's partner, an id the app's own check rejects. Code `CUSTOMER_SCOPE_REFUSED` |
727
+ | `DbClient` option `customerPin` | `true`: an invoke under an active pin carries it as the message's `pin` | `false` (default): such an invoke is refused, never run unpinned |
728
+ | `runWorker` option `customerScope` | `(models) => createCustomerScope(...)`, called once after `init` | without it every pinned invoke is refused |
729
+ | `PIN_SQL`, `pinParams(pin)` | the statement the worker runs, inside the invoke's transaction, right AFTER `APPLY_SQL` | |
730
+ | `CUSTOMER_POLICY_EXPRESSION(column)` | the customer table's policy text, frozen (below) | a column that is not a plain lower-case name |
731
+
732
+ **A rule for the adopting app: a customer-safe model is a plain object whose methods are its own properties.** A model
733
+ that is an instance of a class holds its methods on the class's prototype, so none of them can be listed:
734
+ `createCustomerScope` throws when the worker starts, and the app does not boot. Write such a model as an object literal
735
+ (or assign the methods onto the instance) before listing it. Without a pin nothing changes: an inherited method still
736
+ runs as it always did.
737
+
738
+ **What reaches the database.** On a pooled driver a pinned invoke is: `BEGIN`; `APPLY_SQL` (`'partner'`, the partner);
739
+ `SELECT set_config('app.scope', 'customer', true) AS s, set_config('app.customer_id', ?, true) AS c`; the model,
740
+ inside the worker's own pin; `COMMIT`. Both settings are transaction-local, so nothing of a pin survives into the next
741
+ invoke on the same connection. The contact is carried to the worker (`currentPin().contactId`) and is NEVER a
742
+ database setting: no policy reads it. On SQLite nothing is set; the safe list and the model's own predicate hold.
743
+
744
+ **Why the pin is dropped outside its partner's scope.** `activePin()` answers null under a platform-scope context
745
+ (an app's `asHouse` / `asPlatform`) and under another partner's scope, so an invoke made there goes UNPINNED. This is
746
+ on purpose: an app that widens (an audit row written at the house, a credential lookup) does it in the open, with
747
+ `runWithTenant`, as every widening in this family is — and a pin is never applied at a scope its policy arm was not
748
+ written for (the worker refuses a pin whose partner is not the tenant's, and any pin at platform scope).
749
+
750
+ **No change for an app that never pins.** No pin in force: the message is `{ id, model, method, args, tenant }` as
751
+ before, the worker sends the same statements, and `defineTenancy` adds no key to a manifest without `CUSTOMER`.
752
+
753
+ ### `CUSTOMER_POLICY_EXPRESSION(column)` — frozen
754
+
755
+ The policy of a table in the manifest's `CUSTOMER` map (`{ table: customer column }`): `TENANCY_POLICY_EXPRESSION`'s
756
+ two arms plus `WHEN 'customer' THEN partner_id = current_setting('app.partner_id')::int AND <column> =
757
+ current_setting('app.customer_id')`. Both lookups strict: a pin that lost its customer errors or matches nothing,
758
+ never widens. The text is the one the first app with a customer tier applied in its migrations (022 to 055 at its
759
+ commit `553e262`); `test/tenancyManifest.js` pins its sha256 and `test/tenancyGenerator.js` rebuilds every one of that
760
+ app's applied customer policies (one per table in its `CUSTOMER` map) from this function, byte for byte. The generator (`aria-tenancy`) uses it for a
761
+ CUSTOMER table. A manifest that still carries its own `CUSTOMER_POLICY_EXPRESSION` is accepted only when it produces
762
+ the same text (for every column its `CUSTOMER` names, and `customer_id`), and refused otherwise.
763
+
703
764
  ## Changelog
704
765
 
766
+ - **0.30.0** — The customer pin (above), moved in from the first app that built it: `runPinned`, `runUnpinnedFor`,
767
+ `currentPin`, `activePin`, `pinnedCustomer`, `pinClause`, `normalisePin`, `isPinId`, `PIN_SQL`, `pinParams`;
768
+ `createCustomerScope`; the `DbClient` option `customerPin` and the `runWorker` option `customerScope`;
769
+ `CUSTOMER_POLICY_EXPRESSION` (frozen) and `assertSameCustomerPolicy`. Additive for an app without a customer tier:
770
+ an unpinned invoke's message and statements are byte for byte what they were. **One behaviour change**, for a
771
+ manifest with a customer tier: its own `CUSTOMER_POLICY_EXPRESSION` must produce the package's text (it passed
772
+ through `defineTenancy` untouched before, and the generator rendered it), and `defineTenancy` refuses a `CUSTOMER`
773
+ value that is not a column name; a manifest with a `CUSTOMER` map and no function now gets the package's text
774
+ (the generator threw before). Only one app has a customer tier, and its function produces the package's text.
775
+ Tests (in `npm test`): `customerPin.js` (a real worker, the recording driver), `customerPin.pglite.js` (a real
776
+ worker over PGlite, real row-level security as a non-owner, non-superuser role), and new checks in
777
+ `tenancyManifest.js` and `tenancyGenerator.js`.
705
778
  - **0.29.0** — The tenancy core (above), additive: `sql`, `defineTenancy` + `TENANCY_POLICY_EXPRESSION`,
706
779
  `assertPlatformScope`, `assertPartnerScope`, `keepTenant`, `tenantCacheKey`, `createTenantSettings`, the
707
780
  `DbClient` option `onRefusal` and `runMigrations`' `squashedFrom`. And the **`aria-tenancy` command** (`bin`,
package/client.js CHANGED
@@ -14,6 +14,7 @@
14
14
 
15
15
  const { Worker } = require('worker_threads');
16
16
  const { currentTenant } = require('./tenantContext');
17
+ const { activePin } = require('./customerPin');
17
18
 
18
19
  class DbClient {
19
20
  /**
@@ -50,8 +51,13 @@ class DbClient {
50
51
  * logged, never thrown. The hook's own invokes pass through it as well, so a
51
52
  * hook writing through this client ignores its own model's errors (an audit
52
53
  * hook skips model 'Audit'). Default: none, and invoke() is what it was.
54
+ * @param {boolean} [opts.customerPin=false] - 0.30.0. true: an invoke made while a
55
+ * customer pin is in force (customerPin.js activePin) carries it to the worker,
56
+ * which applies it (runWorker({ customerScope })). false (the default): such an
57
+ * invoke is REFUSED, never run unpinned. Without a pin in force, both are exactly
58
+ * the client they were.
53
59
  */
54
- constructor({ workerPath, logger, callTimeoutMs, slowMs, queueWarnMs, onWorkerDeath, onRefusal } = {}) {
60
+ constructor({ workerPath, logger, callTimeoutMs, slowMs, queueWarnMs, onWorkerDeath, onRefusal, customerPin } = {}) {
55
61
  if (!workerPath) throw new Error('DbClient: workerPath is required');
56
62
  this._workerPath = workerPath;
57
63
  this._logger = logger || console;
@@ -61,6 +67,8 @@ class DbClient {
61
67
  this._onWorkerDeath = typeof onWorkerDeath === 'function' ? onWorkerDeath : null;
62
68
  if (onRefusal != null && typeof onRefusal !== 'function') throw new Error('DbClient: onRefusal must be a function');
63
69
  this._onRefusal = onRefusal || null;
70
+ if (customerPin !== undefined && typeof customerPin !== 'boolean') throw new Error('DbClient: customerPin must be true or false');
71
+ this._customerPin = customerPin === true;
64
72
  this._deathNotified = false;
65
73
  // Queue-warn coalescing: under real saturation EVERY completed call crosses
66
74
  // the threshold — one line each would flood the log (disk I/O during the
@@ -231,6 +239,14 @@ class DbClient {
231
239
  if (!this._worker) {
232
240
  return Promise.reject(new Error('Database worker not initialized'));
233
241
  }
242
+ // 0.30.0 — the customer pin in force for this call, if any (customerPin.js). Read BEFORE anything is queued, so a
243
+ // refused call leaves nothing pending.
244
+ const pin = activePin();
245
+ if (pin && !this._customerPin) {
246
+ const e = new Error(`DbClient: ${model}.${method} was invoked under a customer pin, and this client was not built with { customerPin: true } — refused rather than run unpinned`);
247
+ e.code = 'CUSTOMER_SCOPE_REFUSED';
248
+ return Promise.reject(e);
249
+ }
234
250
  return new Promise((resolve, reject) => {
235
251
  this._nextId = (this._nextId + 1) % Number.MAX_SAFE_INTEGER;
236
252
  const id = this._nextId;
@@ -247,7 +263,11 @@ class DbClient {
247
263
  // The tenant context travels IN THE MESSAGE because AsyncLocalStorage does not cross a
248
264
  // worker thread. null when the app has established none — which a pooled driver refuses
249
265
  // on the far side rather than guessing which tenant was meant.
250
- this._worker.postMessage({ id, model, method, args, tenant: currentTenant() });
266
+ // The pin travels the same way, as its own field, and ONLY when one is in force: an unpinned message is
267
+ // byte for byte the message it always was.
268
+ const msg = { id, model, method, args, tenant: currentTenant() };
269
+ if (pin) msg.pin = pin;
270
+ this._worker.postMessage(msg);
251
271
  });
252
272
  }
253
273
 
package/customerPin.js ADDED
@@ -0,0 +1,144 @@
1
+ /**
2
+ * THE CUSTOMER PIN (0.30.0) — a third level under the tenant context's two: work done for ONE customer of ONE partner
3
+ * (a customer's own people, a device of one customer, staff visiting one customer).
4
+ *
5
+ * Moved here, nearly as it was, from the first app that built it for itself: a security boundary with two copies has
6
+ * one that drifts (tenantContext.js). The pin holds at TWO locks, and both are this package's now:
7
+ *
8
+ * 1. the model layer: under a pin only a method on the app's customer-safe list runs (createCustomerScope,
9
+ * customerScope.js). The LIST is the app's; the mechanism is here.
10
+ * 2. row-level security: inside the invoke's own transaction, AFTER the tenant context's settings, the worker sets
11
+ * `app.scope = 'customer'` and `app.customer_id` (PIN_SQL below), which the `customer` arm of every customer
12
+ * table's policy reads (CUSTOMER_POLICY_EXPRESSION, tenancyManifest.js). A partner-only table's policy sends
13
+ * 'customer' to its ELSE arm, so the partner boundary still holds there.
14
+ *
15
+ * HOW IT TRAVELS. Like the tenant context, in three hops, because AsyncLocalStorage does not cross a worker thread:
16
+ * main thread runPinned({ partnerId, customerId, contactId }, fn) — inside a partner-scope runWithTenant
17
+ * DbClient a client built with `{ customerPin: true }` puts activePin() in the message as `pin` (only when one is
18
+ * in force: an unpinned message is exactly what it was). A client WITHOUT the option refuses an invoke
19
+ * made while a pin is in force, rather than running it unpinned.
20
+ * worker refuses unless the worker was given a customer scope (runWorker({ customerScope })), the tenant is
21
+ * 'partner' scope at the pin's own partner, the method is on the safe list and is not
22
+ * `outsideTransaction`; then applies APPLY_SQL, then PIN_SQL, and runs the model inside this same
23
+ * store (one instance per thread), so `pinnedCustomer()` / `pinClause()` narrow the model's own SQL too.
24
+ *
25
+ * THE CONTACT is carried with the pin to the worker, so a model can name the CALLER from the pin rather than from an
26
+ * argument (currentPin().contactId). It is NEVER a database setting: no policy reads it.
27
+ *
28
+ * THE PIN APPLIES ONLY WHILE THE TENANT IN FORCE IS ITS PARTNER'S (activePin). It is DROPPED under a platform-scope
29
+ * context (an app's asHouse / asPlatform) and under another partner's scope. That is deliberate: code that widens on
30
+ * purpose (an audit write at the house, a credential lookup) does so in the open, with runWithTenant, as every widening
31
+ * in this family is — and a pin is never applied at a scope its policy arm was not written for.
32
+ *
33
+ * ON SQLITE there is no row-level security: the pin rests on the safe list and the model's own predicate alone.
34
+ */
35
+
36
+ 'use strict';
37
+
38
+ const { AsyncLocalStorage } = require('node:async_hooks');
39
+ const { currentTenant } = require('./tenantContext');
40
+
41
+ const store = new AsyncLocalStorage();
42
+
43
+ /**
44
+ * The generic shape of a customer or contact id: a letter or digit, then letters, digits, "_" and "-", at most 64 in
45
+ * all. The value is bound as a parameter and compared as TEXT with the customer column; the shape only keeps out what
46
+ * no id is (empty, whitespace, punctuation, a number, an object). An app with a stricter id passes its own check to
47
+ * createCustomerScope (customerScope.js), which the worker applies as well.
48
+ */
49
+ const ID_SHAPE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
50
+ const isPinId = (v) => typeof v === 'string' && ID_SHAPE.test(v);
51
+
52
+ /** A partner id: a positive safe integer, or a string of digits for one. Nothing else (true, '7.0', ' 7', '0x7'). */
53
+ function partnerIdOf(v) {
54
+ const n = typeof v === 'number' ? v : (typeof v === 'string' && /^\d+$/.test(v) ? Number(v) : NaN);
55
+ return Number.isSafeInteger(n) && n > 0 ? n : null;
56
+ }
57
+
58
+ /** Validate and freeze a pin. Throws with the reason, because every caller is a security path. */
59
+ function normalisePin(pin) {
60
+ if (!pin || typeof pin !== 'object') throw new Error('customerPin: a pin is required, e.g. { partnerId: 7, customerId: \'cus_…\' }');
61
+ const { partnerId, customerId, contactId = null } = pin;
62
+ const p = partnerIdOf(partnerId);
63
+ if (p === null) throw new Error(`customerPin: partner ${JSON.stringify(partnerId)} is not a partner id (a positive whole number)`);
64
+ if (!isPinId(customerId)) throw new Error(`customerPin: ${JSON.stringify(customerId)} is not a customer id`);
65
+ if (contactId != null && !isPinId(contactId)) throw new Error(`customerPin: ${JSON.stringify(contactId)} is not a contact id`);
66
+ return Object.freeze({ partnerId: p, customerId, contactId: contactId == null ? null : contactId });
67
+ }
68
+
69
+ /**
70
+ * Run `fn` pinned to one customer of one partner — and, for a person's session, to the CONTACT it belongs to
71
+ * (`contactId`; null for a device's pin). Throws on a malformed pin. It does NOT set the tenant context: the caller
72
+ * runs it inside a partner-scope runWithTenant (@aria-framework/tenancy's asCustomer does both), and until then
73
+ * activePin() is null and nothing is pinned.
74
+ */
75
+ function runPinned(pin, fn) {
76
+ return store.run(normalisePin(pin), fn);
77
+ }
78
+
79
+ /** The pin in force, `{ partnerId, customerId, contactId }`, or null. */
80
+ function currentPin() {
81
+ return store.getStore() || null;
82
+ }
83
+
84
+ /**
85
+ * The pin to APPLY to an invoke made now: the pin in force, but only while the tenant in force is 'partner' scope at
86
+ * the pin's own partner (header: code that widens on purpose is not followed). DbClient routes by this.
87
+ */
88
+ function activePin() {
89
+ const p = store.getStore();
90
+ if (!p) return null;
91
+ const t = currentTenant();
92
+ return t && t.scope === 'partner' && Number(t.partnerId) === p.partnerId ? p : null;
93
+ }
94
+
95
+ /** The pinned customer's id, or null — what a customer model adds to its own WHERE (the model-layer half). */
96
+ function pinnedCustomer() {
97
+ const p = store.getStore();
98
+ return p ? p.customerId : null;
99
+ }
100
+
101
+ /**
102
+ * ` AND <col> = ?` naming the pinned customer, and its params — or nothing outside a pin. Reads pinnedCustomer THROUGH
103
+ * module.exports, at call time, so a test that switches the model half off switches it off here too. `col` is
104
+ * interpolated, so it must be a plain (optionally table-qualified) column name.
105
+ */
106
+ function pinClause(col) {
107
+ if (typeof col !== 'string' || !/^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)?$/.test(col)) {
108
+ throw new Error(`customerPin: pinClause needs a column name, not ${JSON.stringify(col)}`);
109
+ }
110
+ const pin = module.exports.pinnedCustomer();
111
+ return pin ? { clause: ` AND ${col} = ?`, params: [pin], pin } : { clause: '', params: [], pin: null };
112
+ }
113
+
114
+ /**
115
+ * Run `fn` with NO pin, for the app's own follow-up about ONE (partner, customer) pair (telling that customer's devices
116
+ * what changed after a person's request). The tenant context is untouched; only the pinned routing is left behind.
117
+ * WHEN A PIN IS IN FORCE IT MUST BE THAT PAIR: a pinned session can never use this to reach another customer, of its
118
+ * partner or any other — it throws.
119
+ */
120
+ function runUnpinnedFor({ partnerId, customerId } = {}, fn) {
121
+ const pin = store.getStore();
122
+ if (pin && (pin.customerId !== customerId || pin.partnerId !== partnerIdOf(partnerId))) {
123
+ throw new Error(`customerPin: a session pinned to ${pin.customerId} cannot run unpinned for ${customerId} (partner ${partnerId})`);
124
+ }
125
+ return store.exit(fn);
126
+ }
127
+
128
+ /**
129
+ * The one statement that narrows an invoke's transaction to the pin, run by the worker right AFTER APPLY_SQL (which
130
+ * has set 'partner' scope and the partner). The same text, setting names and value as the first app applied, so the
131
+ * policies already in its migrations keep working. Transaction-LOCAL (is_local true), like APPLY_SQL: nothing of it
132
+ * survives into the next invoke on the same pooled connection.
133
+ */
134
+ const PIN_SQL =
135
+ "SELECT set_config('app.scope', 'customer', true) AS s, set_config('app.customer_id', ?, true) AS c";
136
+
137
+ function pinParams(pin) {
138
+ return [normalisePin(pin).customerId];
139
+ }
140
+
141
+ module.exports = {
142
+ runPinned, runUnpinnedFor, currentPin, activePin, pinnedCustomer, pinClause,
143
+ normalisePin, isPinId, PIN_SQL, pinParams
144
+ };
@@ -0,0 +1,115 @@
1
+ /**
2
+ * createCustomerScope (0.30.0) — the WORKER half of a customer-pinned invoke: the model-layer lock of the customer pin
3
+ * (customerPin.js has the whole design).
4
+ *
5
+ * runWorker({
6
+ * init: (wd) => models,
7
+ * customerScope: (models) => createCustomerScope({ safe: CUSTOMER_SAFE, models })
8
+ * });
9
+ *
10
+ * `safe` is the APP's list, model → the methods a customer-pinned session may call; it stays the app's. Under a pin a
11
+ * method that is not on it is REFUSED, so a partner-wide read (a user list, the whole audit trail) has no way in. Fail
12
+ * closed: a new model method is unreachable from a pinned session until somebody lists it. An empty list refuses
13
+ * every pinned call. Without a pin this is never consulted: the invoke runs exactly as it did before.
14
+ *
15
+ * Every refusal carries `code: 'CUSTOMER_SCOPE_REFUSED'`.
16
+ */
17
+
18
+ 'use strict';
19
+
20
+ const { normalisePin } = require('./customerPin');
21
+
22
+ const SCOPES = new WeakSet();
23
+ const isFn = (f) => typeof f === 'function';
24
+ const isMap = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
25
+ const own = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
26
+
27
+ /**
28
+ * THE RULE FOR "A MODEL METHOD" UNDER A PIN, used in both places that decide it: createCustomerScope's construction
29
+ * check of the safe list, and the worker's pinned dispatch (worker.js), which runs the method from ITS OWN registry.
30
+ * The model must be the registry's OWN property, and the method the model's OWN function property — so nothing
31
+ * inherited (`constructor`, `toString`, `hasOwnProperty`, `valueOf`, `__proto__`) can be listed or reached. Returns the
32
+ * function, or null.
33
+ */
34
+ function ownMethod(registry, model, method) {
35
+ if (!registry || typeof registry !== 'object' || typeof model !== 'string' || typeof method !== 'string') return null;
36
+ if (!own(registry, model)) return null;
37
+ const target = registry[model];
38
+ if (!target || (typeof target !== 'object' && typeof target !== 'function') || !own(target, method)) return null;
39
+ return isFn(target[method]) ? target[method] : null;
40
+ }
41
+
42
+ function refused(message) {
43
+ const e = new Error(message);
44
+ e.code = 'CUSTOMER_SCOPE_REFUSED';
45
+ return e;
46
+ }
47
+
48
+ /**
49
+ * @param {object} o
50
+ * @param {{[model: string]: string[]}} o.safe REQUIRED: the methods a pinned session may call ({} refuses every one)
51
+ * @param {object} o.models REQUIRED: the worker's model registry (what init returned); every listed method must be the
52
+ * model's own function there (ownMethod). Used to check the list only: the worker runs the method from its own
53
+ * registry, so a scope built over another object cannot change what runs
54
+ * @param {(id: string) => boolean} [o.customerId] the app's own, stricter check of a customer id (only `true` passes),
55
+ * applied on top of the package's generic shape
56
+ * @param {(id: string) => boolean} [o.contactId] the same for a contact id (asked only when the pin carries one)
57
+ */
58
+ function createCustomerScope(o = {}) {
59
+ const { safe, models, customerId: checkCustomer, contactId: checkContact } = o;
60
+ if (!isMap(safe)) throw new Error('createCustomerScope: `safe` is required — { Model: [\'method\', ...] }, the app\'s customer-safe list ({} for none)');
61
+ if (!isMap(models)) throw new Error('createCustomerScope: `models` is required — the worker\'s model registry');
62
+ if (checkCustomer !== undefined && !isFn(checkCustomer)) throw new Error('createCustomerScope: `customerId` must be a function when given');
63
+ if (checkContact !== undefined && !isFn(checkContact)) throw new Error('createCustomerScope: `contactId` must be a function when given');
64
+ const list = {};
65
+ for (const model of Object.keys(safe)) {
66
+ const methods = safe[model];
67
+ if (!Array.isArray(methods) || !methods.every((m) => typeof m === 'string' && m)) {
68
+ throw new Error(`createCustomerScope: safe.${model} must be a list of method names`);
69
+ }
70
+ for (const m of methods) {
71
+ if (!ownMethod(models, model, m)) {
72
+ throw new Error(`createCustomerScope: safe lists ${model}.${m}, which is not the model's own method in the registry`);
73
+ }
74
+ }
75
+ list[model] = Object.freeze([...methods]);
76
+ }
77
+ const frozen = Object.freeze(list);
78
+
79
+ /** Is `model.method` on the safe list? */
80
+ function allows(model, method) {
81
+ return typeof model === 'string' && own(frozen, model) && frozen[model].includes(method);
82
+ }
83
+
84
+ /**
85
+ * DECIDE one pinned invoke BEFORE anything runs; the worker then dispatches it from its own registry, by the same path
86
+ * as an unpinned call. Refuses: a malformed pin, or one the app's own checks reject; a tenant that is not 'partner'
87
+ * scope at the pin's own partner (so never at platform scope); a method not on the list. (The worker itself refuses a
88
+ * method that is not the model's own in its registry, and one that declares `outsideTransaction`.)
89
+ *
90
+ * @returns {{ pin: object }} the normalised pin to apply
91
+ */
92
+ function prepare(pin, tenant, model, method) {
93
+ let p;
94
+ try { p = normalisePin(pin); } catch (e) { throw refused(`CustomerScope: ${e.message}`); }
95
+ if (checkCustomer && checkCustomer(p.customerId) !== true) throw refused(`CustomerScope: "${p.customerId}" is not a customer id this app accepts`);
96
+ if (p.contactId != null && checkContact && checkContact(p.contactId) !== true) throw refused(`CustomerScope: "${p.contactId}" is not a contact id this app accepts`);
97
+ if (!tenant || tenant.scope !== 'partner' || tenant.partnerId == null) {
98
+ throw refused(`CustomerScope: a customer pin needs a partner scope, not ${tenant ? tenant.scope : 'none'}`);
99
+ }
100
+ if (Number(tenant.partnerId) !== p.partnerId) {
101
+ throw refused(`CustomerScope: a pin for partner ${p.partnerId} arrived in partner ${tenant.partnerId}'s scope`);
102
+ }
103
+ if (!allows(model, method)) throw refused(`CustomerScope: ${model}.${method} is not reachable from a customer-pinned session`);
104
+ return { pin: p };
105
+ }
106
+
107
+ const scope = Object.freeze({ safe: frozen, allows, prepare });
108
+ SCOPES.add(scope);
109
+ return scope;
110
+ }
111
+
112
+ /** Was this made by createCustomerScope? (runWorker accepts nothing else.) */
113
+ const isCustomerScope = (s) => SCOPES.has(s);
114
+
115
+ module.exports = { createCustomerScope, isCustomerScope, ownMethod, refused, CUSTOMER_SCOPE_REFUSED: 'CUSTOMER_SCOPE_REFUSED' };
package/index.js CHANGED
@@ -54,5 +54,9 @@ module.exports = {
54
54
  sql: require('./sql'),
55
55
  ...require('./tenancyManifest'),
56
56
  ...require('./tenantScope'),
57
- ...require('./tenantSettings')
57
+ ...require('./tenantSettings'),
58
+ // 0.30.0 — the customer pin: the third level under the tenant context's two (customerPin.js), the worker's
59
+ // customer-safe lock (createCustomerScope), and — on tenancyManifest above — the frozen CUSTOMER_POLICY_EXPRESSION.
60
+ ...require('./customerPin'),
61
+ createCustomerScope: require('./customerScope').createCustomerScope
58
62
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aria-framework/db-worker",
3
- "version": "0.29.0",
3
+ "version": "0.30.0",
4
4
  "description": "Aria App Framework — db-worker module. Async RPC bridge over synchronous better-sqlite3: a worker-thread dispatcher (runWorker), a main-thread client with per-call timeouts and crash handling (DbClient), and a SQLite layer with WAL pragmas + a numbered-migration runner (database).",
5
5
  "license": "UNLICENSED",
6
6
  "private": false,
@@ -13,6 +13,8 @@
13
13
  },
14
14
  "files": [
15
15
  "client.js",
16
+ "customerPin.js",
17
+ "customerScope.js",
16
18
  "bin/",
17
19
  "database.js",
18
20
  "dialect.js",
@@ -49,7 +51,7 @@
49
51
  "pg": "^8.23.0"
50
52
  },
51
53
  "scripts": {
52
- "test": "node test/driverContract.js && node test/migrations.js && node test/migrations-notx.js && node test/migrationFailureSurfaces.js && node test/migrationDialect.js && node test/regressions.js && node test/transactions.js && node test/tenantContext.js && node test/tenancyMigration.js && node test/tenancyAttribution.pglite.js && node test/tenancyNullable.pg.js && node test/tenancyPartnerFk.pg.js && node test/tenancyOnUpdate.pg.js && node test/dialectIntrospection.js && node test/tenantRls.pg.js && node test/nestedTransaction.pg.js && node test/clientError.pg.js && node test/migrationRole.pg.js && node test/smoke.js && node test/tier2.js && node test/timezone.pg.js && node test/pinPoolUtc.js && node test/pinAwaited.pg.js && node test/inTransaction.js && node test/sql.js && node test/tenancyManifest.js && node test/tenantScope.js && node test/tenantSettings.js && node test/dbClientRefusal.js && node test/migrationsSquash.js && node test/tenancyGenerator.js",
54
+ "test": "node test/driverContract.js && node test/migrations.js && node test/migrations-notx.js && node test/migrationFailureSurfaces.js && node test/migrationDialect.js && node test/regressions.js && node test/transactions.js && node test/tenantContext.js && node test/tenancyMigration.js && node test/tenancyAttribution.pglite.js && node test/tenancyNullable.pg.js && node test/tenancyPartnerFk.pg.js && node test/tenancyOnUpdate.pg.js && node test/dialectIntrospection.js && node test/tenantRls.pg.js && node test/nestedTransaction.pg.js && node test/clientError.pg.js && node test/migrationRole.pg.js && node test/smoke.js && node test/tier2.js && node test/timezone.pg.js && node test/pinPoolUtc.js && node test/pinAwaited.pg.js && node test/inTransaction.js && node test/sql.js && node test/tenancyManifest.js && node test/tenantScope.js && node test/tenantSettings.js && node test/dbClientRefusal.js && node test/migrationsSquash.js && node test/tenancyGenerator.js && node test/customerPin.js && node test/customerPin.pglite.js",
53
55
  "prepublishOnly": "node ../../test/packaging.js db-worker"
54
56
  }
55
57
  }
@@ -25,7 +25,7 @@
25
25
  * the policy at the end of the same file, a plain-SQLite twin beside it (one tenant there, no policies).
26
26
  *
27
27
  * ── WHAT IS GENERATED — AND HELD BY check — PER TABLE ───────────────────────────────────────────────────────────
28
- * Decided by the manifest alone (PARTNER, and an optional CUSTOMER map with its CUSTOMER_POLICY_EXPRESSION):
28
+ * Decided by the manifest alone (PARTNER, and an optional CUSTOMER map):
29
29
  * Postgres the partner_id column definition, inside the CREATE TABLE — compared WHITESPACE-NORMALISED, the one
30
30
  * comparison that is not byte for byte (a hand-typed migration may wrap it; same tokens);
31
31
  * and, byte for byte as whole statements (CRLF read as LF):
@@ -34,7 +34,8 @@
34
34
  * ALTER TABLE <t> FORCE ROW LEVEL SECURITY;
35
35
  * CREATE POLICY tenant_isolation ON <t> FOR ALL USING (…) WITH CHECK (…);
36
36
  * The policy text is TENANCY_POLICY_EXPRESSION (tenancyManifest.js), never a copy held here; a CUSTOMER
37
- * table's is the manifest's own CUSTOMER_POLICY_EXPRESSION(column) until the customer tier moves here.
37
+ * table's is the package's CUSTOMER_POLICY_EXPRESSION(column) (0.30.0; a manifest's own function is
38
+ * accepted only when it produces the same text, and refused otherwise).
38
39
  * SQLite the partner_id column definition (normalised as above). The skeleton writes the partner index there
39
40
  * too, but check does not hold it: on SQLite — one tenant, no policies — it is an index, not tenancy.
40
41
  * The skeleton also writes, for a CUSTOMER table, the customer column, the composite target UNIQUE (id, <col>,
@@ -116,7 +117,7 @@
116
117
  const fs = require('fs');
117
118
  const path = require('path');
118
119
  const { selectForDialect } = require('./database');
119
- const { TENANCY_POLICY_EXPRESSION } = require('./tenancyManifest');
120
+ const { TENANCY_POLICY_EXPRESSION, CUSTOMER_POLICY_EXPRESSION, assertSameCustomerPolicy } = require('./tenancyManifest');
120
121
 
121
122
  /** The Postgres partner_id definition, in the type the app states (aria.tenancy.json "partnerIdType"). */
122
123
  const PARTNER_ID_TYPES = ['BIGINT', 'INTEGER'];
@@ -229,6 +230,10 @@ function checkManifest(manifest, name = 'the manifest') {
229
230
  if (has(manifest, 'POLICY_EXPRESSION') && manifest.POLICY_EXPRESSION !== TENANCY_POLICY_EXPRESSION) {
230
231
  throw new Error(`${name}: its POLICY_EXPRESSION is not the frozen TENANCY_POLICY_EXPRESSION — the policy every applied migration carries`);
231
232
  }
233
+ // 0.30.0 — a manifest's own customer policy function must produce the package's text (assertSameCustomerPolicy).
234
+ if (has(manifest, 'CUSTOMER_POLICY_EXPRESSION') && manifest.CUSTOMER_POLICY_EXPRESSION !== CUSTOMER_POLICY_EXPRESSION) {
235
+ assertSameCustomerPolicy(manifest.CUSTOMER_POLICY_EXPRESSION, manifest.CUSTOMER, name);
236
+ }
232
237
  }
233
238
 
234
239
  // ── RENDERING ───────────────────────────────────────────────────────────────────────────────────────────────────
@@ -238,10 +243,11 @@ function policyExpression(manifest, table) {
238
243
  const col = (manifest.CUSTOMER || {})[table];
239
244
  let raw = TENANCY_POLICY_EXPRESSION;
240
245
  if (col) {
241
- if (typeof manifest.CUSTOMER_POLICY_EXPRESSION !== 'function') {
242
- throw new Error(`${table} is in CUSTOMER, but the manifest has no CUSTOMER_POLICY_EXPRESSION(column)`);
246
+ // 0.30.0 — the package's text. A manifest still carrying its own function must produce the same text.
247
+ if (has(manifest, 'CUSTOMER_POLICY_EXPRESSION') && manifest.CUSTOMER_POLICY_EXPRESSION !== CUSTOMER_POLICY_EXPRESSION) {
248
+ assertSameCustomerPolicy(manifest.CUSTOMER_POLICY_EXPRESSION, manifest.CUSTOMER, 'the manifest');
243
249
  }
244
- raw = manifest.CUSTOMER_POLICY_EXPRESSION(col);
250
+ raw = CUSTOMER_POLICY_EXPRESSION(col);
245
251
  }
246
252
  // The rendering assumes the frozen layout; if that ever changes, refuse rather than emit a policy re-indented
247
253
  // into something check would then call "the generator's".
@@ -9,8 +9,10 @@
9
9
  * module.exports = defineTenancy({ PARTNER, PLATFORM, PARTNER_NULLABLE, EXCLUDED,
10
10
  * PLATFORM_POSTGRES_ONLY, WIDEN_UNIQUE, ... });
11
11
  *
12
- * ANY OTHER KEY PASSES THROUGH UNTOUCHED — an app with a customer tier keeps its own map and its
13
- * own expression for it, and an app without a `GLOBAL_BY_VALUE` bucket simply passes none.
12
+ * ANY OTHER KEY PASSES THROUGH UNTOUCHED — an app with a customer tier keeps its own CUSTOMER map,
13
+ * and an app without a `GLOBAL_BY_VALUE` bucket simply passes none. Since 0.30.0 the customer tier's
14
+ * policy text is the package's too (CUSTOMER_POLICY_EXPRESSION below): a manifest's own function is
15
+ * accepted only when it produces exactly that text.
14
16
  */
15
17
 
16
18
  'use strict';
@@ -44,6 +46,56 @@ const POLICY_EXPRESSION = `
44
46
  ELSE partner_id = current_setting('app.partner_id')::int
45
47
  END`;
46
48
 
49
+ /**
50
+ * 0.30.0 — the predicate for a CUSTOMER table (a table in the manifest's CUSTOMER map, table → the column naming its
51
+ * customer), VERBATIM for both USING and WITH CHECK. POLICY_EXPRESSION's two arms unchanged, plus:
52
+ *
53
+ * WHEN 'customer' a session pinned to one customer (customerPin.js: the worker sets app.scope = 'customer' and
54
+ * app.customer_id inside the invoke's transaction): its partner AND its customer. BOTH lookups
55
+ * STRICT, for the reason POLICY_EXPRESSION gives. A pin that lost its customer ERRORS OR MATCHES
56
+ * NOTHING — it errors on a connection that never set app.customer_id, and matches nothing on a
57
+ * pooled one an earlier transaction set it on (the setting then reads ''). It never widens.
58
+ *
59
+ * Partner-only tables need no change for the pin: their ELSE arm already reads 'customer' as "this partner".
60
+ *
61
+ * FROZEN, like POLICY_EXPRESSION, and for the same reason: this text is inside migrations an app has applied (the
62
+ * first app with a customer tier, from its 022 on). test/tenancyManifest.js pins its sha256 for the column
63
+ * `customer_id`, and test/tenancyGenerator.js rebuilds that app's applied policies from THIS function byte for byte.
64
+ * `column` is interpolated, so it must be a plain column name.
65
+ */
66
+ const CUSTOMER_POLICY_EXPRESSION = (column) => {
67
+ if (typeof column !== 'string' || !/^[a-z_][a-z0-9_]*$/.test(column)) {
68
+ throw new Error(`CUSTOMER_POLICY_EXPRESSION: ${JSON.stringify(column)} is not a plain column name`);
69
+ }
70
+ return `
71
+ CASE current_setting('app.scope', true)
72
+ WHEN 'platform' THEN true
73
+ WHEN 'customer' THEN partner_id = current_setting('app.partner_id')::int
74
+ AND ${column} = current_setting('app.customer_id')
75
+ ELSE partner_id = current_setting('app.partner_id')::int
76
+ END`;
77
+ };
78
+
79
+ /**
80
+ * A manifest's OWN customer policy function, held to the package's: it must produce the package's text for every
81
+ * column its CUSTOMER map names, and for the probe column `customer_id`. Throws, naming the first column that
82
+ * differs. The caller then uses the package's function.
83
+ */
84
+ function assertSameCustomerPolicy(fn, customer, name) {
85
+ if (typeof fn !== 'function') {
86
+ throw new Error(`${name}: CUSTOMER_POLICY_EXPRESSION must be a function (column) => text, or left out (the package supplies it)`);
87
+ }
88
+ const cols = new Set(['customer_id', ...Object.values(customer || {})]);
89
+ for (const c of cols) {
90
+ let theirs;
91
+ try { theirs = fn(c); } catch (e) { theirs = e; }
92
+ if (theirs !== CUSTOMER_POLICY_EXPRESSION(c)) {
93
+ throw new Error(`${name}: its CUSTOMER_POLICY_EXPRESSION(${JSON.stringify(c)}) is not the package's frozen customer policy text `
94
+ + '(the policy applied migrations carry). Remove it from the manifest; the package supplies it.');
95
+ }
96
+ }
97
+ }
98
+
47
99
  /** The four lists that together are "every table with a decision" — what `all()` returns. */
48
100
  const DECIDED = ['PARTNER', 'PLATFORM', 'PARTNER_NULLABLE', 'EXCLUDED'];
49
101
 
@@ -73,6 +125,17 @@ function defineTenancy(lists) {
73
125
  if (lists.PLATFORM_POSTGRES_ONLY !== undefined && !isMap(lists.PLATFORM_POSTGRES_ONLY)) {
74
126
  throw new Error('defineTenancy: PLATFORM_POSTGRES_ONLY must be a { table: reason } map');
75
127
  }
128
+ // 0.30.0 — the customer tier. CUSTOMER is the app's ({ table: column }); its policy text is the package's.
129
+ if (lists.CUSTOMER !== undefined) {
130
+ if (!isMap(lists.CUSTOMER)) throw new Error('defineTenancy: CUSTOMER must be a { table: customer column } map');
131
+ for (const [t, c] of Object.entries(lists.CUSTOMER)) {
132
+ if (typeof c !== 'string' || !/^[a-z_][a-z0-9_]*$/.test(c)) {
133
+ throw new Error(`defineTenancy: CUSTOMER.${t} must name its customer column, not ${JSON.stringify(c)}`);
134
+ }
135
+ }
136
+ }
137
+ const ownCustomerPolicy = Object.prototype.hasOwnProperty.call(lists, 'CUSTOMER_POLICY_EXPRESSION');
138
+ if (ownCustomerPolicy) assertSameCustomerPolicy(lists.CUSTOMER_POLICY_EXPRESSION, lists.CUSTOMER, 'defineTenancy');
76
139
 
77
140
  const out = { ...lists };
78
141
  for (const k of DECIDED) if (out[k] === undefined) out[k] = {};
@@ -97,6 +160,9 @@ function defineTenancy(lists) {
97
160
  }
98
161
 
99
162
  out.POLICY_EXPRESSION = POLICY_EXPRESSION;
163
+ // Only for a manifest with a customer tier (or one that brought its own, equal, function): a manifest without one
164
+ // gets exactly the keys it got before.
165
+ if (lists.CUSTOMER !== undefined || ownCustomerPolicy) out.CUSTOMER_POLICY_EXPRESSION = CUSTOMER_POLICY_EXPRESSION;
100
166
  /** Every table with a decision, in any list — what the classification guard checks against. */
101
167
  out.all = () => [
102
168
  ...Object.keys(PARTNER),
@@ -112,4 +178,6 @@ function defineTenancy(lists) {
112
178
  return out;
113
179
  }
114
180
 
115
- module.exports = { defineTenancy, TENANCY_POLICY_EXPRESSION: POLICY_EXPRESSION };
181
+ module.exports = {
182
+ defineTenancy, TENANCY_POLICY_EXPRESSION: POLICY_EXPRESSION, CUSTOMER_POLICY_EXPRESSION, assertSameCustomerPolicy
183
+ };
package/worker.js CHANGED
@@ -20,6 +20,8 @@
20
20
  const { parentPort, workerData } = require('worker_threads');
21
21
  const { performance } = require('perf_hooks');
22
22
  const { runWithTenant, APPLY_SQL, applyParams } = require('./tenantContext');
23
+ const { PIN_SQL, pinParams, runPinned } = require('./customerPin');
24
+ const { isCustomerScope, ownMethod, refused } = require('./customerScope');
23
25
 
24
26
  /**
25
27
  * The driver, or null before the app's init() has opened one. Read per call rather than cached:
@@ -43,7 +45,7 @@ function currentDriver() {
43
45
  * On a serial driver (SQLite) there is no RLS and nothing to set. The context is still
44
46
  * established so a model can read it, and no transaction is forced around a read.
45
47
  */
46
- async function withTenant(tenant, label, dispatch, { outsideTransaction = false } = {}) {
48
+ async function withTenant(tenant, label, dispatch, { outsideTransaction = false, pin = null } = {}) {
47
49
  const driver = currentDriver();
48
50
  if (!driver || driver.concurrency !== 'pool') {
49
51
  return tenant ? runWithTenant(tenant, dispatch) : dispatch();
@@ -65,6 +67,9 @@ async function withTenant(tenant, label, dispatch, { outsideTransaction = false
65
67
  if (outsideTransaction) return runWithTenant(tenant, dispatch);
66
68
  return runWithTenant(tenant, () => driver.transaction(async (tx) => {
67
69
  await tx.run(APPLY_SQL, applyParams(tenant));
70
+ // 0.30.0 — a customer-pinned invoke (customerPin.js): narrowed to the customer AFTER the tenant's own settings, in
71
+ // the same transaction. Only when a pin came in the message; an unpinned invoke sends exactly what it always did.
72
+ if (pin) await tx.run(PIN_SQL, pinParams(pin));
68
73
  return dispatch();
69
74
  }));
70
75
  }
@@ -72,11 +77,16 @@ async function withTenant(tenant, label, dispatch, { outsideTransaction = false
72
77
  /**
73
78
  * @param {Object} opts
74
79
  * @param {(workerData: any) => Object} opts.init - App boot; returns the model registry
80
+ * @param {(models: Object) => Object} [opts.customerScope] - 0.30.0: given the registry once after init, returns
81
+ * createCustomerScope({ safe, models }). Without it every customer-pinned invoke is refused.
75
82
  */
76
- async function runWorker({ init }) {
83
+ async function runWorker({ init, customerScope } = {}) {
77
84
  if (typeof init !== 'function') {
78
85
  throw new Error('runWorker({ init }): init must be a function (workerData) => modelRegistry');
79
86
  }
87
+ if (customerScope !== undefined && typeof customerScope !== 'function') {
88
+ throw new Error('runWorker({ customerScope }): customerScope must be a function (models) => createCustomerScope({ safe, models })');
89
+ }
80
90
 
81
91
  try {
82
92
  // AWAITED since 0.6.0. An app's init opens the database and runs migrations, and on
@@ -84,6 +94,11 @@ async function runWorker({ init }) {
84
94
  // model registry and serve queries against an unmigrated database. `await` on a synchronous
85
95
  // init returns the same object it always did, so the SQLite path is unchanged.
86
96
  const models = (await init(workerData)) || {};
97
+ let customer = null;
98
+ if (customerScope) {
99
+ customer = await customerScope(models);
100
+ if (!isCustomerScope(customer)) throw new Error('runWorker({ customerScope }): it must return createCustomerScope({ safe, models })');
101
+ }
87
102
 
88
103
  parentPort.postMessage({ type: 'ready' });
89
104
 
@@ -120,7 +135,7 @@ async function runWorker({ init }) {
120
135
  });
121
136
 
122
137
  async function handle(msg) {
123
- const { id, model, method, args, tenant } = msg;
138
+ const { id, model, method, args, tenant, pin } = msg;
124
139
  // Worker-side execution time, shipped back so the client's slow-call log
125
140
  // attributes slowness to the query that WAS slow, not to calls that were
126
141
  // merely queued behind it. Monotonic clock: a wall-clock (Date.now) delta
@@ -133,13 +148,33 @@ async function runWorker({ init }) {
133
148
  throw new Error(`Unknown method: ${model}.${method}`);
134
149
  }
135
150
 
136
- let result = await withTenant(tenant, `${model}.${method}`, async () => {
151
+ // ONE dispatch, from THIS worker's registry, for an unpinned and a pinned call alike.
152
+ const dispatch = async () => {
137
153
  let r = target[method](...(args || []));
138
154
  if (r && typeof r.then === 'function') {
139
155
  r = await r; // async methods (e.g. bcrypt-backed user ops)
140
156
  }
141
157
  return r;
142
- }, { outsideTransaction: target[method].outsideTransaction === true });
158
+ };
159
+ let result;
160
+ if (pin !== undefined) {
161
+ // 0.30.0 — CUSTOMER-PINNED (customerPin.js). Every refusal happens here, before a transaction is opened. The
162
+ // scope only DECIDES (pin, tenant, safe list); what runs is target[method] above, from this registry.
163
+ if (!customer) {
164
+ throw refused(`db-worker: ${model}.${method} arrived pinned to a customer, and this worker has no customerScope (runWorker({ customerScope }))`);
165
+ }
166
+ const call = customer.prepare(pin, tenant, model, method);
167
+ if (ownMethod(models, model, method) !== target[method]) {
168
+ throw refused(`CustomerScope: ${model}.${method} is not the model's own method in this worker's registry`);
169
+ }
170
+ if (target[method].outsideTransaction === true) {
171
+ throw refused(`CustomerScope: ${model}.${method} runs outside a transaction, where a customer pin cannot apply`);
172
+ }
173
+ result = await withTenant(tenant, `${model}.${method}`, () => runPinned(call.pin, dispatch), { pin: call.pin });
174
+ } else {
175
+ result = await withTenant(tenant, `${model}.${method}`, dispatch,
176
+ { outsideTransaction: target[method].outsideTransaction === true });
177
+ }
143
178
 
144
179
  result = sanitizeForTransfer(result);
145
180
  parentPort.postMessage({ id, result, execMs: Math.round(performance.now() - t0) });