@aria-framework/db-worker 0.29.0 → 0.31.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 +216 -0
- package/bin/tenancy.js +21 -1
- package/client.js +22 -2
- package/customerPin.js +144 -0
- package/customerScope.js +115 -0
- package/dialect.js +66 -0
- package/index.js +14 -1
- package/package.json +6 -2
- package/tableDefinitions.js +603 -0
- package/tableDefinitionsCheck.js +204 -0
- package/tenancyGenerator.js +278 -34
- package/tenancyManifest.js +113 -3
- package/worker.js +40 -5
package/README.md
CHANGED
|
@@ -700,8 +700,224 @@ 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
|
+
|
|
764
|
+
## Table definitions as data (0.31.0)
|
|
765
|
+
|
|
766
|
+
A package that needs tables in the app's database (a shared feature's grants, requests, settings) cannot apply SQL
|
|
767
|
+
from `node_modules` (a second ledger, and an upgrade would change an applied file) and must not create tables at boot.
|
|
768
|
+
So it ships the tables as a DEFINITION SET, and the app's own generator writes them into the app's own migration pair,
|
|
769
|
+
which the app commits, applies and never edits, like any other.
|
|
770
|
+
|
|
771
|
+
```js
|
|
772
|
+
// in the package
|
|
773
|
+
const { defineTables } = require('@aria-framework/db-worker');
|
|
774
|
+
module.exports = defineTables({
|
|
775
|
+
name: 'access', version: '1.0.0',
|
|
776
|
+
comment: ['what these tables are for — carried into the migration as its comment block'],
|
|
777
|
+
anchors: { // tables the APP owns that this set relies on, what they are, and what the set needs of them
|
|
778
|
+
customers: { tenancy: { customer: 'id' }, columns: [{ name: 'id', type: 'TEXT', notNull: true }, { name: 'partner_id', type: 'PARTNER_ID', notNull: true }],
|
|
779
|
+
unique: [['id', 'partner_id']] }
|
|
780
|
+
},
|
|
781
|
+
tables: [{
|
|
782
|
+
name: 'grants', description: 'a customer letting its helper in for a while', tenancy: { customer: 'customer_id' },
|
|
783
|
+
columns: [
|
|
784
|
+
{ name: 'level', type: 'TEXT', notNull: true, check: "level IN ('look', 'change')" },
|
|
785
|
+
{ name: 'given_by', type: { postgres: 'BIGINT', sqlite: 'INTEGER' } },
|
|
786
|
+
{ name: 'state', type: 'TEXT', notNull: true, default: { text: 'live' } },
|
|
787
|
+
{ name: 'ended_at', type: 'TEXT' }
|
|
788
|
+
],
|
|
789
|
+
constraints: [{ name: 'ck_grants_ended', check: "(state = 'live') = (ended_at IS NULL)" }]
|
|
790
|
+
}],
|
|
791
|
+
indexes: [{ name: 'uq_grants_live', table: 'grants', unique: true, columns: ['customer_id', 'partner_id'], where: "state = 'live'" }]
|
|
792
|
+
});
|
|
793
|
+
|
|
794
|
+
// in the app's config/tenancy.js — all its sets in ONE call
|
|
795
|
+
module.exports = defineTenancy({ PARTNER: {...}, PLATFORM: {...}, CUSTOMER: {...}, ...tenancyFragment(accessTables) });
|
|
796
|
+
```
|
|
797
|
+
|
|
798
|
+
```
|
|
799
|
+
npx aria-tenancy new --definitions access [--name <slug>] [--number <NNN> [--fill-gap]] [--print]
|
|
800
|
+
npx aria-tenancy check
|
|
801
|
+
```
|
|
802
|
+
|
|
803
|
+
| Export | What it does | What it refuses |
|
|
804
|
+
|---|---|---|
|
|
805
|
+
| `defineTables(set)` | validates the set and returns a deep-frozen copy | each refusal has a code (`err.refusal`, the list is `REFUSALS` in `tableDefinitions.js`): a name that is not a plain identifier (or is over 63 characters); a reserved word of PostgreSQL or SQLite (`RESERVED`: PostgreSQL's reserved key words and every SQLite keyword, e.g. `user`, `order`, `key`); a table whose name makes a name the GENERATOR writes for it (`uq_…`, `fk_…`, `idx_…`) longer than 63 bytes — PostgreSQL would truncate it; a name used twice or one the generator writes; a unique key or unique index without `partner_id`; a PARTNER-only table with a column named `customer_id` (or like any CUSTOMER table's customer column in the set), or with a key into customer data — a CUSTOMER table of the set or a CUSTOMER anchor (a PARTNER table keys only into PARTNER tables and PARTNER anchors); an anchor without its tenancy (`'PARTNER'`, or `{ customer: <column> }` naming one of its columns; `customers` is always `{ customer: 'id' }`); an anchor named `users`; two string literals side by side; a column the generator writes (`id`, `partner_id`, the customer column, `created_at`); a type other than `TEXT`, `INTEGER`, `BIGINT` (or `{ postgres, sqlite }` of them); a default other than `{ text }`, `{ integer }`, `{ utcNow: true }` or one that does not fit its type; an expression (a CHECK, an index's WHERE) using anything but its table's columns, literals, the comparison and arithmetic operators, `AND OR NOT IN IS NULL BETWEEN LIKE TRUE FALSE` and `length lower upper`; a key into a table that is neither in the set nor an anchor, whose sides differ in length, without `partner_id` at the same position on both sides, or into columns that are not a unique key of the target; `ON DELETE` / `ON UPDATE` other than `NO ACTION`, `RESTRICT`, `CASCADE`; an anchor without `partner_id` (type `PARTNER_ID`, not null); a CUSTOMER table without the anchor `customers (id, partner_id)` and that key |
|
|
806
|
+
| `tenancyFragment(...sets)` | `{ TABLE_DEFINITIONS: [...sets] }`, for the app to spread into `defineTenancy` | a value not built with `defineTables`, a set passed twice, a table in two sets |
|
|
807
|
+
| `defineTenancy({ ..., TABLE_DEFINITIONS })` | classifies each defined table: `PARTNER` (its description as the reason), and `CUSTOMER` with its column; a set's customer tables give a manifest a `CUSTOMER` map (and the package's policy text) | the app classifying a defined table differently: in `PLATFORM`, `PARTNER_NULLABLE`, `EXCLUDED` or `PLATFORM_POSTGRES_ONLY`, with another customer column, or as a customer table where the set has none. Listing it exactly as the set does is accepted |
|
|
808
|
+
| `classificationOf(set)` | `{ PARTNER, CUSTOMER }` of the set's tables | |
|
|
809
|
+
| `aria-tenancy new --definitions <set>` | writes the set's pair: the generator's header naming the set, its version and the layout, the set's comment, each `CREATE TABLE` with the skeleton's generated parts and the set's own columns and constraints, the set's indexes after the tables, and on Postgres the generated ENABLE, FORCE and policy — the same writer and the same tenancy as a hand-filled skeleton. `--print` writes nothing | a set the manifest does not carry, table names beside it, a set some migration already names (a set is generated once), everything `new` refuses for its tables, an anchor that is the app's `principalTable`, and a pair that would fail `aria-tenancy check` (for example a key without `ON UPDATE CASCADE` in an app with `requireUpdateCascade`) |
|
|
810
|
+
| `aria-tenancy check` | additionally holds every policed pair whose first line names a set WHOLE, header line included, BYTE FOR BYTE (CRLF read as LF) to the output of the layout that first line names, for the set the manifest carries. A FROZEN file that names the set (on any line) counts as its pair and is not compared | a set the manifest carries that no pair generates; a pair generated from another version of it; a pair naming a set the manifest does not carry; a layout this db-worker does not have; a file that differs (the message says: restore it, or, if unedited, the set changed without a new version) |
|
|
811
|
+
| `checkDefinedSchema(driver, sets, { partnerIdType })` | compares the database with the sets, through the driver and the dialect's introspection; returns `{ problems, compared }` (counts of tables, columns, keys, indexes, policies and anchors looked at) | a driver, a set or (on Postgres) a `partnerIdType` missing |
|
|
812
|
+
| `assertDefinedSchema(...)` | the same, throwing `TABLE_DEFINITIONS_MISMATCH` naming every problem: what a package calls when the app starts | |
|
|
813
|
+
|
|
814
|
+
**A definitions file is frozen, and so is the layout that wrote it.** Its first line reads, for example,
|
|
815
|
+
|
|
816
|
+
```
|
|
817
|
+
-- 099_demo.postgres.sql — GENERATED from the table definitions demo 1.2.0, layout 1 (aria-tenancy new --definitions demo).
|
|
818
|
+
```
|
|
819
|
+
|
|
820
|
+
and `check` compares the whole file with what THAT layout writes. A layout's output is a function of the set (name,
|
|
821
|
+
version, tables, indexes, anchors, comment), the frozen policy texts, the app's `partnerIdType` and the file's own
|
|
822
|
+
name — never of the manifest's path, the app's folders or when it runs — so an applied file stays equal to its
|
|
823
|
+
layout for ever. Two rules follow:
|
|
824
|
+
|
|
825
|
+
- **Changing any part of a set, its comment included, needs a new version.** `defineTables` cannot know that a
|
|
826
|
+
comment changed; `check` then reports the applied file as different, and its message names that possibility.
|
|
827
|
+
- **Changing how a definitions file is written is a NEW LAYOUT**, never an edit of layout 1: layout 1's output for
|
|
828
|
+
four fixture sets (one of them, `test/fixtures/tenancy-definitions-edge.js`, exists to take every branch of the writer
|
|
829
|
+
the others do not; the branch table is above the pins) is pinned by sha256 in `test/tableDefinitions.js` ("this text is inside migrations apps have
|
|
830
|
+
applied"), so a change to the shared writers that alters it fails the package's own tests. The new layout gets its
|
|
831
|
+
number; layout 1 stays in `tenancyGenerator.js` (`LAYOUTS`) for the files it wrote, selected by their first line.
|
|
832
|
+
|
|
833
|
+
An app that later puts a generated pair in its `frozen` list, or squashes it into a frozen baseline, keeps the pair's
|
|
834
|
+
first line somewhere in a frozen file: `check` then counts that file as the set's pair and does not compare it (the
|
|
835
|
+
app pins it). A squash that drops the line leaves the set "not generated".
|
|
836
|
+
|
|
837
|
+
**Conventions for a package author.** A column naming a user is a plain column with no key (as the reproduced
|
|
838
|
+
migrations have it): a key into the principal table is attribution, and `defineTables` refuses an anchor named
|
|
839
|
+
`users` (and `new` the app's own `principalTable`). Whether a set's keys pass an app's `requireUpdateCascade` /
|
|
840
|
+
`NO_CASCADE` rules is found when that app generates, not in `defineTables`: write every key of a set `ON UPDATE
|
|
841
|
+
CASCADE` — an app that re-parents rows (`requireUpdateCascade`) requires it of every key that is not attribution, and
|
|
842
|
+
an app that does not accepts it — and have no attribution keys at all (a user is a plain column, above), so no app's
|
|
843
|
+
`NO_CASCADE` can name one.
|
|
844
|
+
|
|
845
|
+
A customer's id is held only in the table's declared customer column (`tenancy: { customer }`): a PARTNER table that
|
|
846
|
+
holds a customer's id under another name (`client_id`) cannot be caught by name — that is the author's error and the
|
|
847
|
+
reviewer's to catch.
|
|
848
|
+
|
|
849
|
+
The reserved-word refusal covers common names an author may reach for: `key`, `action`, `index`, `plan`, `row`,
|
|
850
|
+
`filter`, `first`, `last`, `desc`, `query`, `match`, `range`, `current`, `database`, `temp`, `view`, `values`,
|
|
851
|
+
`generated` (and `user`, `order`, `group`, …). Name them `key_name`, `row_count` and so on.
|
|
852
|
+
|
|
853
|
+
**Expressions that mean different things on the two engines, with no error on either** (the tokenizer cannot see
|
|
854
|
+
these; write CHECKs and WHERE clauses with `IN` lists, `=` / `<>`, numbers and `length`):
|
|
855
|
+
- a comparison of TEXT with `<` / `>` (or `BETWEEN` on text) follows collation: the PostgreSQL database's locale
|
|
856
|
+
against SQLite's byte order;
|
|
857
|
+
- `LIKE` is case-sensitive only on PostgreSQL (SQLite ignores ASCII case); `lower` / `upper` differ on non-ASCII text.
|
|
858
|
+
|
|
859
|
+
String literals assume `standard_conforming_strings` is on (the PostgreSQL default): a backslash is an ordinary
|
|
860
|
+
character inside `'…'`. A parenthesised operand of `BETWEEN` is accepted (`v BETWEEN (1) AND 2`).
|
|
861
|
+
|
|
862
|
+
**What the schema check compares.** Per defined table: it exists; every column (defined and generated) with its type
|
|
863
|
+
and NOT NULL; `partner_id`'s DEFAULT against the one the generator writes (a default changed by hand would put a
|
|
864
|
+
platform-scope insert into the wrong partner); the primary key `id`; the unique keys; the named indexes (unique or not, columns in order, partial or
|
|
865
|
+
not); the foreign keys (columns, target, target columns, both actions); and on Postgres ENABLE and FORCE, exactly one
|
|
866
|
+
policy, `tenant_isolation`, PERMISSIVE, FOR ALL, TO public, its USING and WITH CHECK the package's frozen text. **Any
|
|
867
|
+
column, unique key, named index, key or policy the set does not have is a problem too**: a column an app adds to a
|
|
868
|
+
package's table is reported, because the package's code and migration do not know it. Per anchor: the stated columns
|
|
869
|
+
(type, NOT NULL) and a primary key, unique constraint or unique non-partial index on each stated key (any column
|
|
870
|
+
order); its other columns are the app's. **What it does not compare:** CHECK constraints and the other defaults (the engines
|
|
871
|
+
rewrite their text), an index's WHERE text (only that it is partial), and the policy text beyond parentheses,
|
|
872
|
+
whitespace and the casts the server adds (the server keeps a policy deparsed), so a policy differing only in
|
|
873
|
+
parenthesisation would pass; `aria-tenancy check` holds the file itself byte for byte. SQLite has no policies, and the
|
|
874
|
+
result says so (`compared.policies` is 0).
|
|
875
|
+
|
|
876
|
+
**Dialect introspection added** (`dialectFor(kind)`, both engines, one row shape): `columnDetails(table)`,
|
|
877
|
+
`indexes(table)`, `keyColumns(table)`, `policies(table)` (null on SQLite). `columns()` and `foreignKeys()` are
|
|
878
|
+
unchanged. On Postgres `foreignKeys()` joins its catalogue views by constraint name only, so a key of n columns answers
|
|
879
|
+
n × n rows, and it reads a view that lists only tables the current role owns, so an app role that owns nothing gets
|
|
880
|
+
no rows; both measured in `test/tableDefinitions.pglite.js`. `keyColumns()` pairs by position from `pg_constraint`.
|
|
881
|
+
|
|
882
|
+
**What the format cannot express**, refused rather than approximated: a primary key other than `id`; a table without
|
|
883
|
+
`created_at`; another column type; `SET NULL` or `SET DEFAULT` actions (SQLite cannot name a `SET NULL` column, a bare
|
|
884
|
+
one nulls `partner_id`, `SET DEFAULT` re-parents a row); a key into a table outside the set and its anchors (so never
|
|
885
|
+
into `users`); a `PARTNER_NULLABLE` table; and any change to tables that exist — a set is created once, and a changed
|
|
886
|
+
version is reported by `check`, not generated (there is no upgrade path yet).
|
|
887
|
+
|
|
888
|
+
`test/tableDefinitions.js` reproduces one app's applied 053 and 054 (four files) from a definition fixture
|
|
889
|
+
(`test/fixtures/tenancy-definitions-wall.js`): every line of each body is the generator's but for 053's own-column
|
|
890
|
+
lines, which that app aligned by hand two spaces wider (the residue is derived from the definitions and checked), the
|
|
891
|
+
header its own generator wrote, and the row-level-security heading, which named its manifest's path (layout 1 never
|
|
892
|
+
writes one). It also runs every refusal with an accepted control, holds manifests without sets
|
|
893
|
+
and every skeleton to the hashes origin/main produced, runs the SQLite twins and the command. `test/tableDefinitions.pglite.js`
|
|
894
|
+
applies the generated Postgres files on PGlite as a role the policies apply to (partner and customer-pinned reads,
|
|
895
|
+
cross-partner references refused by the composite keys) and plants a difference of each kind for the schema check.
|
|
896
|
+
|
|
703
897
|
## Changelog
|
|
704
898
|
|
|
899
|
+
- **0.31.0** — Table definitions as data (above): `defineTables`, `tenancyFragment`, `classificationOf`,
|
|
900
|
+
`isTableDefinitions`, `TableDefinitionError`, `checkDefinedSchema`, `assertDefinedSchema`; `defineTenancy` reads
|
|
901
|
+
`TABLE_DEFINITIONS`; `aria-tenancy new --definitions <set>`, and `check` holds generated pairs byte for byte; the
|
|
902
|
+
library `tenancyGenerator.js` gains `renderDefinitions`, `planDefinitions`, `definitionSets`, `DEFINED_HEAD`,
|
|
903
|
+
`CURRENT_LAYOUT`, `DEFINITION_LAYOUTS` (layout 1, frozen and pinned); the
|
|
904
|
+
dialects gain `columnDetails`, `indexes`, `keyColumns`, `policies`. Additive: a manifest without `TABLE_DEFINITIONS`
|
|
905
|
+
gets exactly the keys and values it got before, the skeleton and `check` render and answer byte for byte as before
|
|
906
|
+
(hashed against origin/main in `test/tableDefinitions.js`), and the skeleton's table writer is now the one writer
|
|
907
|
+
both use. Tests (in `npm test`): `tableDefinitions.js`, `tableDefinitions.pglite.js`.
|
|
908
|
+
|
|
909
|
+
- **0.30.0** — The customer pin (above), moved in from the first app that built it: `runPinned`, `runUnpinnedFor`,
|
|
910
|
+
`currentPin`, `activePin`, `pinnedCustomer`, `pinClause`, `normalisePin`, `isPinId`, `PIN_SQL`, `pinParams`;
|
|
911
|
+
`createCustomerScope`; the `DbClient` option `customerPin` and the `runWorker` option `customerScope`;
|
|
912
|
+
`CUSTOMER_POLICY_EXPRESSION` (frozen) and `assertSameCustomerPolicy`. Additive for an app without a customer tier:
|
|
913
|
+
an unpinned invoke's message and statements are byte for byte what they were. **One behaviour change**, for a
|
|
914
|
+
manifest with a customer tier: its own `CUSTOMER_POLICY_EXPRESSION` must produce the package's text (it passed
|
|
915
|
+
through `defineTenancy` untouched before, and the generator rendered it), and `defineTenancy` refuses a `CUSTOMER`
|
|
916
|
+
value that is not a column name; a manifest with a `CUSTOMER` map and no function now gets the package's text
|
|
917
|
+
(the generator threw before). Only one app has a customer tier, and its function produces the package's text.
|
|
918
|
+
Tests (in `npm test`): `customerPin.js` (a real worker, the recording driver), `customerPin.pglite.js` (a real
|
|
919
|
+
worker over PGlite, real row-level security as a non-owner, non-superuser role), and new checks in
|
|
920
|
+
`tenancyManifest.js` and `tenancyGenerator.js`.
|
|
705
921
|
- **0.29.0** — The tenancy core (above), additive: `sql`, `defineTenancy` + `TENANCY_POLICY_EXPRESSION`,
|
|
706
922
|
`assertPlatformScope`, `assertPartnerScope`, `keepTenant`, `tenantCacheKey`, `createTenantSettings`, the
|
|
707
923
|
`DbClient` option `onRefusal` and `runMigrations`' `squashedFrom`. And the **`aria-tenancy` command** (`bin`,
|
package/bin/tenancy.js
CHANGED
|
@@ -4,6 +4,9 @@
|
|
|
4
4
|
*
|
|
5
5
|
* aria-tenancy new <table...> [--name <slug>] [--number <NNN> [--fill-gap]] write a NEW .sql / .postgres.sql pair
|
|
6
6
|
* aria-tenancy new --print <table...> print the generated statements; write nothing
|
|
7
|
+
* aria-tenancy new --definitions <set> [--name …] [--number …] [--print]
|
|
8
|
+
* 0.31.0: write (or print) the pair for a package's
|
|
9
|
+
* table definitions the manifest carries
|
|
7
10
|
* aria-tenancy check exit 1 unless every policed migration carries
|
|
8
11
|
* exactly the generated statements
|
|
9
12
|
*
|
|
@@ -17,7 +20,8 @@ const fs = require('fs');
|
|
|
17
20
|
const path = require('path');
|
|
18
21
|
const gen = require('../tenancyGenerator');
|
|
19
22
|
|
|
20
|
-
const USAGE = 'usage: aria-tenancy new <table...> [--name <slug>] [--number <NNN> [--fill-gap]] [--print]\n
|
|
23
|
+
const USAGE = 'usage: aria-tenancy new <table...> [--name <slug>] [--number <NNN> [--fill-gap]] [--print]\n'
|
|
24
|
+
+ ' aria-tenancy new --definitions <set> [--name <slug>] [--number <NNN> [--fill-gap]] [--print]\n aria-tenancy check';
|
|
21
25
|
const fail = (msg) => { console.error(`aria-tenancy: ${msg}`); process.exit(1); };
|
|
22
26
|
|
|
23
27
|
function appDir() {
|
|
@@ -49,6 +53,7 @@ if (command === 'check') {
|
|
|
49
53
|
console.log(`tenancy of the tables born after the frozen migrations (aria-tenancy check, ${config.migrationsName}/):`);
|
|
50
54
|
console.log(` ${stats.tables.length} scoped table(s) in ${config.manifestName} born after the frozen migrations; ${stats.created.length} created by a policed migration`);
|
|
51
55
|
console.log(` ${stats.statementsCompared} generated statement(s) compared, ${stats.keysChecked} key(s) into scoped tables checked (${stats.pgKeys} Postgres), across ${stats.files} policed migration file(s)`);
|
|
56
|
+
if (stats.definitionFiles !== undefined) console.log(` ${stats.definitionFiles} file(s) generated from table definitions held to the generator byte for byte`);
|
|
52
57
|
if (problems.length) {
|
|
53
58
|
for (const p of problems) console.log(` ✗ ${p}`);
|
|
54
59
|
console.log(`\n${problems.length} problem(s) — regenerate with aria-tenancy new; never hand-write tenancy.`);
|
|
@@ -72,8 +77,23 @@ const print = flag('print');
|
|
|
72
77
|
const fillGap = flag('fill-gap');
|
|
73
78
|
const name = opt('name');
|
|
74
79
|
const number = opt('number');
|
|
80
|
+
const definitions = opt('definitions');
|
|
75
81
|
if (argv.some((a) => a.startsWith('--'))) fail(`unknown option ${argv.find((a) => a.startsWith('--'))}\n${USAGE}`);
|
|
76
82
|
const tables = argv;
|
|
83
|
+
if (definitions !== null) {
|
|
84
|
+
// 0.31.0 — the tables are the set's; the pair is written whole or not at all, as below.
|
|
85
|
+
if (tables.length) fail(`--definitions takes no table names (the set names its tables), got ${tables.join(' ')}`);
|
|
86
|
+
try {
|
|
87
|
+
const { files } = gen.planDefinitions(config, manifest, definitions, { name, number, fillGap });
|
|
88
|
+
if (print) {
|
|
89
|
+
for (const [f, text] of Object.entries(files)) console.log(`-- ═══ ${f} ═══\n${text}`);
|
|
90
|
+
} else {
|
|
91
|
+
gen.writePair(config.migrationsDir, files);
|
|
92
|
+
console.log(` wrote ${Object.keys(files).map((f) => `${config.migrationsName}/${f}`).join(' and ')} — generated whole from ${definitions}; commit them and never edit them`);
|
|
93
|
+
}
|
|
94
|
+
} catch (e) { fail(e.message); }
|
|
95
|
+
process.exit(0);
|
|
96
|
+
}
|
|
77
97
|
if (!tables.length) fail(`name at least one table (classified in ${config.manifestName} first)`);
|
|
78
98
|
|
|
79
99
|
try {
|
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
|
-
|
|
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
|
+
};
|
package/customerScope.js
ADDED
|
@@ -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' };
|