@stonyx/orm 0.3.2-beta.153 → 0.3.2-beta.155
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 +319 -24
- package/dist/index.d.ts +1 -0
- package/dist/main.d.ts +116 -0
- package/dist/main.js +119 -0
- package/dist/manage-record.js +234 -9
- package/dist/orm-request.d.ts +121 -3
- package/dist/orm-request.js +211 -8
- package/dist/setup-rest-server.js +51 -5
- package/dist/standalone-db.js +17 -5
- package/dist/types/orm-types.d.ts +101 -0
- package/dist/utils.d.ts +44 -0
- package/dist/utils.js +47 -0
- package/package.json +1 -1
- package/src/index.ts +1 -0
- package/src/main.ts +123 -0
- package/src/manage-record.ts +253 -9
- package/src/orm-request.ts +218 -13
- package/src/setup-rest-server.ts +59 -6
- package/src/standalone-db.ts +17 -6
- package/src/types/orm-types.ts +106 -0
- package/src/types/stonyx-rest-server.d.ts +14 -1
- package/src/utils.ts +50 -0
package/dist/orm-request.js
CHANGED
|
@@ -2,6 +2,124 @@
|
|
|
2
2
|
* REST request handling and access enforcement for @stonyx/orm.
|
|
3
3
|
*
|
|
4
4
|
* ---------------------------------------------------------------------------
|
|
5
|
+
* THE `access()` CONTRACT: `access(request, { model, operation })`
|
|
6
|
+
* ---------------------------------------------------------------------------
|
|
7
|
+
* `auth()` calls your predicate with TWO arguments. The second is the access
|
|
8
|
+
* CONTEXT -- the structural facts about the request, which the framework
|
|
9
|
+
* already holds and which you should read INSTEAD of parsing anything:
|
|
10
|
+
*
|
|
11
|
+
* context.model The model this route was mounted for, as a model name:
|
|
12
|
+
* kebab-case, exactly as declared under
|
|
13
|
+
* `config.orm.paths.model` and keyed in the store --
|
|
14
|
+
* `'owner'`, `'animal'`, `'phone-number'`. NOT the
|
|
15
|
+
* pluralised, dasherized, mount-prefixed ROUTE name. It is
|
|
16
|
+
* read from the OrmRequest instance, fixed at mount time,
|
|
17
|
+
* and no request can influence it.
|
|
18
|
+
*
|
|
19
|
+
* context.operation The operation being authorised. Exactly one of the four
|
|
20
|
+
* verbs `'read'`, `'create'`, `'update'`, `'delete'` --
|
|
21
|
+
* no second vocabulary ON THIS PATH, and never an HTTP
|
|
22
|
+
* method name like `'GET'`. These are the same four
|
|
23
|
+
* strings the permission-array return shape is written in
|
|
24
|
+
* (`['read', 'create']`), because both come from the one
|
|
25
|
+
* `methodAccessMap` below.
|
|
26
|
+
*
|
|
27
|
+
* NOT the hook vocabulary. `HookContext.operation`
|
|
28
|
+
* (`src/hooks.ts`, documented under "Hook Context Object"
|
|
29
|
+
* in the README) carries `'list' | 'get' | 'create' |
|
|
30
|
+
* 'update' | 'delete'` on an identically-named key of an
|
|
31
|
+
* identically-shaped context object, and the access
|
|
32
|
+
* vocabulary collapses `list` and `get` into `'read'`. For
|
|
33
|
+
* one `GET /animals/1` a hook sees `'get'` and `access()`
|
|
34
|
+
* sees `'read'`, so a predicate cannot tell a collection
|
|
35
|
+
* read from a record read. `AccessOperation` makes
|
|
36
|
+
* `operation === 'get'` a compile error for a TypeScript
|
|
37
|
+
* consumer, because a predicate that stops matching falls
|
|
38
|
+
* through to the permission array -- the misreading is
|
|
39
|
+
* fail-open shaped.
|
|
40
|
+
*
|
|
41
|
+
* `undefined` when the dispatched method has no entry in
|
|
42
|
+
* that map. Express delivers `HEAD` to the `GET` handler,
|
|
43
|
+
* so this is reachable. It is left undefined rather than
|
|
44
|
+
* defaulted on purpose -- a fabricated `'read'` would turn
|
|
45
|
+
* an unclassified request into an authorised one. Treat
|
|
46
|
+
* `undefined` as "not classified" and deny.
|
|
47
|
+
*
|
|
48
|
+
* So a consumer writes `if (model === 'owner' && operation === 'read')`. There
|
|
49
|
+
* is no string to parse, no variant to miss, and no way to fail open through a
|
|
50
|
+
* URL shape nobody anticipated.
|
|
51
|
+
*
|
|
52
|
+
* WHAT THE CONTEXT DOES NOT TELL YOU: WHICH SURFACE. It names the model and
|
|
53
|
+
* the verb, not the route. Measured over the live router, six surfaces produce
|
|
54
|
+
* one identical context:
|
|
55
|
+
*
|
|
56
|
+
* GET /owners { model: 'owner', operation: 'read' }
|
|
57
|
+
* GET /owners/gina { model: 'owner', operation: 'read' }
|
|
58
|
+
* GET /owners/gina/pets { model: 'owner', operation: 'read' }
|
|
59
|
+
* GET /owners/gina/relationships/pets { model: 'owner', operation: 'read' }
|
|
60
|
+
* GET /owners/archived { model: 'owner', operation: 'read' }
|
|
61
|
+
* GET /owners/gina?include=pets { model: 'owner', operation: 'read' }
|
|
62
|
+
*
|
|
63
|
+
* So a rule that depends on the SUB-PATH still needs `request.path` -- which is
|
|
64
|
+
* mount-relative and query-free, and is the one read of argument one the
|
|
65
|
+
* warning below sanctions. This repo's own fixture has such a rule: its
|
|
66
|
+
* `/archived` deny cannot be expressed from the context alone, and a predicate
|
|
67
|
+
* migrated to context-only would silently drop it, turning a deny into an
|
|
68
|
+
* allow. The related-resource and `?include=` surfaces serve ANOTHER model's
|
|
69
|
+
* records under `model: 'owner'`, and the context gives no signal of that
|
|
70
|
+
* (abofs/stonyx-orm#196).
|
|
71
|
+
*
|
|
72
|
+
* `record` IS NOT IN THIS CONTEXT, deliberately. `auth()` runs after route
|
|
73
|
+
* matching but BEFORE any handler executes (`@stonyx/rest-server`
|
|
74
|
+
* `src/request.ts:58-60`), so nothing has been fetched yet -- supplying a
|
|
75
|
+
* record would force a pre-fetch on every request, a second store hit and an
|
|
76
|
+
* ordering change in the middle of an authorization path. It is also
|
|
77
|
+
* unnecessary: the FUNCTION return shape already is the per-record hook. Return
|
|
78
|
+
* `(record) => boolean` and the handlers apply it to every record the request
|
|
79
|
+
* touches. Auth-time and record-time are separate decision points.
|
|
80
|
+
*
|
|
81
|
+
* THE SECOND ARGUMENT IS ADDITIVE. JavaScript ignores extra arguments, so an
|
|
82
|
+
* existing `access(request)` predicate keeps working exactly as before. The
|
|
83
|
+
* warning immediately below is therefore still live: `request` is still
|
|
84
|
+
* argument ONE, and reading it is still how predicates fail open.
|
|
85
|
+
*
|
|
86
|
+
* To reach ANOTHER model's predicate -- e.g. to check an animal while servicing
|
|
87
|
+
* an owners route -- use the boot-time registry:
|
|
88
|
+
*
|
|
89
|
+
* const predicate = Orm.instance.getAccess('animal');
|
|
90
|
+
* if (!predicate) return deny;
|
|
91
|
+
* const verdict = predicate(request, { model: 'animal', operation: 'read' });
|
|
92
|
+
*
|
|
93
|
+
* `undefined` means NO PREDICATE COULD BE RESOLVED for that name -- which
|
|
94
|
+
* includes the case where the model has an access class that failed to load,
|
|
95
|
+
* because `setup-rest-server.ts` catches a load failure, warns, and publishes
|
|
96
|
+
* whatever partial map it had. It does NOT mean the model is unrestricted.
|
|
97
|
+
* Treat it as DENY, the same way `operation === undefined` is treated above.
|
|
98
|
+
*
|
|
99
|
+
* PASSING THE CONTEXT MAKES A MODEL-CORRECT ANSWER POSSIBLE. It does not make
|
|
100
|
+
* the answer model-correct on its own -- the resolved predicate has to READ it.
|
|
101
|
+
* Measured against this repo's own shipped access class, on a request express
|
|
102
|
+
* dispatched to `GET /owners/angela`, asked about ANIMALS:
|
|
103
|
+
*
|
|
104
|
+
* getAccess('animal')(ownersRequest, { model: 'animal', operation: 'read' })
|
|
105
|
+
* -> record => record.id !== 'angela' && record.id !== 'restricted'
|
|
106
|
+
*
|
|
107
|
+
* That is the OWNERS filter, and it returns `true` for animal 21 -- the record
|
|
108
|
+
* hidden on every animal surface. Under a mount that predicate recognises
|
|
109
|
+
* neither way it is worse: it falls through to
|
|
110
|
+
* `['read', 'create', 'update', 'delete']`, a full CRUD grant. Either way the
|
|
111
|
+
* context was supplied and the answer is not the animal answer, and it is wrong
|
|
112
|
+
* in the GRANTING direction, because that predicate is arity-1 and identifies
|
|
113
|
+
* its collection from the request. (The first of these is asserted on a live
|
|
114
|
+
* dispatch by AC9 in test/integration/orm-test.ts.)
|
|
115
|
+
*
|
|
116
|
+
* Every predicate in this repo and in every consumer tree is arity-1 on the day
|
|
117
|
+
* this ships, and the caller has no supported way to tell which kind it got --
|
|
118
|
+
* the boot-time arity warning that would surface it is abofs/stonyx-orm#213.
|
|
119
|
+
* So: pass the context, and do not treat a resolved predicate's answer as
|
|
120
|
+
* model-specific until that predicate has been migrated to read the context.
|
|
121
|
+
*
|
|
122
|
+
* ---------------------------------------------------------------------------
|
|
5
123
|
* DO NOT RECONSTRUCT THE REQUEST PATH INSIDE `access()`.
|
|
6
124
|
* ---------------------------------------------------------------------------
|
|
7
125
|
* `auth()` below hands your `access(request)` a raw transport artifact and asks
|
|
@@ -65,7 +183,7 @@ import { getPluralName } from './plural-registry.js';
|
|
|
65
183
|
import { getBeforeHooks, getAfterHooks } from './hooks.js';
|
|
66
184
|
import config from 'stonyx/config';
|
|
67
185
|
import log from 'stonyx/log';
|
|
68
|
-
import { isOrmRecord } from './utils.js';
|
|
186
|
+
import { isOrmRecord, NO_FREE_ID_ERROR } from './utils.js';
|
|
69
187
|
const methodAccessMap = {
|
|
70
188
|
GET: 'read',
|
|
71
189
|
POST: 'create',
|
|
@@ -558,7 +676,39 @@ export default class OrmRequest extends Request {
|
|
|
558
676
|
// is true for a record the request did not create. The map's size is the
|
|
559
677
|
// only O(1) signal that distinguishes an insert from an overwrite.
|
|
560
678
|
const slotsBefore = store.get(model)?.size ?? 0;
|
|
561
|
-
|
|
679
|
+
// THE ONE `createRecord` FAILURE THIS ROUTE ANSWERS RATHER THAN
|
|
680
|
+
// PROPAGATES, and it is narrow on purpose.
|
|
681
|
+
//
|
|
682
|
+
// `assignRecordId` throws when it cannot derive a free store key for a
|
|
683
|
+
// server-assigned id. Unguarded that rejection is auto-forwarded -- there
|
|
684
|
+
// is no catch here, none in @stonyx/rest-server's dispatcher
|
|
685
|
+
// (dist/request.js:41-70), and express 5 hands it to its default error
|
|
686
|
+
// handler, which serialises the STACK, with absolute install paths and the
|
|
687
|
+
// internal module graph, to an unauthenticated caller outside
|
|
688
|
+
// NODE_ENV=production. That is the hazard :553-558 already names in this
|
|
689
|
+
// file, and every sibling refusal in this handler returns an integer
|
|
690
|
+
// status instead. So this one returns 409, matching the client-duplicate
|
|
691
|
+
// refusal at :713: the caller asked for a record and the collection has no
|
|
692
|
+
// id to give it.
|
|
693
|
+
//
|
|
694
|
+
// MATCHED ON THE SHARED PREFIX, not on a literal, and NOT by catching
|
|
695
|
+
// everything: `createRecord` also throws for "ORM is not ready", a
|
|
696
|
+
// read-only view and an unregistered model store, and turning any of those
|
|
697
|
+
// into a 409 would report a configuration fault as a conflict. Anything
|
|
698
|
+
// else is re-thrown unchanged.
|
|
699
|
+
let created;
|
|
700
|
+
try {
|
|
701
|
+
created = createRecord(model, recordAttributes, { serialize: false, _skipAutoPersist: true });
|
|
702
|
+
}
|
|
703
|
+
catch (error) {
|
|
704
|
+
if (!(error instanceof Error) || !error.message.startsWith(NO_FREE_ID_ERROR))
|
|
705
|
+
throw error;
|
|
706
|
+
// Not silently. A collection that can no longer assign an id is a
|
|
707
|
+
// configuration fault (a non-injective id transform), and a bare 409
|
|
708
|
+
// with no diagnostic is indistinguishable from an ordinary duplicate.
|
|
709
|
+
log.error?.(`[@stonyx/orm] ${error.message}`);
|
|
710
|
+
return 409; // Conflict
|
|
711
|
+
}
|
|
562
712
|
const record = isOrmRecord(created) ? created : null;
|
|
563
713
|
if (!record)
|
|
564
714
|
return 500;
|
|
@@ -582,11 +732,32 @@ export default class OrmRequest extends Request {
|
|
|
582
732
|
//
|
|
583
733
|
// Both conditions are required and neither implies the other:
|
|
584
734
|
// createdNewSlot -- the store grew, so this request inserted rather
|
|
585
|
-
// than overwrote.
|
|
586
|
-
//
|
|
587
|
-
// last-INSERTED + 1,
|
|
588
|
-
//
|
|
589
|
-
//
|
|
735
|
+
// than overwrote. SURVIVOR AS OF #203, AND THAT IS
|
|
736
|
+
// WHAT THIS NOTE IS FOR. It used to be killable:
|
|
737
|
+
// `assignRecordId` returned last-INSERTED + 1, so a
|
|
738
|
+
// server-assigned id could land on an occupied slot,
|
|
739
|
+
// `createRecord` updated in place, and removing this
|
|
740
|
+
// half turned access-filter-enforcement-test.ts
|
|
741
|
+
// assertion 31 red. #203 closed that: the
|
|
742
|
+
// server-assigned path now walks past occupied keys,
|
|
743
|
+
// so no create reaching here can overwrite. Measured
|
|
744
|
+
// -- delete `createdNewSlot &&` below: `dev` gives
|
|
745
|
+
// 55 pass / 1 fail with assertion 31 RED, this tree
|
|
746
|
+
// gives 56 pass / 0 fail, GREEN.
|
|
747
|
+
// KEPT ANYWAY, AND NOT FOR THE OLD REASON. Without
|
|
748
|
+
// it a denied create becomes `store.remove` on a key
|
|
749
|
+
// the caller may have influenced, which :815-820
|
|
750
|
+
// records as having been an unauthenticated deletion
|
|
751
|
+
// primitive across the whole id space. BECOMES
|
|
752
|
+
// KILLABLE AGAIN the moment any caller-supplied id
|
|
753
|
+
// can reach `createRecord` from this handler --
|
|
754
|
+
// which is exactly what has-many.ts:65 and
|
|
755
|
+
// belongs-to.ts:45 already do for ANOTHER model's
|
|
756
|
+
// store (abofs/stonyx-orm#207), and what a third
|
|
757
|
+
// un-stripped id channel would do for this one
|
|
758
|
+
// (#204). Do not delete it on the strength of #203
|
|
759
|
+
// being closed; that is the reasoning :862-867 warns
|
|
760
|
+
// about, one level up.
|
|
590
761
|
// identity -- the slot still holds the object we just created,
|
|
591
762
|
// so nothing between createRecord and here replaced
|
|
592
763
|
// it. Deleting this half SURVIVES the suite, and it
|
|
@@ -1036,9 +1207,41 @@ export default class OrmRequest extends Request {
|
|
|
1036
1207
|
// answers 500 -- and the documented sample itself can throw
|
|
1037
1208
|
// (`request.originalUrl.split(...)` when originalUrl is absent), so the
|
|
1038
1209
|
// failure mode is reachable by following the docs.
|
|
1210
|
+
// -------------------------------------------------------------------------
|
|
1211
|
+
// #202 -- hand the consumer the STRUCTURAL facts, not just the transport.
|
|
1212
|
+
//
|
|
1213
|
+
// Both members are already in hand here. `model` is `this.model`, the name
|
|
1214
|
+
// setup-rest-server mounted this route for; `operation` is the SAME
|
|
1215
|
+
// `methodAccessMap` lookup the permission-array branch at the bottom of
|
|
1216
|
+
// this method performs, so the predicate form and the array form cannot
|
|
1217
|
+
// answer differently about the same request.
|
|
1218
|
+
//
|
|
1219
|
+
// NEITHER IS DERIVED FROM THE REQUEST TARGET, and that is the whole point.
|
|
1220
|
+
// Deriving `model` here from `request.baseUrl` (or from the mounted route
|
|
1221
|
+
// name, or from `getPluralName(this.model)`) would move all five fail-open
|
|
1222
|
+
// variants listed in this file's header OUT of the consumer and INTO the
|
|
1223
|
+
// framework, where every consumer inherits them at once. `this.model` is
|
|
1224
|
+
// assigned once at mount time and no request can influence it.
|
|
1225
|
+
//
|
|
1226
|
+
// `operation` is left UNDEFINED for a method with no entry in
|
|
1227
|
+
// `methodAccessMap`, rather than defaulted. Express delivers HEAD to the
|
|
1228
|
+
// GET handler, so an unmapped method really does reach this line; a
|
|
1229
|
+
// `?? 'read'` here would hand the consumer a fabricated authorisation fact
|
|
1230
|
+
// and turn an unclassified request into an authorised one. Undefined is
|
|
1231
|
+
// the honest answer.
|
|
1232
|
+
//
|
|
1233
|
+
// `record` is deliberately absent -- see `AccessContext` in
|
|
1234
|
+
// src/types/orm-types.ts. Nothing is fetched at this point and adding a
|
|
1235
|
+
// lookup here would put a store read in the middle of an authorization
|
|
1236
|
+
// path. The function return shape below IS the per-record hook.
|
|
1237
|
+
// -------------------------------------------------------------------------
|
|
1238
|
+
const context = {
|
|
1239
|
+
model: this.model,
|
|
1240
|
+
operation: methodAccessMap[request.method],
|
|
1241
|
+
};
|
|
1039
1242
|
let access;
|
|
1040
1243
|
try {
|
|
1041
|
-
access = this.access(request);
|
|
1244
|
+
access = this.access(request, context);
|
|
1042
1245
|
}
|
|
1043
1246
|
catch (error) {
|
|
1044
1247
|
// Same reasoning as `isDenied`: fail closed, but say so. An `access()`
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { waitForModule } from 'stonyx';
|
|
2
|
-
import { store } from '@stonyx/orm';
|
|
2
|
+
import Orm, { store } from '@stonyx/orm';
|
|
3
3
|
import OrmRequest from './orm-request.js';
|
|
4
4
|
import MetaRequest from './meta-request.js';
|
|
5
5
|
import RestServer from '@stonyx/rest-server';
|
|
@@ -8,7 +8,7 @@ import { dbKey } from './db.js';
|
|
|
8
8
|
import { getPluralName } from './plural-registry.js';
|
|
9
9
|
import log from 'stonyx/log';
|
|
10
10
|
export default async function (route, accessPath, metaRoute) {
|
|
11
|
-
const
|
|
11
|
+
const accessFunctions = {};
|
|
12
12
|
try {
|
|
13
13
|
await forEachFileImport(accessPath, (accessClass) => {
|
|
14
14
|
const accessInstance = new accessClass();
|
|
@@ -25,9 +25,9 @@ export default async function (route, accessPath, metaRoute) {
|
|
|
25
25
|
continue;
|
|
26
26
|
if (!store.data.has(model))
|
|
27
27
|
throw new Error(`Unable to define access for Invalid Model "${model}". Model does not exist`);
|
|
28
|
-
if (
|
|
28
|
+
if (accessFunctions[model])
|
|
29
29
|
throw new Error(`Access for model "${model}" has already been defined by another access class.`);
|
|
30
|
-
|
|
30
|
+
accessFunctions[model] = accessInstance.access;
|
|
31
31
|
}
|
|
32
32
|
});
|
|
33
33
|
}
|
|
@@ -35,11 +35,57 @@ export default async function (route, accessPath, metaRoute) {
|
|
|
35
35
|
log.error?.(error instanceof Error ? error.message : String(error));
|
|
36
36
|
log.warn?.('You must define a valid access configuration file in order to access ORM generated REST endpoints.');
|
|
37
37
|
}
|
|
38
|
+
// -------------------------------------------------------------------------
|
|
39
|
+
// #202 -- the registry has to survive this function.
|
|
40
|
+
//
|
|
41
|
+
// `accessFunctions` used to be a function-local that was discarded at the return
|
|
42
|
+
// below, so the only thing that ever saw it was the mount loop. Each mounted
|
|
43
|
+
// OrmRequest then held its OWN model's predicate and nothing held the map, so
|
|
44
|
+
// at request time there was no route from a model NAME to that model's
|
|
45
|
+
// predicate -- which is what abofs/stonyx-orm#196 and #207 need in order to
|
|
46
|
+
// ask model X's predicate about a request routed to model Y.
|
|
47
|
+
//
|
|
48
|
+
// Published BEFORE `await waitForModule('rest-server')`, deliberately: that
|
|
49
|
+
// await is the ONLY yield point in this function, and the rest-server module
|
|
50
|
+
// may already be listening by the time it reports ready, so an assignment
|
|
51
|
+
// after it would leave a window in which a route is live and the registry is
|
|
52
|
+
// not.
|
|
53
|
+
//
|
|
54
|
+
// It is NOT before the mount loop for that reason, and the comment here used
|
|
55
|
+
// to say it was. `RestServer.mountRoute` is fully synchronous -- construct,
|
|
56
|
+
// registerCalls(), api.use() -- and nothing between the loop and this
|
|
57
|
+
// function's closing brace yields, so the event loop cannot deliver a request
|
|
58
|
+
// in there and the window that clause described cannot open. Measured:
|
|
59
|
+
// moving this assignment to the last statement of the function leaves the
|
|
60
|
+
// suite at 951 pass / 0 fail. Being ahead of the mount loop is free and
|
|
61
|
+
// harmless; it is not what makes the ordering correct.
|
|
62
|
+
//
|
|
63
|
+
// Assigned unconditionally, including when the try above failed and the map
|
|
64
|
+
// is empty or partial: the mount loop below is driven by this exact object,
|
|
65
|
+
// so at the moment of assignment whatever is reachable through
|
|
66
|
+
// `Orm.instance` is the same set of predicates that is about to enforce.
|
|
67
|
+
// A guard such as `if (Object.keys(accessFunctions).length)` would let the
|
|
68
|
+
// registry go silently missing on a total load failure, and a later consumer
|
|
69
|
+
// would read `undefined` from `getAccess` and have to distinguish "no access
|
|
70
|
+
// class" from "the registry was never published" -- which it cannot. That is
|
|
71
|
+
// the reasoning, and it is REASONING, not something this suite tests: the
|
|
72
|
+
// guarded variant is also 951 pass / 0 fail, AC8 included, because every boot
|
|
73
|
+
// in this suite loads a non-empty access map so the guard never fires. AC8
|
|
74
|
+
// demonstrably cannot catch it. Catching it needs a boot with
|
|
75
|
+
// `orm.paths.access` pointed at an empty directory, which this suite has no
|
|
76
|
+
// harness for.
|
|
77
|
+
//
|
|
78
|
+
// One further limit on "by construction": the mount loop passes `access` BY
|
|
79
|
+
// VALUE into each OrmRequest, so the enforcing set is a snapshot taken here,
|
|
80
|
+
// while `getAccess` reads the map live. The two are the same set at boot and
|
|
81
|
+
// stay the same set only for as long as nobody writes to the public field.
|
|
82
|
+
// The equality is a boot-time fact, not an invariant.
|
|
83
|
+
Orm.instance.accessFunctions = accessFunctions;
|
|
38
84
|
await waitForModule('rest-server');
|
|
39
85
|
// Remove "/" prefix and name mount point accordingly
|
|
40
86
|
const name = route === '/' ? 'index' : (route[0] === '/' ? route.slice(1) : route);
|
|
41
87
|
// Configure endpoints for models and views with access configuration
|
|
42
|
-
for (const [model, access] of Object.entries(
|
|
88
|
+
for (const [model, access] of Object.entries(accessFunctions)) {
|
|
43
89
|
const pluralizedModel = getPluralName(model);
|
|
44
90
|
const modelName = name === 'index' ? pluralizedModel : `${name}/${pluralizedModel}`;
|
|
45
91
|
RestServer.instance.mountRoute(OrmRequest, { name: modelName, options: { model, access } });
|
package/dist/standalone-db.js
CHANGED
|
@@ -7,6 +7,10 @@
|
|
|
7
7
|
*/
|
|
8
8
|
import fs from 'fs/promises';
|
|
9
9
|
import path from 'path';
|
|
10
|
+
// `./utils.js` pulls in `@stonyx/utils/string` and nothing else -- no ORM
|
|
11
|
+
// bootstrap, no `@stonyx/orm` index, no side effects -- so the "no framework
|
|
12
|
+
// dependencies" property above still holds.
|
|
13
|
+
import { maxNumericId } from './utils.js';
|
|
10
14
|
export default class StandaloneDB {
|
|
11
15
|
mode;
|
|
12
16
|
dbPath;
|
|
@@ -102,11 +106,19 @@ export default class StandaloneDB {
|
|
|
102
106
|
async create(collection, data) {
|
|
103
107
|
const records = await this.readCollection(collection);
|
|
104
108
|
if (!data.id) {
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
109
|
+
// SHARED WITH `assignRecordId` (src/manage-record.ts), which is the other
|
|
110
|
+
// place this repo picks a server-assigned id. It was a second copy of the
|
|
111
|
+
// reduce, and nothing here pointed at it — a maintainer editing this
|
|
112
|
+
// method could not discover the other existed. See `maxNumericId` for why
|
|
113
|
+
// it is not `Math.max` (abofs/stonyx-orm#203).
|
|
114
|
+
//
|
|
115
|
+
// THE TWO ARE NOT THE SAME FUNCTION beyond this line, deliberately.
|
|
116
|
+
// `StandaloneDB` has no model, id-type or transform concept, so `maxId + 1`
|
|
117
|
+
// IS its store key; `assignRecordId` has to map the candidate through the
|
|
118
|
+
// model's declared id transform first, and then walk past occupied keys.
|
|
119
|
+
// Transplanting this method's remaining logic into the ORM reproduces
|
|
120
|
+
// #203's landing-key defect exactly — which is what AC4 pins.
|
|
121
|
+
data.id = maxNumericId(records) + 1;
|
|
110
122
|
}
|
|
111
123
|
// Check for duplicate id
|
|
112
124
|
const existing = records.find(r => r.id === data.id);
|
|
@@ -162,3 +162,104 @@ export interface SnapshotEntry {
|
|
|
162
162
|
source?: string;
|
|
163
163
|
viewQuery?: string;
|
|
164
164
|
}
|
|
165
|
+
/**
|
|
166
|
+
* The shapes a consumer `access()` predicate may return.
|
|
167
|
+
*
|
|
168
|
+
* - `false` (or any falsy value) -- deny, 403.
|
|
169
|
+
* - `true` -- allow, with no per-record filter.
|
|
170
|
+
* - a permission string or array of them, drawn from the same four verbs as
|
|
171
|
+
* {@link AccessContext.operation}. A BARE STRING IS ONE PERMISSION, not a
|
|
172
|
+
* grant of all four.
|
|
173
|
+
* - a `(record) => boolean` predicate -- allow, and filter every record the
|
|
174
|
+
* request touches through it.
|
|
175
|
+
*
|
|
176
|
+
* Anything else fails CLOSED. See `src/orm-request.ts` `auth()`.
|
|
177
|
+
*/
|
|
178
|
+
export type AccessMethod = string | boolean | string[] | ((record: unknown) => boolean);
|
|
179
|
+
/**
|
|
180
|
+
* The closed vocabulary `AccessContext.operation` is drawn from
|
|
181
|
+
* (abofs/stonyx-orm#202).
|
|
182
|
+
*
|
|
183
|
+
* A literal union rather than `string`, so the guarantee the prose makes is the
|
|
184
|
+
* one the compiler enforces: a consumer who writes `operation === 'GET'` or
|
|
185
|
+
* `operation === 'get'` -- the hook vocabulary, see below -- gets a compile
|
|
186
|
+
* error instead of a comparison that never matches. A predicate that stops
|
|
187
|
+
* matching falls through to the permission array, so the misreading is
|
|
188
|
+
* fail-open shaped.
|
|
189
|
+
*
|
|
190
|
+
* In-repo precedent: `PersistErrorDetail.operation` in `src/main.ts`.
|
|
191
|
+
*/
|
|
192
|
+
export type AccessOperation = 'read' | 'create' | 'update' | 'delete';
|
|
193
|
+
/**
|
|
194
|
+
* The structural facts about the request being authorised, handed to a consumer
|
|
195
|
+
* `access()` predicate as its SECOND argument (abofs/stonyx-orm#202).
|
|
196
|
+
*
|
|
197
|
+
* These are the facts the framework already holds at authorisation time. Before
|
|
198
|
+
* #202 a consumer had to reconstruct both of them by string-matching a URL, and
|
|
199
|
+
* five independent fail-open variants of that reconstruction were found in one
|
|
200
|
+
* three-line documented example -- each one wrong in the direction that GRANTS
|
|
201
|
+
* access. Read these instead; there is nothing to parse and no variant to miss.
|
|
202
|
+
*
|
|
203
|
+
* `record` is deliberately NOT a member. `auth()` runs after route matching but
|
|
204
|
+
* before any handler executes (`@stonyx/rest-server` `src/request.ts:58-60`),
|
|
205
|
+
* so nothing has been fetched yet -- carrying a record here would force a
|
|
206
|
+
* pre-fetch on every request. It is also unnecessary: the `(record) => boolean`
|
|
207
|
+
* return shape of {@link AccessMethod} already IS the per-record hook, applied
|
|
208
|
+
* by the handlers. Auth-time and record-time are separate decision points.
|
|
209
|
+
*/
|
|
210
|
+
export interface AccessContext {
|
|
211
|
+
/**
|
|
212
|
+
* The model this route was mounted for, e.g. `'owner'` or `'phone-number'`.
|
|
213
|
+
*
|
|
214
|
+
* Model names are kebab-case, as declared under `config.orm.paths.model` and
|
|
215
|
+
* keyed in the store -- NOT the pluralised, mount-prefixed route name. It is
|
|
216
|
+
* read from the `OrmRequest` instance and is never derived from the request
|
|
217
|
+
* target, so a mount prefix, a case-varied path, a query string or an
|
|
218
|
+
* absolute-form request-target cannot change it.
|
|
219
|
+
*/
|
|
220
|
+
model: string;
|
|
221
|
+
/**
|
|
222
|
+
* The operation being authorised. Exactly one of the four {@link
|
|
223
|
+
* AccessOperation} verbs, or `undefined`. These are exactly the values of
|
|
224
|
+
* `methodAccessMap` in `src/orm-request.ts`, which is also what the
|
|
225
|
+
* permission-array return shape is matched against -- so the two forms cannot
|
|
226
|
+
* disagree.
|
|
227
|
+
*
|
|
228
|
+
* NOT the hook vocabulary. `HookContext.operation` (`src/hooks.ts`) carries
|
|
229
|
+
* `'list' | 'get' | 'create' | 'update' | 'delete'` on an identically-named
|
|
230
|
+
* key of an identically-shaped context object, and the access vocabulary
|
|
231
|
+
* collapses `list` and `get` into `'read'`. For one `GET /animals/1` a hook
|
|
232
|
+
* sees `'get'` and `access()` sees `'read'`. "No second vocabulary" is a
|
|
233
|
+
* statement about the ACCESS path only.
|
|
234
|
+
*
|
|
235
|
+
* `undefined` when the dispatched method has no entry in that map. Express
|
|
236
|
+
* delivers `HEAD` to the `GET` handler, so this is reachable. It is left
|
|
237
|
+
* undefined rather than defaulted on purpose: a fabricated `'read'` would
|
|
238
|
+
* turn an unclassified request into an authorised one.
|
|
239
|
+
*
|
|
240
|
+
* The KEY is required even though the value may be undefined: `auth()` always
|
|
241
|
+
* sets it, and a context that simply omitted it would be indistinguishable
|
|
242
|
+
* from one that classified the request and found nothing.
|
|
243
|
+
*/
|
|
244
|
+
operation: AccessOperation | undefined;
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* A consumer `access()` predicate.
|
|
248
|
+
*
|
|
249
|
+
* The second argument is ADDITIVE: JavaScript ignores extra arguments, so every
|
|
250
|
+
* pre-#202 single-argument predicate keeps working untouched. Changing the
|
|
251
|
+
* FIRST argument instead would have been the breaking form, and a predicate
|
|
252
|
+
* that can no longer identify its collection falls through to a full CRUD
|
|
253
|
+
* grant -- so the "safer" breaking change would have converted every unmigrated
|
|
254
|
+
* predicate into a fail-open.
|
|
255
|
+
*
|
|
256
|
+
* `context` is nonetheless REQUIRED in the type, and that costs back-compat
|
|
257
|
+
* nothing. TypeScript already lets a fewer-parameter implementation satisfy a
|
|
258
|
+
* more-parameter signature, so an arity-1 predicate assigns to this type
|
|
259
|
+
* cleanly -- measured under `--strict`. What the `?` bought was the opposite of
|
|
260
|
+
* safety: it silently permitted `getAccess('animal')?.(request)` at the CALL
|
|
261
|
+
* site, i.e. exactly the omission {@link AccessContext} exists to prevent, and
|
|
262
|
+
* that call gets the model-wrong answer. Required, a caller that drops the
|
|
263
|
+
* context gets `TS2554: Expected 2 arguments, but got 1`.
|
|
264
|
+
*/
|
|
265
|
+
export type AccessFunction = (request: unknown, context: AccessContext) => AccessMethod;
|
package/dist/utils.d.ts
CHANGED
|
@@ -5,3 +5,47 @@ export declare function isDbError(error: unknown): error is {
|
|
|
5
5
|
};
|
|
6
6
|
export declare function isOrmRecord(value: unknown): value is OrmRecord;
|
|
7
7
|
export declare function pluralize(word: string): string;
|
|
8
|
+
/**
|
|
9
|
+
* The highest NUMERIC id held by a set of records, or `0` when there is none.
|
|
10
|
+
*
|
|
11
|
+
* ONE COPY, and the duplication it replaces is the reason it lives here. Three
|
|
12
|
+
* near-identical reduces existed at once: `assignRecordId` (server-assigned id
|
|
13
|
+
* selection), `StandaloneDB.create` (src/standalone-db.ts) and the #203 test
|
|
14
|
+
* helper. `docs/improvements.md`'s standing WET Code category prescribes
|
|
15
|
+
* exactly this remedy -- extract into the module that already acts as the
|
|
16
|
+
* shared utility -- and `assignRecordId` already imported `isOrmRecord` from
|
|
17
|
+
* here.
|
|
18
|
+
*
|
|
19
|
+
* NON-NUMBERS ARE SKIPPED RATHER THAN COERCED TO `0`, AND THAT IS STYLISTIC.
|
|
20
|
+
* `StandaloneDB`'s shape mapped them to `0`, which can never beat a seed of
|
|
21
|
+
* `0`. Measured over eleven input classes (`[]`, `1`, `NaN`, `'5'`, `'abc'`,
|
|
22
|
+
* `-3`, `0`, `null`, `undefined`, `Infinity`, and mixed arrays) the two shapes
|
|
23
|
+
* produce IDENTICAL output on every one. In particular `typeof NaN` is
|
|
24
|
+
* `'number'`, so NEITHER shape coerces `NaN` -- both reject it on `NaN > max`,
|
|
25
|
+
* which is `false`. An earlier revision of this code asserted that the skip was
|
|
26
|
+
* what made the `NaN` case work; it is not, the comparison is, and that claim
|
|
27
|
+
* has been removed rather than left standing.
|
|
28
|
+
*
|
|
29
|
+
* WHAT IS LOAD-BEARING is that this is not `Math.max(...ids)`. `Math.max`
|
|
30
|
+
* returns `NaN` if any operand is `NaN`, and a record CAN be held under the key
|
|
31
|
+
* `NaN` -- so the obvious fix assigns `NaN`, lands on that slot and overwrites
|
|
32
|
+
* it, which is abofs/stonyx-orm#203 in a new disguise. Pinned by
|
|
33
|
+
* test/unit/assign-record-id-test.ts AC2; before that file existed the whole
|
|
34
|
+
* suite scored 951/0 under exactly that fix.
|
|
35
|
+
*/
|
|
36
|
+
export declare function maxNumericId(records: {
|
|
37
|
+
id?: unknown;
|
|
38
|
+
}[]): number;
|
|
39
|
+
/**
|
|
40
|
+
* The message prefix `assignRecordId` throws with when no free id can be
|
|
41
|
+
* derived for a model, and the ONE string `createHandler` matches on to answer
|
|
42
|
+
* `409` instead of letting the rejection reach express's default handler.
|
|
43
|
+
*
|
|
44
|
+
* It lives here rather than in either file because both need it and neither
|
|
45
|
+
* should own a copy: a literal in two places is how the two id coercions in
|
|
46
|
+
* orm-request.ts drifted apart (see `coerceId`). The repo has no error codes
|
|
47
|
+
* and no custom error classes -- 24 bare `throw new Error` sites across `src/`
|
|
48
|
+
* -- so a shared prefix is the narrowest way to make ONE failure distinguishable
|
|
49
|
+
* without inventing an error taxonomy this codebase does not use.
|
|
50
|
+
*/
|
|
51
|
+
export declare const NO_FREE_ID_ERROR = "Cannot assign record ID: no free id available";
|
package/dist/utils.js
CHANGED
|
@@ -15,3 +15,50 @@ export function pluralize(word) {
|
|
|
15
15
|
}
|
|
16
16
|
return basePluralize(word);
|
|
17
17
|
}
|
|
18
|
+
/**
|
|
19
|
+
* The highest NUMERIC id held by a set of records, or `0` when there is none.
|
|
20
|
+
*
|
|
21
|
+
* ONE COPY, and the duplication it replaces is the reason it lives here. Three
|
|
22
|
+
* near-identical reduces existed at once: `assignRecordId` (server-assigned id
|
|
23
|
+
* selection), `StandaloneDB.create` (src/standalone-db.ts) and the #203 test
|
|
24
|
+
* helper. `docs/improvements.md`'s standing WET Code category prescribes
|
|
25
|
+
* exactly this remedy -- extract into the module that already acts as the
|
|
26
|
+
* shared utility -- and `assignRecordId` already imported `isOrmRecord` from
|
|
27
|
+
* here.
|
|
28
|
+
*
|
|
29
|
+
* NON-NUMBERS ARE SKIPPED RATHER THAN COERCED TO `0`, AND THAT IS STYLISTIC.
|
|
30
|
+
* `StandaloneDB`'s shape mapped them to `0`, which can never beat a seed of
|
|
31
|
+
* `0`. Measured over eleven input classes (`[]`, `1`, `NaN`, `'5'`, `'abc'`,
|
|
32
|
+
* `-3`, `0`, `null`, `undefined`, `Infinity`, and mixed arrays) the two shapes
|
|
33
|
+
* produce IDENTICAL output on every one. In particular `typeof NaN` is
|
|
34
|
+
* `'number'`, so NEITHER shape coerces `NaN` -- both reject it on `NaN > max`,
|
|
35
|
+
* which is `false`. An earlier revision of this code asserted that the skip was
|
|
36
|
+
* what made the `NaN` case work; it is not, the comparison is, and that claim
|
|
37
|
+
* has been removed rather than left standing.
|
|
38
|
+
*
|
|
39
|
+
* WHAT IS LOAD-BEARING is that this is not `Math.max(...ids)`. `Math.max`
|
|
40
|
+
* returns `NaN` if any operand is `NaN`, and a record CAN be held under the key
|
|
41
|
+
* `NaN` -- so the obvious fix assigns `NaN`, lands on that slot and overwrites
|
|
42
|
+
* it, which is abofs/stonyx-orm#203 in a new disguise. Pinned by
|
|
43
|
+
* test/unit/assign-record-id-test.ts AC2; before that file existed the whole
|
|
44
|
+
* suite scored 951/0 under exactly that fix.
|
|
45
|
+
*/
|
|
46
|
+
export function maxNumericId(records) {
|
|
47
|
+
return records.reduce((max, record) => {
|
|
48
|
+
const { id } = record;
|
|
49
|
+
return typeof id === 'number' && id > max ? id : max;
|
|
50
|
+
}, 0);
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* The message prefix `assignRecordId` throws with when no free id can be
|
|
54
|
+
* derived for a model, and the ONE string `createHandler` matches on to answer
|
|
55
|
+
* `409` instead of letting the rejection reach express's default handler.
|
|
56
|
+
*
|
|
57
|
+
* It lives here rather than in either file because both need it and neither
|
|
58
|
+
* should own a copy: a literal in two places is how the two id coercions in
|
|
59
|
+
* orm-request.ts drifted apart (see `coerceId`). The repo has no error codes
|
|
60
|
+
* and no custom error classes -- 24 bare `throw new Error` sites across `src/`
|
|
61
|
+
* -- so a shared prefix is the narrowest way to make ONE failure distinguishable
|
|
62
|
+
* without inventing an error taxonomy this codebase does not use.
|
|
63
|
+
*/
|
|
64
|
+
export const NO_FREE_ID_ERROR = 'Cannot assign record ID: no free id available';
|
package/package.json
CHANGED
package/src/index.ts
CHANGED
|
@@ -27,6 +27,7 @@ import { count, avg, sum, min, max } from './aggregates.js';
|
|
|
27
27
|
export { default } from './main.js';
|
|
28
28
|
export { store, relationships } from './main.js';
|
|
29
29
|
export type { PersistErrorDetail } from './main.js';
|
|
30
|
+
export type { AccessContext, AccessFunction, AccessMethod, AccessOperation } from './types/orm-types.js'; // access() contract (#202)
|
|
30
31
|
export { Model, View, Serializer }; // base classes
|
|
31
32
|
export { attr, belongsTo, hasMany, createRecord, updateRecord }; // helpers
|
|
32
33
|
export { count, avg, sum, min, max }; // aggregate helpers
|