@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,284 +1,3 @@
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
2
  import Orm, { store, createRecord, updateRecord } from '@stonyx/orm';
284
3
  import { camelCaseToKebabCase } from '@stonyx/utils/string';
@@ -286,10 +5,8 @@ import { getPluralName } from './plural-registry.js';
286
5
  import { getBeforeHooks, getAfterHooks } from './hooks.js';
287
6
  import type { HookContext } from './hooks.js';
288
7
  import config from 'stonyx/config';
289
- import log from 'stonyx/log';
290
- import type { OrmRecord, AccessContext, AccessFunction, AccessMethod, AccessOperation, LinkageFilter } from './types/orm-types.js';
291
- import { isOrmRecord, NO_FREE_ID_ERROR } from './utils.js';
292
- import { interpretAccess, createLinkageFilter } from './access-verdict.js';
8
+ import type { OrmRecord } from './types/orm-types.js';
9
+ import { isOrmRecord } from './utils.js';
293
10
 
294
11
  interface OrmRequest$ extends Request {
295
12
  protocol?: string;
@@ -316,9 +33,10 @@ interface JsonApiResponse {
316
33
  included?: unknown[];
317
34
  }
318
35
 
36
+ type AccessMethod = string | boolean | string[] | ((record: unknown) => boolean);
319
37
  type HandlerFn = (request: OrmRequest$, state: { [key: string]: unknown }) => unknown | Promise<unknown>;
320
38
 
321
- const methodAccessMap: { [key: string]: AccessOperation } = {
39
+ const methodAccessMap: { [key: string]: string } = {
322
40
  GET: 'read',
323
41
  POST: 'create',
324
42
  DELETE: 'delete',
@@ -366,128 +84,21 @@ function getBaseUrl(request: OrmRequest$): string {
366
84
  return `${protocol}://${host}`;
367
85
  }
368
86
 
369
- /**
370
- * The ONE coercion from a caller-supplied id to the key the store holds it
371
- * under. Every id-bearing surface in this file goes through it, and none has a
372
- * copy: `getId()` (URL params), `normalizeBodyId()` (JSON body), and the
373
- * post-create `context.record` lookup in `_withHooks`.
374
- *
375
- * WHY IT IS SHARED RATHER THAN DUPLICATED. `getId()` and `normalizeBodyId()`
376
- * each had their own arithmetic, and they disagreed: `parseInt(id)` versus
377
- * `parseInt(id, 10)`. On a hex-shaped id that is a two-record difference --
378
- *
379
- * GET /animals/0x2391 -> record 9105 (getId -> parseInt('0x2391') = 9105)
380
- * POST /animals {"id":"0x2391"} -> lookup under 0 (normalize -> parseInt('0x2391',10) = 0)
381
- * -> a MISS, so the duplicate check was skipped and
382
- * createRecord OVERWROTE 9105 in place, answering 200
383
- *
384
- * -- a narrower form of the raw-versus-normalised divergence that the body-id
385
- * normalisation was added to close, reintroduced by the fix for it. Two
386
- * coercions that must agree cannot be kept in agreement by review; they have to
387
- * be one function. Pinned by assertion 43.
388
- *
389
- * The third copy was found later and in a quieter place: `_withHooks` populated
390
- * `context.record` for `create` with `isNaN(id) ? id : parseInt(id)` -- this
391
- * function's body, inlined verbatim, feeding `store.get`. It was equivalent on
392
- * every input reachable there, which is exactly what the two that DID diverge
393
- * looked like until someone tried a hex id.
394
- *
395
- * SHARING IT IS NOT THE SAME AS IT BEING RIGHT EVERYWHERE. On a model declaring
396
- * `id = attr('string')` a numeric-looking id is filed under the STRING key, so
397
- * this coercion resolves `'9107'` to `9107` and the post-create lookup misses:
398
- * `context.record` is `undefined` for an after-`create` hook. Inherited -- the
399
- * inlined copy computed the same thing -- and NOT fixed here, because picking
400
- * the right coercion needs the model's declared id type, which is the same
401
- * structural information abofs/stonyx-orm#202 is about. Filed as
402
- * abofs/stonyx-orm#209 and pinned by assertion 50, so closing it turns a test
403
- * red rather than passing silently.
404
- *
405
- * `parseInt` and not `Number`, deliberately, and the anchor is NOT `getId`.
406
- * It is `src/transforms.ts:7` -- `number: (value) => parseInt(value as string)`,
407
- * also radix-less -- because that transform is what actually produces the store
408
- * KEY a record is filed under. `getId` merely agrees with it. They differ from
409
- * `Number` on `'1e3'` (1 vs 1000) and `'9105.5'` (9105 vs 9105.5), so switching
410
- * this function to `Number` would make the lookup key disagree with the landing
411
- * key on those shapes.
412
- *
413
- * THE CHANGE THAT WOULD BREAK THIS: adding a radix to `transforms.number`
414
- * (`parseInt(value, 10)`). That is a one-word edit in a file with no connection
415
- * to authorization, it would silently reopen the hex divergence in the other
416
- * direction, and this comment would still read as correct. Assertion 45 pins
417
- * the transform's radix-less shape directly, so that edit turns a test red
418
- * rather than shipping.
419
- *
420
- * The reason `parseInt` is safe here is the `isNaN` gate in front of it:
421
- * `parseInt('9105h')` is `9105`, and truncating a partially-valid id into a
422
- * DIFFERENT VALID key is exactly how a collision lookup gets skipped. The gate
423
- * rejects it as a string instead, so nothing is ever truncated. That gate, not
424
- * the parser, is the load-bearing half -- assertion 43 pins it.
425
- */
426
- function coerceId(id: string): string | number {
427
- if (isNaN(id as unknown as number)) return id;
428
-
429
- return parseInt(id);
430
- }
431
-
432
87
  function getId(params: { id?: string; [key: string]: unknown }): string | number {
433
88
  const id = params.id;
434
89
  if (!id) return '';
90
+ if (isNaN(id as unknown as number)) return id;
435
91
 
436
- return coerceId(id);
437
- }
438
-
439
- /**
440
- * Normalise a caller-supplied BODY id to the key the store will hold it under.
441
- *
442
- * `getId()` above is params-shaped: it takes `{ id?: string }` off the URL,
443
- * where the value is always a string and a falsy one means "no id". A JSON body
444
- * id is neither -- it can arrive as a number, and `0` is a legitimate id that
445
- * `getId()` would flatten to `''`.
446
- *
447
- * WHY THIS EXISTS AT ALL. createHandler used to look the collision up with the
448
- * RAW body value while every other surface normalised through `getId()`. The
449
- * store is a Map keyed by the coerced value, so `store.find(model, '21')` misses
450
- * the entry held under `21` and the duplicate check is skipped by typing the id
451
- * as a string. On `dev` that silently overwrote the colliding record and
452
- * answered 200; combined with the denied-create rollback added for #190 it
453
- * became an unauthenticated DELETE of any id. Normalising here is half of that
454
- * fix -- see the rollback in createHandler for the other half.
455
- *
456
- * It shares `coerceId` with `getId` so the two surfaces cannot drift apart
457
- * again, and differs from `getId` in exactly ONE place, below.
458
- */
459
- function normalizeBodyId(id: string | number): string | number {
460
- // Non-strings pass through untouched: a JSON body id can arrive as a number,
461
- // and `getId`'s falsy-flatten must NOT apply to it -- `0` is a legitimate id
462
- // and `getId` would turn it into `''`. (assertion 30 sweeps id `0`.)
463
- if (typeof id !== 'string') return id;
464
-
465
- // THE ONE DIVERGENCE FROM `getId`, and it mirrors rather than contradicts it:
466
- // `getId` maps a falsy param to `''`, and `''` is the only string a body can
467
- // carry that means "no id" -- `createRecord` treats it as absent and assigns a
468
- // server id. Coercing it instead would make it address a real slot, because
469
- // `parseInt('')` is `NaN` and a record CAN be held under `NaN` (a truthy but
470
- // non-numeric id such as `' '` survives `assignRecordId`'s falsy guard and
471
- // then NaNs in the id transform). So `POST {"id":""}` would answer 409 against
472
- // an unrelated record it never named. Pinned by assertion 44.
473
- //
474
- // Note what is deliberately NOT special-cased here any more: whitespace.
475
- // `id.trim() === ''` used to short-circuit `' '` as well, which made the
476
- // body surface DISAGREE with the URL surface -- `getId({id:' '})` is `NaN`,
477
- // so `' '` addresses the NaN slot on every other route while the collision
478
- // lookup missed it. Same class of bug as the hex divergence above.
479
- if (id === '') return id;
480
-
481
- return coerceId(id);
92
+ return parseInt(id);
482
93
  }
483
94
 
484
95
  function buildResponse(
485
96
  data: unknown,
486
97
  includeParam: string | undefined,
487
98
  recordOrRecords: OrmRecord | OrmRecord[],
488
- options: { links?: { [key: string]: string }; baseUrl?: string; linkage?: LinkageFilter } = {}
99
+ options: { links?: { [key: string]: string }; baseUrl?: string } = {}
489
100
  ): JsonApiResponse {
490
- const { links, baseUrl, linkage } = options;
101
+ const { links, baseUrl } = options;
491
102
  const response: JsonApiResponse = { data };
492
103
 
493
104
  // Add top-level links
@@ -500,116 +111,23 @@ function buildResponse(
500
111
  const includes = parseInclude(includeParam);
501
112
  if (includes.length === 0) return response;
502
113
 
503
- // THE SAME FILTER OBJECT DECIDES MEMBERSHIP AND LINKAGE, AND IT IS PASSED TO
504
- // BOTH (abofs/stonyx-orm#233). It carries #234's per-type verdict cache and
505
- // per-(type, id) decision cache, so the traversal below and the `toJSON`
506
- // calls beneath it share one resolution of the consumer's `access()` per
507
- // type for the whole response. Building a second filter here would double
508
- // every predicate call and, worse, could answer the two questions
509
- // differently about the same record.
510
- const includedRecords = collectIncludedRecords(recordOrRecords, includes, linkage);
114
+ const includedRecords = collectIncludedRecords(recordOrRecords, includes);
511
115
  if (includedRecords.length > 0) {
512
- // LINKAGE, NOT MEMBERSHIP -- and the distinction is the whole reason this
513
- // line is one story's and the line above it is another's
514
- // (abofs/stonyx-orm#235 and #233 respectively).
515
- //
516
- // - WHICH RESOURCES REACH THIS ARRAY is decided by
517
- // `collectIncludedRecords` on the line above. That is MEMBERSHIP and
518
- // it is #233's. As of #233 that call is given the SAME `linkage`
519
- // filter, so a hidden owner is no longer a member: she is dropped at
520
- // the push site and her subtree is never traversed. Pinned by
521
- // `[DEFECT] #233 AC2` and `[DEFECT] #233 AC4`; the re-specification of
522
- // `[GUARD] #235 X1`, which pinned the PRE-#233 answer here, is in that
523
- // same test.
524
- // - WHAT A RECORD ALREADY IN THIS ARRAY MAY NAME in its own
525
- // `relationships.*.data` is LINKAGE -- the same question #234 answers
526
- // for the primary document -- and that is what the `linkage` option
527
- // below decides. Before it, `GET /animals/1?include=owner,owner.pets`
528
- // filtered the primary document's `owner.data` to `null` and then
529
- // handed back eight PERMITTED animals in `included` each naming
530
- // `{"type":"owner","id":"angela"}` -- angela's whole `pets` set,
531
- // `[1, 3, 7, 10, 11, 15, 17, 20]`. `included` itself is NINE
532
- // resources there: those eight animals plus the hidden owner, whose
533
- // membership is #233's and not an animal. Neither #233 nor #234
534
- // closes that.
535
- //
536
- // THE FILTER IS THE CALLER'S, PASSED IN, NOT BUILT HERE. Both call sites
537
- // already hold one for the primary document, and sharing it is what keeps
538
- // the per-type verdict cache and the per-(type, id) decision cache alive
539
- // across the primary document AND the sideload -- one verdict resolution
540
- // per type for the whole response, pinned by `[GUARD] #235 C1`. Building a
541
- // fresh filter here would resolve the consumer's `access()` once per
542
- // included record instead.
543
- //
544
- // `linkage` IS OPTIONAL IN THE TYPE AND IS NOT OPTIONAL IN PRACTICE.
545
- // Stating it precisely because the opposite claim stood here in an earlier
546
- // draft of this change: BOTH of this function's callers supply a filter
547
- // (`getCollectionHandler` and `getSingleHandler`, the only two), so the
548
- // `undefined` branch has no live caller in this module today. It is
549
- // optional so that omitting it degrades to the PRE-#234 document rather
550
- // than to a denial -- `Record.toJSON` reads an ABSENT option as "no verdict
551
- // was supplied" and emits linkage in full.
552
- //
553
- // WHAT IT MUST NEVER BE HANDED IS A NON-FUNCTION. `toJSON` does NOT read a
554
- // non-function as absent: `Object.prototype.toString.call(linkage)` must be
555
- // `'[object Function]'`, and anything else -- `null`, an `AsyncFunction`,
556
- // and INCLUDING the primitive `true` -- DENIES every relationship on the
557
- // document and logs once. `toJSON({ linkage: true })` emits `null` linkage.
558
- // So do not "simplify" this to a boolean, and do not make it default to
559
- // `true`: both spellings look like "allow everything" and mean the exact
560
- // opposite (abofs/stonyx-orm#224).
561
- response.included = includedRecords.map(record => record.toJSON?.({ baseUrl, linkage }));
116
+ response.included = includedRecords.map(record => record.toJSON?.({ baseUrl }));
562
117
  }
563
118
 
564
119
  return response;
565
120
  }
566
121
 
567
122
  /**
568
- * Recursively traverse an include path and collect related records.
569
- *
570
- * ---------------------------------------------------------------------------
571
- * THE `linkage` FILTER DECIDES MEMBERSHIP HERE (abofs/stonyx-orm#233)
572
- * ---------------------------------------------------------------------------
573
- * A resource reaches `included` because some record NAMED it, and until #233
574
- * being named was the whole test. That made `?include=` a restoration of every
575
- * record the read surfaces withhold: `GET /owners/angela` is 404 and
576
- * `GET /animals/1?include=owner` returned her document in full, attributes and
577
- * all. Measured on dev @ 8dda5d6, over the live router.
578
- *
579
- * FILTERED AT THE PUSH SITE, AND THE SITE MATTERS. The obvious alternative --
580
- * let the traversal run and filter `collectIncludedRecords`' RETURN value --
581
- * closes the membership half and leaves the worse half open: dropping a parent
582
- * AFTER traversing through it publishes that parent's exact child set. On this
583
- * repo's own fixture `GET /animals/1?include=owner,owner.pets` names angela's
584
- * eight animals `[1, 3, 7, 10, 11, 15, 17, 20]`, which IS her `pets` array,
585
- * reconstructed from a resource the caller may not read. So a denied record is
586
- * `continue`d before it is pushed to `included` AND before it is pushed to
587
- * `nextRecords`, which is what prunes the subtree.
588
- *
589
- * A DENIED RECORD IS DELIBERATELY NOT ADDED TO `seen`. `seen` is the
590
- * deduplicator for records that DID enter `included`; putting a denial in it
591
- * would conflate "already emitted" with "withheld", and the `else if` branch
592
- * below would then push a denied record into `nextRecords` for deeper
593
- * traversal -- re-opening the prune this function just closed. Re-asking is
594
- * free: #234's filter caches per `(type, id)`, so the second ask is a `Map`
595
- * hit and not a call into the consumer's `access()`.
596
- *
597
- * ABSENT FILTER MEANS PRE-#233 BEHAVIOUR, NOT A DENIAL. `linkage` is optional
598
- * for the same reason it is optional on `buildResponse` and on
599
- * `Record.toJSON`: an absent option means "no verdict was supplied", and the
600
- * honest degradation is the document that shipped before, not an empty one.
601
- * Both of `buildResponse`'s callers -- `getCollectionHandler` and
602
- * `getSingleHandler`, the only two -- supply it, which is pinned by
603
- * `[GUARD] #233 AC8`. What must never arrive here is a non-function; the
604
- * guard below is the fail-closed reading of one.
123
+ * Recursively traverse an include path and collect related records
605
124
  */
606
125
  function traverseIncludePath(
607
126
  currentRecords: OrmRecord[],
608
127
  includePath: string[],
609
128
  depth: number,
610
129
  seen: Map<string, Set<string | number>>,
611
- included: OrmRecord[],
612
- linkage?: LinkageFilter
130
+ included: OrmRecord[]
613
131
  ): void {
614
132
  if (depth >= includePath.length) return; // Reached end of path
615
133
 
@@ -635,19 +153,6 @@ function traverseIncludePath(
635
153
  const type = relatedRecord.__model.__name;
636
154
  const id = relatedRecord.id as string | number;
637
155
 
638
- // MEMBERSHIP AND PRUNE, abofs/stonyx-orm#233. `continue` skips BOTH
639
- // pushes below -- the record does not enter `included` and it does not
640
- // become a parent at the next depth.
641
- //
642
- // FAIL CLOSED ON A RECORD WHOSE TYPE CANNOT BE NAMED, the same reading
643
- // #232's `isLinkable` uses on the relationship routes: `type` is the key
644
- // the verdict is resolved under, so a missing or empty one means there
645
- // is no predicate to ask and no way to ask it. Denying is the only safe
646
- // answer, and it is only reachable while a filter is in force -- with no
647
- // filter this whole check is skipped and the pre-#233 document is
648
- // emitted unchanged.
649
- if (linkage && !(typeof type === 'string' && type !== '' && linkage(type, relatedRecord))) continue;
650
-
651
156
  // Initialize Set for this type if needed
652
157
  let seenIds = seen.get(type);
653
158
  if (!seenIds) {
@@ -669,15 +174,11 @@ function traverseIncludePath(
669
174
 
670
175
  // If there are more segments in the path, recursively process
671
176
  if (depth < includePath.length - 1 && nextRecords.length > 0) {
672
- traverseIncludePath(nextRecords, includePath, depth + 1, seen, included, linkage);
177
+ traverseIncludePath(nextRecords, includePath, depth + 1, seen, included);
673
178
  }
674
179
  }
675
180
 
676
- function collectIncludedRecords(
677
- data: OrmRecord | OrmRecord[],
678
- includes: string[][],
679
- linkage?: LinkageFilter
680
- ): OrmRecord[] {
181
+ function collectIncludedRecords(data: OrmRecord | OrmRecord[], includes: string[][]): OrmRecord[] {
681
182
  if (!includes || includes.length === 0) return [];
682
183
  if (!data) return [];
683
184
 
@@ -689,7 +190,7 @@ function collectIncludedRecords(
689
190
 
690
191
  // Process each include path
691
192
  for (const includePath of includes) {
692
- traverseIncludePath(records, includePath, 0, seen, included, linkage);
193
+ traverseIncludePath(records, includePath, 0, seen, included);
693
194
  }
694
195
 
695
196
  return included;
@@ -750,46 +251,12 @@ function createFilterPredicate(filters: Filter[]): ((record: { [key: string]: un
750
251
  });
751
252
  }
752
253
 
753
- /**
754
- * A function-style `access` return is a per-record predicate, and it is only
755
- * meaningful if every surface that can hand a record to a caller consults it.
756
- * Before #190 exactly one of seven did.
757
- *
758
- * Enforcement is deliberately post-fetch. `access` returns an opaque JS
759
- * predicate and `store.findAll(model, conditions)` accepts only an equality
760
- * conditions object that the SQL drivers translate to a WHERE clause, so
761
- * query-layer enforcement would require a breaking change to the published
762
- * `access` contract. That belongs in #197, not in a security patch. Six of the
763
- * seven surfaces fetch by primary key anyway, so this costs exactly one row.
764
- */
765
- function isDenied(filter: unknown, record: unknown): boolean {
766
- if (typeof filter !== 'function') return false;
767
-
768
- // A predicate that throws is treated as a denial. Unguarded, a throw escapes
769
- // to express's default handler, which answers 500 (with a stack trace outside
770
- // NODE_ENV=production) while a missing id still answers 404 -- so a
771
- // record-dependent throw re-separates "hidden" from "does not exist" and
772
- // hands back the oracle this whole change exists to close.
773
- try {
774
- return !(filter as (record: unknown) => boolean)(record);
775
- } catch (error) {
776
- // Denied, but not silently. A consumer predicate that throws on every
777
- // record turns the whole collection into a 404 wall, and with no
778
- // diagnostic that is indistinguishable from an empty database. `stonyx/log`
779
- // is the module convention (see setup-rest-server.ts); optional-call
780
- // because a consumer may not have configured the log types.
781
- log.error?.(`[@stonyx/orm] access filter threw for model -- denying. ${error instanceof Error ? error.message : String(error)}`);
782
-
783
- return true;
784
- }
785
- }
786
-
787
254
  export default class OrmRequest extends Request {
788
255
  model: string;
789
- access: AccessFunction;
256
+ access: (request: unknown) => AccessMethod;
790
257
  handlers: { [key: string]: { [key: string]: HandlerFn } };
791
258
 
792
- constructor({ model, access }: { model: string; access: AccessFunction }) {
259
+ constructor({ model, access }: { model: string; access: (request: unknown) => AccessMethod }) {
793
260
  super(...arguments as unknown as unknown[]);
794
261
 
795
262
  this.model = model;
@@ -812,68 +279,29 @@ export default class OrmRequest extends Request {
812
279
  if (queryFilterPredicate) recordsToReturn = recordsToReturn.filter(queryFilterPredicate as (record: OrmRecord) => boolean);
813
280
 
814
281
  const baseUrl = getBaseUrl(request);
815
-
816
- // ONE filter per REQUEST, not one per record: it carries the per-type
817
- // verdict cache and the per-(type, id) decision cache, and both are
818
- // worthless if it is rebuilt inside the map. Measured on this exact
819
- // surface with no `include=`: 48 linkage entries collapse to 7 distinct
820
- // (type, id) pairs.
821
- const linkage = createLinkageFilter(request);
822
- const data = recordsToReturn.map(record => record.toJSON?.({ fields: modelFields, baseUrl, linkage }));
282
+ const data = recordsToReturn.map(record => record.toJSON?.({ fields: modelFields, baseUrl }));
823
283
 
824
284
  return buildResponse(data, request.query?.include, recordsToReturn, {
825
285
  links: { self: `${baseUrl}/${pluralizedModel}` },
826
- baseUrl,
827
- // THE SAME filter object the primary documents above were serialized
828
- // with, deliberately: it carries the caches, and rebuilding one here
829
- // would re-resolve every type (abofs/stonyx-orm#235).
830
- linkage
286
+ baseUrl
831
287
  });
832
288
  };
833
289
 
834
- const getSingleHandler: HandlerFn = async (request, { filter }) => {
290
+ const getSingleHandler: HandlerFn = async (request) => {
835
291
  const record = await store.find(model, getId(request.params)) as OrmRecord | undefined;
836
292
  if (!record) return 404;
837
- // 404, never 403: the status for "exists but filtered out" must be
838
- // identical to "does not exist", or the fix trades an authorization
839
- // bypass for a narrower existence oracle.
840
- if (isDenied(filter, record)) return 404;
841
293
 
842
294
  const fieldsMap = parseFields(request.query);
843
295
  const modelFields = fieldsMap.get(pluralizedModel) || fieldsMap.get(model);
844
296
 
845
297
  const baseUrl = getBaseUrl(request);
846
- const linkage = createLinkageFilter(request);
847
-
848
- // `buildResponse` IS given the filter now (abofs/stonyx-orm#235), and it
849
- // is the SAME object the primary document is serialized with -- one
850
- // verdict per type for the whole response, sideload included.
851
- //
852
- // The boundary, so the next reader does not have to derive it: this
853
- // closes what a record already in `included` may NAME. WHETHER a
854
- // resource appears in `included` at all is MEMBERSHIP and it is
855
- // abofs/stonyx-orm#233's. THAT IS NOW CLOSED TOO, and the same `linkage`
856
- // object closes it: `buildResponse` hands this filter to
857
- // `collectIncludedRecords`, which denies at the push site. Corrected
858
- // rather than deleted -- this comment read "a hidden owner is still a
859
- // member here", which is the sentence the identical copy in
860
- // `buildResponse` carried and which #233 falsified in both places. They
861
- // are still two questions and neither closes the other: a record can be
862
- // a member while its own linkage is filtered.
863
- return buildResponse(record.toJSON?.({ fields: modelFields, baseUrl, linkage }), request.query?.include, record, {
298
+ return buildResponse(record.toJSON?.({ fields: modelFields, baseUrl }), request.query?.include, record, {
864
299
  links: { self: `${baseUrl}/${pluralizedModel}/${request.params.id}` },
865
- baseUrl,
866
- linkage
300
+ baseUrl
867
301
  });
868
302
  };
869
303
 
870
- const createHandler: HandlerFn = async (request, { filter }) => {
871
- // BOUND, not destructured (abofs/stonyx-orm#235). `HandlerFn` has always
872
- // delivered the request as argument one; this handler simply discarded
873
- // the binding, which is why its response document named ids every read
874
- // surface withholds. `createLinkageFilter` needs the live request and
875
- // there is no signature change involved in giving it one.
876
- const { body, query } = request;
304
+ const createHandler: HandlerFn = async ({ body, query }) => {
877
305
  const { type, id, attributes, relationships: rels } = (body?.data || {}) as {
878
306
  type?: string;
879
307
  id?: string | number;
@@ -886,113 +314,14 @@ export default class OrmRequest extends Request {
886
314
  const fieldsMap = parseFields(query);
887
315
  const modelFields = fieldsMap.get(pluralizedModel) || fieldsMap.get(model);
888
316
 
889
- // GATE 0 -- the POST existence oracle.
890
- //
891
- // The duplicate check runs before the filter and `store.find` sees hidden
892
- // records, so POST leaks existence through its STATUS. A previous revision
893
- // filtered the collision status (403 when the colliding record is denied,
894
- // 409 when it is visible) and that is NOT sufficient, because the status
895
- // of a create is a third outcome. With a payload the caller is permitted
896
- // to create -- the normative case for a per-tenant filter, and the case an
897
- // attacker picks -- all three are distinguishable in ONE request per id:
898
- //
899
- // POST /animals {id:22, owner:'gina'} -> 403 a HIDDEN record has this id
900
- // POST /animals {id:9500, owner:'gina'} -> 200 this id is FREE
901
- // POST /animals {id:8, owner:'gina'} -> 409 a VISIBLE record has this id
902
- //
903
- // Filtering only the collision status narrows that to callers who cannot
904
- // create a record they are allowed to see. It does not close it.
905
- //
906
- // It cannot be closed while a caller both chooses the id and learns
907
- // whether the create succeeded: a successful create must answer
908
- // differently from a refused one. So when a per-record filter is in force
909
- // the caller does not get to choose the id at all. The refusal is
910
- // UNCONDITIONAL and happens BEFORE any store lookup, so no status, and no
911
- // lookup cost, can depend on whether that id exists. 403 -- the same
912
- // status as a denied create -- so the two cannot be separated either.
913
- //
914
- // BOTH HALVES OF THAT ARE PINNED, because both were once asserted here and
915
- // pinned by nothing:
916
- //
917
- // status -- assertion 22 sweeps payload x id x id-type, plus `null`.
918
- // latency -- assertion 41 asserts NO `store.find` is issued on this
919
- // path. Moving the refusal to after a lookup and returning
920
- // the same 403 left the suite green while re-opening a
921
- // hit-versus-miss timing difference on every id-bearing POST,
922
- // which is what would turn #197 from a ~0.06ms post-fetch
923
- // residual into a live timing oracle on create.
924
- //
925
- // AND THE GUARANTEE IS ONLY AS WIDE AS THE CHANNELS IT COVERS. It reads on
926
- // the `id` member of the resource object, so it holds only while that is
927
- // the ONLY way a caller id can reach `createRecord`. It was not: the
928
- // relationships loop below re-admitted one under `key === "id"` and the
929
- // gate never fired. Both strips -- `attributes.id` and `relationships.id`
930
- // -- are therefore part of THIS gate, not tidiness, and assertion 39 pins
931
- // them. Adding a third channel without a strip re-opens the oracle.
932
- //
933
- // Scoped to function-style `access` because that is exactly the population
934
- // the oracle exists for: with no per-record filter there are no hidden
935
- // records, and 409 discloses nothing GET /:id does not already.
936
- //
937
- // RESIDUALS, stated rather than implied.
938
- //
939
- // - a caller can still learn that a collection HAS a per-record filter
940
- // (403 rather than 409/200 for an id-bearing POST). That discloses a
941
- // configuration fact, not a record.
942
- // - this gate is about ids arriving on THIS model's create route. It
943
- // says nothing about a write to ANOTHER collection: a `POST /owners`
944
- // carrying `relationships: {pets: {data: {id: 21}}}` -- or
945
- // `attributes: {pets: [21, 22]}`, which never enters the
946
- // relationships loop at all -- re-parents hidden animal 21 onto an
947
- // owner the caller may write, which changes the very field the
948
- // animals predicate reads and DE-HIDES it. Blocking that needs animal
949
- // 21 checked against the ANIMAL model's predicate while servicing an
950
- // OWNERS route, i.e. cross-model access resolution: abofs/stonyx-orm
951
- // #207, blocked on #202 (`access` receives the model structurally)
952
- // and #196 (setup-rest-server discards the model->predicate map at
953
- // boot). NOT closed here, and no comment in this file may say it is.
954
- //
955
- // See README `### Known limitations`.
956
- if (id !== undefined) {
957
- if (typeof filter === 'function') return 403; // Forbidden
958
-
959
- // `normalizeBodyId`, not the raw value: a string-typed id misses the
960
- // store's numeric key, which skipped this check entirely.
961
- const existing = await store.find(model, normalizeBodyId(id));
962
- if (existing) return 409; // Conflict
963
- }
317
+ // Check for duplicate ID
318
+ if (id !== undefined && await store.find(model, id)) return 409; // Conflict
964
319
 
965
320
  const { id: _ignoredId, ...sanitizedAttributes } = attributes || {};
966
321
 
967
- // Extract relationship IDs from JSON:API relationships object.
968
- //
969
- // `key` comes VERBATIM from the request body, so `id` is stripped here for
970
- // exactly the same reason it is stripped from `attributes` on the line
971
- // above -- and it must be, or GATE 0 is walked around by moving one field:
972
- //
973
- // POST /animals {"id":21, ...} -> 403 GATE 0 fires
974
- // POST /animals {"relationships":{"id":{"data":{"id":21}}},
975
- // "attributes":{"owner":"gina"}} -> 200 BYPASS
976
- //
977
- // Top-level `id` stayed `undefined`, so GATE 0 never fired and the
978
- // collision lookup never ran; `createRecord` took its last-entry-wins
979
- // branch, overwrote hidden record 21 in place and reset its `owner` to a
980
- // value the caller chose -- de-hiding it permanently. That is #190 itself,
981
- // on the create surface. Pinned by assertion 39.
982
- //
983
- // The `id` member of the resource object is now the ONLY channel a caller
984
- // id can arrive on FOR THIS MODEL'S OWN CREATE ROUTE, which is what makes
985
- // GATE 0's guarantee checkable rather than merely asserted. It is not a
986
- // statement about the record's reachability in general -- a relationship
987
- // write on another collection reaches it without ever touching this
988
- // handler (abofs/stonyx-orm#207). INHERITED from `dev`, which carries this
989
- // loop verbatim; the general form -- the loop accepts any key, not just
990
- // `id`, so a body key that is not a declared relationship is still
991
- // mass-assigned -- is abofs/stonyx-orm#204.
322
+ // Extract relationship IDs from JSON:API relationships object
992
323
  if (rels) {
993
324
  for (const [key, value] of Object.entries(rels)) {
994
- if (key === 'id') continue;
995
-
996
325
  const relData = value?.data;
997
326
  if (relData && relData.id !== undefined) {
998
327
  (sanitizedAttributes as { [key: string]: unknown })[key] = relData.id;
@@ -1001,169 +330,16 @@ export default class OrmRequest extends Request {
1001
330
  }
1002
331
 
1003
332
  const recordAttributes = id !== undefined ? { id, ...sanitizedAttributes } : sanitizedAttributes;
1004
-
1005
- // Slot count BEFORE the write. `createRecord` writes to the store before
1006
- // the predicate can run, and the rollback below must be able to prove the
1007
- // slot it removes is one THIS REQUEST created. Identity alone cannot
1008
- // prove it: when `assignRecordId` lands on an occupied id, `createRecord`
1009
- // mutates the existing OrmRecord IN PLACE, so `store.get(...) === record`
1010
- // is true for a record the request did not create. The map's size is the
1011
- // only O(1) signal that distinguishes an insert from an overwrite.
1012
- const slotsBefore = store.get(model)?.size ?? 0;
1013
-
1014
- // THE ONE `createRecord` FAILURE THIS ROUTE ANSWERS RATHER THAN
1015
- // PROPAGATES, and it is narrow on purpose.
1016
- //
1017
- // `assignRecordId` throws when it cannot derive a free store key for a
1018
- // server-assigned id. Unguarded that rejection is auto-forwarded -- there
1019
- // is no catch here, none in @stonyx/rest-server's dispatcher
1020
- // (dist/request.js:41-70), and express 5 hands it to its default error
1021
- // handler, which serialises the STACK, with absolute install paths and the
1022
- // internal module graph, to an unauthenticated caller outside
1023
- // NODE_ENV=production. That is the hazard :553-558 already names in this
1024
- // file, and every sibling refusal in this handler returns an integer
1025
- // status instead. So this one returns 409, matching the client-duplicate
1026
- // refusal at :713: the caller asked for a record and the collection has no
1027
- // id to give it.
1028
- //
1029
- // MATCHED ON THE SHARED PREFIX, not on a literal, and NOT by catching
1030
- // everything: `createRecord` also throws for "ORM is not ready", a
1031
- // read-only view and an unregistered model store, and turning any of those
1032
- // into a 409 would report a configuration fault as a conflict. Anything
1033
- // else is re-thrown unchanged.
1034
- let created;
1035
-
1036
- try {
1037
- created = createRecord(model, recordAttributes as { [key: string]: unknown }, { serialize: false, _skipAutoPersist: true });
1038
- } catch (error) {
1039
- if (!(error instanceof Error) || !error.message.startsWith(NO_FREE_ID_ERROR)) throw error;
1040
-
1041
- // Not silently. A collection that can no longer assign an id is a
1042
- // configuration fault (a non-injective id transform), and a bare 409
1043
- // with no diagnostic is indistinguishable from an ordinary duplicate.
1044
- log.error?.(`[@stonyx/orm] ${error.message}`);
1045
-
1046
- return 409; // Conflict
1047
- }
1048
-
333
+ const created = createRecord(model, recordAttributes as { [key: string]: unknown }, { serialize: false, _skipAutoPersist: true });
1049
334
  const record = isOrmRecord(created) ? created : null;
1050
335
  if (!record) return 500;
1051
336
 
1052
- const createdNewSlot = (store.get(model)?.size ?? 0) > slotsBefore;
1053
-
1054
- // 403 here, NOT 404. The oracle argument does not apply to create: there
1055
- // is no pre-existing record whose existence could leak, the caller
1056
- // supplied the attributes, and 404 on a mounted collection route is
1057
- // indistinguishable from "model not mounted" -- a genuinely different
1058
- // failure a developer needs to diagnose.
1059
- //
1060
- // The rollback is not optional. createRecord writes to the store BEFORE
1061
- // the predicate can run, so returning 403 alone would leave the record
1062
- // behind: a worse bug than the bypass being fixed.
1063
- if (isDenied(filter, record)) {
1064
- // ROLL BACK BY IDENTITY, NEVER BY ID. `store.remove(model, record.id)`
1065
- // on its own is a write primitive keyed by a value the caller may have
1066
- // supplied: with the raw-id collision bypass above, a denied
1067
- // `POST {"id":"21"}` answered 403 and DELETED hidden record 21 -- an
1068
- // unauthenticated deletion primitive across the whole id space, created
1069
- // by adding a rollback to a lookup that could be skipped.
1070
- //
1071
- // Both conditions are required and neither implies the other:
1072
- // createdNewSlot -- the store grew, so this request inserted rather
1073
- // than overwrote. SURVIVOR AS OF #203, AND THAT IS
1074
- // WHAT THIS NOTE IS FOR. It used to be killable:
1075
- // `assignRecordId` returned last-INSERTED + 1, so a
1076
- // server-assigned id could land on an occupied slot,
1077
- // `createRecord` updated in place, and removing this
1078
- // half turned access-filter-enforcement-test.ts
1079
- // assertion 31 red. #203 closed that: the
1080
- // server-assigned path now walks past occupied keys,
1081
- // so no create reaching here can overwrite. Measured
1082
- // -- delete `createdNewSlot &&` below: `dev` gives
1083
- // 55 pass / 1 fail with assertion 31 RED, this tree
1084
- // gives 56 pass / 0 fail, GREEN.
1085
- // KEPT ANYWAY, AND NOT FOR THE OLD REASON. Without
1086
- // it a denied create becomes `store.remove` on a key
1087
- // the caller may have influenced, which :815-820
1088
- // records as having been an unauthenticated deletion
1089
- // primitive across the whole id space. BECOMES
1090
- // KILLABLE AGAIN the moment any caller-supplied id
1091
- // can reach `createRecord` from this handler --
1092
- // which is exactly what has-many.ts:65 and
1093
- // belongs-to.ts:45 already do for ANOTHER model's
1094
- // store (abofs/stonyx-orm#207), and what a third
1095
- // un-stripped id channel would do for this one
1096
- // (#204). Do not delete it on the strength of #203
1097
- // being closed; that is the reasoning :862-867 warns
1098
- // about, one level up.
1099
- // identity -- the slot still holds the object we just created,
1100
- // so nothing between createRecord and here replaced
1101
- // it. Deleting this half SURVIVES the suite, and it
1102
- // is kept anyway. WHY IT IS REDUNDANT: there is no
1103
- // `await` anywhere between `slotsBefore` and
1104
- // `store.remove` -- the whole window is synchronous,
1105
- // so it is atomic under Node's event loop; before-
1106
- // `create` hooks run BEFORE the handler
1107
- // (`_withHooks` runs its hook loop ahead of
1108
- // `await handler(...)`), and a consumer predicate
1109
- // inside `isDenied` runs AFTER `createdNewSlot` is
1110
- // computed and cannot flip it. That is a property of
1111
- // THIS function, not of GATE 0 -- an earlier note
1112
- // credited GATE 0, which was both wrong (a caller id
1113
- // reached createRecord through the relationships
1114
- // loop, #204) and the wrong kind of reason: a guard
1115
- // justified on code sixty lines upstream gets
1116
- // silently re-armed when that code moves.
1117
- // SO IT BECOMES REACHABLE IF AN `await` IS
1118
- // INTRODUCED HERE, which is the change a future
1119
- // editor would actually make. Stated here rather
1120
- // than by reference: `docs/` is not in `files`, so
1121
- // a pointer into it resolves to nothing for anyone
1122
- // who installed this package. README carries the
1123
- // consumer-facing half.
1124
- if (createdNewSlot && store.get(model, record.id as string | number) === record) {
1125
- store.remove(model, record.id as string | number, { _skipAutoPersist: true });
1126
- }
1127
-
1128
- return 403;
1129
- }
1130
-
1131
- // The filter is built HERE, per invocation, and never hoisted into the
1132
- // OrmRequest constructor where the other per-mount values live: a verdict
1133
- // cached across requests answers a second caller with the first caller's
1134
- // authorization (src/access-verdict.ts says so at the constructor an
1135
- // implementer would reach for).
1136
- //
1137
- // AND IT IS BUILT AFTER `createRecord`, AFTER THE ROLLBACK WINDOW AND
1138
- // AFTER `isDenied`, so the record is in its final form at the call. The
1139
- // filter is lazy per type and per (type, id), so it cannot observe a
1140
- // pre-write state even if it were built earlier.
1141
- //
1142
- // `fields` is passed here and NOT in `updateHandler`: the two handlers
1143
- // are asymmetric on purpose (`updateHandler` has no `fieldsMap` in
1144
- // scope), and a single copy-pasted wiring would drop it from one of them.
1145
- return { data: record.toJSON?.({ fields: modelFields, linkage: createLinkageFilter(request) }) };
337
+ return { data: record.toJSON?.({ fields: modelFields }) };
1146
338
  };
1147
339
 
1148
- const updateHandler: HandlerFn = async (request, { filter }) => {
1149
- // Bound rather than destructured, for the reason given in
1150
- // `createHandler` above (abofs/stonyx-orm#235). `PATCH /animals/1`
1151
- // returned 200 naming angela seconds after `GET /animals/1` returned
1152
- // `owner.data: null` for the same record -- one HTTP verb apart.
1153
- const { body, params } = request;
340
+ const updateHandler: HandlerFn = async ({ body, params }) => {
1154
341
  const found = await store.find(model, getId(params));
1155
342
  if (!found || !isOrmRecord(found)) return 404;
1156
- // Checked BEFORE any attribute is applied. 404 rather than 403 for the
1157
- // same reason as GET /:id -- 403 would disclose both that the record
1158
- // exists and that this caller specifically is excluded.
1159
- //
1160
- // NOT redundant behind GATE 1, and not defence in depth either: GATE 1's
1161
- // verdict is computed BEFORE the before-hook loop runs, and a before-hook
1162
- // is a published extension point that can change the answer -- by
1163
- // mutating the record, or against a predicate that closes over
1164
- // per-request state. This is the only re-evaluation after that window.
1165
- // Pinned by assertion 32; deleting it turns a 404 into an applied update.
1166
- if (isDenied(filter, found)) return 404;
1167
343
  const record = found;
1168
344
  const { attributes, relationships: rels } = (body?.data || {}) as {
1169
345
  attributes?: { [key: string]: unknown };
@@ -1186,19 +362,6 @@ export default class OrmRequest extends Request {
1186
362
  if (rels) {
1187
363
  const relUpdates: { [key: string]: unknown } = {};
1188
364
  for (const [key, value] of Object.entries(rels)) {
1189
- // The same missing key filter as createHandler's, and as the
1190
- // attribute loop directly above -- which already had it, while this
1191
- // loop did not. A PATCH carrying
1192
- // `relationships:{"id":{"data":{"id":9101}}}` reached `updateRecord`
1193
- // and RE-KEYED the record: the object held under store key 9102 then
1194
- // reported id 9101, so a visible record claimed a hidden record's
1195
- // identity on every surface that reads `record.id` rather than the map
1196
- // key. Gated by GATE 1 on the addressed record, so it is store
1197
- // corruption rather than a filter bypass -- but it is the same one-line
1198
- // omission two handlers apart. Pinned by assertion 40; INHERITED from
1199
- // `dev`; abofs/stonyx-orm#204.
1200
- if (key === 'id') continue;
1201
-
1202
365
  const relData = value?.data;
1203
366
  if (relData && relData.id !== undefined) {
1204
367
  relUpdates[key] = relData.id;
@@ -1209,41 +372,11 @@ export default class OrmRequest extends Request {
1209
372
  }
1210
373
  }
1211
374
 
1212
- // No `fields` and no `baseUrl`, both unchanged: `updateHandler` has no
1213
- // `fieldsMap` in scope, and adding `baseUrl` would put `links` on a
1214
- // document that has never carried them -- an unrelated behaviour change.
1215
- // #224 AC6's "emits `data: []` WITH links" is a statement about the READ
1216
- // surfaces; on these two handlers a filtered relationship and a
1217
- // genuinely-empty one are both a bare `{ data }`, which is what makes
1218
- // them indistinguishable here too.
1219
- return { data: record.toJSON?.({ linkage: createLinkageFilter(request) }) };
375
+ return { data: record.toJSON?.() };
1220
376
  };
1221
377
 
1222
- const deleteHandler: HandlerFn = async ({ params }, { filter }) => {
1223
- // Coerced ONCE. `getId(params)` was evaluated twice here -- once to find
1224
- // the record and once to remove it -- and a coercion evaluated repeatedly
1225
- // is a coercion that can be edited in one place and not the other, which
1226
- // is the defect `coerceId` exists to prevent.
1227
- const recordId = getId(params);
1228
- const record = await store.find(model, recordId) as OrmRecord | undefined;
1229
-
1230
- // BEHAVIOUR CHANGE (#190): a DELETE of a record that never existed
1231
- // returned 204 before this change. It now returns 404, matching the
1232
- // denied case below. This is deliberate and load-bearing -- if a denied
1233
- // delete returned 404 while a missing one returned 204, the pair would be
1234
- // a perfect existence oracle and the whole fix would be worthless.
1235
- // Returning 204 for a denied delete was rejected instead: it falsely
1236
- // reports success for a request that changed nothing.
1237
- if (!record) return 404;
1238
- // Re-evaluated after the before-hook loop, exactly as in updateHandler --
1239
- // GATE 1 decided before the hooks ran. Pinned by assertion 33; deleting it
1240
- // turns a 404 into a destroyed record.
1241
- if (isDenied(filter, record)) return 404;
1242
-
1243
- // Removed by the id of the record actually fetched, not by re-deriving it
1244
- // from the params a second time: the record the filter tested and the
1245
- // record removed are then provably the same one.
1246
- store.remove(model, record.id as string | number, { _skipAutoPersist: true });
378
+ const deleteHandler: HandlerFn = ({ params }) => {
379
+ store.remove(model, getId(params), { _skipAutoPersist: true });
1247
380
  return 204;
1248
381
  };
1249
382
 
@@ -1272,65 +405,9 @@ export default class OrmRequest extends Request {
1272
405
  }
1273
406
  }
1274
407
 
1275
- // Wraps a handler with before/after hook execution.
1276
- //
1277
- // ===========================================================================
1278
- // TWO AUTHORIZATION GATES, AND EVERY EXECUTOR SITS BEHIND ONE OF THEM (#190)
1279
- //
1280
- // The defect this function was fixed for is NOT "a delete persists past a
1281
- // 404". It is that _withHooks has SEVERAL executors downstream of the
1282
- // handler, and originally the handler's response gated none of them. Three
1283
- // exist today:
1284
- //
1285
- // 1. sqlDb.persist -- issues real SQL against the backing store
1286
- // 2. the after-hook pipeline -- the PUBLISHED consumer extension point;
1287
- // a cascade delete, a webhook, a search-index
1288
- // purge. `context.recordId` and
1289
- // `context.oldState` are populated for it.
1290
- // 3. Orm.db.save() -- a full serialize-and-write of the store
1291
- //
1292
- // Gating them one at a time is how this keeps regressing, so the rule is:
1293
- // compute denial ONCE at each point where it becomes knowable, and keep every
1294
- // executor downstream of a gate. If you add a fourth executor to this
1295
- // function, it goes below GATE 2 or it is a security bug.
1296
- //
1297
- // GATE 1 (pre-handler) is required because before-hooks and `context.oldState`
1298
- // run/are built BEFORE the handler can consult the filter. Without it a denied
1299
- // DELETE still handed the hidden record's full contents to consumer code.
1300
- // GATE 2 (post-handler) covers everything the handler's status can reach.
1301
- // ===========================================================================
408
+ // Wraps a handler with before/after hook execution
1302
409
  private _withHooks(operation: string, handler: HandlerFn): HandlerFn {
1303
410
  return async (request: OrmRequest$, state: { [key: string]: unknown }) => {
1304
- // `|| {}` so this function behaves like the relationship routes below,
1305
- // which declare `state` with a `= {}` default. It is unkillable through
1306
- // the rest-server dispatcher, which always passes `getState(req)`; it is
1307
- // listed as such in the guards-redundant-by-construction table rather
1308
- // than left silently unkillable, and it defends the WHOLE function (the
1309
- // context, the snapshot and the handler call all read `callState`) rather
1310
- // than one destructure that the next line would throw past anyway.
1311
- const callState = (state || {}) as { [key: string]: unknown };
1312
-
1313
- // ---------------------------------------------------------------------
1314
- // THE AUTHORIZATION SNAPSHOT. Read ONCE, here, before any consumer code
1315
- // can run.
1316
- //
1317
- // `callState` is the object `auth()` planted the filter in, and it is
1318
- // also handed to every before-hook as `context.state` -- a published,
1319
- // WRITABLE extension point. So `state.filter` is an INPUT to the
1320
- // authorization decision, not only an output channel, and re-reading it
1321
- // after the hook loop lets a consumer hook disarm the filter:
1322
- //
1323
- // beforeHook('get', 'animal', ctx => { delete ctx.state.filter })
1324
- // -> GET /animals/21 turned 404 into 200
1325
- // -> GET /animals turned 20 records into 22
1326
- //
1327
- // GATE 1 already used this snapshot, so writes held; the READ handlers
1328
- // re-destructured `filter` from the live bag and did not. Everything
1329
- // downstream now reads `filter` from here, and the handler is handed
1330
- // `handlerState` below -- never `callState`.
1331
- // ---------------------------------------------------------------------
1332
- const { filter } = callState as { filter?: unknown };
1333
-
1334
411
  // Build context object for hooks
1335
412
  const context: HookContext = {
1336
413
  model: this.model,
@@ -1339,37 +416,12 @@ export default class OrmRequest extends Request {
1339
416
  params: request.params,
1340
417
  body: request.body,
1341
418
  query: request.query,
1342
- // Deliberately the LIVE object: `redirect` and `pipe` are read back off
1343
- // it by @stonyx/rest-server after the handler returns, so hooks must be
1344
- // able to write to it. What must not happen is the authorization
1345
- // decision reading it back, which is what the snapshot above prevents.
1346
- state: callState,
419
+ state,
1347
420
  };
1348
421
 
1349
422
  // Capture old state for operations that modify data
1350
423
  if (operation === 'update' || operation === 'delete') {
1351
424
  const existingRecord = await store.find(this.model, getId(request.params)) as OrmRecord | undefined;
1352
-
1353
- // GATE 1 -- pre-handler. This record fetch already happened for
1354
- // oldState, so the check is free.
1355
- //
1356
- // Returning here rather than letting updateHandler/deleteHandler
1357
- // produce the same 404 is the point: everything between here and there
1358
- // is an executor the caller is not authorized to reach.
1359
- // - context.oldState is a deep copy of the HIDDEN RECORD'S CONTENTS.
1360
- // Building it and handing it to a before-hook discloses exactly what
1361
- // the filter exists to hide.
1362
- // - context.recordId is populated for delete BEFORE the handler runs,
1363
- // which is the same shape as the sqlDb landmine one layer up:
1364
- // `afterHook('delete', ctx => cascadeDelete(ctx.recordId))` destroys
1365
- // children behind a correct 404.
1366
- // - a before-hook may return a value and short-circuit, which would
1367
- // otherwise return a response without the filter ever executing.
1368
- //
1369
- // 404, not 403, for the same reason as getSingleHandler: the status for
1370
- // "exists but filtered out" must equal "does not exist".
1371
- if (existingRecord && isDenied(filter, existingRecord)) return 404;
1372
-
1373
425
  if (existingRecord) {
1374
426
  // Deep copy the record's data to preserve old state
1375
427
  context.oldState = JSON.parse(JSON.stringify(existingRecord.__data || existingRecord));
@@ -1389,52 +441,16 @@ export default class OrmRequest extends Request {
1389
441
  }
1390
442
 
1391
443
  // Execute main handler
1392
- // The handler receives the SNAPSHOT, never the live bag. `filter` is
1393
- // assigned LAST so it wins over anything a before-hook wrote to
1394
- // `callState.filter` -- including a `delete`, which the spread would
1395
- // otherwise carry through as an absent key. Every other key a hook adds
1396
- // is still visible to the handler; only the authorization input is
1397
- // pinned.
1398
- const handlerState = { ...callState, filter };
1399
- const response = await handler(request, handlerState);
444
+ const response = await handler(request, state);
1400
445
 
1401
446
  // Set context.record for update BEFORE persist so SQL drivers can read it
1402
447
  if (operation === 'update' && (response as JsonApiResponse)?.data) {
1403
448
  context.record = store.get(this.model, getId(request.params));
1404
449
  }
1405
450
 
1406
- // GATE 2 -- post-handler. A denied or failed handler returns a bare status
1407
- // integer, and no executor below may run for one.
1408
- //
1409
- // `>= 400` deliberately covers every failure status, not just the
1410
- // authorization ones: a 400 (POST with no `type`) and a 409 (duplicate id)
1411
- // are equally requests in which nothing happened, and a persist or a
1412
- // cascade hook for one of them is just as wrong.
1413
- // `Number.isInteger` is a TYPE guard, not a behaviour guard, and it is
1414
- // unkillable TODAY: the only non-integer a handler in this file can
1415
- // return is a `{ data, links }` object, and `{} >= 400` is `false` by JS
1416
- // coercion, so dropping it changes no reachable outcome. It is kept
1417
- // because `>=` coerces rather than rejects, and the shapes it coerces
1418
- // are not obvious -- `[500] >= 400` is TRUE, so a handler that one day
1419
- // returned an array would have every response read as a denial. Listed
1420
- // as an equivalent mutant rather than left to read as coverage; it
1421
- // becomes killable the moment a handler returns anything array-like or
1422
- // numeric-string-like.
1423
- const denied = Number.isInteger(response) && (response as number) >= 400;
1424
-
1425
- // EXECUTOR 1 -- SQL persistence, for all write operations.
1426
- //
1427
- // `response` is passed to sqlDb.persist below, but it is dropped at the
1428
- // driver boundary: _persistDelete(modelName, context) never receives it
1429
- // and guards only on context.recordId -- which _withHooks set above,
1430
- // BEFORE the handler ran. Without this gate a correct 404 still issues
1431
- // DELETE FROM ... WHERE id = ? on every SQL backend.
1432
- //
1433
- // No file-backed test can observe that, because Orm.instance.sqlDb is
1434
- // null in file/directory mode. See the stubbed-sqlDb assertions in
1435
- // test/unit/access-filter-enforcement-test.ts.
451
+ // Persist to SQL database for all write operations (create/update/delete)
1436
452
  const sqlDb = Orm.instance.sqlDb;
1437
- if (sqlDb && WRITE_OPERATIONS.has(operation) && !denied) {
453
+ if (sqlDb && WRITE_OPERATIONS.has(operation)) {
1438
454
  await sqlDb.persist(operation, this.model, context, response);
1439
455
  }
1440
456
 
@@ -1448,45 +464,20 @@ export default class OrmRequest extends Request {
1448
464
  } else if (operation === 'create' && (response as JsonApiResponse)?.data && ((response as { data: { id?: unknown } }).data.id)) {
1449
465
  // For create, get the record from store using the ID from the response
1450
466
  const responseData = (response as { data: { id: string | number } }).data;
1451
- // `normalizeBodyId`, not a copy of its body. This line WAS
1452
- // `isNaN(id) ? id : parseInt(id)` -- `coerceId` inlined verbatim, a
1453
- // third coercion feeding a store lookup, sitting under a docblock that
1454
- // said neither surface had a copy. Equivalent on every input that can
1455
- // reach this truthy-guarded branch (`21`->`21`, `'21'`->`21`,
1456
- // `'angela'`->`'angela'`; `''` and `0` cannot reach it), so this is a
1457
- // de-duplication rather than a behaviour change -- and that is the
1458
- // point: the two that disagreed were equivalent on every input anyone
1459
- // checked, too.
1460
- context.record = store.get(this.model, normalizeBodyId(responseData.id) as string | number);
467
+ const recordId = isNaN(responseData.id as unknown as number) ? responseData.id : parseInt(responseData.id as string);
468
+ context.record = store.get(this.model, recordId);
1461
469
  } else if (operation === 'delete') {
1462
470
  // For delete, the record may no longer exist, but we have oldState
1463
471
  context.recordId = getId(request.params);
1464
472
  }
1465
473
 
1466
- // EXECUTOR 2 -- the after-hook pipeline. This is the published consumer
1467
- // extension point (`afterHook` is exported from @stonyx/orm and from
1468
- // ./hooks), so it is the executor with the widest possible blast radius:
1469
- // a cascade delete, a webhook, a token revocation, a search-index purge.
1470
- //
1471
- // BEHAVIOUR CHANGE (#190): after-hooks no longer fire for a request that
1472
- // failed. Previously `afterHook('delete', ...)` ran with a populated
1473
- // context.recordId on a 404, so a consumer cascade destroyed children for
1474
- // a request that deleted nothing. Firing a hook named "after<operation>"
1475
- // for an operation that did not occur is a booby trap, and the denied case
1476
- // is unreachable-before-#190 while the missing case is inherited debt --
1477
- // both are closed by the same gate. `context.response` therefore only ever
1478
- // carries a success status into a hook.
1479
- if (!denied) {
1480
- for (const hook of getAfterHooks(operation, this.model)) {
1481
- await hook(context);
1482
- }
474
+ // Run after hooks sequentially
475
+ for (const hook of getAfterHooks(operation, this.model)) {
476
+ await hook(context);
1483
477
  }
1484
478
 
1485
- // EXECUTOR 3 -- file/directory autosave. Ungated this let an
1486
- // unauthenticated caller force a full serialize-and-write of the entire
1487
- // store on every DELETE of any id, with no record touched: amplification
1488
- // rather than corruption, but the same root cause and the same fix.
1489
- if (config.orm.db.autosave === 'onUpdate' && WRITE_OPERATIONS.has(operation) && !denied) {
479
+ // Auto-save DB after write operations when configured
480
+ if (config.orm.db.autosave === 'onUpdate' && WRITE_OPERATIONS.has(operation)) {
1490
481
  await (Orm.db as { save(): Promise<void> }).save();
1491
482
  }
1492
483
 
@@ -1506,118 +497,21 @@ export default class OrmRequest extends Request {
1506
497
  const dasherizedName = camelCaseToKebabCase(relationshipName);
1507
498
 
1508
499
  // Related resource route: GET /:id/{relationship}
1509
- //
1510
- // These generated routes are not wrapped by _withHooks, which is why they
1511
- // were the least obvious two of the seven unguarded surfaces in #190.
1512
- // They are still dispatched by @stonyx/rest-server as
1513
- // `handler(req, getState(req))`, so `state` -- and therefore the filter
1514
- // planted by auth() -- has always been available here; it was simply
1515
- // never declared or read.
1516
- routes[`/:id/${dasherizedName}`] = async (request: OrmRequest$, { filter }: { [key: string]: unknown } = {}) => {
500
+ routes[`/:id/${dasherizedName}`] = async (request: OrmRequest$) => {
1517
501
  const record = await store.find(model, getId(request.params)) as OrmRecord | undefined;
1518
502
  if (!record) return 404;
1519
- // Filtering the PARENT: a caller who may not see the record may not see
1520
- // what it is related to either.
1521
- if (isDenied(filter, record)) return 404;
1522
503
 
1523
504
  const relatedData = record.__relationships[relationshipName];
1524
505
  const baseUrl = getBaseUrl(request);
1525
506
 
1526
- // ONE FILTER, TWO JOBS, AND abofs/stonyx-orm#232 IS THE SECOND ONE.
1527
- //
1528
- // As LINKAGE (#234) it decides which ids the emitted documents may NAME
1529
- // in their own `relationships.*.data`. As MEMBERSHIP (this issue) it
1530
- // decides whether the related record is served here AT ALL -- the
1531
- // related resource is PRIMARY data on this route, so there is no
1532
- // linkage-consistency question to answer separately.
1533
- //
1534
- // Until #232 this route filtered only the PARENT, so a record its own
1535
- // model's predicate hides was served in full from another model's
1536
- // route, at ZERO query parameters. Measured on dev @ 8dda5d6:
1537
- //
1538
- // GET /owners/angela -> 404
1539
- // GET /animals/1/owner -> 200, owner:angela, full attributes
1540
- // GET /traits/2/tag -> 200, a model NO access class
1541
- // claims, on a collection that has
1542
- // no mounted route at all
1543
- //
1544
- // ARGUMENT ONE IS THE LIVE REQUEST, NOT A DERIVED ONE. A fabricated
1545
- // request addressing the RELATED resource was the original design and
1546
- // it is dropped: #241 removed the shipped fixture's read of argument
1547
- // one, so a fabricated value changes nothing it could observe.
1548
- // `createLinkageFilter` is also a published public export
1549
- // (src/index.ts) whose resolution granularity is per TYPE; supplying a
1550
- // per-RECORD request would mean widening it, which takes a consumer
1551
- // `access()` from ~2 calls to ~7 on a plain `GET /animals`. That is a
1552
- // separate, consumer-visible story.
1553
- //
1554
- // GUARDED BY OWN-PROPERTY IDENTITY, NOT BY THE #234 AC13 PIN. That pin
1555
- // (test/unit/linkage-verdict-test.ts, `strictEqual(seen[0].request,
1556
- // READ_REQUEST)`) calls `createLinkageFilter` DIRECTLY, so it pins the
1557
- // function's pass-through and constrains no call site -- an earlier
1558
- // revision of this comment cited it for this decision and was wrong.
1559
- // `Object.create(request)` here measured 1015 / 0 with nothing red.
1560
- // test/integration/orm-test.ts, `#232 AC9`, now asserts that the object
1561
- // the predicate is handed OWNS `params` (`Object.hasOwn`) and has
1562
- // nothing request-shaped behind it on the prototype chain. A derived
1563
- // request inherits `params` -- so it satisfies every value assertion
1564
- // there -- and reds on those two. Measured: with the derived request in
1565
- // place, 1014 / 1, and that one is this guard.
1566
- //
1567
- // THE RESIDUAL THAT FOLLOWS FROM THAT IS DISCLOSED, NOT PAPERED OVER.
1568
- // `recordId` is `null` here and the request names a record of a
1569
- // DIFFERENT model, so a consumer predicate can express a model-level or
1570
- // a request-level deny for a related resource, but NOT a per-record
1571
- // one. README.md and docs/usage-patterns.md say so; a ledger assertion
1572
- // in test/unit/relationship-route-access-test.ts keeps them saying it.
1573
- const linkage = createLinkageFilter(request);
1574
-
1575
- // FAIL CLOSED ON A RECORD WHOSE TYPE CANNOT BE NAMED. `isLinkable` is
1576
- // keyed on the model name; without one there is no predicate to ask,
1577
- // and an unidentifiable input must never be the permissive path.
1578
- const isLinkable = (r: OrmRecord) => {
1579
- const type = (r as { __model?: { __name?: string } }).__model?.__name;
1580
-
1581
- return typeof type === 'string' && type !== '' && linkage(type, r);
1582
- };
1583
-
1584
507
  let data: unknown;
1585
508
  if (info.isArray) {
1586
- // hasMany - return array, MINUS the members this caller may not see.
1587
- // Dropped, never errored: the result is byte-identical to a genuinely
1588
- // empty relationship, so this route is not an existence oracle.
509
+ // hasMany - return array
1589
510
  const related = Array.isArray(relatedData) ? relatedData.filter(isOrmRecord) : [];
1590
- data = related.filter(isLinkable).map(r => r.toJSON?.({ baseUrl, linkage }));
511
+ data = related.map(r => r.toJSON?.({ baseUrl }));
1591
512
  } else {
1592
- // belongsTo - return single or null. A DENIED target is `data: null`,
1593
- // BYTE-IDENTICAL to a relationship that is genuinely empty, for the
1594
- // same reason the hasMany branch above drops rather than errors: this
1595
- // route must not be an existence oracle for the RELATED record.
1596
- //
1597
- // THE OTHER SPELLING WAS 404 AND IT WAS MEASURED AS A DISCLOSURE.
1598
- // Unauthenticated, zero query parameters, one request each, on `tag`
1599
- // -- the model with no route mounted at all, which is exactly what
1600
- // #240 AC5 exists to protect:
1601
- //
1602
- // GET /traits/1/tag [ABSENT] -> 200 application/json len 68
1603
- // GET /traits/2/tag [DENIED] -> 404 text/plain len 9
1604
- //
1605
- // and `GET /traits/1` and `GET /traits/2` both report
1606
- // `relationships.tag = {"data":null}` byte-identical modulo the id,
1607
- // because #234 closed THAT oracle deliberately. A 404 here would let
1608
- // a caller ask which of those two nulls was a denial. Under
1609
- // `data: null` the pair closes completely: 200/200, same
1610
- // content-type, same content-length, bodies identical modulo the
1611
- // parent id the caller put in the URL. It opens nothing -- `links`
1612
- // are entirely parent-derived, there is no `meta` and no counts.
1613
- //
1614
- // This is also what README.md's module-wide rule already demanded:
1615
- // every status on a record route must be identical for filtered-out
1616
- // and does-not-exist. The route now CONFORMS to that rule rather than
1617
- // carving an exception out of it.
1618
- if (!isOrmRecord(relatedData)) data = null;
1619
- else if (!isLinkable(relatedData)) data = null;
1620
- else data = relatedData.toJSON?.({ baseUrl, linkage });
513
+ // belongsTo - return single or null
514
+ data = isOrmRecord(relatedData) ? relatedData.toJSON?.({ baseUrl }) : null;
1621
515
  }
1622
516
 
1623
517
  return {
@@ -1627,100 +521,23 @@ export default class OrmRequest extends Request {
1627
521
  };
1628
522
 
1629
523
  // Relationship linkage route: GET /:id/relationships/{relationship}
1630
- //
1631
- // NO `linkage` FILTER FROM abofs/stonyx-orm#235, AND THAT IS A SCOPE
1632
- // BOUNDARY RATHER THAN AN OVERSIGHT -- abofs/stonyx-orm#232 OWNS THIS
1633
- // ROUTE, and PR #247 is IN FLIGHT against it in this same sprint. If you
1634
- // are reading this after #247 landed, the filtering below is #232's and
1635
- // this note records why it was never #235's to add.
1636
- //
1637
- // The three sites #235 does own -- `buildResponse`'s `included`, and the
1638
- // two write handlers, `POST /:models` and `PATCH /:models/:id` -- all
1639
- // reach the filter through `record.toJSON()`, which is where the
1640
- // `linkage` OPTION is applied.
1641
- //
1642
- // The related-resource branch above ALSO passes a `linkage` filter, and
1643
- // it is NOT one of those three: it is abofs/stonyx-orm#234's code and
1644
- // predates this change. `git diff 8dda5d6..HEAD -- src/orm-request.ts`
1645
- // leaves that branch byte-unchanged.
1646
- //
1647
- // This branch builds its `{ type, id }` objects BY
1648
- // HAND and never calls `toJSON` at all, so the `linkage` option cannot
1649
- // reach it -- whatever this route filters, it has to filter itself, which
1650
- // is precisely why doing so is a separate change with a separate owner.
1651
- //
1652
- // It is also a DIFFERENT QUESTION. Everywhere #235 touches, linkage is
1653
- // metadata ABOUT a document. Here the linkage IS the primary data, so
1654
- // dropping an entry is a MEMBERSHIP decision about what this route
1655
- // serves -- the same class as abofs/stonyx-orm#233 and #196, not the
1656
- // class #234/#235 close. That is why it is absent from #224 §2a's
1657
- // seven-site inventory.
1658
- //
1659
- // MEASURED, so the next person does not re-derive it. Against this
1660
- // branch's baseline of 1011/0, wiring `createLinkageFilter` into the
1661
- // belongsTo branch below takes the suite to 1009/2, reddening
1662
- // `[GUARD] #235 X2` and the
1663
- // `GET /animals/:id/relationships/owner returns relationship linkage`
1664
- // test -- the latter is #232's own reproduction, not a regression.
1665
- //
1666
- // THE BASELINE IS QUOTED WITH THE RESULT BECAUSE AN EARLIER REVISION OF
1667
- // THIS COMMENT SAID 993/2 AND SHIPPED IT. This file lands in consumers'
1668
- // `node_modules`, so a wrong number here is a wrong number in the
1669
- // published package. 993+2 = 995 is the DEV baseline, carried over from
1670
- // a branch on which `[GUARD] #235 X2` does not exist. A pass/fail pair
1671
- // with no baseline beside it cannot be checked by reading, which is how
1672
- // it survived three artifacts and a review; the qualitative claim was
1673
- // right the whole time and only the count was wrong.
1674
- //
1675
- // `[GUARD] #235 X2` in test/integration/orm-test.ts pins the OWNERSHIP
1676
- // BOUNDARY here rather than this route's current answer, so that it
1677
- // survives #247 landing. Read its comment before changing it.
1678
- routes[`/:id/relationships/${dasherizedName}`] = async (request: OrmRequest$, { filter }: { [key: string]: unknown } = {}) => {
524
+ routes[`/:id/relationships/${dasherizedName}`] = async (request: OrmRequest$) => {
1679
525
  const record = await store.find(model, getId(request.params)) as OrmRecord | undefined;
1680
526
  if (!record) return 404;
1681
- if (isDenied(filter, record)) return 404;
1682
527
 
1683
528
  const relatedData = record.__relationships[relationshipName];
1684
529
  const baseUrl = getBaseUrl(request);
1685
530
 
1686
- // THE ONE READ SURFACE THAT DOES NOT GO THROUGH `toJSON()`. It builds
1687
- // `{ type, id }` BY HAND, which is why #234's linkage filter never
1688
- // reached it and why this half belongs to abofs/stonyx-orm#232 rather
1689
- // than to #234: on this route the linkage IS the primary data of an
1690
- // opt-in request, so filtering it changes the route's MEMBERSHIP
1691
- // semantics, not the ids named inside somebody else's document.
1692
- //
1693
- // DELIBERATELY NOT STATED AS A COUNT. README.md's Consumer Contracts
1694
- // section enumerates the surfaces on which the framework resolves a
1695
- // verdict and hands it to `toJSON()`, and that enumeration GROWS --
1696
- // abofs/stonyx-orm#235 adds the two write handlers and the `included`
1697
- // records. This route is not on that list under any count, because it
1698
- // never calls `toJSON()`: whatever it filters, it filters here. A
1699
- // number written into this comment would be false the next time that
1700
- // list changes, and the README already carries the enumeration.
1701
- //
1702
- // Same filter, same argument-one decision, same residual as
1703
- // `/:id/{relationship}` above -- read the block there.
1704
- const linkage = createLinkageFilter(request);
1705
- const isLinkable = (r: OrmRecord) => {
1706
- const type = (r as { __model?: { __name?: string } }).__model?.__name;
1707
-
1708
- return typeof type === 'string' && type !== '' && linkage(type, r);
1709
- };
1710
-
1711
531
  let data: unknown;
1712
532
  if (info.isArray) {
1713
533
  // hasMany - return array of linkage objects
1714
534
  const related = Array.isArray(relatedData) ? relatedData.filter(isOrmRecord) : [];
1715
535
  data = related
1716
536
  .filter((r): r is OrmRecord & { __model: { __name: string } } => Boolean(r.__model))
1717
- .filter(isLinkable)
1718
537
  .map(r => ({ type: r.__model.__name, id: r.id }));
1719
538
  } else {
1720
- // belongsTo - return single linkage or null. A DENIED target is
1721
- // `data: null`, indistinguishable from a genuinely empty one -- see
1722
- // the measured oracle in the `/:id/{relationship}` block above.
1723
- if (isOrmRecord(relatedData) && relatedData.__model && isLinkable(relatedData)) {
539
+ // belongsTo - return single linkage or null
540
+ if (isOrmRecord(relatedData) && relatedData.__model) {
1724
541
  data = { type: relatedData.__model.__name, id: relatedData.id };
1725
542
  } else {
1726
543
  data = null;
@@ -1737,140 +554,32 @@ export default class OrmRequest extends Request {
1737
554
  };
1738
555
  }
1739
556
 
1740
- // Catch-alls for invalid relationship names. Every valid relationship was
1741
- // registered above, so reaching either of these means the relationship does
1742
- // not exist and the answer is 404 regardless of the record.
1743
- //
1744
- // These deliberately carry NO access check and no store lookup. An earlier
1745
- // revision of #190 added `if (isDenied(filter, record)) return 404` here for
1746
- // symmetry with the seven real surfaces, but both branches returned 404, so
1747
- // the guard was unobservable by construction -- a mutation deleting it
1748
- // survived the entire suite because no test that could distinguish it can
1749
- // exist. Unkillable code in an authorization diff reads as coverage and is
1750
- // not, so it is gone; skipping the lookup also removes the timing difference
1751
- // between an existing and a missing parent.
1752
- //
1753
- // IF THIS ROUTE EVER RETURNS ANYTHING OTHER THAN A CONSTANT 404, it becomes
1754
- // the eighth surface and must filter the parent first, exactly like
1755
- // `/:id/{relationship}` above.
1756
- routes[`/:id/:relationship`] = async () => 404;
1757
- routes[`/:id/relationships/:relationship`] = async () => 404;
1758
-
1759
- return routes;
1760
- }
557
+ // Catch-all for invalid relationship names on related resource route
558
+ routes[`/:id/:relationship`] = async (request: OrmRequest$) => {
559
+ const record = await store.find(model, getId(request.params));
560
+ if (!record) return 404;
1761
561
 
1762
- auth(request: OrmRequest$, state: { [key: string]: unknown }): number | undefined {
1763
- // A consumer `access()` that throws is a DENIAL, matching `isDenied` one
1764
- // layer down. Unguarded it propagates to express's default handler, which
1765
- // answers 500 -- and the documented sample itself can throw
1766
- // (`request.originalUrl.split(...)` when originalUrl is absent), so the
1767
- // failure mode is reachable by following the docs.
1768
- // -------------------------------------------------------------------------
1769
- // #202 -- hand the consumer the STRUCTURAL facts, not just the transport.
1770
- //
1771
- // Both members are already in hand here. `model` is `this.model`, the name
1772
- // setup-rest-server mounted this route for; `operation` is the SAME
1773
- // `methodAccessMap` lookup the permission-array branch at the bottom of
1774
- // this method performs, so the predicate form and the array form cannot
1775
- // answer differently about the same request.
1776
- //
1777
- // NEITHER IS DERIVED FROM THE REQUEST TARGET, and that is the whole point.
1778
- // Deriving `model` here from `request.baseUrl` (or from the mounted route
1779
- // name, or from `getPluralName(this.model)`) would move all five fail-open
1780
- // variants listed in this file's header OUT of the consumer and INTO the
1781
- // framework, where every consumer inherits them at once. `this.model` is
1782
- // assigned once at mount time and no request can influence it.
1783
- //
1784
- // `operation` is left UNDEFINED for a method with no entry in
1785
- // `methodAccessMap`, rather than defaulted. Express delivers HEAD to the
1786
- // GET handler, so an unmapped method really does reach this line; a
1787
- // `?? 'read'` here would hand the consumer a fabricated authorisation fact
1788
- // and turn an unclassified request into an authorised one. Undefined is
1789
- // the honest answer.
1790
- //
1791
- // `record` is deliberately absent -- see `AccessContext` in
1792
- // src/types/orm-types.ts. Nothing is fetched at this point and adding a
1793
- // lookup here would put a store read in the middle of an authorization
1794
- // path. The function return shape below IS the per-record hook.
1795
- //
1796
- // -------------------------------------------------------------------------
1797
- // #236 -- `recordId`, the DECODED route-parameter id, for the same reason.
1798
- //
1799
- // WHICH RECORD is the third structural fact the framework already holds and
1800
- // the consumer was left to re-derive, and re-deriving it failed OPEN. The
1801
- // documented sample compared `request.path` -- the RAW, undecoded pathname
1802
- // -- against a literal `/archived`, while the router DECODES `:id`. So
1803
- // `GET /owners/%61rchived` walked past the deny and was dispatched as the
1804
- // record `archived`: 200 with the record in full, and DELETE answered 204
1805
- // with the record destroyed, unauthenticated. Four spellings measured, all
1806
- // four through; 255 non-canonical spellings of that 8-character id decode
1807
- // to the same key, so this was never a deny-list of one.
1808
- //
1809
- // TWO CONSUMER-SIDE NORMALISATIONS WERE MEASURED WRONG IN OPPOSITE
1810
- // DIRECTIONS, which is the argument for doing it once, here.
1811
- // `.toLowerCase()` case-folds a route-parameter VALUE on the axis that
1812
- // governs literal SEGMENTS: with a distinct owner seeded at `ARCHIVED`,
1813
- // `GET /owners/ARCHIVED` was a false DENY on the wrong record and
1814
- // `GET /owners/%41RCHIVED` a false ALLOW on that same one.
1815
- // `decodeURIComponent(request.path)` decodes THEN splits while the router
1816
- // splits THEN decodes, so it over-denied `/owners/archived%2fx` -- 403 for
1817
- // a genuinely distinct record. Failing closed there was luck, not design.
1818
- //
1819
- // `getId(request.params)` AND NOT `request.params.id`, for exactly the
1820
- // reason `operation` is a `methodAccessMap` lookup: it is the SAME single
1821
- // coercion the store lookup one layer down performs, so the predicate and
1822
- // the dispatch cannot disagree about which record a request addresses.
1823
- // The raw string would reintroduce that divergence on hex-shaped ids --
1824
- // `GET /animals/0x2391` looks up record `9105`.
1825
- //
1826
- // NOTHING HERE PARSES THE REQUEST TARGET EITHER. `request.params` is what
1827
- // the router matched, so a mount prefix, an absolute-form target, a query
1828
- // string or a case-varied mount cannot move this value -- the same
1829
- // guarantee `model` carries, by the same means.
1830
- //
1831
- // `null` and not `undefined` on a collection route, so the KEY IS ALWAYS
1832
- // PRESENT -- the rule `operation`'s own docblock already establishes. A
1833
- // context reaching a predicate WITHOUT the key therefore did not come from
1834
- // here; it was hand-assembled by a caller resolving the predicate through
1835
- // `Orm.instance.getAccess()`, and that absence stays deniable only because
1836
- // `auth()` never produces it.
1837
- // -------------------------------------------------------------------------
1838
- const context: AccessContext = {
1839
- model: this.model,
1840
- operation: methodAccessMap[request.method],
1841
- recordId: request.params && 'id' in request.params ? getId(request.params) : null,
562
+ // If we reach here, relationship doesn't exist (valid ones were registered above)
563
+ return 404;
1842
564
  };
1843
565
 
1844
- let access: AccessMethod;
1845
- try {
1846
- access = this.access(request, context);
1847
- } catch (error) {
1848
- // Same reasoning as `isDenied`: fail closed, but say so. An `access()`
1849
- // that throws denies EVERY request to the collection, and a silent 403
1850
- // wall is the hardest possible thing to diagnose from the outside.
1851
- log.error?.(`[@stonyx/orm] access() threw for model "${this.model}" -- denying. ${error instanceof Error ? error.message : String(error)}`);
1852
-
1853
- return 403; // Forbidden
1854
- }
566
+ // Catch-all for invalid relationship names on relationship linkage route
567
+ routes[`/:id/relationships/:relationship`] = async (request: OrmRequest$) => {
568
+ const record = await store.find(model, getId(request.params));
569
+ if (!record) return 404;
1855
570
 
1856
- // THE READING OF THE RETURN SHAPE LIVES IN ONE PLACE (#234).
1857
- //
1858
- // It used to be inline here, and it was the only copy, which was fine while
1859
- // `auth()` was the only thing that had to ask. It is not any more: the
1860
- // linkage path has to ask model X's predicate about model X's records while
1861
- // servicing a request routed to model Y, and a second inline copy of these
1862
- // six branches would be a second authorization vocabulary -- one that can
1863
- // drift, and that reviewers would have to notice had drifted. The branch
1864
- // order in `interpretAccess` is this block, moved, not rewritten.
1865
- const verdict = interpretAccess(access, methodAccessMap[request.method]);
571
+ return 404;
572
+ };
1866
573
 
1867
- if (!verdict.granted) return 403;
574
+ return routes;
575
+ }
1868
576
 
1869
- // The function return shape is the per-record hook, and `state` is the
1870
- // whole transport for it: @stonyx/rest-server memoises one state object per
1871
- // request and hands the same one to `auth()` and to the handler.
1872
- if (verdict.filter) state.filter = verdict.filter;
577
+ auth(request: OrmRequest$, state: { [key: string]: unknown }): number | undefined {
578
+ const access = this.access(request);
1873
579
 
580
+ if (!access) return 403;
581
+ if (Array.isArray(access) && !access.includes(methodAccessMap[request.method])) return 403;
582
+ if (typeof access === 'function') state.filter = access;
1874
583
  return undefined;
1875
584
  }
1876
585
  }