@stonyx/orm 0.3.2-alpha.7 → 0.3.2-alpha.71

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 (63) hide show
  1. package/README.md +968 -11
  2. package/config/environment.js +8 -0
  3. package/dist/access-verdict.d.ts +59 -0
  4. package/dist/access-verdict.js +222 -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/index.d.ts +3 -0
  15. package/dist/index.js +8 -0
  16. package/dist/main.d.ts +116 -0
  17. package/dist/main.js +129 -0
  18. package/dist/manage-record.js +268 -12
  19. package/dist/mysql/connection.d.ts +1 -0
  20. package/dist/mysql/mysql-db.d.ts +8 -0
  21. package/dist/mysql/mysql-db.js +44 -10
  22. package/dist/orm-request.d.ts +216 -3
  23. package/dist/orm-request.js +924 -55
  24. package/dist/postgres/connection.d.ts +1 -0
  25. package/dist/postgres/connection.js +8 -6
  26. package/dist/postgres/postgres-db.d.ts +8 -0
  27. package/dist/postgres/postgres-db.js +44 -10
  28. package/dist/record.d.ts +16 -0
  29. package/dist/record.js +62 -6
  30. package/dist/relationships.js +1 -1
  31. package/dist/serializer.js +38 -2
  32. package/dist/setup-rest-server.js +51 -5
  33. package/dist/standalone-db.js +17 -5
  34. package/dist/store.d.ts +13 -1
  35. package/dist/store.js +65 -6
  36. package/dist/types/orm-types.d.ts +139 -0
  37. package/dist/utils.d.ts +44 -0
  38. package/dist/utils.js +47 -0
  39. package/package.json +16 -7
  40. package/src/access-verdict.ts +248 -0
  41. package/src/commands.ts +43 -0
  42. package/src/dynamodb/connection.ts +50 -0
  43. package/src/dynamodb/dynamodb-db.ts +811 -0
  44. package/src/dynamodb/operation-builder.ts +202 -0
  45. package/src/dynamodb/type-map.ts +54 -0
  46. package/src/index.ts +10 -0
  47. package/src/main.ts +133 -0
  48. package/src/manage-record.ts +294 -18
  49. package/src/mysql/connection.ts +1 -0
  50. package/src/mysql/mysql-db.ts +44 -12
  51. package/src/orm-request.ts +944 -56
  52. package/src/postgres/connection.ts +10 -6
  53. package/src/postgres/postgres-db.ts +44 -12
  54. package/src/record.ts +82 -6
  55. package/src/relationships.ts +1 -1
  56. package/src/serializer.ts +39 -2
  57. package/src/setup-rest-server.ts +59 -6
  58. package/src/standalone-db.ts +17 -6
  59. package/src/store.ts +68 -6
  60. package/src/types/orm-types.ts +146 -1
  61. package/src/types/stonyx-rest-server.d.ts +14 -1
  62. package/src/types/stonyx.d.ts +7 -1
  63. package/src/utils.ts +50 -0
