@stonyx/orm 0.3.2-alpha.89 → 0.3.2-alpha.90

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.
@@ -1,286 +1,4 @@
1
- /**
2
- * REST request handling and access enforcement for @stonyx/orm.
3
- *
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.
69
- *
70
- * THE RELATED-RESOURCE HALF OF THAT SENTENCE IS NOW OUT OF DATE AND IS
71
- * CORRECTED HERE RATHER THAN DELETED. Both relationship route families resolve
72
- * the RELATED model's own access class and ask it
73
- * `{ model: <related>, operation: 'read', recordId: null }`
74
- * (abofs/stonyx-orm#232), so those surfaces no longer serve another model's
75
- * records under `model: 'owner'` unexamined. What the context still gives no
76
- * signal of is WHICH related record is being asked about -- `recordId` is
77
- * `null` there and `request.params` names a record of a different model. See
78
- * `AccessContext.recordId` in ./types/orm-types.ts for the full statement of
79
- * that limit.
80
- *
81
- * AND THE `?include=` HALF IS NOW OUT OF DATE TOO, CORRECTED THE SAME WAY. It
82
- * read: "`?include=` is still unfiltered and is abofs/stonyx-orm#233 / #235."
83
- * Both have landed. #235 filters what a record already in `included` may NAME,
84
- * and #233 filters MEMBERSHIP at the traversal's push site -- see
85
- * `traverseIncludePath` below. The ask is the same shape as the
86
- * related-resource one and carries the same limit: `recordId` is `null`, so a
87
- * deny expressible only as a request-scoped `return false` -- which is how the
88
- * shipped sample spells `/archived` -- still cannot fire on this path. That
89
- * residual is abofs/stonyx-orm#243's, not #233's, and it is measured
90
- * byte-identical on `dev`.
91
- *
92
- * SUPERSEDED 2026-09-01 BY abofs/stonyx-orm#236/#237, AND KEPT FOR THE
93
- * CONSTRAINT IT STATES RATHER THAN AS A DESCRIPTION OF THE CODE. The context
94
- * now also carries `recordId` -- the DECODED route-parameter id, see
95
- * `AccessContext.recordId` in ./types/orm-types.ts -- so the fixture's
96
- * `/archived` deny IS expressible from the context alone, and the shipped
97
- * sample no longer reads `request.path` at all. Retiring this wording WITH the
98
- * measurement that retires it, rather than by deletion, is
99
- * abofs/stonyx-orm#238.
100
- *
101
- * `record` IS NOT IN THIS CONTEXT, deliberately. `auth()` runs after route
102
- * matching but BEFORE any handler executes (`@stonyx/rest-server`
103
- * `src/request.ts:58-60`), so nothing has been fetched yet -- supplying a
104
- * record would force a pre-fetch on every request, a second store hit and an
105
- * ordering change in the middle of an authorization path. It is also
106
- * unnecessary: the FUNCTION return shape already is the per-record hook. Return
107
- * `(record) => boolean` and the handlers apply it to every record the request
108
- * touches. Auth-time and record-time are separate decision points.
109
- *
110
- * THE SECOND ARGUMENT IS ADDITIVE. JavaScript ignores extra arguments, so an
111
- * existing `access(request)` predicate keeps working exactly as before. The
112
- * warning immediately below is therefore still live: `request` is still
113
- * argument ONE, and reading it is still how predicates fail open.
114
- *
115
- * To reach ANOTHER model's predicate -- e.g. to check an animal while servicing
116
- * an owners route -- use the boot-time registry:
117
- *
118
- * const predicate = Orm.instance.getAccess('animal');
119
- * if (!predicate) return deny;
120
- * const verdict = predicate(request, { model: 'animal', operation: 'read' });
121
- *
122
- * `undefined` means NO PREDICATE COULD BE RESOLVED for that name -- which
123
- * includes the case where the model has an access class that failed to load,
124
- * because `setup-rest-server.ts` catches a load failure, warns, and publishes
125
- * whatever partial map it had. It does NOT mean the model is unrestricted.
126
- * Treat it as DENY, the same way `operation === undefined` is treated above.
127
- *
128
- * PASSING THE CONTEXT MAKES A MODEL-CORRECT ANSWER POSSIBLE. It does not make
129
- * the answer model-correct on its own -- the resolved predicate has to READ it.
130
- * Measured against an ARITY-1 predicate, on a request express dispatched to
131
- * `GET /owners/angela`, asked about ANIMALS:
132
- *
133
- * getAccess('animal')(ownersRequest, { model: 'animal', operation: 'read' })
134
- * -> record => record.id !== 'angela' && record.id !== 'restricted'
135
- *
136
- * That is the OWNERS filter, and it returns `true` for animal 21 -- the record
137
- * hidden on every animal surface. Under a mount that predicate recognises
138
- * neither way it is worse: it falls through to
139
- * `['read', 'create', 'update', 'delete']`, a full CRUD grant. Either way the
140
- * context was supplied and the answer is not the animal answer, and it is wrong
141
- * in the GRANTING direction, because that predicate is arity-1 and identifies
142
- * its collection from the request. (Asserted on a live dispatch by AC9 in
143
- * test/integration/orm-test.ts, against a deliberately arity-1 predicate.)
144
- *
145
- * This repo's own sample access class has since been MIGRATED to read the
146
- * context (abofs/stonyx-orm#222), so `getAccess('animal')` here now answers
147
- * with the animal filter. That is not true of a consumer tree: an arity-1
148
- * predicate keeps working -- the second argument is additive -- and the caller
149
- * has no supported way to tell which kind it got. The boot-time arity warning
150
- * that surfaces one is abofs/stonyx-orm#221.
151
- * So: pass the context, and do not treat a resolved predicate's answer as
152
- * model-specific until that predicate has been migrated to read the context.
153
- *
154
- * ---------------------------------------------------------------------------
155
- * DO NOT RECONSTRUCT THE REQUEST PATH INSIDE `access()`.
156
- * ---------------------------------------------------------------------------
157
- * You do not have to. `auth()` below hands your predicate the ACCESS CONTEXT as
158
- * argument two, and `context.model` already names the collection -- see the
159
- * contract section above. Argument ONE is still the raw transport artifact, and
160
- * everything from here to the end of this banner is the record of what happened
161
- * when predicates worked the collection out from it. IT IS HISTORY, NOT
162
- * GUIDANCE: do not write any of it into a new predicate. Every attempt to
163
- * identify the collection by parsing the request target has failed OPEN. Five
164
- * distinct variants of the same three-line example have now been found, each
165
- * after the previous was fixed, by five different people:
166
- *
167
- * 1. `request.url` is mount-relative under `RestServer.mountRoute`, so a
168
- * prefix match against it is ALWAYS false.
169
- * 2. `request.originalUrl` carries the query string, so an anchored equality
170
- * check misses `/owners?filter[age]=30`.
171
- * 3. The router is a bare `express()` (`caseSensitive: false`) while a
172
- * hand-written matcher is case-SENSITIVE, so `GET /OwNeRs/angela` walks
173
- * past it. Router-side: abofs/stonyx-rest-server#47.
174
- * 4. Under a configured `ORM_REST_ROUTE` a hard-coded `/owners` matches
175
- * nothing -- environment-specifically, which is worse.
176
- * 5. HTTP/1.1 permits an ABSOLUTE-FORM request-target. Express routes on
177
- * `parseurl(req).pathname`, but `originalUrl` is the raw target, so
178
- * `GET http://anything.example/owners/angela` reaches the handler with
179
- * `originalUrl === 'http://anything.example/owners/angela'`. A `/owners`
180
- * prefix match is false, `access()` falls through to whatever it returns
181
- * last, and the record comes back in full. It walks past a hard
182
- * `return false` deny the same way.
183
- *
184
- * The fix is not a sixth rule, and it is not a better string to match. It is to
185
- * stop identifying the collection at all: read `context.model`. That is a claim
186
- * about IDENTIFYING THE COLLECTION, not about the sample as a whole -- the
187
- * `/archived` SUB-PATH rule is still a string match, and abofs/stonyx-orm#228 is
188
- * a sixth spelling that gets past it.
189
- *
190
- * SUPERSEDED 2026-09-01 BY abofs/stonyx-orm#236/#237: the `/archived` rule is
191
- * no longer a string match against the request target -- it compares the
192
- * decoded `recordId` the framework supplies -- and abofs/stonyx-orm#228 is
193
- * CLOSED. Retirement of this wording: abofs/stonyx-orm#238.
194
- *
195
- * An intermediate revision of the sample read `request.baseUrl` -- the mount
196
- * Express ACTUALLY MATCHED. That closed all five variants (no query string,
197
- * not mount-relative, unaffected by absolute-form, already carrying the
198
- * configured `ORM_REST_ROUTE` prefix), but it was a transport artifact
199
- * standing in for a structural fact and the sample no longer does it.
200
- * `context.model` IS the structural fact, so variants 1, 2, 4 and 5 are
201
- * unconstructible against a migrated predicate rather than handled.
202
- *
203
- * VARIANT 3 SURVIVES, and is deliberately not in that list. It is the general
204
- * shape "a hand-written matcher normalises differently from the router", and a
205
- * migrated predicate still runs one string comparison for any SUB-PATH rule --
206
- * in the shipped sample, the `/archived` deny. That comparison folds case but
207
- * does not decode, so `GET /owners/%61rchived` steps past it. See the
208
- * normalisation paragraph below and abofs/stonyx-orm#228.
209
- *
210
- * SUPERSEDED 2026-09-01 BY abofs/stonyx-orm#236/#237. Variant 3 lived in that
211
- * one string comparison, and the comparison is gone: the sample compares the
212
- * decoded `recordId`. Left standing rather than edited because the same
213
- * "variant 3 survives" wording sits at four sites -- this header, README.md
214
- * twice, and test/sample/access/global-access.ts -- three of which SHIP, so
215
- * retiring one of four leaves the shipped copies contradicting each other.
216
- * Retiring all four WITH their measurement is abofs/stonyx-orm#238.
217
- *
218
- * ONE READ OF ARGUMENT ONE SURVIVES, AND IT MUST: `request.path`. It is
219
- * mount-relative and query-free, and it is for rules that distinguish SUB-PATHS
220
- * beneath the mount. The context names which model and which verb, NOT which
221
- * route, so the sample's `/archived` deny cannot be expressed from the context
222
- * alone and a context-ONLY rewrite would silently turn that deny into an allow.
223
- *
224
- * SUPERSEDED 2026-09-01 BY abofs/stonyx-orm#236/#237: NO read of argument one
225
- * survives in the shipped sample. `recordId` names WHICH RECORD the route was
226
- * addressed to, so the `/archived` deny is expressible from the context alone
227
- * -- and it still must not be dropped; expressible is not optional. Retirement
228
- * of this wording: abofs/stonyx-orm#238.
229
- *
230
- * NORMALISE THE WAY THE ROUTER DOES, AND CASE-FOLDING ALONE IS NOT THAT. The
231
- * sample lower-cases before comparing, because a matcher stricter than the
232
- * case-insensitive router can be stepped around. That closes the case gap only.
233
- * Express sets `request.path` from the RAW, UNDECODED pathname while the router
234
- * DECODES `:id`, so `GET /owners/%61rchived` reaches a `path === '/archived'`
235
- * comparison as `/%61rchived` and walks past the deny. That gap is live in the
236
- * sample and is tracked as abofs/stonyx-orm#228; the `.toLowerCase()` is not a
237
- * complete normalisation recipe. Compare record ids at their real case.
238
- *
239
- * DO NOT FOLLOW THE PARAGRAPH ABOVE. SUPERSEDED 2026-09-01 BY
240
- * abofs/stonyx-orm#236/#237, and flagged here rather than merely dated because
241
- * it is an INSTRUCTION, not a stale observation. `.toLowerCase()` on the access
242
- * path was measured WRONG IN BOTH DIRECTIONS AT ONCE: with a distinct owner
243
- * seeded at `ARCHIVED`, `GET /owners/ARCHIVED` was a false DENY on the wrong
244
- * record and `GET /owners/%41RCHIVED` a false ALLOW on that same record. A
245
- * record id is a VALUE, not a literal route segment, and express's
246
- * `case sensitive routing` governs literal segments only. Compare
247
- * `context.recordId` AS IT ARRIVES: do not case-fold it, do not decode it, do
248
- * not derive it from `request.path`. `AccessContext.recordId` in
249
- * ./types/orm-types.ts is the contract and says "Do NOT case-fold it"; the same
250
- * published tarball ships both files, and THIS paragraph is the one that is
251
- * wrong. Retiring it WITH its measurement is abofs/stonyx-orm#238.
252
- *
253
- * `?? ''` is not a defence. It converts an absent request target into an empty
254
- * string, which matches no collection, which falls through to the permission
255
- * array -- a total grant. An input you cannot identify must DENY, and that
256
- * applies to BOTH arguments: since #202 the guard and the read can sit on
257
- * different objects, and a guard on argument two does not protect a read of
258
- * argument one. The sample returns `false` for an absent `model` AND for an
259
- * absent or non-string `request.path`, rather than falling through either way.
260
- *
261
- * SUPERSEDED 2026-09-01 BY abofs/stonyx-orm#236/#237 as to WHAT is guarded --
262
- * the principle is unchanged. The sample no longer reads `request.path`, so it
263
- * returns `false` for an absent `model` AND for an absent `recordId`
264
- * (`undefined`, the one spelling `auth()` never produces). Retirement of this
265
- * wording: abofs/stonyx-orm#238.
266
- *
267
- * THE REAL FIX IS abofs/stonyx-orm#202: `access()` should receive the model,
268
- * the operation and the record. Prefer the array shape (`['read']`) or `false`
269
- * until #202 lands; the function shape is what requires any matching at all.
270
- *
271
- * The enforcement gates in this file (GATE 0/1/2, the create rollback, the
272
- * per-handler `isDenied` re-checks) are correct independently of that -- they
273
- * enforce whatever predicate you return. The stopgap is the part where YOU have
274
- * to work out which predicate to return.
275
- *
276
- * AND A PREDICATE IS NOT A GUARANTEE THAT A HIDDEN RECORD CANNOT BE MODIFIED.
277
- * It is evaluated against the record the route is ADDRESSED TO, on that model
278
- * only. A write to a DIFFERENT collection can still re-parent a hidden record
279
- * and de-hide it -- abofs/stonyx-orm#207, which is blocked on #202 and #196.
280
- * See `### Known limitations` in README.
281
- */
282
1
  import { Request } from '@stonyx/rest-server';
283
- import type { AccessFunction } from './types/orm-types.js';
284
2
  interface OrmRequest$ extends Request {
285
3
  protocol?: string;
286
4
  method: string;
@@ -295,12 +13,13 @@ interface OrmRequest$ extends Request {
295
13
  };
296
14
  get(header: string): string;
297
15
  }
16
+ type AccessMethod = string | boolean | string[] | ((record: unknown) => boolean);
298
17
  type HandlerFn = (request: OrmRequest$, state: {
299
18
  [key: string]: unknown;
300
19
  }) => unknown | Promise<unknown>;
301
20
  export default class OrmRequest extends Request {
302
21
  model: string;
303
- access: AccessFunction;
22
+ access: (request: unknown) => AccessMethod;
304
23
  handlers: {
305
24
  [key: string]: {
306
25
  [key: string]: HandlerFn;
@@ -308,7 +27,7 @@ export default class OrmRequest extends Request {
308
27
  };
309
28
  constructor({ model, access }: {
310
29
  model: string;
311
- access: AccessFunction;
30
+ access: (request: unknown) => AccessMethod;
312
31
  });
313
32
  private _withHooks;
314
33
  private _generateRelationshipRoutes;