@stonyx/orm 0.3.2-alpha.8 → 0.3.2-alpha.80

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.
Files changed (65) hide show
  1. package/README.md +1137 -11
  2. package/config/environment.js +8 -0
  3. package/dist/access-verdict.d.ts +85 -0
  4. package/dist/access-verdict.js +284 -0
  5. package/dist/commands.js +34 -0
  6. package/dist/dynamodb/connection.d.ts +31 -0
  7. package/dist/dynamodb/connection.js +28 -0
  8. package/dist/dynamodb/dynamodb-db.d.ts +142 -0
  9. package/dist/dynamodb/dynamodb-db.js +596 -0
  10. package/dist/dynamodb/operation-builder.d.ts +76 -0
  11. package/dist/dynamodb/operation-builder.js +116 -0
  12. package/dist/dynamodb/type-map.d.ts +31 -0
  13. package/dist/dynamodb/type-map.js +48 -0
  14. package/dist/hooks.d.ts +15 -1
  15. package/dist/index.d.ts +3 -0
  16. package/dist/index.js +8 -0
  17. package/dist/main.d.ts +116 -0
  18. package/dist/main.js +129 -0
  19. package/dist/manage-record.js +268 -12
  20. package/dist/mysql/connection.d.ts +1 -0
  21. package/dist/mysql/mysql-db.d.ts +8 -0
  22. package/dist/mysql/mysql-db.js +44 -10
  23. package/dist/orm-request.d.ts +264 -3
  24. package/dist/orm-request.js +1138 -61
  25. package/dist/postgres/connection.d.ts +1 -0
  26. package/dist/postgres/connection.js +8 -6
  27. package/dist/postgres/postgres-db.d.ts +8 -0
  28. package/dist/postgres/postgres-db.js +44 -10
  29. package/dist/record.d.ts +16 -0
  30. package/dist/record.js +154 -6
  31. package/dist/relationships.js +1 -1
  32. package/dist/serializer.js +38 -2
  33. package/dist/setup-rest-server.js +51 -5
  34. package/dist/standalone-db.js +17 -5
  35. package/dist/store.d.ts +13 -1
  36. package/dist/store.js +65 -6
  37. package/dist/types/orm-types.d.ts +234 -0
  38. package/dist/utils.d.ts +44 -0
  39. package/dist/utils.js +47 -0
  40. package/package.json +16 -7
  41. package/src/access-verdict.ts +312 -0
  42. package/src/commands.ts +43 -0
  43. package/src/dynamodb/connection.ts +50 -0
  44. package/src/dynamodb/dynamodb-db.ts +811 -0
  45. package/src/dynamodb/operation-builder.ts +202 -0
  46. package/src/dynamodb/type-map.ts +54 -0
  47. package/src/hooks.ts +15 -1
  48. package/src/index.ts +10 -0
  49. package/src/main.ts +133 -0
  50. package/src/manage-record.ts +294 -18
  51. package/src/mysql/connection.ts +1 -0
  52. package/src/mysql/mysql-db.ts +44 -12
  53. package/src/orm-request.ts +1159 -63
  54. package/src/postgres/connection.ts +10 -6
  55. package/src/postgres/postgres-db.ts +44 -12
  56. package/src/record.ts +182 -6
  57. package/src/relationships.ts +1 -1
  58. package/src/serializer.ts +39 -2
  59. package/src/setup-rest-server.ts +59 -6
  60. package/src/standalone-db.ts +17 -6
  61. package/src/store.ts +68 -6
  62. package/src/types/orm-types.ts +242 -1
  63. package/src/types/stonyx-rest-server.d.ts +14 -1
  64. package/src/types/stonyx.d.ts +7 -1
  65. package/src/utils.ts +50 -0