@@ -1,3 +1,216 @@
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
+ * `record` IS NOT IN THIS CONTEXT, deliberately. `auth()` runs after route
73
+ * matching but BEFORE any handler executes (`@stonyx/rest-server`
74
+ * `src/request.ts:58-60`), so nothing has been fetched yet -- supplying a
75
+ * record would force a pre-fetch on every request, a second store hit and an
76
+ * ordering change in the middle of an authorization path. It is also
77
+ * unnecessary: the FUNCTION return shape already is the per-record hook. Return
78
+ * `(record) => boolean` and the handlers apply it to every record the request
79
+ * touches. Auth-time and record-time are separate decision points.
80
+ *
81
+ * THE SECOND ARGUMENT IS ADDITIVE. JavaScript ignores extra arguments, so an
82
+ * existing `access(request)` predicate keeps working exactly as before. The
83
+ * warning immediately below is therefore still live: `request` is still
84
+ * argument ONE, and reading it is still how predicates fail open.
85
+ *
86
+ * To reach ANOTHER model's predicate -- e.g. to check an animal while servicing
87
+ * an owners route -- use the boot-time registry:
88
+ *
89
+ * const predicate = Orm.instance.getAccess('animal');
90
+ * if (!predicate) return deny;
91
+ * const verdict = predicate(request, { model: 'animal', operation: 'read' });
92
+ *
93
+ * `undefined` means NO PREDICATE COULD BE RESOLVED for that name -- which
94
+ * includes the case where the model has an access class that failed to load,
95
+ * because `setup-rest-server.ts` catches a load failure, warns, and publishes
96
+ * whatever partial map it had. It does NOT mean the model is unrestricted.
97
+ * Treat it as DENY, the same way `operation === undefined` is treated above.
98
+ *
99
+ * PASSING THE CONTEXT MAKES A MODEL-CORRECT ANSWER POSSIBLE. It does not make
100
+ * the answer model-correct on its own -- the resolved predicate has to READ it.
101
+ * Measured against an ARITY-1 predicate, on a request express dispatched to
102
+ * `GET /owners/angela`, asked about ANIMALS:
103
+ *
104
+ * getAccess('animal')(ownersRequest, { model: 'animal', operation: 'read' })
105
+ * -> record => record.id !== 'angela' && record.id !== 'restricted'
106
+ *
107
+ * That is the OWNERS filter, and it returns `true` for animal 21 -- the record
108
+ * hidden on every animal surface. Under a mount that predicate recognises
109
+ * neither way it is worse: it falls through to
110
+ * `['read', 'create', 'update', 'delete']`, a full CRUD grant. Either way the
111
+ * context was supplied and the answer is not the animal answer, and it is wrong
112
+ * in the GRANTING direction, because that predicate is arity-1 and identifies
113
+ * its collection from the request. (Asserted on a live dispatch by AC9 in
114
+ * test/integration/orm-test.ts, against a deliberately arity-1 predicate.)
115
+ *
116
+ * This repo's own sample access class has since been MIGRATED to read the
117
+ * context (abofs/stonyx-orm#222), so `getAccess('animal')` here now answers
118
+ * with the animal filter. That is not true of a consumer tree: an arity-1
119
+ * predicate keeps working -- the second argument is additive -- and the caller
120
+ * has no supported way to tell which kind it got. The boot-time arity warning
121
+ * that surfaces one is abofs/stonyx-orm#221.
122
+ * So: pass the context, and do not treat a resolved predicate's answer as
123
+ * model-specific until that predicate has been migrated to read the context.
124
+ *
125
+ * ---------------------------------------------------------------------------
126
+ * DO NOT RECONSTRUCT THE REQUEST PATH INSIDE `access()`.
127
+ * ---------------------------------------------------------------------------
128
+ * You do not have to. `auth()` below hands your predicate the ACCESS CONTEXT as
129
+ * argument two, and `context.model` already names the collection -- see the
130
+ * contract section above. Argument ONE is still the raw transport artifact, and
131
+ * everything from here to the end of this banner is the record of what happened
132
+ * when predicates worked the collection out from it. IT IS HISTORY, NOT
133
+ * GUIDANCE: do not write any of it into a new predicate. Every attempt to
134
+ * identify the collection by parsing the request target has failed OPEN. Five
135
+ * distinct variants of the same three-line example have now been found, each
136
+ * after the previous was fixed, by five different people:
137
+ *
138
+ * 1. `request.url` is mount-relative under `RestServer.mountRoute`, so a
139
+ * prefix match against it is ALWAYS false.
140
+ * 2. `request.originalUrl` carries the query string, so an anchored equality
141
+ * check misses `/owners?filter[age]=30`.
142
+ * 3. The router is a bare `express()` (`caseSensitive: false`) while a
143
+ * hand-written matcher is case-SENSITIVE, so `GET /OwNeRs/angela` walks
144
+ * past it. Router-side: abofs/stonyx-rest-server#47.
145
+ * 4. Under a configured `ORM_REST_ROUTE` a hard-coded `/owners` matches
146
+ * nothing -- environment-specifically, which is worse.
147
+ * 5. HTTP/1.1 permits an ABSOLUTE-FORM request-target. Express routes on
148
+ * `parseurl(req).pathname`, but `originalUrl` is the raw target, so
149
+ * `GET http://anything.example/owners/angela` reaches the handler with
150
+ * `originalUrl === 'http://anything.example/owners/angela'`. A `/owners`
151
+ * prefix match is false, `access()` falls through to whatever it returns
152
+ * last, and the record comes back in full. It walks past a hard
153
+ * `return false` deny the same way.
154
+ *
155
+ * The fix is not a sixth rule, and it is not a better string to match. It is to
156
+ * stop identifying the collection at all: read `context.model`. That is a claim
157
+ * about IDENTIFYING THE COLLECTION, not about the sample as a whole -- the
158
+ * `/archived` SUB-PATH rule is still a string match, and abofs/stonyx-orm#228 is
159
+ * a sixth spelling that gets past it.
160
+ *
161
+ * An intermediate revision of the sample read `request.baseUrl` -- the mount
162
+ * Express ACTUALLY MATCHED. That closed all five variants (no query string,
163
+ * not mount-relative, unaffected by absolute-form, already carrying the
164
+ * configured `ORM_REST_ROUTE` prefix), but it was a transport artifact
165
+ * standing in for a structural fact and the sample no longer does it.
166
+ * `context.model` IS the structural fact, so variants 1, 2, 4 and 5 are
167
+ * unconstructible against a migrated predicate rather than handled.
168
+ *
169
+ * VARIANT 3 SURVIVES, and is deliberately not in that list. It is the general
170
+ * shape "a hand-written matcher normalises differently from the router", and a
171
+ * migrated predicate still runs one string comparison for any SUB-PATH rule --
172
+ * in the shipped sample, the `/archived` deny. That comparison folds case but
173
+ * does not decode, so `GET /owners/%61rchived` steps past it. See the
174
+ * normalisation paragraph below and abofs/stonyx-orm#228.
175
+ *
176
+ * ONE READ OF ARGUMENT ONE SURVIVES, AND IT MUST: `request.path`. It is
177
+ * mount-relative and query-free, and it is for rules that distinguish SUB-PATHS
178
+ * beneath the mount. The context names which model and which verb, NOT which
179
+ * route, so the sample's `/archived` deny cannot be expressed from the context
180
+ * alone and a context-ONLY rewrite would silently turn that deny into an allow.
181
+ *
182
+ * NORMALISE THE WAY THE ROUTER DOES, AND CASE-FOLDING ALONE IS NOT THAT. The
183
+ * sample lower-cases before comparing, because a matcher stricter than the
184
+ * case-insensitive router can be stepped around. That closes the case gap only.
185
+ * Express sets `request.path` from the RAW, UNDECODED pathname while the router
186
+ * DECODES `:id`, so `GET /owners/%61rchived` reaches a `path === '/archived'`
187
+ * comparison as `/%61rchived` and walks past the deny. That gap is live in the
188
+ * sample and is tracked as abofs/stonyx-orm#228; the `.toLowerCase()` is not a
189
+ * complete normalisation recipe. Compare record ids at their real case.
190
+ *
191
+ * `?? ''` is not a defence. It converts an absent request target into an empty
192
+ * string, which matches no collection, which falls through to the permission
193
+ * array -- a total grant. An input you cannot identify must DENY, and that
194
+ * applies to BOTH arguments: since #202 the guard and the read can sit on
195
+ * different objects, and a guard on argument two does not protect a read of
196
+ * argument one. The sample returns `false` for an absent `model` AND for an
197
+ * absent or non-string `request.path`, rather than falling through either way.
198
+ *
199
+ * THE REAL FIX IS abofs/stonyx-orm#202: `access()` should receive the model,
200
+ * the operation and the record. Prefer the array shape (`['read']`) or `false`
201
+ * until #202 lands; the function shape is what requires any matching at all.
202
+ *
203
+ * The enforcement gates in this file (GATE 0/1/2, the create rollback, the
204
+ * per-handler `isDenied` re-checks) are correct independently of that -- they
205
+ * enforce whatever predicate you return. The stopgap is the part where YOU have
206
+ * to work out which predicate to return.
207
+ *
208
+ * AND A PREDICATE IS NOT A GUARANTEE THAT A HIDDEN RECORD CANNOT BE MODIFIED.
209
+ * It is evaluated against the record the route is ADDRESSED TO, on that model
210
+ * only. A write to a DIFFERENT collection can still re-parent a hidden record
211
+ * and de-hide it -- abofs/stonyx-orm#207, which is blocked on #202 and #196.
212
+ * See `### Known limitations` in README.
213
+ */
1
214
  import { Request } from '@stonyx/rest-server';
2
215
  import Orm, { store, createRecord, updateRecord } from '@stonyx/orm';
3
216
  import { camelCaseToKebabCase } from '@stonyx/utils/string';
@@ -5,8 +218,10 @@ import { getPluralName } from './plural-registry.js';
5
218
  import { getBeforeHooks, getAfterHooks } from './hooks.js';
6
219
  import type { HookContext } from './hooks.js';
7
220
  import config from 'stonyx/config';
8
- import type { OrmRecord } from './types/orm-types.js';
9
- import { isOrmRecord } from './utils.js';
221
+ import log from 'stonyx/log';
222
+ import type { OrmRecord, AccessContext, AccessFunction, AccessMethod, AccessOperation } from './types/orm-types.js';
223
+ import { isOrmRecord, NO_FREE_ID_ERROR } from './utils.js';
224
+ import { interpretAccess, createLinkageFilter } from './access-verdict.js';
10
225
 
11
226
  interface OrmRequest$ extends Request {
12
227
  protocol?: string;
@@ -33,10 +248,9 @@ interface JsonApiResponse {
33
248
  included?: unknown[];
34
249
  }
35
250
 
36
- type AccessMethod = string | boolean | string[] | ((record: unknown) => boolean);
37
251
  type HandlerFn = (request: OrmRequest$, state: { [key: string]: unknown }) => unknown | Promise<unknown>;
38
252
 
39
- const methodAccessMap: { [key: string]: string } = {
253
+ const methodAccessMap: { [key: string]: AccessOperation } = {
40
254
  GET: 'read',
41
255
  POST: 'create',
42
256
  DELETE: 'delete',
@@ -84,12 +298,119 @@ function getBaseUrl(request: OrmRequest$): string {
84
298
  return `${protocol}://${host}`;
85
299
  }
86
300
 
301
+ /**
302
+ * The ONE coercion from a caller-supplied id to the key the store holds it
303
+ * under. Every id-bearing surface in this file goes through it, and none has a
304
+ * copy: `getId()` (URL params), `normalizeBodyId()` (JSON body), and the
305
+ * post-create `context.record` lookup in `_withHooks`.
306
+ *
307
+ * WHY IT IS SHARED RATHER THAN DUPLICATED. `getId()` and `normalizeBodyId()`
308
+ * each had their own arithmetic, and they disagreed: `parseInt(id)` versus
309
+ * `parseInt(id, 10)`. On a hex-shaped id that is a two-record difference --
310
+ *
311
+ * GET /animals/0x2391 -> record 9105 (getId -> parseInt('0x2391') = 9105)
312
+ * POST /animals {"id":"0x2391"} -> lookup under 0 (normalize -> parseInt('0x2391',10) = 0)
313
+ * -> a MISS, so the duplicate check was skipped and
314
+ * createRecord OVERWROTE 9105 in place, answering 200
315
+ *
316
+ * -- a narrower form of the raw-versus-normalised divergence that the body-id
317
+ * normalisation was added to close, reintroduced by the fix for it. Two
318
+ * coercions that must agree cannot be kept in agreement by review; they have to
319
+ * be one function. Pinned by assertion 43.
320
+ *
321
+ * The third copy was found later and in a quieter place: `_withHooks` populated
322
+ * `context.record` for `create` with `isNaN(id) ? id : parseInt(id)` -- this
323
+ * function's body, inlined verbatim, feeding `store.get`. It was equivalent on
324
+ * every input reachable there, which is exactly what the two that DID diverge
325
+ * looked like until someone tried a hex id.
326
+ *
327
+ * SHARING IT IS NOT THE SAME AS IT BEING RIGHT EVERYWHERE. On a model declaring
328
+ * `id = attr('string')` a numeric-looking id is filed under the STRING key, so
329
+ * this coercion resolves `'9107'` to `9107` and the post-create lookup misses:
330
+ * `context.record` is `undefined` for an after-`create` hook. Inherited -- the
331
+ * inlined copy computed the same thing -- and NOT fixed here, because picking
332
+ * the right coercion needs the model's declared id type, which is the same
333
+ * structural information abofs/stonyx-orm#202 is about. Filed as
334
+ * abofs/stonyx-orm#209 and pinned by assertion 50, so closing it turns a test
335
+ * red rather than passing silently.
336
+ *
337
+ * `parseInt` and not `Number`, deliberately, and the anchor is NOT `getId`.
338
+ * It is `src/transforms.ts:7` -- `number: (value) => parseInt(value as string)`,
339
+ * also radix-less -- because that transform is what actually produces the store
340
+ * KEY a record is filed under. `getId` merely agrees with it. They differ from
341
+ * `Number` on `'1e3'` (1 vs 1000) and `'9105.5'` (9105 vs 9105.5), so switching
342
+ * this function to `Number` would make the lookup key disagree with the landing
343
+ * key on those shapes.
344
+ *
345
+ * THE CHANGE THAT WOULD BREAK THIS: adding a radix to `transforms.number`
346
+ * (`parseInt(value, 10)`). That is a one-word edit in a file with no connection
347
+ * to authorization, it would silently reopen the hex divergence in the other
348
+ * direction, and this comment would still read as correct. Assertion 45 pins
349
+ * the transform's radix-less shape directly, so that edit turns a test red
350
+ * rather than shipping.
351
+ *
352
+ * The reason `parseInt` is safe here is the `isNaN` gate in front of it:
353
+ * `parseInt('9105h')` is `9105`, and truncating a partially-valid id into a
354
+ * DIFFERENT VALID key is exactly how a collision lookup gets skipped. The gate
355
+ * rejects it as a string instead, so nothing is ever truncated. That gate, not
356
+ * the parser, is the load-bearing half -- assertion 43 pins it.
357
+ */
358
+ function coerceId(id: string): string | number {
359
+ if (isNaN(id as unknown as number)) return id;
360
+
361
+ return parseInt(id);
362
+ }
363
+
87
364
  function getId(params: { id?: string; [key: string]: unknown }): string | number {
88
365
  const id = params.id;
89
366
  if (!id) return '';
90
- if (isNaN(id as unknown as number)) return id;
91
367
 
92
- return parseInt(id);
368
+ return coerceId(id);
369
+ }
370
+
371
+ /**
372
+ * Normalise a caller-supplied BODY id to the key the store will hold it under.
373
+ *
374
+ * `getId()` above is params-shaped: it takes `{ id?: string }` off the URL,
375
+ * where the value is always a string and a falsy one means "no id". A JSON body
376
+ * id is neither -- it can arrive as a number, and `0` is a legitimate id that
377
+ * `getId()` would flatten to `''`.
378
+ *
379
+ * WHY THIS EXISTS AT ALL. createHandler used to look the collision up with the
380
+ * RAW body value while every other surface normalised through `getId()`. The
381
+ * store is a Map keyed by the coerced value, so `store.find(model, '21')` misses
382
+ * the entry held under `21` and the duplicate check is skipped by typing the id
383
+ * as a string. On `dev` that silently overwrote the colliding record and
384
+ * answered 200; combined with the denied-create rollback added for #190 it
385
+ * became an unauthenticated DELETE of any id. Normalising here is half of that
386
+ * fix -- see the rollback in createHandler for the other half.
387
+ *
388
+ * It shares `coerceId` with `getId` so the two surfaces cannot drift apart
389
+ * again, and differs from `getId` in exactly ONE place, below.
390
+ */
391
+ function normalizeBodyId(id: string | number): string | number {
392
+ // Non-strings pass through untouched: a JSON body id can arrive as a number,
393
+ // and `getId`'s falsy-flatten must NOT apply to it -- `0` is a legitimate id
394
+ // and `getId` would turn it into `''`. (assertion 30 sweeps id `0`.)
395
+ if (typeof id !== 'string') return id;
396
+
397
+ // THE ONE DIVERGENCE FROM `getId`, and it mirrors rather than contradicts it:
398
+ // `getId` maps a falsy param to `''`, and `''` is the only string a body can
399
+ // carry that means "no id" -- `createRecord` treats it as absent and assigns a
400
+ // server id. Coercing it instead would make it address a real slot, because
401
+ // `parseInt('')` is `NaN` and a record CAN be held under `NaN` (a truthy but
402
+ // non-numeric id such as `' '` survives `assignRecordId`'s falsy guard and
403
+ // then NaNs in the id transform). So `POST {"id":""}` would answer 409 against
404
+ // an unrelated record it never named. Pinned by assertion 44.
405
+ //
406
+ // Note what is deliberately NOT special-cased here any more: whitespace.
407
+ // `id.trim() === ''` used to short-circuit `' '` as well, which made the
408
+ // body surface DISAGREE with the URL surface -- `getId({id:' '})` is `NaN`,
409
+ // so `' '` addresses the NaN slot on every other route while the collision
410
+ // lookup missed it. Same class of bug as the hex divergence above.
411
+ if (id === '') return id;
412
+
413
+ return coerceId(id);
93
414
  }
94
415
 
95
416
  function buildResponse(
@@ -113,6 +434,13 @@ function buildResponse(
113
434
 
114
435
  const includedRecords = collectIncludedRecords(recordOrRecords, includes);
115
436
  if (includedRecords.length > 0) {
437
+ // NO `linkage` ARGUMENT, deliberately, and abofs/stonyx-orm#235 owns adding
438
+ // one. Until it does, a PERMITTED record here emits the full pre-#234
439
+ // document: `GET /animals/1?include=owner` filters the primary document's
440
+ // `owner.data` to `null` and then names `owner:angela` in `included`.
441
+ // Whether a resource reaches this array at all is a different question
442
+ // (membership, abofs/stonyx-orm#233) and closing that one does not close
443
+ // this one.
116
444
  response.included = includedRecords.map(record => record.toJSON?.({ baseUrl }));
117
445
  }
118
446
 
@@ -251,12 +579,46 @@ function createFilterPredicate(filters: Filter[]): ((record: { [key: string]: un
251
579
  });
252
580
  }
253
581
 
582
+ /**
583
+ * A function-style `access` return is a per-record predicate, and it is only
584
+ * meaningful if every surface that can hand a record to a caller consults it.
585
+ * Before #190 exactly one of seven did.
586
+ *
587
+ * Enforcement is deliberately post-fetch. `access` returns an opaque JS
588
+ * predicate and `store.findAll(model, conditions)` accepts only an equality
589
+ * conditions object that the SQL drivers translate to a WHERE clause, so
590
+ * query-layer enforcement would require a breaking change to the published
591
+ * `access` contract. That belongs in #197, not in a security patch. Six of the
592
+ * seven surfaces fetch by primary key anyway, so this costs exactly one row.
593
+ */
594
+ function isDenied(filter: unknown, record: unknown): boolean {
595
+ if (typeof filter !== 'function') return false;
596
+
597
+ // A predicate that throws is treated as a denial. Unguarded, a throw escapes
598
+ // to express's default handler, which answers 500 (with a stack trace outside
599
+ // NODE_ENV=production) while a missing id still answers 404 -- so a
600
+ // record-dependent throw re-separates "hidden" from "does not exist" and
601
+ // hands back the oracle this whole change exists to close.
602
+ try {
603
+ return !(filter as (record: unknown) => boolean)(record);
604
+ } catch (error) {
605
+ // Denied, but not silently. A consumer predicate that throws on every
606
+ // record turns the whole collection into a 404 wall, and with no
607
+ // diagnostic that is indistinguishable from an empty database. `stonyx/log`
608
+ // is the module convention (see setup-rest-server.ts); optional-call
609
+ // because a consumer may not have configured the log types.
610
+ log.error?.(`[@stonyx/orm] access filter threw for model -- denying. ${error instanceof Error ? error.message : String(error)}`);
611
+
612
+ return true;
613
+ }
614
+ }
615
+
254
616
  export default class OrmRequest extends Request {
255
617
  model: string;
256
- access: (request: unknown) => AccessMethod;
618
+ access: AccessFunction;
257
619
  handlers: { [key: string]: { [key: string]: HandlerFn } };
258
620
 
259
- constructor({ model, access }: { model: string; access: (request: unknown) => AccessMethod }) {
621
+ constructor({ model, access }: { model: string; access: AccessFunction }) {
260
622
  super(...arguments as unknown as unknown[]);
261
623
 
262
624
  this.model = model;
@@ -279,7 +641,14 @@ export default class OrmRequest extends Request {
279
641
  if (queryFilterPredicate) recordsToReturn = recordsToReturn.filter(queryFilterPredicate as (record: OrmRecord) => boolean);
280
642
 
281
643
  const baseUrl = getBaseUrl(request);
282
- const data = recordsToReturn.map(record => record.toJSON?.({ fields: modelFields, baseUrl }));
644
+
645
+ // ONE filter per REQUEST, not one per record: it carries the per-type
646
+ // verdict cache and the per-(type, id) decision cache, and both are
647
+ // worthless if it is rebuilt inside the map. Measured on this exact
648
+ // surface with no `include=`: 48 linkage entries collapse to 7 distinct
649
+ // (type, id) pairs.
650
+ const linkage = createLinkageFilter(request);
651
+ const data = recordsToReturn.map(record => record.toJSON?.({ fields: modelFields, baseUrl, linkage }));
283
652
 
284
653
  return buildResponse(data, request.query?.include, recordsToReturn, {
285
654
  links: { self: `${baseUrl}/${pluralizedModel}` },
@@ -287,21 +656,43 @@ export default class OrmRequest extends Request {
287
656
  });
288
657
  };
289
658
 
290
- const getSingleHandler: HandlerFn = async (request) => {
659
+ const getSingleHandler: HandlerFn = async (request, { filter }) => {
291
660
  const record = await store.find(model, getId(request.params)) as OrmRecord | undefined;
292
661
  if (!record) return 404;
662
+ // 404, never 403: the status for "exists but filtered out" must be
663
+ // identical to "does not exist", or the fix trades an authorization
664
+ // bypass for a narrower existence oracle.
665
+ if (isDenied(filter, record)) return 404;
293
666
 
294
667
  const fieldsMap = parseFields(request.query);
295
668
  const modelFields = fieldsMap.get(pluralizedModel) || fieldsMap.get(model);
296
669
 
297
670
  const baseUrl = getBaseUrl(request);
298
- return buildResponse(record.toJSON?.({ fields: modelFields, baseUrl }), request.query?.include, record, {
671
+ const linkage = createLinkageFilter(request);
672
+
673
+ // `buildResponse` is deliberately NOT given the linkage filter, and the
674
+ // residual that leaves is NOT the one #233 owns. Two different questions:
675
+ //
676
+ // - WHETHER A RESOURCE APPEARS in `included` at all is MEMBERSHIP ->
677
+ // abofs/stonyx-orm#233.
678
+ // - What a record already IN `included` may NAME is LINKAGE -- the same
679
+ // question #234 answers for the primary document -- and it is
680
+ // abofs/stonyx-orm#235, which also owns createHandler/updateHandler.
681
+ //
682
+ // The residual, stated so the next reader does not have to derive it:
683
+ // `buildResponse` calls `record.toJSON?.({ baseUrl })` with no `linkage`
684
+ // argument, so a PERMITTED record in `included` emits the full pre-#234
685
+ // document. Measured: `GET /animals/1?include=owner` returns
686
+ // `owner.data: null` on the primary document and `owner:angela` in
687
+ // `included`. One query parameter deep. Only the PRIMARY document's
688
+ // linkage is filtered here.
689
+ return buildResponse(record.toJSON?.({ fields: modelFields, baseUrl, linkage }), request.query?.include, record, {
299
690
  links: { self: `${baseUrl}/${pluralizedModel}/${request.params.id}` },
300
691
  baseUrl
301
692
  });
302
693
  };
303
694
 
304
- const createHandler: HandlerFn = async ({ body, query }) => {
695
+ const createHandler: HandlerFn = async ({ body, query }, { filter }) => {
305
696
  const { type, id, attributes, relationships: rels } = (body?.data || {}) as {
306
697
  type?: string;
307
698
  id?: string | number;
@@ -314,14 +705,113 @@ export default class OrmRequest extends Request {
314
705
  const fieldsMap = parseFields(query);
315
706
  const modelFields = fieldsMap.get(pluralizedModel) || fieldsMap.get(model);
316
707
 
317
- // Check for duplicate ID
318
- if (id !== undefined && await store.find(model, id)) return 409; // Conflict
708
+ // GATE 0 -- the POST existence oracle.
709
+ //
710
+ // The duplicate check runs before the filter and `store.find` sees hidden
711
+ // records, so POST leaks existence through its STATUS. A previous revision
712
+ // filtered the collision status (403 when the colliding record is denied,
713
+ // 409 when it is visible) and that is NOT sufficient, because the status
714
+ // of a create is a third outcome. With a payload the caller is permitted
715
+ // to create -- the normative case for a per-tenant filter, and the case an
716
+ // attacker picks -- all three are distinguishable in ONE request per id:
717
+ //
718
+ // POST /animals {id:22, owner:'gina'} -> 403 a HIDDEN record has this id
719
+ // POST /animals {id:9500, owner:'gina'} -> 200 this id is FREE
720
+ // POST /animals {id:8, owner:'gina'} -> 409 a VISIBLE record has this id
721
+ //
722
+ // Filtering only the collision status narrows that to callers who cannot
723
+ // create a record they are allowed to see. It does not close it.
724
+ //
725
+ // It cannot be closed while a caller both chooses the id and learns
726
+ // whether the create succeeded: a successful create must answer
727
+ // differently from a refused one. So when a per-record filter is in force
728
+ // the caller does not get to choose the id at all. The refusal is
729
+ // UNCONDITIONAL and happens BEFORE any store lookup, so no status, and no
730
+ // lookup cost, can depend on whether that id exists. 403 -- the same
731
+ // status as a denied create -- so the two cannot be separated either.
732
+ //
733
+ // BOTH HALVES OF THAT ARE PINNED, because both were once asserted here and
734
+ // pinned by nothing:
735
+ //
736
+ // status -- assertion 22 sweeps payload x id x id-type, plus `null`.
737
+ // latency -- assertion 41 asserts NO `store.find` is issued on this
738
+ // path. Moving the refusal to after a lookup and returning
739
+ // the same 403 left the suite green while re-opening a
740
+ // hit-versus-miss timing difference on every id-bearing POST,
741
+ // which is what would turn #197 from a ~0.06ms post-fetch
742
+ // residual into a live timing oracle on create.
743
+ //
744
+ // AND THE GUARANTEE IS ONLY AS WIDE AS THE CHANNELS IT COVERS. It reads on
745
+ // the `id` member of the resource object, so it holds only while that is
746
+ // the ONLY way a caller id can reach `createRecord`. It was not: the
747
+ // relationships loop below re-admitted one under `key === "id"` and the
748
+ // gate never fired. Both strips -- `attributes.id` and `relationships.id`
749
+ // -- are therefore part of THIS gate, not tidiness, and assertion 39 pins
750
+ // them. Adding a third channel without a strip re-opens the oracle.
751
+ //
752
+ // Scoped to function-style `access` because that is exactly the population
753
+ // the oracle exists for: with no per-record filter there are no hidden
754
+ // records, and 409 discloses nothing GET /:id does not already.
755
+ //
756
+ // RESIDUALS, stated rather than implied.
757
+ //
758
+ // - a caller can still learn that a collection HAS a per-record filter
759
+ // (403 rather than 409/200 for an id-bearing POST). That discloses a
760
+ // configuration fact, not a record.
761
+ // - this gate is about ids arriving on THIS model's create route. It
762
+ // says nothing about a write to ANOTHER collection: a `POST /owners`
763
+ // carrying `relationships: {pets: {data: {id: 21}}}` -- or
764
+ // `attributes: {pets: [21, 22]}`, which never enters the
765
+ // relationships loop at all -- re-parents hidden animal 21 onto an
766
+ // owner the caller may write, which changes the very field the
767
+ // animals predicate reads and DE-HIDES it. Blocking that needs animal
768
+ // 21 checked against the ANIMAL model's predicate while servicing an
769
+ // OWNERS route, i.e. cross-model access resolution: abofs/stonyx-orm
770
+ // #207, blocked on #202 (`access` receives the model structurally)
771
+ // and #196 (setup-rest-server discards the model->predicate map at
772
+ // boot). NOT closed here, and no comment in this file may say it is.
773
+ //
774
+ // See README `### Known limitations`.
775
+ if (id !== undefined) {
776
+ if (typeof filter === 'function') return 403; // Forbidden
777
+
778
+ // `normalizeBodyId`, not the raw value: a string-typed id misses the
779
+ // store's numeric key, which skipped this check entirely.
780
+ const existing = await store.find(model, normalizeBodyId(id));
781
+ if (existing) return 409; // Conflict
782
+ }
319
783
 
320
784
  const { id: _ignoredId, ...sanitizedAttributes } = attributes || {};
321
785
 
322
- // Extract relationship IDs from JSON:API relationships object
786
+ // Extract relationship IDs from JSON:API relationships object.
787
+ //
788
+ // `key` comes VERBATIM from the request body, so `id` is stripped here for
789
+ // exactly the same reason it is stripped from `attributes` on the line
790
+ // above -- and it must be, or GATE 0 is walked around by moving one field:
791
+ //
792
+ // POST /animals {"id":21, ...} -> 403 GATE 0 fires
793
+ // POST /animals {"relationships":{"id":{"data":{"id":21}}},
794
+ // "attributes":{"owner":"gina"}} -> 200 BYPASS
795
+ //
796
+ // Top-level `id` stayed `undefined`, so GATE 0 never fired and the
797
+ // collision lookup never ran; `createRecord` took its last-entry-wins
798
+ // branch, overwrote hidden record 21 in place and reset its `owner` to a
799
+ // value the caller chose -- de-hiding it permanently. That is #190 itself,
800
+ // on the create surface. Pinned by assertion 39.
801
+ //
802
+ // The `id` member of the resource object is now the ONLY channel a caller
803
+ // id can arrive on FOR THIS MODEL'S OWN CREATE ROUTE, which is what makes
804
+ // GATE 0's guarantee checkable rather than merely asserted. It is not a
805
+ // statement about the record's reachability in general -- a relationship
806
+ // write on another collection reaches it without ever touching this
807
+ // handler (abofs/stonyx-orm#207). INHERITED from `dev`, which carries this
808
+ // loop verbatim; the general form -- the loop accepts any key, not just
809
+ // `id`, so a body key that is not a declared relationship is still
810
+ // mass-assigned -- is abofs/stonyx-orm#204.
323
811
  if (rels) {
324
812
  for (const [key, value] of Object.entries(rels)) {
813
+ if (key === 'id') continue;
814
+
325
815
  const relData = value?.data;
326
816
  if (relData && relData.id !== undefined) {
327
817
  (sanitizedAttributes as { [key: string]: unknown })[key] = relData.id;
@@ -330,16 +820,150 @@ export default class OrmRequest extends Request {
330
820
  }
331
821
 
332
822
  const recordAttributes = id !== undefined ? { id, ...sanitizedAttributes } : sanitizedAttributes;
333
- const created = createRecord(model, recordAttributes as { [key: string]: unknown }, { serialize: false, _skipAutoPersist: true });
823
+
824
+ // Slot count BEFORE the write. `createRecord` writes to the store before
825
+ // the predicate can run, and the rollback below must be able to prove the
826
+ // slot it removes is one THIS REQUEST created. Identity alone cannot
827
+ // prove it: when `assignRecordId` lands on an occupied id, `createRecord`
828
+ // mutates the existing OrmRecord IN PLACE, so `store.get(...) === record`
829
+ // is true for a record the request did not create. The map's size is the
830
+ // only O(1) signal that distinguishes an insert from an overwrite.
831
+ const slotsBefore = store.get(model)?.size ?? 0;
832
+
833
+ // THE ONE `createRecord` FAILURE THIS ROUTE ANSWERS RATHER THAN
834
+ // PROPAGATES, and it is narrow on purpose.
835
+ //
836
+ // `assignRecordId` throws when it cannot derive a free store key for a
837
+ // server-assigned id. Unguarded that rejection is auto-forwarded -- there
838
+ // is no catch here, none in @stonyx/rest-server's dispatcher
839
+ // (dist/request.js:41-70), and express 5 hands it to its default error
840
+ // handler, which serialises the STACK, with absolute install paths and the
841
+ // internal module graph, to an unauthenticated caller outside
842
+ // NODE_ENV=production. That is the hazard :553-558 already names in this
843
+ // file, and every sibling refusal in this handler returns an integer
844
+ // status instead. So this one returns 409, matching the client-duplicate
845
+ // refusal at :713: the caller asked for a record and the collection has no
846
+ // id to give it.
847
+ //
848
+ // MATCHED ON THE SHARED PREFIX, not on a literal, and NOT by catching
849
+ // everything: `createRecord` also throws for "ORM is not ready", a
850
+ // read-only view and an unregistered model store, and turning any of those
851
+ // into a 409 would report a configuration fault as a conflict. Anything
852
+ // else is re-thrown unchanged.
853
+ let created;
854
+
855
+ try {
856
+ created = createRecord(model, recordAttributes as { [key: string]: unknown }, { serialize: false, _skipAutoPersist: true });
857
+ } catch (error) {
858
+ if (!(error instanceof Error) || !error.message.startsWith(NO_FREE_ID_ERROR)) throw error;
859
+
860
+ // Not silently. A collection that can no longer assign an id is a
861
+ // configuration fault (a non-injective id transform), and a bare 409
862
+ // with no diagnostic is indistinguishable from an ordinary duplicate.
863
+ log.error?.(`[@stonyx/orm] ${error.message}`);
864
+
865
+ return 409; // Conflict
866
+ }
867
+
334
868
  const record = isOrmRecord(created) ? created : null;
335
869
  if (!record) return 500;
336
870
 
871
+ const createdNewSlot = (store.get(model)?.size ?? 0) > slotsBefore;
872
+
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 as string | number) === record) {
944
+ store.remove(model, record.id as string | number, { _skipAutoPersist: true });
945
+ }
946
+
947
+ return 403;
948
+ }
949
+
337
950
  return { data: record.toJSON?.({ fields: modelFields }) };
338
951
  };
339
952
 
340
- const updateHandler: HandlerFn = async ({ body, params }) => {
953
+ const updateHandler: HandlerFn = async ({ body, params }, { filter }) => {
341
954
  const found = await store.find(model, getId(params));
342
955
  if (!found || !isOrmRecord(found)) return 404;
956
+ // Checked BEFORE any attribute is applied. 404 rather than 403 for the
957
+ // same reason as GET /:id -- 403 would disclose both that the record
958
+ // exists and that this caller specifically is excluded.
959
+ //
960
+ // NOT redundant behind GATE 1, and not defence in depth either: GATE 1's
961
+ // verdict is computed BEFORE the before-hook loop runs, and a before-hook
962
+ // is a published extension point that can change the answer -- by
963
+ // mutating the record, or against a predicate that closes over
964
+ // per-request state. This is the only re-evaluation after that window.
965
+ // Pinned by assertion 32; deleting it turns a 404 into an applied update.
966
+ if (isDenied(filter, found)) return 404;
343
967
  const record = found;
344
968
  const { attributes, relationships: rels } = (body?.data || {}) as {
345
969
  attributes?: { [key: string]: unknown };
@@ -362,6 +986,19 @@ export default class OrmRequest extends Request {
362
986
  if (rels) {
363
987
  const relUpdates: { [key: string]: unknown } = {};
364
988
  for (const [key, value] of Object.entries(rels)) {
989
+ // The same missing key filter as createHandler's, and as the
990
+ // attribute loop directly above -- which already had it, while this
991
+ // loop did not. A PATCH carrying
992
+ // `relationships:{"id":{"data":{"id":9101}}}` reached `updateRecord`
993
+ // and RE-KEYED the record: the object held under store key 9102 then
994
+ // reported id 9101, so a visible record claimed a hidden record's
995
+ // identity on every surface that reads `record.id` rather than the map
996
+ // key. Gated by GATE 1 on the addressed record, so it is store
997
+ // corruption rather than a filter bypass -- but it is the same one-line
998
+ // omission two handlers apart. Pinned by assertion 40; INHERITED from
999
+ // `dev`; abofs/stonyx-orm#204.
1000
+ if (key === 'id') continue;
1001
+
365
1002
  const relData = value?.data;
366
1003
  if (relData && relData.id !== undefined) {
367
1004
  relUpdates[key] = relData.id;
@@ -375,8 +1012,31 @@ export default class OrmRequest extends Request {
375
1012
  return { data: record.toJSON?.() };
376
1013
  };
377
1014
 
378
- const deleteHandler: HandlerFn = ({ params }) => {
379
- store.remove(model, getId(params));
1015
+ const deleteHandler: HandlerFn = async ({ params }, { filter }) => {
1016
+ // Coerced ONCE. `getId(params)` was evaluated twice here -- once to find
1017
+ // the record and once to remove it -- and a coercion evaluated repeatedly
1018
+ // is a coercion that can be edited in one place and not the other, which
1019
+ // is the defect `coerceId` exists to prevent.
1020
+ const recordId = getId(params);
1021
+ const record = await store.find(model, recordId) as OrmRecord | undefined;
1022
+
1023
+ // BEHAVIOUR CHANGE (#190): a DELETE of a record that never existed
1024
+ // returned 204 before this change. It now returns 404, matching the
1025
+ // denied case below. This is deliberate and load-bearing -- if a denied
1026
+ // delete returned 404 while a missing one returned 204, the pair would be
1027
+ // a perfect existence oracle and the whole fix would be worthless.
1028
+ // Returning 204 for a denied delete was rejected instead: it falsely
1029
+ // reports success for a request that changed nothing.
1030
+ if (!record) return 404;
1031
+ // Re-evaluated after the before-hook loop, exactly as in updateHandler --
1032
+ // GATE 1 decided before the hooks ran. Pinned by assertion 33; deleting it
1033
+ // turns a 404 into a destroyed record.
1034
+ if (isDenied(filter, record)) return 404;
1035
+
1036
+ // Removed by the id of the record actually fetched, not by re-deriving it
1037
+ // from the params a second time: the record the filter tested and the
1038
+ // record removed are then provably the same one.
1039
+ store.remove(model, record.id as string | number, { _skipAutoPersist: true });
380
1040
  return 204;
381
1041
  };
382
1042
 
@@ -405,9 +1065,65 @@ export default class OrmRequest extends Request {
405
1065
  }
406
1066
  }
407
1067
 
408
- // Wraps a handler with before/after hook execution
1068
+ // Wraps a handler with before/after hook execution.
1069
+ //
1070
+ // ===========================================================================
1071
+ // TWO AUTHORIZATION GATES, AND EVERY EXECUTOR SITS BEHIND ONE OF THEM (#190)
1072
+ //
1073
+ // The defect this function was fixed for is NOT "a delete persists past a
1074
+ // 404". It is that _withHooks has SEVERAL executors downstream of the
1075
+ // handler, and originally the handler's response gated none of them. Three
1076
+ // exist today:
1077
+ //
1078
+ // 1. sqlDb.persist -- issues real SQL against the backing store
1079
+ // 2. the after-hook pipeline -- the PUBLISHED consumer extension point;
1080
+ // a cascade delete, a webhook, a search-index
1081
+ // purge. `context.recordId` and
1082
+ // `context.oldState` are populated for it.
1083
+ // 3. Orm.db.save() -- a full serialize-and-write of the store
1084
+ //
1085
+ // Gating them one at a time is how this keeps regressing, so the rule is:
1086
+ // compute denial ONCE at each point where it becomes knowable, and keep every
1087
+ // executor downstream of a gate. If you add a fourth executor to this
1088
+ // function, it goes below GATE 2 or it is a security bug.
1089
+ //
1090
+ // GATE 1 (pre-handler) is required because before-hooks and `context.oldState`
1091
+ // run/are built BEFORE the handler can consult the filter. Without it a denied
1092
+ // DELETE still handed the hidden record's full contents to consumer code.
1093
+ // GATE 2 (post-handler) covers everything the handler's status can reach.
1094
+ // ===========================================================================
409
1095
  private _withHooks(operation: string, handler: HandlerFn): HandlerFn {
410
1096
  return async (request: OrmRequest$, state: { [key: string]: unknown }) => {
1097
+ // `|| {}` so this function behaves like the relationship routes below,
1098
+ // which declare `state` with a `= {}` default. It is unkillable through
1099
+ // the rest-server dispatcher, which always passes `getState(req)`; it is
1100
+ // listed as such in the guards-redundant-by-construction table rather
1101
+ // than left silently unkillable, and it defends the WHOLE function (the
1102
+ // context, the snapshot and the handler call all read `callState`) rather
1103
+ // than one destructure that the next line would throw past anyway.
1104
+ const callState = (state || {}) as { [key: string]: unknown };
1105
+
1106
+ // ---------------------------------------------------------------------
1107
+ // THE AUTHORIZATION SNAPSHOT. Read ONCE, here, before any consumer code
1108
+ // can run.
1109
+ //
1110
+ // `callState` is the object `auth()` planted the filter in, and it is
1111
+ // also handed to every before-hook as `context.state` -- a published,
1112
+ // WRITABLE extension point. So `state.filter` is an INPUT to the
1113
+ // authorization decision, not only an output channel, and re-reading it
1114
+ // after the hook loop lets a consumer hook disarm the filter:
1115
+ //
1116
+ // beforeHook('get', 'animal', ctx => { delete ctx.state.filter })
1117
+ // -> GET /animals/21 turned 404 into 200
1118
+ // -> GET /animals turned 20 records into 22
1119
+ //
1120
+ // GATE 1 already used this snapshot, so writes held; the READ handlers
1121
+ // re-destructured `filter` from the live bag and did not. Everything
1122
+ // downstream now reads `filter` from here, and the handler is handed
1123
+ // `handlerState` below -- never `callState`.
1124
+ // ---------------------------------------------------------------------
1125
+ const { filter } = callState as { filter?: unknown };
1126
+
411
1127
  // Build context object for hooks
412
1128
  const context: HookContext = {
413
1129
  model: this.model,
@@ -416,12 +1132,37 @@ export default class OrmRequest extends Request {
416
1132
  params: request.params,
417
1133
  body: request.body,
418
1134
  query: request.query,
419
- state,
1135
+ // Deliberately the LIVE object: `redirect` and `pipe` are read back off
1136
+ // it by @stonyx/rest-server after the handler returns, so hooks must be
1137
+ // able to write to it. What must not happen is the authorization
1138
+ // decision reading it back, which is what the snapshot above prevents.
1139
+ state: callState,
420
1140
  };
421
1141
 
422
1142
  // Capture old state for operations that modify data
423
1143
  if (operation === 'update' || operation === 'delete') {
424
1144
  const existingRecord = await store.find(this.model, getId(request.params)) as OrmRecord | undefined;
1145
+
1146
+ // GATE 1 -- pre-handler. This record fetch already happened for
1147
+ // oldState, so the check is free.
1148
+ //
1149
+ // Returning here rather than letting updateHandler/deleteHandler
1150
+ // produce the same 404 is the point: everything between here and there
1151
+ // is an executor the caller is not authorized to reach.
1152
+ // - context.oldState is a deep copy of the HIDDEN RECORD'S CONTENTS.
1153
+ // Building it and handing it to a before-hook discloses exactly what
1154
+ // the filter exists to hide.
1155
+ // - context.recordId is populated for delete BEFORE the handler runs,
1156
+ // which is the same shape as the sqlDb landmine one layer up:
1157
+ // `afterHook('delete', ctx => cascadeDelete(ctx.recordId))` destroys
1158
+ // children behind a correct 404.
1159
+ // - a before-hook may return a value and short-circuit, which would
1160
+ // otherwise return a response without the filter ever executing.
1161
+ //
1162
+ // 404, not 403, for the same reason as getSingleHandler: the status for
1163
+ // "exists but filtered out" must equal "does not exist".
1164
+ if (existingRecord && isDenied(filter, existingRecord)) return 404;
1165
+
425
1166
  if (existingRecord) {
426
1167
  // Deep copy the record's data to preserve old state
427
1168
  context.oldState = JSON.parse(JSON.stringify(existingRecord.__data || existingRecord));
@@ -441,11 +1182,52 @@ export default class OrmRequest extends Request {
441
1182
  }
442
1183
 
443
1184
  // Execute main handler
444
- const response = await handler(request, state);
1185
+ // The handler receives the SNAPSHOT, never the live bag. `filter` is
1186
+ // assigned LAST so it wins over anything a before-hook wrote to
1187
+ // `callState.filter` -- including a `delete`, which the spread would
1188
+ // otherwise carry through as an absent key. Every other key a hook adds
1189
+ // is still visible to the handler; only the authorization input is
1190
+ // pinned.
1191
+ const handlerState = { ...callState, filter };
1192
+ const response = await handler(request, handlerState);
1193
+
1194
+ // Set context.record for update BEFORE persist so SQL drivers can read it
1195
+ if (operation === 'update' && (response as JsonApiResponse)?.data) {
1196
+ context.record = store.get(this.model, getId(request.params));
1197
+ }
445
1198
 
446
- // Persist to SQL database for create/update (delete is handled by store.remove auto-persist)
1199
+ // GATE 2 -- post-handler. A denied or failed handler returns a bare status
1200
+ // integer, and no executor below may run for one.
1201
+ //
1202
+ // `>= 400` deliberately covers every failure status, not just the
1203
+ // authorization ones: a 400 (POST with no `type`) and a 409 (duplicate id)
1204
+ // are equally requests in which nothing happened, and a persist or a
1205
+ // cascade hook for one of them is just as wrong.
1206
+ // `Number.isInteger` is a TYPE guard, not a behaviour guard, and it is
1207
+ // unkillable TODAY: the only non-integer a handler in this file can
1208
+ // return is a `{ data, links }` object, and `{} >= 400` is `false` by JS
1209
+ // coercion, so dropping it changes no reachable outcome. It is kept
1210
+ // because `>=` coerces rather than rejects, and the shapes it coerces
1211
+ // are not obvious -- `[500] >= 400` is TRUE, so a handler that one day
1212
+ // returned an array would have every response read as a denial. Listed
1213
+ // as an equivalent mutant rather than left to read as coverage; it
1214
+ // becomes killable the moment a handler returns anything array-like or
1215
+ // numeric-string-like.
1216
+ const denied = Number.isInteger(response) && (response as number) >= 400;
1217
+
1218
+ // EXECUTOR 1 -- SQL persistence, for all write operations.
1219
+ //
1220
+ // `response` is passed to sqlDb.persist below, but it is dropped at the
1221
+ // driver boundary: _persistDelete(modelName, context) never receives it
1222
+ // and guards only on context.recordId -- which _withHooks set above,
1223
+ // BEFORE the handler ran. Without this gate a correct 404 still issues
1224
+ // DELETE FROM ... WHERE id = ? on every SQL backend.
1225
+ //
1226
+ // No file-backed test can observe that, because Orm.instance.sqlDb is
1227
+ // null in file/directory mode. See the stubbed-sqlDb assertions in
1228
+ // test/unit/access-filter-enforcement-test.ts.
447
1229
  const sqlDb = Orm.instance.sqlDb;
448
- if (sqlDb && (operation === 'create' || operation === 'update')) {
1230
+ if (sqlDb && WRITE_OPERATIONS.has(operation) && !denied) {
449
1231
  await sqlDb.persist(operation, this.model, context, response);
450
1232
  }
451
1233
 
@@ -459,22 +1241,45 @@ export default class OrmRequest extends Request {
459
1241
  } else if (operation === 'create' && (response as JsonApiResponse)?.data && ((response as { data: { id?: unknown } }).data.id)) {
460
1242
  // For create, get the record from store using the ID from the response
461
1243
  const responseData = (response as { data: { id: string | number } }).data;
462
- const recordId = isNaN(responseData.id as unknown as number) ? responseData.id : parseInt(responseData.id as string);
463
- context.record = store.get(this.model, recordId);
464
- } else if (operation === 'update' && (response as JsonApiResponse)?.data) {
465
- context.record = store.get(this.model, getId(request.params));
1244
+ // `normalizeBodyId`, not a copy of its body. This line WAS
1245
+ // `isNaN(id) ? id : parseInt(id)` -- `coerceId` inlined verbatim, a
1246
+ // third coercion feeding a store lookup, sitting under a docblock that
1247
+ // said neither surface had a copy. Equivalent on every input that can
1248
+ // reach this truthy-guarded branch (`21`->`21`, `'21'`->`21`,
1249
+ // `'angela'`->`'angela'`; `''` and `0` cannot reach it), so this is a
1250
+ // de-duplication rather than a behaviour change -- and that is the
1251
+ // point: the two that disagreed were equivalent on every input anyone
1252
+ // checked, too.
1253
+ context.record = store.get(this.model, normalizeBodyId(responseData.id) as string | number);
466
1254
  } else if (operation === 'delete') {
467
1255
  // For delete, the record may no longer exist, but we have oldState
468
1256
  context.recordId = getId(request.params);
469
1257
  }
470
1258
 
471
- // Run after hooks sequentially
472
- for (const hook of getAfterHooks(operation, this.model)) {
473
- await hook(context);
1259
+ // EXECUTOR 2 -- the after-hook pipeline. This is the published consumer
1260
+ // extension point (`afterHook` is exported from @stonyx/orm and from
1261
+ // ./hooks), so it is the executor with the widest possible blast radius:
1262
+ // a cascade delete, a webhook, a token revocation, a search-index purge.
1263
+ //
1264
+ // BEHAVIOUR CHANGE (#190): after-hooks no longer fire for a request that
1265
+ // failed. Previously `afterHook('delete', ...)` ran with a populated
1266
+ // context.recordId on a 404, so a consumer cascade destroyed children for
1267
+ // a request that deleted nothing. Firing a hook named "after<operation>"
1268
+ // for an operation that did not occur is a booby trap, and the denied case
1269
+ // is unreachable-before-#190 while the missing case is inherited debt --
1270
+ // both are closed by the same gate. `context.response` therefore only ever
1271
+ // carries a success status into a hook.
1272
+ if (!denied) {
1273
+ for (const hook of getAfterHooks(operation, this.model)) {
1274
+ await hook(context);
1275
+ }
474
1276
  }
475
1277
 
476
- // Auto-save DB after write operations when configured
477
- if (config.orm.db.autosave === 'onUpdate' && WRITE_OPERATIONS.has(operation)) {
1278
+ // EXECUTOR 3 -- file/directory autosave. Ungated this let an
1279
+ // unauthenticated caller force a full serialize-and-write of the entire
1280
+ // store on every DELETE of any id, with no record touched: amplification
1281
+ // rather than corruption, but the same root cause and the same fix.
1282
+ if (config.orm.db.autosave === 'onUpdate' && WRITE_OPERATIONS.has(operation) && !denied) {
478
1283
  await (Orm.db as { save(): Promise<void> }).save();
479
1284
  }
480
1285
 
@@ -494,21 +1299,38 @@ export default class OrmRequest extends Request {
494
1299
  const dasherizedName = camelCaseToKebabCase(relationshipName);
495
1300
 
496
1301
  // Related resource route: GET /:id/{relationship}
497
- routes[`/:id/${dasherizedName}`] = async (request: OrmRequest$) => {
1302
+ //
1303
+ // These generated routes are not wrapped by _withHooks, which is why they
1304
+ // were the least obvious two of the seven unguarded surfaces in #190.
1305
+ // They are still dispatched by @stonyx/rest-server as
1306
+ // `handler(req, getState(req))`, so `state` -- and therefore the filter
1307
+ // planted by auth() -- has always been available here; it was simply
1308
+ // never declared or read.
1309
+ routes[`/:id/${dasherizedName}`] = async (request: OrmRequest$, { filter }: { [key: string]: unknown } = {}) => {
498
1310
  const record = await store.find(model, getId(request.params)) as OrmRecord | undefined;
499
1311
  if (!record) return 404;
1312
+ // Filtering the PARENT: a caller who may not see the record may not see
1313
+ // what it is related to either.
1314
+ if (isDenied(filter, record)) return 404;
500
1315
 
501
1316
  const relatedData = record.__relationships[relationshipName];
502
1317
  const baseUrl = getBaseUrl(request);
503
1318
 
1319
+ // LINKAGE ONLY. This filter decides which ids the emitted documents may
1320
+ // NAME in their own `relationships.*.data`; it does NOT decide whether
1321
+ // the related records themselves are served -- that is the parent-only
1322
+ // filtering this route has done since #190, and widening it to the
1323
+ // related record is abofs/stonyx-orm#196.
1324
+ const linkage = createLinkageFilter(request);
1325
+
504
1326
  let data: unknown;
505
1327
  if (info.isArray) {
506
1328
  // hasMany - return array
507
1329
  const related = Array.isArray(relatedData) ? relatedData.filter(isOrmRecord) : [];
508
- data = related.map(r => r.toJSON?.({ baseUrl }));
1330
+ data = related.map(r => r.toJSON?.({ baseUrl, linkage }));
509
1331
  } else {
510
1332
  // belongsTo - return single or null
511
- data = isOrmRecord(relatedData) ? relatedData.toJSON?.({ baseUrl }) : null;
1333
+ data = isOrmRecord(relatedData) ? relatedData.toJSON?.({ baseUrl, linkage }) : null;
512
1334
  }
513
1335
 
514
1336
  return {
@@ -518,9 +1340,10 @@ export default class OrmRequest extends Request {
518
1340
  };
519
1341
 
520
1342
  // Relationship linkage route: GET /:id/relationships/{relationship}
521
- routes[`/:id/relationships/${dasherizedName}`] = async (request: OrmRequest$) => {
1343
+ routes[`/:id/relationships/${dasherizedName}`] = async (request: OrmRequest$, { filter }: { [key: string]: unknown } = {}) => {
522
1344
  const record = await store.find(model, getId(request.params)) as OrmRecord | undefined;
523
1345
  if (!record) return 404;
1346
+ if (isDenied(filter, record)) return 404;
524
1347
 
525
1348
  const relatedData = record.__relationships[relationshipName];
526
1349
  const baseUrl = getBaseUrl(request);
@@ -551,32 +1374,97 @@ export default class OrmRequest extends Request {
551
1374
  };
552
1375
  }
553
1376
 
554
- // Catch-all for invalid relationship names on related resource route
555
- routes[`/:id/:relationship`] = async (request: OrmRequest$) => {
556
- const record = await store.find(model, getId(request.params));
557
- if (!record) return 404;
1377
+ // Catch-alls for invalid relationship names. Every valid relationship was
1378
+ // registered above, so reaching either of these means the relationship does
1379
+ // not exist and the answer is 404 regardless of the record.
1380
+ //
1381
+ // These deliberately carry NO access check and no store lookup. An earlier
1382
+ // revision of #190 added `if (isDenied(filter, record)) return 404` here for
1383
+ // symmetry with the seven real surfaces, but both branches returned 404, so
1384
+ // the guard was unobservable by construction -- a mutation deleting it
1385
+ // survived the entire suite because no test that could distinguish it can
1386
+ // exist. Unkillable code in an authorization diff reads as coverage and is
1387
+ // not, so it is gone; skipping the lookup also removes the timing difference
1388
+ // between an existing and a missing parent.
1389
+ //
1390
+ // IF THIS ROUTE EVER RETURNS ANYTHING OTHER THAN A CONSTANT 404, it becomes
1391
+ // the eighth surface and must filter the parent first, exactly like
1392
+ // `/:id/{relationship}` above.
1393
+ routes[`/:id/:relationship`] = async () => 404;
1394
+ routes[`/:id/relationships/:relationship`] = async () => 404;
558
1395
 
559
- // If we reach here, relationship doesn't exist (valid ones were registered above)
560
- return 404;
1396
+ return routes;
1397
+ }
1398
+
1399
+ auth(request: OrmRequest$, state: { [key: string]: unknown }): number | undefined {
1400
+ // A consumer `access()` that throws is a DENIAL, matching `isDenied` one
1401
+ // layer down. Unguarded it propagates to express's default handler, which
1402
+ // answers 500 -- and the documented sample itself can throw
1403
+ // (`request.originalUrl.split(...)` when originalUrl is absent), so the
1404
+ // failure mode is reachable by following the docs.
1405
+ // -------------------------------------------------------------------------
1406
+ // #202 -- hand the consumer the STRUCTURAL facts, not just the transport.
1407
+ //
1408
+ // Both members are already in hand here. `model` is `this.model`, the name
1409
+ // setup-rest-server mounted this route for; `operation` is the SAME
1410
+ // `methodAccessMap` lookup the permission-array branch at the bottom of
1411
+ // this method performs, so the predicate form and the array form cannot
1412
+ // answer differently about the same request.
1413
+ //
1414
+ // NEITHER IS DERIVED FROM THE REQUEST TARGET, and that is the whole point.
1415
+ // Deriving `model` here from `request.baseUrl` (or from the mounted route
1416
+ // name, or from `getPluralName(this.model)`) would move all five fail-open
1417
+ // variants listed in this file's header OUT of the consumer and INTO the
1418
+ // framework, where every consumer inherits them at once. `this.model` is
1419
+ // assigned once at mount time and no request can influence it.
1420
+ //
1421
+ // `operation` is left UNDEFINED for a method with no entry in
1422
+ // `methodAccessMap`, rather than defaulted. Express delivers HEAD to the
1423
+ // GET handler, so an unmapped method really does reach this line; a
1424
+ // `?? 'read'` here would hand the consumer a fabricated authorisation fact
1425
+ // and turn an unclassified request into an authorised one. Undefined is
1426
+ // the honest answer.
1427
+ //
1428
+ // `record` is deliberately absent -- see `AccessContext` in
1429
+ // src/types/orm-types.ts. Nothing is fetched at this point and adding a
1430
+ // lookup here would put a store read in the middle of an authorization
1431
+ // path. The function return shape below IS the per-record hook.
1432
+ // -------------------------------------------------------------------------
1433
+ const context: AccessContext = {
1434
+ model: this.model,
1435
+ operation: methodAccessMap[request.method],
561
1436
  };
562
1437
 
563
- // Catch-all for invalid relationship names on relationship linkage route
564
- routes[`/:id/relationships/:relationship`] = async (request: OrmRequest$) => {
565
- const record = await store.find(model, getId(request.params));
566
- if (!record) return 404;
1438
+ let access: AccessMethod;
1439
+ try {
1440
+ access = this.access(request, context);
1441
+ } catch (error) {
1442
+ // Same reasoning as `isDenied`: fail closed, but say so. An `access()`
1443
+ // that throws denies EVERY request to the collection, and a silent 403
1444
+ // wall is the hardest possible thing to diagnose from the outside.
1445
+ log.error?.(`[@stonyx/orm] access() threw for model "${this.model}" -- denying. ${error instanceof Error ? error.message : String(error)}`);
567
1446
 
568
- return 404;
569
- };
1447
+ return 403; // Forbidden
1448
+ }
570
1449
 
571
- return routes;
572
- }
1450
+ // THE READING OF THE RETURN SHAPE LIVES IN ONE PLACE (#234).
1451
+ //
1452
+ // It used to be inline here, and it was the only copy, which was fine while
1453
+ // `auth()` was the only thing that had to ask. It is not any more: the
1454
+ // linkage path has to ask model X's predicate about model X's records while
1455
+ // servicing a request routed to model Y, and a second inline copy of these
1456
+ // six branches would be a second authorization vocabulary -- one that can
1457
+ // drift, and that reviewers would have to notice had drifted. The branch
1458
+ // order in `interpretAccess` is this block, moved, not rewritten.
1459
+ const verdict = interpretAccess(access, methodAccessMap[request.method]);
573
1460
 
574
- auth(request: OrmRequest$, state: { [key: string]: unknown }): number | undefined {
575
- const access = this.access(request);
1461
+ if (!verdict.granted) return 403;
1462
+
1463
+ // The function return shape is the per-record hook, and `state` is the
1464
+ // whole transport for it: @stonyx/rest-server memoises one state object per
1465
+ // request and hands the same one to `auth()` and to the handler.
1466
+ if (verdict.filter) state.filter = verdict.filter;
576
1467
 
577
- if (!access) return 403;
578
- if (Array.isArray(access) && !access.includes(methodAccessMap[request.method])) return 403;
579
- if (typeof access === 'function') state.filter = access;
580
1468
  return undefined;
581
1469
  }
582
1470
  }