@@ -1,10 +1,273 @@
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. The related-resource and `?include=` surfaces serve ANOTHER model's
69
+ * records under `model: 'owner'`, and the context gives no signal of that
70
+ * (abofs/stonyx-orm#196).
71
+ *
72
+ * SUPERSEDED 2026-09-01 BY abofs/stonyx-orm#236/#237, AND KEPT FOR THE
73
+ * CONSTRAINT IT STATES RATHER THAN AS A DESCRIPTION OF THE CODE. The context
74
+ * now also carries `recordId` -- the DECODED route-parameter id, see
75
+ * `AccessContext.recordId` in ./types/orm-types.ts -- so the fixture's
76
+ * `/archived` deny IS expressible from the context alone, and the shipped
77
+ * sample no longer reads `request.path` at all. Retiring this wording WITH the
78
+ * measurement that retires it, rather than by deletion, is
79
+ * abofs/stonyx-orm#238.
80
+ *
81
+ * `record` IS NOT IN THIS CONTEXT, deliberately. `auth()` runs after route
82
+ * matching but BEFORE any handler executes (`@stonyx/rest-server`
83
+ * `src/request.ts:58-60`), so nothing has been fetched yet -- supplying a
84
+ * record would force a pre-fetch on every request, a second store hit and an
85
+ * ordering change in the middle of an authorization path. It is also
86
+ * unnecessary: the FUNCTION return shape already is the per-record hook. Return
87
+ * `(record) => boolean` and the handlers apply it to every record the request
88
+ * touches. Auth-time and record-time are separate decision points.
89
+ *
90
+ * THE SECOND ARGUMENT IS ADDITIVE. JavaScript ignores extra arguments, so an
91
+ * existing `access(request)` predicate keeps working exactly as before. The
92
+ * warning immediately below is therefore still live: `request` is still
93
+ * argument ONE, and reading it is still how predicates fail open.
94
+ *
95
+ * To reach ANOTHER model's predicate -- e.g. to check an animal while servicing
96
+ * an owners route -- use the boot-time registry:
97
+ *
98
+ * const predicate = Orm.instance.getAccess('animal');
99
+ * if (!predicate) return deny;
100
+ * const verdict = predicate(request, { model: 'animal', operation: 'read' });
101
+ *
102
+ * `undefined` means NO PREDICATE COULD BE RESOLVED for that name -- which
103
+ * includes the case where the model has an access class that failed to load,
104
+ * because `setup-rest-server.ts` catches a load failure, warns, and publishes
105
+ * whatever partial map it had. It does NOT mean the model is unrestricted.
106
+ * Treat it as DENY, the same way `operation === undefined` is treated above.
107
+ *
108
+ * PASSING THE CONTEXT MAKES A MODEL-CORRECT ANSWER POSSIBLE. It does not make
109
+ * the answer model-correct on its own -- the resolved predicate has to READ it.
110
+ * Measured against an ARITY-1 predicate, on a request express dispatched to
111
+ * `GET /owners/angela`, asked about ANIMALS:
112
+ *
113
+ * getAccess('animal')(ownersRequest, { model: 'animal', operation: 'read' })
114
+ * -> record => record.id !== 'angela' && record.id !== 'restricted'
115
+ *
116
+ * That is the OWNERS filter, and it returns `true` for animal 21 -- the record
117
+ * hidden on every animal surface. Under a mount that predicate recognises
118
+ * neither way it is worse: it falls through to
119
+ * `['read', 'create', 'update', 'delete']`, a full CRUD grant. Either way the
120
+ * context was supplied and the answer is not the animal answer, and it is wrong
121
+ * in the GRANTING direction, because that predicate is arity-1 and identifies
122
+ * its collection from the request. (Asserted on a live dispatch by AC9 in
123
+ * test/integration/orm-test.ts, against a deliberately arity-1 predicate.)
124
+ *
125
+ * This repo's own sample access class has since been MIGRATED to read the
126
+ * context (abofs/stonyx-orm#222), so `getAccess('animal')` here now answers
127
+ * with the animal filter. That is not true of a consumer tree: an arity-1
128
+ * predicate keeps working -- the second argument is additive -- and the caller
129
+ * has no supported way to tell which kind it got. The boot-time arity warning
130
+ * that surfaces one is abofs/stonyx-orm#221.
131
+ * So: pass the context, and do not treat a resolved predicate's answer as
132
+ * model-specific until that predicate has been migrated to read the context.
133
+ *
134
+ * ---------------------------------------------------------------------------
135
+ * DO NOT RECONSTRUCT THE REQUEST PATH INSIDE `access()`.
136
+ * ---------------------------------------------------------------------------
137
+ * You do not have to. `auth()` below hands your predicate the ACCESS CONTEXT as
138
+ * argument two, and `context.model` already names the collection -- see the
139
+ * contract section above. Argument ONE is still the raw transport artifact, and
140
+ * everything from here to the end of this banner is the record of what happened
141
+ * when predicates worked the collection out from it. IT IS HISTORY, NOT
142
+ * GUIDANCE: do not write any of it into a new predicate. Every attempt to
143
+ * identify the collection by parsing the request target has failed OPEN. Five
144
+ * distinct variants of the same three-line example have now been found, each
145
+ * after the previous was fixed, by five different people:
146
+ *
147
+ * 1. `request.url` is mount-relative under `RestServer.mountRoute`, so a
148
+ * prefix match against it is ALWAYS false.
149
+ * 2. `request.originalUrl` carries the query string, so an anchored equality
150
+ * check misses `/owners?filter[age]=30`.
151
+ * 3. The router is a bare `express()` (`caseSensitive: false`) while a
152
+ * hand-written matcher is case-SENSITIVE, so `GET /OwNeRs/angela` walks
153
+ * past it. Router-side: abofs/stonyx-rest-server#47.
154
+ * 4. Under a configured `ORM_REST_ROUTE` a hard-coded `/owners` matches
155
+ * nothing -- environment-specifically, which is worse.
156
+ * 5. HTTP/1.1 permits an ABSOLUTE-FORM request-target. Express routes on
157
+ * `parseurl(req).pathname`, but `originalUrl` is the raw target, so
158
+ * `GET http://anything.example/owners/angela` reaches the handler with
159
+ * `originalUrl === 'http://anything.example/owners/angela'`. A `/owners`
160
+ * prefix match is false, `access()` falls through to whatever it returns
161
+ * last, and the record comes back in full. It walks past a hard
162
+ * `return false` deny the same way.
163
+ *
164
+ * The fix is not a sixth rule, and it is not a better string to match. It is to
165
+ * stop identifying the collection at all: read `context.model`. That is a claim
166
+ * about IDENTIFYING THE COLLECTION, not about the sample as a whole -- the
167
+ * `/archived` SUB-PATH rule is still a string match, and abofs/stonyx-orm#228 is
168
+ * a sixth spelling that gets past it.
169
+ *
170
+ * SUPERSEDED 2026-09-01 BY abofs/stonyx-orm#236/#237: the `/archived` rule is
171
+ * no longer a string match against the request target -- it compares the
172
+ * decoded `recordId` the framework supplies -- and abofs/stonyx-orm#228 is
173
+ * CLOSED. Retirement of this wording: abofs/stonyx-orm#238.
174
+ *
175
+ * An intermediate revision of the sample read `request.baseUrl` -- the mount
176
+ * Express ACTUALLY MATCHED. That closed all five variants (no query string,
177
+ * not mount-relative, unaffected by absolute-form, already carrying the
178
+ * configured `ORM_REST_ROUTE` prefix), but it was a transport artifact
179
+ * standing in for a structural fact and the sample no longer does it.
180
+ * `context.model` IS the structural fact, so variants 1, 2, 4 and 5 are
181
+ * unconstructible against a migrated predicate rather than handled.
182
+ *
183
+ * VARIANT 3 SURVIVES, and is deliberately not in that list. It is the general
184
+ * shape "a hand-written matcher normalises differently from the router", and a
185
+ * migrated predicate still runs one string comparison for any SUB-PATH rule --
186
+ * in the shipped sample, the `/archived` deny. That comparison folds case but
187
+ * does not decode, so `GET /owners/%61rchived` steps past it. See the
188
+ * normalisation paragraph below and abofs/stonyx-orm#228.
189
+ *
190
+ * SUPERSEDED 2026-09-01 BY abofs/stonyx-orm#236/#237. Variant 3 lived in that
191
+ * one string comparison, and the comparison is gone: the sample compares the
192
+ * decoded `recordId`. Left standing rather than edited because the same
193
+ * "variant 3 survives" wording sits at four sites -- this header, README.md
194
+ * twice, and test/sample/access/global-access.ts -- three of which SHIP, so
195
+ * retiring one of four leaves the shipped copies contradicting each other.
196
+ * Retiring all four WITH their measurement is abofs/stonyx-orm#238.
197
+ *
198
+ * ONE READ OF ARGUMENT ONE SURVIVES, AND IT MUST: `request.path`. It is
199
+ * mount-relative and query-free, and it is for rules that distinguish SUB-PATHS
200
+ * beneath the mount. The context names which model and which verb, NOT which
201
+ * route, so the sample's `/archived` deny cannot be expressed from the context
202
+ * alone and a context-ONLY rewrite would silently turn that deny into an allow.
203
+ *
204
+ * SUPERSEDED 2026-09-01 BY abofs/stonyx-orm#236/#237: NO read of argument one
205
+ * survives in the shipped sample. `recordId` names WHICH RECORD the route was
206
+ * addressed to, so the `/archived` deny is expressible from the context alone
207
+ * -- and it still must not be dropped; expressible is not optional. Retirement
208
+ * of this wording: abofs/stonyx-orm#238.
209
+ *
210
+ * NORMALISE THE WAY THE ROUTER DOES, AND CASE-FOLDING ALONE IS NOT THAT. The
211
+ * sample lower-cases before comparing, because a matcher stricter than the
212
+ * case-insensitive router can be stepped around. That closes the case gap only.
213
+ * Express sets `request.path` from the RAW, UNDECODED pathname while the router
214
+ * DECODES `:id`, so `GET /owners/%61rchived` reaches a `path === '/archived'`
215
+ * comparison as `/%61rchived` and walks past the deny. That gap is live in the
216
+ * sample and is tracked as abofs/stonyx-orm#228; the `.toLowerCase()` is not a
217
+ * complete normalisation recipe. Compare record ids at their real case.
218
+ *
219
+ * DO NOT FOLLOW THE PARAGRAPH ABOVE. SUPERSEDED 2026-09-01 BY
220
+ * abofs/stonyx-orm#236/#237, and flagged here rather than merely dated because
221
+ * it is an INSTRUCTION, not a stale observation. `.toLowerCase()` on the access
222
+ * path was measured WRONG IN BOTH DIRECTIONS AT ONCE: with a distinct owner
223
+ * seeded at `ARCHIVED`, `GET /owners/ARCHIVED` was a false DENY on the wrong
224
+ * record and `GET /owners/%41RCHIVED` a false ALLOW on that same record. A
225
+ * record id is a VALUE, not a literal route segment, and express's
226
+ * `case sensitive routing` governs literal segments only. Compare
227
+ * `context.recordId` AS IT ARRIVES: do not case-fold it, do not decode it, do
228
+ * not derive it from `request.path`. `AccessContext.recordId` in
229
+ * ./types/orm-types.ts is the contract and says "Do NOT case-fold it"; the same
230
+ * published tarball ships both files, and THIS paragraph is the one that is
231
+ * wrong. Retiring it WITH its measurement is abofs/stonyx-orm#238.
232
+ *
233
+ * `?? ''` is not a defence. It converts an absent request target into an empty
234
+ * string, which matches no collection, which falls through to the permission
235
+ * array -- a total grant. An input you cannot identify must DENY, and that
236
+ * applies to BOTH arguments: since #202 the guard and the read can sit on
237
+ * different objects, and a guard on argument two does not protect a read of
238
+ * argument one. The sample returns `false` for an absent `model` AND for an
239
+ * absent or non-string `request.path`, rather than falling through either way.
240
+ *
241
+ * SUPERSEDED 2026-09-01 BY abofs/stonyx-orm#236/#237 as to WHAT is guarded --
242
+ * the principle is unchanged. The sample no longer reads `request.path`, so it
243
+ * returns `false` for an absent `model` AND for an absent `recordId`
244
+ * (`undefined`, the one spelling `auth()` never produces). Retirement of this
245
+ * wording: abofs/stonyx-orm#238.
246
+ *
247
+ * THE REAL FIX IS abofs/stonyx-orm#202: `access()` should receive the model,
248
+ * the operation and the record. Prefer the array shape (`['read']`) or `false`
249
+ * until #202 lands; the function shape is what requires any matching at all.
250
+ *
251
+ * The enforcement gates in this file (GATE 0/1/2, the create rollback, the
252
+ * per-handler `isDenied` re-checks) are correct independently of that -- they
253
+ * enforce whatever predicate you return. The stopgap is the part where YOU have
254
+ * to work out which predicate to return.
255
+ *
256
+ * AND A PREDICATE IS NOT A GUARANTEE THAT A HIDDEN RECORD CANNOT BE MODIFIED.
257
+ * It is evaluated against the record the route is ADDRESSED TO, on that model
258
+ * only. A write to a DIFFERENT collection can still re-parent a hidden record
259
+ * and de-hide it -- abofs/stonyx-orm#207, which is blocked on #202 and #196.
260
+ * See `### Known limitations` in README.
261
+ */
1
262
  import { Request } from '@stonyx/rest-server';
2
263
  import Orm, { store, createRecord, updateRecord } from '@stonyx/orm';
3
264
  import { camelCaseToKebabCase } from '@stonyx/utils/string';
4
265
  import { getPluralName } from './plural-registry.js';
5
266
  import { getBeforeHooks, getAfterHooks } from './hooks.js';
6
267
  import config from 'stonyx/config';
7
- import { isOrmRecord } from './utils.js';
268
+ import log from 'stonyx/log';
269
+ import { isOrmRecord, NO_FREE_ID_ERROR } from './utils.js';
270
+ import { interpretAccess, createLinkageFilter } from './access-verdict.js';
8
271
  const methodAccessMap = {
9
272
  GET: 'read',
10
273
  POST: 'create',
@@ -48,16 +311,120 @@ function getBaseUrl(request) {
48
311
  const host = request.get('host');
49
312
  return `${protocol}://${host}`;
50
313
  }
314
+ /**
315
+ * The ONE coercion from a caller-supplied id to the key the store holds it
316
+ * under. Every id-bearing surface in this file goes through it, and none has a
317
+ * copy: `getId()` (URL params), `normalizeBodyId()` (JSON body), and the
318
+ * post-create `context.record` lookup in `_withHooks`.
319
+ *
320
+ * WHY IT IS SHARED RATHER THAN DUPLICATED. `getId()` and `normalizeBodyId()`
321
+ * each had their own arithmetic, and they disagreed: `parseInt(id)` versus
322
+ * `parseInt(id, 10)`. On a hex-shaped id that is a two-record difference --
323
+ *
324
+ * GET /animals/0x2391 -> record 9105 (getId -> parseInt('0x2391') = 9105)
325
+ * POST /animals {"id":"0x2391"} -> lookup under 0 (normalize -> parseInt('0x2391',10) = 0)
326
+ * -> a MISS, so the duplicate check was skipped and
327
+ * createRecord OVERWROTE 9105 in place, answering 200
328
+ *
329
+ * -- a narrower form of the raw-versus-normalised divergence that the body-id
330
+ * normalisation was added to close, reintroduced by the fix for it. Two
331
+ * coercions that must agree cannot be kept in agreement by review; they have to
332
+ * be one function. Pinned by assertion 43.
333
+ *
334
+ * The third copy was found later and in a quieter place: `_withHooks` populated
335
+ * `context.record` for `create` with `isNaN(id) ? id : parseInt(id)` -- this
336
+ * function's body, inlined verbatim, feeding `store.get`. It was equivalent on
337
+ * every input reachable there, which is exactly what the two that DID diverge
338
+ * looked like until someone tried a hex id.
339
+ *
340
+ * SHARING IT IS NOT THE SAME AS IT BEING RIGHT EVERYWHERE. On a model declaring
341
+ * `id = attr('string')` a numeric-looking id is filed under the STRING key, so
342
+ * this coercion resolves `'9107'` to `9107` and the post-create lookup misses:
343
+ * `context.record` is `undefined` for an after-`create` hook. Inherited -- the
344
+ * inlined copy computed the same thing -- and NOT fixed here, because picking
345
+ * the right coercion needs the model's declared id type, which is the same
346
+ * structural information abofs/stonyx-orm#202 is about. Filed as
347
+ * abofs/stonyx-orm#209 and pinned by assertion 50, so closing it turns a test
348
+ * red rather than passing silently.
349
+ *
350
+ * `parseInt` and not `Number`, deliberately, and the anchor is NOT `getId`.
351
+ * It is `src/transforms.ts:7` -- `number: (value) => parseInt(value as string)`,
352
+ * also radix-less -- because that transform is what actually produces the store
353
+ * KEY a record is filed under. `getId` merely agrees with it. They differ from
354
+ * `Number` on `'1e3'` (1 vs 1000) and `'9105.5'` (9105 vs 9105.5), so switching
355
+ * this function to `Number` would make the lookup key disagree with the landing
356
+ * key on those shapes.
357
+ *
358
+ * THE CHANGE THAT WOULD BREAK THIS: adding a radix to `transforms.number`
359
+ * (`parseInt(value, 10)`). That is a one-word edit in a file with no connection
360
+ * to authorization, it would silently reopen the hex divergence in the other
361
+ * direction, and this comment would still read as correct. Assertion 45 pins
362
+ * the transform's radix-less shape directly, so that edit turns a test red
363
+ * rather than shipping.
364
+ *
365
+ * The reason `parseInt` is safe here is the `isNaN` gate in front of it:
366
+ * `parseInt('9105h')` is `9105`, and truncating a partially-valid id into a
367
+ * DIFFERENT VALID key is exactly how a collision lookup gets skipped. The gate
368
+ * rejects it as a string instead, so nothing is ever truncated. That gate, not
369
+ * the parser, is the load-bearing half -- assertion 43 pins it.
370
+ */
371
+ function coerceId(id) {
372
+ if (isNaN(id))
373
+ return id;
374
+ return parseInt(id);
375
+ }
51
376
  function getId(params) {
52
377
  const id = params.id;
53
378
  if (!id)
54
379
  return '';
55
- if (isNaN(id))
380
+ return coerceId(id);
381
+ }
382
+ /**
383
+ * Normalise a caller-supplied BODY id to the key the store will hold it under.
384
+ *
385
+ * `getId()` above is params-shaped: it takes `{ id?: string }` off the URL,
386
+ * where the value is always a string and a falsy one means "no id". A JSON body
387
+ * id is neither -- it can arrive as a number, and `0` is a legitimate id that
388
+ * `getId()` would flatten to `''`.
389
+ *
390
+ * WHY THIS EXISTS AT ALL. createHandler used to look the collision up with the
391
+ * RAW body value while every other surface normalised through `getId()`. The
392
+ * store is a Map keyed by the coerced value, so `store.find(model, '21')` misses
393
+ * the entry held under `21` and the duplicate check is skipped by typing the id
394
+ * as a string. On `dev` that silently overwrote the colliding record and
395
+ * answered 200; combined with the denied-create rollback added for #190 it
396
+ * became an unauthenticated DELETE of any id. Normalising here is half of that
397
+ * fix -- see the rollback in createHandler for the other half.
398
+ *
399
+ * It shares `coerceId` with `getId` so the two surfaces cannot drift apart
400
+ * again, and differs from `getId` in exactly ONE place, below.
401
+ */
402
+ function normalizeBodyId(id) {
403
+ // Non-strings pass through untouched: a JSON body id can arrive as a number,
404
+ // and `getId`'s falsy-flatten must NOT apply to it -- `0` is a legitimate id
405
+ // and `getId` would turn it into `''`. (assertion 30 sweeps id `0`.)
406
+ if (typeof id !== 'string')
56
407
  return id;
57
- return parseInt(id);
408
+ // THE ONE DIVERGENCE FROM `getId`, and it mirrors rather than contradicts it:
409
+ // `getId` maps a falsy param to `''`, and `''` is the only string a body can
410
+ // carry that means "no id" -- `createRecord` treats it as absent and assigns a
411
+ // server id. Coercing it instead would make it address a real slot, because
412
+ // `parseInt('')` is `NaN` and a record CAN be held under `NaN` (a truthy but
413
+ // non-numeric id such as `' '` survives `assignRecordId`'s falsy guard and
414
+ // then NaNs in the id transform). So `POST {"id":""}` would answer 409 against
415
+ // an unrelated record it never named. Pinned by assertion 44.
416
+ //
417
+ // Note what is deliberately NOT special-cased here any more: whitespace.
418
+ // `id.trim() === ''` used to short-circuit `' '` as well, which made the
419
+ // body surface DISAGREE with the URL surface -- `getId({id:' '})` is `NaN`,
420
+ // so `' '` addresses the NaN slot on every other route while the collision
421
+ // lookup missed it. Same class of bug as the hex divergence above.
422
+ if (id === '')
423
+ return id;
424
+ return coerceId(id);
58
425
  }
59
426
  function buildResponse(data, includeParam, recordOrRecords, options = {}) {
60
- const { links, baseUrl } = options;
427
+ const { links, baseUrl, linkage } = options;
61
428
  const response = { data };
62
429
  // Add top-level links
63
430
  if (links) {
@@ -70,7 +437,53 @@ function buildResponse(data, includeParam, recordOrRecords, options = {}) {
70
437
  return response;
71
438
  const includedRecords = collectIncludedRecords(recordOrRecords, includes);
72
439
  if (includedRecords.length > 0) {
73
- response.included = includedRecords.map(record => record.toJSON?.({ baseUrl }));
440
+ // LINKAGE, NOT MEMBERSHIP -- and the distinction is the whole reason this
441
+ // line is one story's and the line above it is another's
442
+ // (abofs/stonyx-orm#235 and #233 respectively).
443
+ //
444
+ // - WHICH RESOURCES REACH THIS ARRAY is decided by
445
+ // `collectIncludedRecords` on the line above. That is MEMBERSHIP, it is
446
+ // #233's, and it is deliberately untouched here: a hidden owner is
447
+ // still a member of `included` after this change. Pinned green by
448
+ // `[GUARD] #235 X1` so that #235 cannot close #233 incidentally.
449
+ // - WHAT A RECORD ALREADY IN THIS ARRAY MAY NAME in its own
450
+ // `relationships.*.data` is LINKAGE -- the same question #234 answers
451
+ // for the primary document -- and that is what the `linkage` option
452
+ // below decides. Before it, `GET /animals/1?include=owner,owner.pets`
453
+ // filtered the primary document's `owner.data` to `null` and then
454
+ // handed back eight PERMITTED animals in `included` each naming
455
+ // `{"type":"owner","id":"angela"}` -- angela's whole `pets` set,
456
+ // `[1, 3, 7, 10, 11, 15, 17, 20]`. `included` itself is NINE
457
+ // resources there: those eight animals plus the hidden owner, whose
458
+ // membership is #233's and not an animal. Neither #233 nor #234
459
+ // closes that.
460
+ //
461
+ // THE FILTER IS THE CALLER'S, PASSED IN, NOT BUILT HERE. Both call sites
462
+ // already hold one for the primary document, and sharing it is what keeps
463
+ // the per-type verdict cache and the per-(type, id) decision cache alive
464
+ // across the primary document AND the sideload -- one verdict resolution
465
+ // per type for the whole response, pinned by `[GUARD] #235 C1`. Building a
466
+ // fresh filter here would resolve the consumer's `access()` once per
467
+ // included record instead.
468
+ //
469
+ // `linkage` IS OPTIONAL IN THE TYPE AND IS NOT OPTIONAL IN PRACTICE.
470
+ // Stating it precisely because the opposite claim stood here in an earlier
471
+ // draft of this change: BOTH of this function's callers supply a filter
472
+ // (`getCollectionHandler` and `getSingleHandler`, the only two), so the
473
+ // `undefined` branch has no live caller in this module today. It is
474
+ // optional so that omitting it degrades to the PRE-#234 document rather
475
+ // than to a denial -- `Record.toJSON` reads an ABSENT option as "no verdict
476
+ // was supplied" and emits linkage in full.
477
+ //
478
+ // WHAT IT MUST NEVER BE HANDED IS A NON-FUNCTION. `toJSON` does NOT read a
479
+ // non-function as absent: `Object.prototype.toString.call(linkage)` must be
480
+ // `'[object Function]'`, and anything else -- `null`, an `AsyncFunction`,
481
+ // and INCLUDING the primitive `true` -- DENIES every relationship on the
482
+ // document and logs once. `toJSON({ linkage: true })` emits `null` linkage.
483
+ // So do not "simplify" this to a boolean, and do not make it default to
484
+ // `true`: both spellings look like "allow everything" and mean the exact
485
+ // opposite (abofs/stonyx-orm#224).
486
+ response.included = includedRecords.map(record => record.toJSON?.({ baseUrl, linkage }));
74
487
  }
75
488
  return response;
76
489
  }
@@ -187,6 +600,39 @@ function createFilterPredicate(filters) {
187
600
  return String(current) === value;
188
601
  });
189
602
  }
603
+ /**
604
+ * A function-style `access` return is a per-record predicate, and it is only
605
+ * meaningful if every surface that can hand a record to a caller consults it.
606
+ * Before #190 exactly one of seven did.
607
+ *
608
+ * Enforcement is deliberately post-fetch. `access` returns an opaque JS
609
+ * predicate and `store.findAll(model, conditions)` accepts only an equality
610
+ * conditions object that the SQL drivers translate to a WHERE clause, so
611
+ * query-layer enforcement would require a breaking change to the published
612
+ * `access` contract. That belongs in #197, not in a security patch. Six of the
613
+ * seven surfaces fetch by primary key anyway, so this costs exactly one row.
614
+ */
615
+ function isDenied(filter, record) {
616
+ if (typeof filter !== 'function')
617
+ return false;
618
+ // A predicate that throws is treated as a denial. Unguarded, a throw escapes
619
+ // to express's default handler, which answers 500 (with a stack trace outside
620
+ // NODE_ENV=production) while a missing id still answers 404 -- so a
621
+ // record-dependent throw re-separates "hidden" from "does not exist" and
622
+ // hands back the oracle this whole change exists to close.
623
+ try {
624
+ return !filter(record);
625
+ }
626
+ catch (error) {
627
+ // Denied, but not silently. A consumer predicate that throws on every
628
+ // record turns the whole collection into a 404 wall, and with no
629
+ // diagnostic that is indistinguishable from an empty database. `stonyx/log`
630
+ // is the module convention (see setup-rest-server.ts); optional-call
631
+ // because a consumer may not have configured the log types.
632
+ log.error?.(`[@stonyx/orm] access filter threw for model -- denying. ${error instanceof Error ? error.message : String(error)}`);
633
+ return true;
634
+ }
635
+ }
190
636
  export default class OrmRequest extends Request {
191
637
  model;
192
638
  access;
@@ -210,37 +656,168 @@ export default class OrmRequest extends Request {
210
656
  if (queryFilterPredicate)
211
657
  recordsToReturn = recordsToReturn.filter(queryFilterPredicate);
212
658
  const baseUrl = getBaseUrl(request);
213
- const data = recordsToReturn.map(record => record.toJSON?.({ fields: modelFields, baseUrl }));
659
+ // ONE filter per REQUEST, not one per record: it carries the per-type
660
+ // verdict cache and the per-(type, id) decision cache, and both are
661
+ // worthless if it is rebuilt inside the map. Measured on this exact
662
+ // surface with no `include=`: 48 linkage entries collapse to 7 distinct
663
+ // (type, id) pairs.
664
+ const linkage = createLinkageFilter(request);
665
+ const data = recordsToReturn.map(record => record.toJSON?.({ fields: modelFields, baseUrl, linkage }));
214
666
  return buildResponse(data, request.query?.include, recordsToReturn, {
215
667
  links: { self: `${baseUrl}/${pluralizedModel}` },
216
- baseUrl
668
+ baseUrl,
669
+ // THE SAME filter object the primary documents above were serialized
670
+ // with, deliberately: it carries the caches, and rebuilding one here
671
+ // would re-resolve every type (abofs/stonyx-orm#235).
672
+ linkage
217
673
  });
218
674
  };
219
- const getSingleHandler = async (request) => {
675
+ const getSingleHandler = async (request, { filter }) => {
220
676
  const record = await store.find(model, getId(request.params));
221
677
  if (!record)
222
678
  return 404;
679
+ // 404, never 403: the status for "exists but filtered out" must be
680
+ // identical to "does not exist", or the fix trades an authorization
681
+ // bypass for a narrower existence oracle.
682
+ if (isDenied(filter, record))
683
+ return 404;
223
684
  const fieldsMap = parseFields(request.query);
224
685
  const modelFields = fieldsMap.get(pluralizedModel) || fieldsMap.get(model);
225
686
  const baseUrl = getBaseUrl(request);
226
- return buildResponse(record.toJSON?.({ fields: modelFields, baseUrl }), request.query?.include, record, {
687
+ const linkage = createLinkageFilter(request);
688
+ // `buildResponse` IS given the filter now (abofs/stonyx-orm#235), and it
689
+ // is the SAME object the primary document is serialized with -- one
690
+ // verdict per type for the whole response, sideload included.
691
+ //
692
+ // The boundary that remains, so the next reader does not have to derive
693
+ // it: this closes what a record already in `included` may NAME. WHETHER a
694
+ // resource appears in `included` at all is MEMBERSHIP and it is
695
+ // abofs/stonyx-orm#233's -- a hidden owner is still a member here.
696
+ // Neither question closes the other.
697
+ return buildResponse(record.toJSON?.({ fields: modelFields, baseUrl, linkage }), request.query?.include, record, {
227
698
  links: { self: `${baseUrl}/${pluralizedModel}/${request.params.id}` },
228
- baseUrl
699
+ baseUrl,
700
+ linkage
229
701
  });
230
702
  };
231
- const createHandler = async ({ body, query }) => {
703
+ const createHandler = async (request, { filter }) => {
704
+ // BOUND, not destructured (abofs/stonyx-orm#235). `HandlerFn` has always
705
+ // delivered the request as argument one; this handler simply discarded
706
+ // the binding, which is why its response document named ids every read
707
+ // surface withholds. `createLinkageFilter` needs the live request and
708
+ // there is no signature change involved in giving it one.
709
+ const { body, query } = request;
232
710
  const { type, id, attributes, relationships: rels } = (body?.data || {});
233
711
  if (!type)
234
712
  return 400; // Bad request
235
713
  const fieldsMap = parseFields(query);
236
714
  const modelFields = fieldsMap.get(pluralizedModel) || fieldsMap.get(model);
237
- // Check for duplicate ID
238
- if (id !== undefined && await store.find(model, id))
239
- return 409; // Conflict
715
+ // GATE 0 -- the POST existence oracle.
716
+ //
717
+ // The duplicate check runs before the filter and `store.find` sees hidden
718
+ // records, so POST leaks existence through its STATUS. A previous revision
719
+ // filtered the collision status (403 when the colliding record is denied,
720
+ // 409 when it is visible) and that is NOT sufficient, because the status
721
+ // of a create is a third outcome. With a payload the caller is permitted
722
+ // to create -- the normative case for a per-tenant filter, and the case an
723
+ // attacker picks -- all three are distinguishable in ONE request per id:
724
+ //
725
+ // POST /animals {id:22, owner:'gina'} -> 403 a HIDDEN record has this id
726
+ // POST /animals {id:9500, owner:'gina'} -> 200 this id is FREE
727
+ // POST /animals {id:8, owner:'gina'} -> 409 a VISIBLE record has this id
728
+ //
729
+ // Filtering only the collision status narrows that to callers who cannot
730
+ // create a record they are allowed to see. It does not close it.
731
+ //
732
+ // It cannot be closed while a caller both chooses the id and learns
733
+ // whether the create succeeded: a successful create must answer
734
+ // differently from a refused one. So when a per-record filter is in force
735
+ // the caller does not get to choose the id at all. The refusal is
736
+ // UNCONDITIONAL and happens BEFORE any store lookup, so no status, and no
737
+ // lookup cost, can depend on whether that id exists. 403 -- the same
738
+ // status as a denied create -- so the two cannot be separated either.
739
+ //
740
+ // BOTH HALVES OF THAT ARE PINNED, because both were once asserted here and
741
+ // pinned by nothing:
742
+ //
743
+ // status -- assertion 22 sweeps payload x id x id-type, plus `null`.
744
+ // latency -- assertion 41 asserts NO `store.find` is issued on this
745
+ // path. Moving the refusal to after a lookup and returning
746
+ // the same 403 left the suite green while re-opening a
747
+ // hit-versus-miss timing difference on every id-bearing POST,
748
+ // which is what would turn #197 from a ~0.06ms post-fetch
749
+ // residual into a live timing oracle on create.
750
+ //
751
+ // AND THE GUARANTEE IS ONLY AS WIDE AS THE CHANNELS IT COVERS. It reads on
752
+ // the `id` member of the resource object, so it holds only while that is
753
+ // the ONLY way a caller id can reach `createRecord`. It was not: the
754
+ // relationships loop below re-admitted one under `key === "id"` and the
755
+ // gate never fired. Both strips -- `attributes.id` and `relationships.id`
756
+ // -- are therefore part of THIS gate, not tidiness, and assertion 39 pins
757
+ // them. Adding a third channel without a strip re-opens the oracle.
758
+ //
759
+ // Scoped to function-style `access` because that is exactly the population
760
+ // the oracle exists for: with no per-record filter there are no hidden
761
+ // records, and 409 discloses nothing GET /:id does not already.
762
+ //
763
+ // RESIDUALS, stated rather than implied.
764
+ //
765
+ // - a caller can still learn that a collection HAS a per-record filter
766
+ // (403 rather than 409/200 for an id-bearing POST). That discloses a
767
+ // configuration fact, not a record.
768
+ // - this gate is about ids arriving on THIS model's create route. It
769
+ // says nothing about a write to ANOTHER collection: a `POST /owners`
770
+ // carrying `relationships: {pets: {data: {id: 21}}}` -- or
771
+ // `attributes: {pets: [21, 22]}`, which never enters the
772
+ // relationships loop at all -- re-parents hidden animal 21 onto an
773
+ // owner the caller may write, which changes the very field the
774
+ // animals predicate reads and DE-HIDES it. Blocking that needs animal
775
+ // 21 checked against the ANIMAL model's predicate while servicing an
776
+ // OWNERS route, i.e. cross-model access resolution: abofs/stonyx-orm
777
+ // #207, blocked on #202 (`access` receives the model structurally)
778
+ // and #196 (setup-rest-server discards the model->predicate map at
779
+ // boot). NOT closed here, and no comment in this file may say it is.
780
+ //
781
+ // See README `### Known limitations`.
782
+ if (id !== undefined) {
783
+ if (typeof filter === 'function')
784
+ return 403; // Forbidden
785
+ // `normalizeBodyId`, not the raw value: a string-typed id misses the
786
+ // store's numeric key, which skipped this check entirely.
787
+ const existing = await store.find(model, normalizeBodyId(id));
788
+ if (existing)
789
+ return 409; // Conflict
790
+ }
240
791
  const { id: _ignoredId, ...sanitizedAttributes } = attributes || {};
241
- // Extract relationship IDs from JSON:API relationships object
792
+ // Extract relationship IDs from JSON:API relationships object.
793
+ //
794
+ // `key` comes VERBATIM from the request body, so `id` is stripped here for
795
+ // exactly the same reason it is stripped from `attributes` on the line
796
+ // above -- and it must be, or GATE 0 is walked around by moving one field:
797
+ //
798
+ // POST /animals {"id":21, ...} -> 403 GATE 0 fires
799
+ // POST /animals {"relationships":{"id":{"data":{"id":21}}},
800
+ // "attributes":{"owner":"gina"}} -> 200 BYPASS
801
+ //
802
+ // Top-level `id` stayed `undefined`, so GATE 0 never fired and the
803
+ // collision lookup never ran; `createRecord` took its last-entry-wins
804
+ // branch, overwrote hidden record 21 in place and reset its `owner` to a
805
+ // value the caller chose -- de-hiding it permanently. That is #190 itself,
806
+ // on the create surface. Pinned by assertion 39.
807
+ //
808
+ // The `id` member of the resource object is now the ONLY channel a caller
809
+ // id can arrive on FOR THIS MODEL'S OWN CREATE ROUTE, which is what makes
810
+ // GATE 0's guarantee checkable rather than merely asserted. It is not a
811
+ // statement about the record's reachability in general -- a relationship
812
+ // write on another collection reaches it without ever touching this
813
+ // handler (abofs/stonyx-orm#207). INHERITED from `dev`, which carries this
814
+ // loop verbatim; the general form -- the loop accepts any key, not just
815
+ // `id`, so a body key that is not a declared relationship is still
816
+ // mass-assigned -- is abofs/stonyx-orm#204.
242
817
  if (rels) {
243
818
  for (const [key, value] of Object.entries(rels)) {
819
+ if (key === 'id')
820
+ continue;
244
821
  const relData = value?.data;
245
822
  if (relData && relData.id !== undefined) {
246
823
  sanitizedAttributes[key] = relData.id;
@@ -248,16 +825,163 @@ export default class OrmRequest extends Request {
248
825
  }
249
826
  }
250
827
  const recordAttributes = id !== undefined ? { id, ...sanitizedAttributes } : sanitizedAttributes;
251
- const created = createRecord(model, recordAttributes, { serialize: false, _skipAutoPersist: true });
828
+ // Slot count BEFORE the write. `createRecord` writes to the store before
829
+ // the predicate can run, and the rollback below must be able to prove the
830
+ // slot it removes is one THIS REQUEST created. Identity alone cannot
831
+ // prove it: when `assignRecordId` lands on an occupied id, `createRecord`
832
+ // mutates the existing OrmRecord IN PLACE, so `store.get(...) === record`
833
+ // is true for a record the request did not create. The map's size is the
834
+ // only O(1) signal that distinguishes an insert from an overwrite.
835
+ const slotsBefore = store.get(model)?.size ?? 0;
836
+ // THE ONE `createRecord` FAILURE THIS ROUTE ANSWERS RATHER THAN
837
+ // PROPAGATES, and it is narrow on purpose.
838
+ //
839
+ // `assignRecordId` throws when it cannot derive a free store key for a
840
+ // server-assigned id. Unguarded that rejection is auto-forwarded -- there
841
+ // is no catch here, none in @stonyx/rest-server's dispatcher
842
+ // (dist/request.js:41-70), and express 5 hands it to its default error
843
+ // handler, which serialises the STACK, with absolute install paths and the
844
+ // internal module graph, to an unauthenticated caller outside
845
+ // NODE_ENV=production. That is the hazard :553-558 already names in this
846
+ // file, and every sibling refusal in this handler returns an integer
847
+ // status instead. So this one returns 409, matching the client-duplicate
848
+ // refusal at :713: the caller asked for a record and the collection has no
849
+ // id to give it.
850
+ //
851
+ // MATCHED ON THE SHARED PREFIX, not on a literal, and NOT by catching
852
+ // everything: `createRecord` also throws for "ORM is not ready", a
853
+ // read-only view and an unregistered model store, and turning any of those
854
+ // into a 409 would report a configuration fault as a conflict. Anything
855
+ // else is re-thrown unchanged.
856
+ let created;
857
+ try {
858
+ created = createRecord(model, recordAttributes, { serialize: false, _skipAutoPersist: true });
859
+ }
860
+ catch (error) {
861
+ if (!(error instanceof Error) || !error.message.startsWith(NO_FREE_ID_ERROR))
862
+ throw error;
863
+ // Not silently. A collection that can no longer assign an id is a
864
+ // configuration fault (a non-injective id transform), and a bare 409
865
+ // with no diagnostic is indistinguishable from an ordinary duplicate.
866
+ log.error?.(`[@stonyx/orm] ${error.message}`);
867
+ return 409; // Conflict
868
+ }
252
869
  const record = isOrmRecord(created) ? created : null;
253
870
  if (!record)
254
871
  return 500;
255
- return { data: record.toJSON?.({ fields: modelFields }) };
872
+ const createdNewSlot = (store.get(model)?.size ?? 0) > slotsBefore;
873
+ // 403 here, NOT 404. The oracle argument does not apply to create: there
874
+ // is no pre-existing record whose existence could leak, the caller
875
+ // supplied the attributes, and 404 on a mounted collection route is
876
+ // indistinguishable from "model not mounted" -- a genuinely different
877
+ // failure a developer needs to diagnose.
878
+ //
879
+ // The rollback is not optional. createRecord writes to the store BEFORE
880
+ // the predicate can run, so returning 403 alone would leave the record
881
+ // behind: a worse bug than the bypass being fixed.
882
+ if (isDenied(filter, record)) {
883
+ // ROLL BACK BY IDENTITY, NEVER BY ID. `store.remove(model, record.id)`
884
+ // on its own is a write primitive keyed by a value the caller may have
885
+ // supplied: with the raw-id collision bypass above, a denied
886
+ // `POST {"id":"21"}` answered 403 and DELETED hidden record 21 -- an
887
+ // unauthenticated deletion primitive across the whole id space, created
888
+ // by adding a rollback to a lookup that could be skipped.
889
+ //
890
+ // Both conditions are required and neither implies the other:
891
+ // createdNewSlot -- the store grew, so this request inserted rather
892
+ // than overwrote. SURVIVOR AS OF #203, AND THAT IS
893
+ // WHAT THIS NOTE IS FOR. It used to be killable:
894
+ // `assignRecordId` returned last-INSERTED + 1, so a
895
+ // server-assigned id could land on an occupied slot,
896
+ // `createRecord` updated in place, and removing this
897
+ // half turned access-filter-enforcement-test.ts
898
+ // assertion 31 red. #203 closed that: the
899
+ // server-assigned path now walks past occupied keys,
900
+ // so no create reaching here can overwrite. Measured
901
+ // -- delete `createdNewSlot &&` below: `dev` gives
902
+ // 55 pass / 1 fail with assertion 31 RED, this tree
903
+ // gives 56 pass / 0 fail, GREEN.
904
+ // KEPT ANYWAY, AND NOT FOR THE OLD REASON. Without
905
+ // it a denied create becomes `store.remove` on a key
906
+ // the caller may have influenced, which :815-820
907
+ // records as having been an unauthenticated deletion
908
+ // primitive across the whole id space. BECOMES
909
+ // KILLABLE AGAIN the moment any caller-supplied id
910
+ // can reach `createRecord` from this handler --
911
+ // which is exactly what has-many.ts:65 and
912
+ // belongs-to.ts:45 already do for ANOTHER model's
913
+ // store (abofs/stonyx-orm#207), and what a third
914
+ // un-stripped id channel would do for this one
915
+ // (#204). Do not delete it on the strength of #203
916
+ // being closed; that is the reasoning :862-867 warns
917
+ // about, one level up.
918
+ // identity -- the slot still holds the object we just created,
919
+ // so nothing between createRecord and here replaced
920
+ // it. Deleting this half SURVIVES the suite, and it
921
+ // is kept anyway. WHY IT IS REDUNDANT: there is no
922
+ // `await` anywhere between `slotsBefore` and
923
+ // `store.remove` -- the whole window is synchronous,
924
+ // so it is atomic under Node's event loop; before-
925
+ // `create` hooks run BEFORE the handler
926
+ // (`_withHooks` runs its hook loop ahead of
927
+ // `await handler(...)`), and a consumer predicate
928
+ // inside `isDenied` runs AFTER `createdNewSlot` is
929
+ // computed and cannot flip it. That is a property of
930
+ // THIS function, not of GATE 0 -- an earlier note
931
+ // credited GATE 0, which was both wrong (a caller id
932
+ // reached createRecord through the relationships
933
+ // loop, #204) and the wrong kind of reason: a guard
934
+ // justified on code sixty lines upstream gets
935
+ // silently re-armed when that code moves.
936
+ // SO IT BECOMES REACHABLE IF AN `await` IS
937
+ // INTRODUCED HERE, which is the change a future
938
+ // editor would actually make. Stated here rather
939
+ // than by reference: `docs/` is not in `files`, so
940
+ // a pointer into it resolves to nothing for anyone
941
+ // who installed this package. README carries the
942
+ // consumer-facing half.
943
+ if (createdNewSlot && store.get(model, record.id) === record) {
944
+ store.remove(model, record.id, { _skipAutoPersist: true });
945
+ }
946
+ return 403;
947
+ }
948
+ // The filter is built HERE, per invocation, and never hoisted into the
949
+ // OrmRequest constructor where the other per-mount values live: a verdict
950
+ // cached across requests answers a second caller with the first caller's
951
+ // authorization (src/access-verdict.ts says so at the constructor an
952
+ // implementer would reach for).
953
+ //
954
+ // AND IT IS BUILT AFTER `createRecord`, AFTER THE ROLLBACK WINDOW AND
955
+ // AFTER `isDenied`, so the record is in its final form at the call. The
956
+ // filter is lazy per type and per (type, id), so it cannot observe a
957
+ // pre-write state even if it were built earlier.
958
+ //
959
+ // `fields` is passed here and NOT in `updateHandler`: the two handlers
960
+ // are asymmetric on purpose (`updateHandler` has no `fieldsMap` in
961
+ // scope), and a single copy-pasted wiring would drop it from one of them.
962
+ return { data: record.toJSON?.({ fields: modelFields, linkage: createLinkageFilter(request) }) };
256
963
  };
257
- const updateHandler = async ({ body, params }) => {
964
+ const updateHandler = async (request, { filter }) => {
965
+ // Bound rather than destructured, for the reason given in
966
+ // `createHandler` above (abofs/stonyx-orm#235). `PATCH /animals/1`
967
+ // returned 200 naming angela seconds after `GET /animals/1` returned
968
+ // `owner.data: null` for the same record -- one HTTP verb apart.
969
+ const { body, params } = request;
258
970
  const found = await store.find(model, getId(params));
259
971
  if (!found || !isOrmRecord(found))
260
972
  return 404;
973
+ // Checked BEFORE any attribute is applied. 404 rather than 403 for the
974
+ // same reason as GET /:id -- 403 would disclose both that the record
975
+ // exists and that this caller specifically is excluded.
976
+ //
977
+ // NOT redundant behind GATE 1, and not defence in depth either: GATE 1's
978
+ // verdict is computed BEFORE the before-hook loop runs, and a before-hook
979
+ // is a published extension point that can change the answer -- by
980
+ // mutating the record, or against a predicate that closes over
981
+ // per-request state. This is the only re-evaluation after that window.
982
+ // Pinned by assertion 32; deleting it turns a 404 into an applied update.
983
+ if (isDenied(filter, found))
984
+ return 404;
261
985
  const record = found;
262
986
  const { attributes, relationships: rels } = (body?.data || {});
263
987
  if (!attributes && !rels)
@@ -277,6 +1001,19 @@ export default class OrmRequest extends Request {
277
1001
  if (rels) {
278
1002
  const relUpdates = {};
279
1003
  for (const [key, value] of Object.entries(rels)) {
1004
+ // The same missing key filter as createHandler's, and as the
1005
+ // attribute loop directly above -- which already had it, while this
1006
+ // loop did not. A PATCH carrying
1007
+ // `relationships:{"id":{"data":{"id":9101}}}` reached `updateRecord`
1008
+ // and RE-KEYED the record: the object held under store key 9102 then
1009
+ // reported id 9101, so a visible record claimed a hidden record's
1010
+ // identity on every surface that reads `record.id` rather than the map
1011
+ // key. Gated by GATE 1 on the addressed record, so it is store
1012
+ // corruption rather than a filter bypass -- but it is the same one-line
1013
+ // omission two handlers apart. Pinned by assertion 40; INHERITED from
1014
+ // `dev`; abofs/stonyx-orm#204.
1015
+ if (key === 'id')
1016
+ continue;
280
1017
  const relData = value?.data;
281
1018
  if (relData && relData.id !== undefined) {
282
1019
  relUpdates[key] = relData.id;
@@ -286,10 +1023,40 @@ export default class OrmRequest extends Request {
286
1023
  updateRecord(record, relUpdates, { _skipAutoPersist: true });
287
1024
  }
288
1025
  }
289
- return { data: record.toJSON?.() };
1026
+ // No `fields` and no `baseUrl`, both unchanged: `updateHandler` has no
1027
+ // `fieldsMap` in scope, and adding `baseUrl` would put `links` on a
1028
+ // document that has never carried them -- an unrelated behaviour change.
1029
+ // #224 AC6's "emits `data: []` WITH links" is a statement about the READ
1030
+ // surfaces; on these two handlers a filtered relationship and a
1031
+ // genuinely-empty one are both a bare `{ data }`, which is what makes
1032
+ // them indistinguishable here too.
1033
+ return { data: record.toJSON?.({ linkage: createLinkageFilter(request) }) };
290
1034
  };
291
- const deleteHandler = ({ params }) => {
292
- store.remove(model, getId(params));
1035
+ const deleteHandler = async ({ params }, { filter }) => {
1036
+ // Coerced ONCE. `getId(params)` was evaluated twice here -- once to find
1037
+ // the record and once to remove it -- and a coercion evaluated repeatedly
1038
+ // is a coercion that can be edited in one place and not the other, which
1039
+ // is the defect `coerceId` exists to prevent.
1040
+ const recordId = getId(params);
1041
+ const record = await store.find(model, recordId);
1042
+ // BEHAVIOUR CHANGE (#190): a DELETE of a record that never existed
1043
+ // returned 204 before this change. It now returns 404, matching the
1044
+ // denied case below. This is deliberate and load-bearing -- if a denied
1045
+ // delete returned 404 while a missing one returned 204, the pair would be
1046
+ // a perfect existence oracle and the whole fix would be worthless.
1047
+ // Returning 204 for a denied delete was rejected instead: it falsely
1048
+ // reports success for a request that changed nothing.
1049
+ if (!record)
1050
+ return 404;
1051
+ // Re-evaluated after the before-hook loop, exactly as in updateHandler --
1052
+ // GATE 1 decided before the hooks ran. Pinned by assertion 33; deleting it
1053
+ // turns a 404 into a destroyed record.
1054
+ if (isDenied(filter, record))
1055
+ return 404;
1056
+ // Removed by the id of the record actually fetched, not by re-deriving it
1057
+ // from the params a second time: the record the filter tested and the
1058
+ // record removed are then provably the same one.
1059
+ store.remove(model, record.id, { _skipAutoPersist: true });
293
1060
  return 204;
294
1061
  };
295
1062
  // Wrap handlers with hooks
@@ -314,9 +1081,63 @@ export default class OrmRequest extends Request {
314
1081
  };
315
1082
  }
316
1083
  }
317
- // Wraps a handler with before/after hook execution
1084
+ // Wraps a handler with before/after hook execution.
1085
+ //
1086
+ // ===========================================================================
1087
+ // TWO AUTHORIZATION GATES, AND EVERY EXECUTOR SITS BEHIND ONE OF THEM (#190)
1088
+ //
1089
+ // The defect this function was fixed for is NOT "a delete persists past a
1090
+ // 404". It is that _withHooks has SEVERAL executors downstream of the
1091
+ // handler, and originally the handler's response gated none of them. Three
1092
+ // exist today:
1093
+ //
1094
+ // 1. sqlDb.persist -- issues real SQL against the backing store
1095
+ // 2. the after-hook pipeline -- the PUBLISHED consumer extension point;
1096
+ // a cascade delete, a webhook, a search-index
1097
+ // purge. `context.recordId` and
1098
+ // `context.oldState` are populated for it.
1099
+ // 3. Orm.db.save() -- a full serialize-and-write of the store
1100
+ //
1101
+ // Gating them one at a time is how this keeps regressing, so the rule is:
1102
+ // compute denial ONCE at each point where it becomes knowable, and keep every
1103
+ // executor downstream of a gate. If you add a fourth executor to this
1104
+ // function, it goes below GATE 2 or it is a security bug.
1105
+ //
1106
+ // GATE 1 (pre-handler) is required because before-hooks and `context.oldState`
1107
+ // run/are built BEFORE the handler can consult the filter. Without it a denied
1108
+ // DELETE still handed the hidden record's full contents to consumer code.
1109
+ // GATE 2 (post-handler) covers everything the handler's status can reach.
1110
+ // ===========================================================================
318
1111
  _withHooks(operation, handler) {
319
1112
  return async (request, state) => {
1113
+ // `|| {}` so this function behaves like the relationship routes below,
1114
+ // which declare `state` with a `= {}` default. It is unkillable through
1115
+ // the rest-server dispatcher, which always passes `getState(req)`; it is
1116
+ // listed as such in the guards-redundant-by-construction table rather
1117
+ // than left silently unkillable, and it defends the WHOLE function (the
1118
+ // context, the snapshot and the handler call all read `callState`) rather
1119
+ // than one destructure that the next line would throw past anyway.
1120
+ const callState = (state || {});
1121
+ // ---------------------------------------------------------------------
1122
+ // THE AUTHORIZATION SNAPSHOT. Read ONCE, here, before any consumer code
1123
+ // can run.
1124
+ //
1125
+ // `callState` is the object `auth()` planted the filter in, and it is
1126
+ // also handed to every before-hook as `context.state` -- a published,
1127
+ // WRITABLE extension point. So `state.filter` is an INPUT to the
1128
+ // authorization decision, not only an output channel, and re-reading it
1129
+ // after the hook loop lets a consumer hook disarm the filter:
1130
+ //
1131
+ // beforeHook('get', 'animal', ctx => { delete ctx.state.filter })
1132
+ // -> GET /animals/21 turned 404 into 200
1133
+ // -> GET /animals turned 20 records into 22
1134
+ //
1135
+ // GATE 1 already used this snapshot, so writes held; the READ handlers
1136
+ // re-destructured `filter` from the live bag and did not. Everything
1137
+ // downstream now reads `filter` from here, and the handler is handed
1138
+ // `handlerState` below -- never `callState`.
1139
+ // ---------------------------------------------------------------------
1140
+ const { filter } = callState;
320
1141
  // Build context object for hooks
321
1142
  const context = {
322
1143
  model: this.model,
@@ -325,11 +1146,35 @@ export default class OrmRequest extends Request {
325
1146
  params: request.params,
326
1147
  body: request.body,
327
1148
  query: request.query,
328
- state,
1149
+ // Deliberately the LIVE object: `redirect` and `pipe` are read back off
1150
+ // it by @stonyx/rest-server after the handler returns, so hooks must be
1151
+ // able to write to it. What must not happen is the authorization
1152
+ // decision reading it back, which is what the snapshot above prevents.
1153
+ state: callState,
329
1154
  };
330
1155
  // Capture old state for operations that modify data
331
1156
  if (operation === 'update' || operation === 'delete') {
332
1157
  const existingRecord = await store.find(this.model, getId(request.params));
1158
+ // GATE 1 -- pre-handler. This record fetch already happened for
1159
+ // oldState, so the check is free.
1160
+ //
1161
+ // Returning here rather than letting updateHandler/deleteHandler
1162
+ // produce the same 404 is the point: everything between here and there
1163
+ // is an executor the caller is not authorized to reach.
1164
+ // - context.oldState is a deep copy of the HIDDEN RECORD'S CONTENTS.
1165
+ // Building it and handing it to a before-hook discloses exactly what
1166
+ // the filter exists to hide.
1167
+ // - context.recordId is populated for delete BEFORE the handler runs,
1168
+ // which is the same shape as the sqlDb landmine one layer up:
1169
+ // `afterHook('delete', ctx => cascadeDelete(ctx.recordId))` destroys
1170
+ // children behind a correct 404.
1171
+ // - a before-hook may return a value and short-circuit, which would
1172
+ // otherwise return a response without the filter ever executing.
1173
+ //
1174
+ // 404, not 403, for the same reason as getSingleHandler: the status for
1175
+ // "exists but filtered out" must equal "does not exist".
1176
+ if (existingRecord && isDenied(filter, existingRecord))
1177
+ return 404;
333
1178
  if (existingRecord) {
334
1179
  // Deep copy the record's data to preserve old state
335
1180
  context.oldState = JSON.parse(JSON.stringify(existingRecord.__data || existingRecord));
@@ -347,10 +1192,49 @@ export default class OrmRequest extends Request {
347
1192
  }
348
1193
  }
349
1194
  // Execute main handler
350
- const response = await handler(request, state);
351
- // Persist to SQL database for create/update (delete is handled by store.remove auto-persist)
1195
+ // The handler receives the SNAPSHOT, never the live bag. `filter` is
1196
+ // assigned LAST so it wins over anything a before-hook wrote to
1197
+ // `callState.filter` -- including a `delete`, which the spread would
1198
+ // otherwise carry through as an absent key. Every other key a hook adds
1199
+ // is still visible to the handler; only the authorization input is
1200
+ // pinned.
1201
+ const handlerState = { ...callState, filter };
1202
+ const response = await handler(request, handlerState);
1203
+ // Set context.record for update BEFORE persist so SQL drivers can read it
1204
+ if (operation === 'update' && response?.data) {
1205
+ context.record = store.get(this.model, getId(request.params));
1206
+ }
1207
+ // GATE 2 -- post-handler. A denied or failed handler returns a bare status
1208
+ // integer, and no executor below may run for one.
1209
+ //
1210
+ // `>= 400` deliberately covers every failure status, not just the
1211
+ // authorization ones: a 400 (POST with no `type`) and a 409 (duplicate id)
1212
+ // are equally requests in which nothing happened, and a persist or a
1213
+ // cascade hook for one of them is just as wrong.
1214
+ // `Number.isInteger` is a TYPE guard, not a behaviour guard, and it is
1215
+ // unkillable TODAY: the only non-integer a handler in this file can
1216
+ // return is a `{ data, links }` object, and `{} >= 400` is `false` by JS
1217
+ // coercion, so dropping it changes no reachable outcome. It is kept
1218
+ // because `>=` coerces rather than rejects, and the shapes it coerces
1219
+ // are not obvious -- `[500] >= 400` is TRUE, so a handler that one day
1220
+ // returned an array would have every response read as a denial. Listed
1221
+ // as an equivalent mutant rather than left to read as coverage; it
1222
+ // becomes killable the moment a handler returns anything array-like or
1223
+ // numeric-string-like.
1224
+ const denied = Number.isInteger(response) && response >= 400;
1225
+ // EXECUTOR 1 -- SQL persistence, for all write operations.
1226
+ //
1227
+ // `response` is passed to sqlDb.persist below, but it is dropped at the
1228
+ // driver boundary: _persistDelete(modelName, context) never receives it
1229
+ // and guards only on context.recordId -- which _withHooks set above,
1230
+ // BEFORE the handler ran. Without this gate a correct 404 still issues
1231
+ // DELETE FROM ... WHERE id = ? on every SQL backend.
1232
+ //
1233
+ // No file-backed test can observe that, because Orm.instance.sqlDb is
1234
+ // null in file/directory mode. See the stubbed-sqlDb assertions in
1235
+ // test/unit/access-filter-enforcement-test.ts.
352
1236
  const sqlDb = Orm.instance.sqlDb;
353
- if (sqlDb && (operation === 'create' || operation === 'update')) {
1237
+ if (sqlDb && WRITE_OPERATIONS.has(operation) && !denied) {
354
1238
  await sqlDb.persist(operation, this.model, context, response);
355
1239
  }
356
1240
  // Add response and relevant records to context
@@ -364,22 +1248,44 @@ export default class OrmRequest extends Request {
364
1248
  else if (operation === 'create' && response?.data && (response.data.id)) {
365
1249
  // For create, get the record from store using the ID from the response
366
1250
  const responseData = response.data;
367
- const recordId = isNaN(responseData.id) ? responseData.id : parseInt(responseData.id);
368
- context.record = store.get(this.model, recordId);
369
- }
370
- else if (operation === 'update' && response?.data) {
371
- context.record = store.get(this.model, getId(request.params));
1251
+ // `normalizeBodyId`, not a copy of its body. This line WAS
1252
+ // `isNaN(id) ? id : parseInt(id)` -- `coerceId` inlined verbatim, a
1253
+ // third coercion feeding a store lookup, sitting under a docblock that
1254
+ // said neither surface had a copy. Equivalent on every input that can
1255
+ // reach this truthy-guarded branch (`21`->`21`, `'21'`->`21`,
1256
+ // `'angela'`->`'angela'`; `''` and `0` cannot reach it), so this is a
1257
+ // de-duplication rather than a behaviour change -- and that is the
1258
+ // point: the two that disagreed were equivalent on every input anyone
1259
+ // checked, too.
1260
+ context.record = store.get(this.model, normalizeBodyId(responseData.id));
372
1261
  }
373
1262
  else if (operation === 'delete') {
374
1263
  // For delete, the record may no longer exist, but we have oldState
375
1264
  context.recordId = getId(request.params);
376
1265
  }
377
- // Run after hooks sequentially
378
- for (const hook of getAfterHooks(operation, this.model)) {
379
- await hook(context);
1266
+ // EXECUTOR 2 -- the after-hook pipeline. This is the published consumer
1267
+ // extension point (`afterHook` is exported from @stonyx/orm and from
1268
+ // ./hooks), so it is the executor with the widest possible blast radius:
1269
+ // a cascade delete, a webhook, a token revocation, a search-index purge.
1270
+ //
1271
+ // BEHAVIOUR CHANGE (#190): after-hooks no longer fire for a request that
1272
+ // failed. Previously `afterHook('delete', ...)` ran with a populated
1273
+ // context.recordId on a 404, so a consumer cascade destroyed children for
1274
+ // a request that deleted nothing. Firing a hook named "after<operation>"
1275
+ // for an operation that did not occur is a booby trap, and the denied case
1276
+ // is unreachable-before-#190 while the missing case is inherited debt --
1277
+ // both are closed by the same gate. `context.response` therefore only ever
1278
+ // carries a success status into a hook.
1279
+ if (!denied) {
1280
+ for (const hook of getAfterHooks(operation, this.model)) {
1281
+ await hook(context);
1282
+ }
380
1283
  }
381
- // Auto-save DB after write operations when configured
382
- if (config.orm.db.autosave === 'onUpdate' && WRITE_OPERATIONS.has(operation)) {
1284
+ // EXECUTOR 3 -- file/directory autosave. Ungated this let an
1285
+ // unauthenticated caller force a full serialize-and-write of the entire
1286
+ // store on every DELETE of any id, with no record touched: amplification
1287
+ // rather than corruption, but the same root cause and the same fix.
1288
+ if (config.orm.db.autosave === 'onUpdate' && WRITE_OPERATIONS.has(operation) && !denied) {
383
1289
  await Orm.db.save();
384
1290
  }
385
1291
  return response;
@@ -391,21 +1297,38 @@ export default class OrmRequest extends Request {
391
1297
  // Dasherize the relationship name for URL paths (e.g., accessLinks -> access-links)
392
1298
  const dasherizedName = camelCaseToKebabCase(relationshipName);
393
1299
  // Related resource route: GET /:id/{relationship}
394
- routes[`/:id/${dasherizedName}`] = async (request) => {
1300
+ //
1301
+ // These generated routes are not wrapped by _withHooks, which is why they
1302
+ // were the least obvious two of the seven unguarded surfaces in #190.
1303
+ // They are still dispatched by @stonyx/rest-server as
1304
+ // `handler(req, getState(req))`, so `state` -- and therefore the filter
1305
+ // planted by auth() -- has always been available here; it was simply
1306
+ // never declared or read.
1307
+ routes[`/:id/${dasherizedName}`] = async (request, { filter } = {}) => {
395
1308
  const record = await store.find(model, getId(request.params));
396
1309
  if (!record)
397
1310
  return 404;
1311
+ // Filtering the PARENT: a caller who may not see the record may not see
1312
+ // what it is related to either.
1313
+ if (isDenied(filter, record))
1314
+ return 404;
398
1315
  const relatedData = record.__relationships[relationshipName];
399
1316
  const baseUrl = getBaseUrl(request);
1317
+ // LINKAGE ONLY. This filter decides which ids the emitted documents may
1318
+ // NAME in their own `relationships.*.data`; it does NOT decide whether
1319
+ // the related records themselves are served -- that is the parent-only
1320
+ // filtering this route has done since #190, and widening it to the
1321
+ // related record is abofs/stonyx-orm#196.
1322
+ const linkage = createLinkageFilter(request);
400
1323
  let data;
401
1324
  if (info.isArray) {
402
1325
  // hasMany - return array
403
1326
  const related = Array.isArray(relatedData) ? relatedData.filter(isOrmRecord) : [];
404
- data = related.map(r => r.toJSON?.({ baseUrl }));
1327
+ data = related.map(r => r.toJSON?.({ baseUrl, linkage }));
405
1328
  }
406
1329
  else {
407
1330
  // belongsTo - return single or null
408
- data = isOrmRecord(relatedData) ? relatedData.toJSON?.({ baseUrl }) : null;
1331
+ data = isOrmRecord(relatedData) ? relatedData.toJSON?.({ baseUrl, linkage }) : null;
409
1332
  }
410
1333
  return {
411
1334
  links: { self: `${baseUrl}/${pluralizedModel}/${request.params.id}/${dasherizedName}` },
@@ -413,10 +1336,60 @@ export default class OrmRequest extends Request {
413
1336
  };
414
1337
  };
415
1338
  // Relationship linkage route: GET /:id/relationships/{relationship}
416
- routes[`/:id/relationships/${dasherizedName}`] = async (request) => {
1339
+ //
1340
+ // NO `linkage` FILTER FROM abofs/stonyx-orm#235, AND THAT IS A SCOPE
1341
+ // BOUNDARY RATHER THAN AN OVERSIGHT -- abofs/stonyx-orm#232 OWNS THIS
1342
+ // ROUTE, and PR #247 is IN FLIGHT against it in this same sprint. If you
1343
+ // are reading this after #247 landed, the filtering below is #232's and
1344
+ // this note records why it was never #235's to add.
1345
+ //
1346
+ // The three sites #235 does own -- `buildResponse`'s `included`, and the
1347
+ // two write handlers, `POST /:models` and `PATCH /:models/:id` -- all
1348
+ // reach the filter through `record.toJSON()`, which is where the
1349
+ // `linkage` OPTION is applied.
1350
+ //
1351
+ // The related-resource branch above ALSO passes a `linkage` filter, and
1352
+ // it is NOT one of those three: it is abofs/stonyx-orm#234's code and
1353
+ // predates this change. `git diff 8dda5d6..HEAD -- src/orm-request.ts`
1354
+ // leaves that branch byte-unchanged.
1355
+ //
1356
+ // This branch builds its `{ type, id }` objects BY
1357
+ // HAND and never calls `toJSON` at all, so the `linkage` option cannot
1358
+ // reach it -- whatever this route filters, it has to filter itself, which
1359
+ // is precisely why doing so is a separate change with a separate owner.
1360
+ //
1361
+ // It is also a DIFFERENT QUESTION. Everywhere #235 touches, linkage is
1362
+ // metadata ABOUT a document. Here the linkage IS the primary data, so
1363
+ // dropping an entry is a MEMBERSHIP decision about what this route
1364
+ // serves -- the same class as abofs/stonyx-orm#233 and #196, not the
1365
+ // class #234/#235 close. That is why it is absent from #224 §2a's
1366
+ // seven-site inventory.
1367
+ //
1368
+ // MEASURED, so the next person does not re-derive it. Against this
1369
+ // branch's baseline of 1011/0, wiring `createLinkageFilter` into the
1370
+ // belongsTo branch below takes the suite to 1009/2, reddening
1371
+ // `[GUARD] #235 X2` and the
1372
+ // `GET /animals/:id/relationships/owner returns relationship linkage`
1373
+ // test -- the latter is #232's own reproduction, not a regression.
1374
+ //
1375
+ // THE BASELINE IS QUOTED WITH THE RESULT BECAUSE AN EARLIER REVISION OF
1376
+ // THIS COMMENT SAID 993/2 AND SHIPPED IT. This file lands in consumers'
1377
+ // `node_modules`, so a wrong number here is a wrong number in the
1378
+ // published package. 993+2 = 995 is the DEV baseline, carried over from
1379
+ // a branch on which `[GUARD] #235 X2` does not exist. A pass/fail pair
1380
+ // with no baseline beside it cannot be checked by reading, which is how
1381
+ // it survived three artifacts and a review; the qualitative claim was
1382
+ // right the whole time and only the count was wrong.
1383
+ //
1384
+ // `[GUARD] #235 X2` in test/integration/orm-test.ts pins the OWNERSHIP
1385
+ // BOUNDARY here rather than this route's current answer, so that it
1386
+ // survives #247 landing. Read its comment before changing it.
1387
+ routes[`/:id/relationships/${dasherizedName}`] = async (request, { filter } = {}) => {
417
1388
  const record = await store.find(model, getId(request.params));
418
1389
  if (!record)
419
1390
  return 404;
1391
+ if (isDenied(filter, record))
1392
+ return 404;
420
1393
  const relatedData = record.__relationships[relationshipName];
421
1394
  const baseUrl = getBaseUrl(request);
422
1395
  let data;
@@ -445,31 +1418,135 @@ export default class OrmRequest extends Request {
445
1418
  };
446
1419
  };
447
1420
  }
448
- // Catch-all for invalid relationship names on related resource route
449
- routes[`/:id/:relationship`] = async (request) => {
450
- const record = await store.find(model, getId(request.params));
451
- if (!record)
452
- return 404;
453
- // If we reach here, relationship doesn't exist (valid ones were registered above)
454
- return 404;
455
- };
456
- // Catch-all for invalid relationship names on relationship linkage route
457
- routes[`/:id/relationships/:relationship`] = async (request) => {
458
- const record = await store.find(model, getId(request.params));
459
- if (!record)
460
- return 404;
461
- return 404;
462
- };
1421
+ // Catch-alls for invalid relationship names. Every valid relationship was
1422
+ // registered above, so reaching either of these means the relationship does
1423
+ // not exist and the answer is 404 regardless of the record.
1424
+ //
1425
+ // These deliberately carry NO access check and no store lookup. An earlier
1426
+ // revision of #190 added `if (isDenied(filter, record)) return 404` here for
1427
+ // symmetry with the seven real surfaces, but both branches returned 404, so
1428
+ // the guard was unobservable by construction -- a mutation deleting it
1429
+ // survived the entire suite because no test that could distinguish it can
1430
+ // exist. Unkillable code in an authorization diff reads as coverage and is
1431
+ // not, so it is gone; skipping the lookup also removes the timing difference
1432
+ // between an existing and a missing parent.
1433
+ //
1434
+ // IF THIS ROUTE EVER RETURNS ANYTHING OTHER THAN A CONSTANT 404, it becomes
1435
+ // the eighth surface and must filter the parent first, exactly like
1436
+ // `/:id/{relationship}` above.
1437
+ routes[`/:id/:relationship`] = async () => 404;
1438
+ routes[`/:id/relationships/:relationship`] = async () => 404;
463
1439
  return routes;
464
1440
  }
465
1441
  auth(request, state) {
466
- const access = this.access(request);
467
- if (!access)
468
- return 403;
469
- if (Array.isArray(access) && !access.includes(methodAccessMap[request.method]))
1442
+ // A consumer `access()` that throws is a DENIAL, matching `isDenied` one
1443
+ // layer down. Unguarded it propagates to express's default handler, which
1444
+ // answers 500 -- and the documented sample itself can throw
1445
+ // (`request.originalUrl.split(...)` when originalUrl is absent), so the
1446
+ // failure mode is reachable by following the docs.
1447
+ // -------------------------------------------------------------------------
1448
+ // #202 -- hand the consumer the STRUCTURAL facts, not just the transport.
1449
+ //
1450
+ // Both members are already in hand here. `model` is `this.model`, the name
1451
+ // setup-rest-server mounted this route for; `operation` is the SAME
1452
+ // `methodAccessMap` lookup the permission-array branch at the bottom of
1453
+ // this method performs, so the predicate form and the array form cannot
1454
+ // answer differently about the same request.
1455
+ //
1456
+ // NEITHER IS DERIVED FROM THE REQUEST TARGET, and that is the whole point.
1457
+ // Deriving `model` here from `request.baseUrl` (or from the mounted route
1458
+ // name, or from `getPluralName(this.model)`) would move all five fail-open
1459
+ // variants listed in this file's header OUT of the consumer and INTO the
1460
+ // framework, where every consumer inherits them at once. `this.model` is
1461
+ // assigned once at mount time and no request can influence it.
1462
+ //
1463
+ // `operation` is left UNDEFINED for a method with no entry in
1464
+ // `methodAccessMap`, rather than defaulted. Express delivers HEAD to the
1465
+ // GET handler, so an unmapped method really does reach this line; a
1466
+ // `?? 'read'` here would hand the consumer a fabricated authorisation fact
1467
+ // and turn an unclassified request into an authorised one. Undefined is
1468
+ // the honest answer.
1469
+ //
1470
+ // `record` is deliberately absent -- see `AccessContext` in
1471
+ // src/types/orm-types.ts. Nothing is fetched at this point and adding a
1472
+ // lookup here would put a store read in the middle of an authorization
1473
+ // path. The function return shape below IS the per-record hook.
1474
+ //
1475
+ // -------------------------------------------------------------------------
1476
+ // #236 -- `recordId`, the DECODED route-parameter id, for the same reason.
1477
+ //
1478
+ // WHICH RECORD is the third structural fact the framework already holds and
1479
+ // the consumer was left to re-derive, and re-deriving it failed OPEN. The
1480
+ // documented sample compared `request.path` -- the RAW, undecoded pathname
1481
+ // -- against a literal `/archived`, while the router DECODES `:id`. So
1482
+ // `GET /owners/%61rchived` walked past the deny and was dispatched as the
1483
+ // record `archived`: 200 with the record in full, and DELETE answered 204
1484
+ // with the record destroyed, unauthenticated. Four spellings measured, all
1485
+ // four through; 255 non-canonical spellings of that 8-character id decode
1486
+ // to the same key, so this was never a deny-list of one.
1487
+ //
1488
+ // TWO CONSUMER-SIDE NORMALISATIONS WERE MEASURED WRONG IN OPPOSITE
1489
+ // DIRECTIONS, which is the argument for doing it once, here.
1490
+ // `.toLowerCase()` case-folds a route-parameter VALUE on the axis that
1491
+ // governs literal SEGMENTS: with a distinct owner seeded at `ARCHIVED`,
1492
+ // `GET /owners/ARCHIVED` was a false DENY on the wrong record and
1493
+ // `GET /owners/%41RCHIVED` a false ALLOW on that same one.
1494
+ // `decodeURIComponent(request.path)` decodes THEN splits while the router
1495
+ // splits THEN decodes, so it over-denied `/owners/archived%2fx` -- 403 for
1496
+ // a genuinely distinct record. Failing closed there was luck, not design.
1497
+ //
1498
+ // `getId(request.params)` AND NOT `request.params.id`, for exactly the
1499
+ // reason `operation` is a `methodAccessMap` lookup: it is the SAME single
1500
+ // coercion the store lookup one layer down performs, so the predicate and
1501
+ // the dispatch cannot disagree about which record a request addresses.
1502
+ // The raw string would reintroduce that divergence on hex-shaped ids --
1503
+ // `GET /animals/0x2391` looks up record `9105`.
1504
+ //
1505
+ // NOTHING HERE PARSES THE REQUEST TARGET EITHER. `request.params` is what
1506
+ // the router matched, so a mount prefix, an absolute-form target, a query
1507
+ // string or a case-varied mount cannot move this value -- the same
1508
+ // guarantee `model` carries, by the same means.
1509
+ //
1510
+ // `null` and not `undefined` on a collection route, so the KEY IS ALWAYS
1511
+ // PRESENT -- the rule `operation`'s own docblock already establishes. A
1512
+ // context reaching a predicate WITHOUT the key therefore did not come from
1513
+ // here; it was hand-assembled by a caller resolving the predicate through
1514
+ // `Orm.instance.getAccess()`, and that absence stays deniable only because
1515
+ // `auth()` never produces it.
1516
+ // -------------------------------------------------------------------------
1517
+ const context = {
1518
+ model: this.model,
1519
+ operation: methodAccessMap[request.method],
1520
+ recordId: request.params && 'id' in request.params ? getId(request.params) : null,
1521
+ };
1522
+ let access;
1523
+ try {
1524
+ access = this.access(request, context);
1525
+ }
1526
+ catch (error) {
1527
+ // Same reasoning as `isDenied`: fail closed, but say so. An `access()`
1528
+ // that throws denies EVERY request to the collection, and a silent 403
1529
+ // wall is the hardest possible thing to diagnose from the outside.
1530
+ log.error?.(`[@stonyx/orm] access() threw for model "${this.model}" -- denying. ${error instanceof Error ? error.message : String(error)}`);
1531
+ return 403; // Forbidden
1532
+ }
1533
+ // THE READING OF THE RETURN SHAPE LIVES IN ONE PLACE (#234).
1534
+ //
1535
+ // It used to be inline here, and it was the only copy, which was fine while
1536
+ // `auth()` was the only thing that had to ask. It is not any more: the
1537
+ // linkage path has to ask model X's predicate about model X's records while
1538
+ // servicing a request routed to model Y, and a second inline copy of these
1539
+ // six branches would be a second authorization vocabulary -- one that can
1540
+ // drift, and that reviewers would have to notice had drifted. The branch
1541
+ // order in `interpretAccess` is this block, moved, not rewritten.
1542
+ const verdict = interpretAccess(access, methodAccessMap[request.method]);
1543
+ if (!verdict.granted)
470
1544
  return 403;
471
- if (typeof access === 'function')
472
- state.filter = access;
1545
+ // The function return shape is the per-record hook, and `state` is the
1546
+ // whole transport for it: @stonyx/rest-server memoises one state object per
1547
+ // request and hands the same one to `auth()` and to the handler.
1548
+ if (verdict.filter)
1549
+ state.filter = verdict.filter;
473
1550
  return undefined;
474
1551
  }
475
1552
  }