@stonyx/orm 0.3.2-alpha.6 → 0.3.2-alpha.60

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 (53) hide show
  1. package/README.md +580 -10
  2. package/config/{environment.ts → environment.js} +8 -0
  3. package/dist/commands.js +34 -0
  4. package/dist/dynamodb/connection.d.ts +31 -0
  5. package/dist/dynamodb/connection.js +28 -0
  6. package/dist/dynamodb/dynamodb-db.d.ts +142 -0
  7. package/dist/dynamodb/dynamodb-db.js +596 -0
  8. package/dist/dynamodb/operation-builder.d.ts +76 -0
  9. package/dist/dynamodb/operation-builder.js +116 -0
  10. package/dist/dynamodb/type-map.d.ts +31 -0
  11. package/dist/dynamodb/type-map.js +48 -0
  12. package/dist/index.d.ts +1 -0
  13. package/dist/main.d.ts +116 -0
  14. package/dist/main.js +129 -0
  15. package/dist/manage-record.js +34 -3
  16. package/dist/mysql/connection.d.ts +1 -0
  17. package/dist/mysql/mysql-db.d.ts +8 -0
  18. package/dist/mysql/mysql-db.js +44 -10
  19. package/dist/orm-request.d.ts +181 -3
  20. package/dist/orm-request.js +794 -47
  21. package/dist/postgres/connection.d.ts +1 -0
  22. package/dist/postgres/connection.js +8 -6
  23. package/dist/postgres/postgres-db.d.ts +8 -0
  24. package/dist/postgres/postgres-db.js +44 -10
  25. package/dist/record.js +7 -5
  26. package/dist/relationships.js +1 -1
  27. package/dist/serializer.js +38 -2
  28. package/dist/setup-rest-server.js +51 -5
  29. package/dist/store.d.ts +13 -1
  30. package/dist/store.js +65 -6
  31. package/dist/types/orm-types.d.ts +112 -0
  32. package/package.json +16 -7
  33. package/src/commands.ts +43 -0
  34. package/src/dynamodb/connection.ts +50 -0
  35. package/src/dynamodb/dynamodb-db.ts +811 -0
  36. package/src/dynamodb/operation-builder.ts +202 -0
  37. package/src/dynamodb/type-map.ts +54 -0
  38. package/src/index.ts +1 -0
  39. package/src/main.ts +133 -0
  40. package/src/manage-record.ts +41 -9
  41. package/src/mysql/connection.ts +1 -0
  42. package/src/mysql/mysql-db.ts +44 -12
  43. package/src/orm-request.ts +809 -50
  44. package/src/postgres/connection.ts +10 -6
  45. package/src/postgres/postgres-db.ts +44 -12
  46. package/src/record.ts +8 -5
  47. package/src/relationships.ts +1 -1
  48. package/src/serializer.ts +39 -2
  49. package/src/setup-rest-server.ts +59 -6
  50. package/src/store.ts +68 -6
  51. package/src/types/orm-types.ts +118 -0
  52. package/src/types/stonyx-rest-server.d.ts +14 -1
  53. package/src/types/stonyx.d.ts +7 -1
@@ -1,9 +1,188 @@
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 this repo's own shipped access class, on a request express
102
+ * dispatched to `GET /owners/angela`, asked about ANIMALS:
103
+ *
104
+ * getAccess('animal')(ownersRequest, { model: 'animal', operation: 'read' })
105
+ * -> record => record.id !== 'angela' && record.id !== 'restricted'
106
+ *
107
+ * That is the OWNERS filter, and it returns `true` for animal 21 -- the record
108
+ * hidden on every animal surface. Under a mount that predicate recognises
109
+ * neither way it is worse: it falls through to
110
+ * `['read', 'create', 'update', 'delete']`, a full CRUD grant. Either way the
111
+ * context was supplied and the answer is not the animal answer, and it is wrong
112
+ * in the GRANTING direction, because that predicate is arity-1 and identifies
113
+ * its collection from the request. (The first of these is asserted on a live
114
+ * dispatch by AC9 in test/integration/orm-test.ts.)
115
+ *
116
+ * Every predicate in this repo and in every consumer tree is arity-1 on the day
117
+ * this ships, and the caller has no supported way to tell which kind it got --
118
+ * the boot-time arity warning that would surface it is abofs/stonyx-orm#213.
119
+ * So: pass the context, and do not treat a resolved predicate's answer as
120
+ * model-specific until that predicate has been migrated to read the context.
121
+ *
122
+ * ---------------------------------------------------------------------------
123
+ * DO NOT RECONSTRUCT THE REQUEST PATH INSIDE `access()`.
124
+ * ---------------------------------------------------------------------------
125
+ * `auth()` below hands your `access(request)` a raw transport artifact and asks
126
+ * you to work out which collection it addresses. Every attempt to do that by
127
+ * parsing the request target has failed OPEN. Five distinct variants of the
128
+ * same three-line example have now been found, each after the previous was
129
+ * fixed, by five different people:
130
+ *
131
+ * 1. `request.url` is mount-relative under `RestServer.mountRoute`, so a
132
+ * prefix match against it is ALWAYS false.
133
+ * 2. `request.originalUrl` carries the query string, so an anchored equality
134
+ * check misses `/owners?filter[age]=30`.
135
+ * 3. The router is a bare `express()` (`caseSensitive: false`) while a
136
+ * hand-written matcher is case-SENSITIVE, so `GET /OwNeRs/angela` walks
137
+ * past it. Router-side: abofs/stonyx-rest-server#47.
138
+ * 4. Under a configured `ORM_REST_ROUTE` a hard-coded `/owners` matches
139
+ * nothing -- environment-specifically, which is worse.
140
+ * 5. HTTP/1.1 permits an ABSOLUTE-FORM request-target. Express routes on
141
+ * `parseurl(req).pathname`, but `originalUrl` is the raw target, so
142
+ * `GET http://anything.example/owners/angela` reaches the handler with
143
+ * `originalUrl === 'http://anything.example/owners/angela'`. A `/owners`
144
+ * prefix match is false, `access()` falls through to whatever it returns
145
+ * last, and the record comes back in full. It walks past a hard
146
+ * `return false` deny the same way.
147
+ *
148
+ * The fix is not a sixth rule. It is to stop parsing:
149
+ *
150
+ * `request.baseUrl` is the mount Express ACTUALLY MATCHED when it dispatched
151
+ * the request. It carries no query string, it is not mount-relative, it is
152
+ * unaffected by absolute-form, and it already includes the configured
153
+ * `ORM_REST_ROUTE` prefix -- so there is nothing to derive and nothing to
154
+ * join. Compare it lower-cased (the router matched case-insensitively) and
155
+ * fail CLOSED when it is absent. Use `request.path` -- mount-relative and
156
+ * query-free -- if you need to distinguish sub-paths.
157
+ *
158
+ * `?? ''` is not a defence. It converts an absent request target into an empty
159
+ * string, which matches no collection, which falls through to the permission
160
+ * array -- a total grant. An input you cannot identify must DENY.
161
+ *
162
+ * THAT IS STILL A STOPGAP. `baseUrl` closes all five variants, but it is a
163
+ * transport artifact being asked to stand in for a structural fact.
164
+ * THE REAL FIX IS abofs/stonyx-orm#202: `access()` should receive the model,
165
+ * the operation and the record. Prefer the array shape (`['read']`) or `false`
166
+ * until #202 lands; the function shape is what requires any matching at all.
167
+ *
168
+ * The enforcement gates in this file (GATE 0/1/2, the create rollback, the
169
+ * per-handler `isDenied` re-checks) are correct independently of that -- they
170
+ * enforce whatever predicate you return. The stopgap is the part where YOU have
171
+ * to work out which predicate to return.
172
+ *
173
+ * AND A PREDICATE IS NOT A GUARANTEE THAT A HIDDEN RECORD CANNOT BE MODIFIED.
174
+ * It is evaluated against the record the route is ADDRESSED TO, on that model
175
+ * only. A write to a DIFFERENT collection can still re-parent a hidden record
176
+ * and de-hide it -- abofs/stonyx-orm#207, which is blocked on #202 and #196.
177
+ * See `### Known limitations` in README.
178
+ */
1
179
  import { Request } from '@stonyx/rest-server';
2
180
  import Orm, { store, createRecord, updateRecord } from '@stonyx/orm';
3
181
  import { camelCaseToKebabCase } from '@stonyx/utils/string';
4
182
  import { getPluralName } from './plural-registry.js';
5
183
  import { getBeforeHooks, getAfterHooks } from './hooks.js';
6
184
  import config from 'stonyx/config';
185
+ import log from 'stonyx/log';
7
186
  import { isOrmRecord } from './utils.js';
8
187
  const methodAccessMap = {
9
188
  GET: 'read',
@@ -48,13 +227,117 @@ function getBaseUrl(request) {
48
227
  const host = request.get('host');
49
228
  return `${protocol}://${host}`;
50
229
  }
230
+ /**
231
+ * The ONE coercion from a caller-supplied id to the key the store holds it
232
+ * under. Every id-bearing surface in this file goes through it, and none has a
233
+ * copy: `getId()` (URL params), `normalizeBodyId()` (JSON body), and the
234
+ * post-create `context.record` lookup in `_withHooks`.
235
+ *
236
+ * WHY IT IS SHARED RATHER THAN DUPLICATED. `getId()` and `normalizeBodyId()`
237
+ * each had their own arithmetic, and they disagreed: `parseInt(id)` versus
238
+ * `parseInt(id, 10)`. On a hex-shaped id that is a two-record difference --
239
+ *
240
+ * GET /animals/0x2391 -> record 9105 (getId -> parseInt('0x2391') = 9105)
241
+ * POST /animals {"id":"0x2391"} -> lookup under 0 (normalize -> parseInt('0x2391',10) = 0)
242
+ * -> a MISS, so the duplicate check was skipped and
243
+ * createRecord OVERWROTE 9105 in place, answering 200
244
+ *
245
+ * -- a narrower form of the raw-versus-normalised divergence that the body-id
246
+ * normalisation was added to close, reintroduced by the fix for it. Two
247
+ * coercions that must agree cannot be kept in agreement by review; they have to
248
+ * be one function. Pinned by assertion 43.
249
+ *
250
+ * The third copy was found later and in a quieter place: `_withHooks` populated
251
+ * `context.record` for `create` with `isNaN(id) ? id : parseInt(id)` -- this
252
+ * function's body, inlined verbatim, feeding `store.get`. It was equivalent on
253
+ * every input reachable there, which is exactly what the two that DID diverge
254
+ * looked like until someone tried a hex id.
255
+ *
256
+ * SHARING IT IS NOT THE SAME AS IT BEING RIGHT EVERYWHERE. On a model declaring
257
+ * `id = attr('string')` a numeric-looking id is filed under the STRING key, so
258
+ * this coercion resolves `'9107'` to `9107` and the post-create lookup misses:
259
+ * `context.record` is `undefined` for an after-`create` hook. Inherited -- the
260
+ * inlined copy computed the same thing -- and NOT fixed here, because picking
261
+ * the right coercion needs the model's declared id type, which is the same
262
+ * structural information abofs/stonyx-orm#202 is about. Filed as
263
+ * abofs/stonyx-orm#209 and pinned by assertion 50, so closing it turns a test
264
+ * red rather than passing silently.
265
+ *
266
+ * `parseInt` and not `Number`, deliberately, and the anchor is NOT `getId`.
267
+ * It is `src/transforms.ts:7` -- `number: (value) => parseInt(value as string)`,
268
+ * also radix-less -- because that transform is what actually produces the store
269
+ * KEY a record is filed under. `getId` merely agrees with it. They differ from
270
+ * `Number` on `'1e3'` (1 vs 1000) and `'9105.5'` (9105 vs 9105.5), so switching
271
+ * this function to `Number` would make the lookup key disagree with the landing
272
+ * key on those shapes.
273
+ *
274
+ * THE CHANGE THAT WOULD BREAK THIS: adding a radix to `transforms.number`
275
+ * (`parseInt(value, 10)`). That is a one-word edit in a file with no connection
276
+ * to authorization, it would silently reopen the hex divergence in the other
277
+ * direction, and this comment would still read as correct. Assertion 45 pins
278
+ * the transform's radix-less shape directly, so that edit turns a test red
279
+ * rather than shipping.
280
+ *
281
+ * The reason `parseInt` is safe here is the `isNaN` gate in front of it:
282
+ * `parseInt('9105h')` is `9105`, and truncating a partially-valid id into a
283
+ * DIFFERENT VALID key is exactly how a collision lookup gets skipped. The gate
284
+ * rejects it as a string instead, so nothing is ever truncated. That gate, not
285
+ * the parser, is the load-bearing half -- assertion 43 pins it.
286
+ */
287
+ function coerceId(id) {
288
+ if (isNaN(id))
289
+ return id;
290
+ return parseInt(id);
291
+ }
51
292
  function getId(params) {
52
293
  const id = params.id;
53
294
  if (!id)
54
295
  return '';
55
- if (isNaN(id))
296
+ return coerceId(id);
297
+ }
298
+ /**
299
+ * Normalise a caller-supplied BODY id to the key the store will hold it under.
300
+ *
301
+ * `getId()` above is params-shaped: it takes `{ id?: string }` off the URL,
302
+ * where the value is always a string and a falsy one means "no id". A JSON body
303
+ * id is neither -- it can arrive as a number, and `0` is a legitimate id that
304
+ * `getId()` would flatten to `''`.
305
+ *
306
+ * WHY THIS EXISTS AT ALL. createHandler used to look the collision up with the
307
+ * RAW body value while every other surface normalised through `getId()`. The
308
+ * store is a Map keyed by the coerced value, so `store.find(model, '21')` misses
309
+ * the entry held under `21` and the duplicate check is skipped by typing the id
310
+ * as a string. On `dev` that silently overwrote the colliding record and
311
+ * answered 200; combined with the denied-create rollback added for #190 it
312
+ * became an unauthenticated DELETE of any id. Normalising here is half of that
313
+ * fix -- see the rollback in createHandler for the other half.
314
+ *
315
+ * It shares `coerceId` with `getId` so the two surfaces cannot drift apart
316
+ * again, and differs from `getId` in exactly ONE place, below.
317
+ */
318
+ function normalizeBodyId(id) {
319
+ // Non-strings pass through untouched: a JSON body id can arrive as a number,
320
+ // and `getId`'s falsy-flatten must NOT apply to it -- `0` is a legitimate id
321
+ // and `getId` would turn it into `''`. (assertion 30 sweeps id `0`.)
322
+ if (typeof id !== 'string')
56
323
  return id;
57
- return parseInt(id);
324
+ // THE ONE DIVERGENCE FROM `getId`, and it mirrors rather than contradicts it:
325
+ // `getId` maps a falsy param to `''`, and `''` is the only string a body can
326
+ // carry that means "no id" -- `createRecord` treats it as absent and assigns a
327
+ // server id. Coercing it instead would make it address a real slot, because
328
+ // `parseInt('')` is `NaN` and a record CAN be held under `NaN` (a truthy but
329
+ // non-numeric id such as `' '` survives `assignRecordId`'s falsy guard and
330
+ // then NaNs in the id transform). So `POST {"id":""}` would answer 409 against
331
+ // an unrelated record it never named. Pinned by assertion 44.
332
+ //
333
+ // Note what is deliberately NOT special-cased here any more: whitespace.
334
+ // `id.trim() === ''` used to short-circuit `' '` as well, which made the
335
+ // body surface DISAGREE with the URL surface -- `getId({id:' '})` is `NaN`,
336
+ // so `' '` addresses the NaN slot on every other route while the collision
337
+ // lookup missed it. Same class of bug as the hex divergence above.
338
+ if (id === '')
339
+ return id;
340
+ return coerceId(id);
58
341
  }
59
342
  function buildResponse(data, includeParam, recordOrRecords, options = {}) {
60
343
  const { links, baseUrl } = options;
@@ -187,6 +470,39 @@ function createFilterPredicate(filters) {
187
470
  return String(current) === value;
188
471
  });
189
472
  }
473
+ /**
474
+ * A function-style `access` return is a per-record predicate, and it is only
475
+ * meaningful if every surface that can hand a record to a caller consults it.
476
+ * Before #190 exactly one of seven did.
477
+ *
478
+ * Enforcement is deliberately post-fetch. `access` returns an opaque JS
479
+ * predicate and `store.findAll(model, conditions)` accepts only an equality
480
+ * conditions object that the SQL drivers translate to a WHERE clause, so
481
+ * query-layer enforcement would require a breaking change to the published
482
+ * `access` contract. That belongs in #197, not in a security patch. Six of the
483
+ * seven surfaces fetch by primary key anyway, so this costs exactly one row.
484
+ */
485
+ function isDenied(filter, record) {
486
+ if (typeof filter !== 'function')
487
+ return false;
488
+ // A predicate that throws is treated as a denial. Unguarded, a throw escapes
489
+ // to express's default handler, which answers 500 (with a stack trace outside
490
+ // NODE_ENV=production) while a missing id still answers 404 -- so a
491
+ // record-dependent throw re-separates "hidden" from "does not exist" and
492
+ // hands back the oracle this whole change exists to close.
493
+ try {
494
+ return !filter(record);
495
+ }
496
+ catch (error) {
497
+ // Denied, but not silently. A consumer predicate that throws on every
498
+ // record turns the whole collection into a 404 wall, and with no
499
+ // diagnostic that is indistinguishable from an empty database. `stonyx/log`
500
+ // is the module convention (see setup-rest-server.ts); optional-call
501
+ // because a consumer may not have configured the log types.
502
+ log.error?.(`[@stonyx/orm] access filter threw for model -- denying. ${error instanceof Error ? error.message : String(error)}`);
503
+ return true;
504
+ }
505
+ }
190
506
  export default class OrmRequest extends Request {
191
507
  model;
192
508
  access;
@@ -216,10 +532,15 @@ export default class OrmRequest extends Request {
216
532
  baseUrl
217
533
  });
218
534
  };
219
- const getSingleHandler = async (request) => {
535
+ const getSingleHandler = async (request, { filter }) => {
220
536
  const record = await store.find(model, getId(request.params));
221
537
  if (!record)
222
538
  return 404;
539
+ // 404, never 403: the status for "exists but filtered out" must be
540
+ // identical to "does not exist", or the fix trades an authorization
541
+ // bypass for a narrower existence oracle.
542
+ if (isDenied(filter, record))
543
+ return 404;
223
544
  const fieldsMap = parseFields(request.query);
224
545
  const modelFields = fieldsMap.get(pluralizedModel) || fieldsMap.get(model);
225
546
  const baseUrl = getBaseUrl(request);
@@ -228,19 +549,118 @@ export default class OrmRequest extends Request {
228
549
  baseUrl
229
550
  });
230
551
  };
231
- const createHandler = async ({ body, query }) => {
552
+ const createHandler = async ({ body, query }, { filter }) => {
232
553
  const { type, id, attributes, relationships: rels } = (body?.data || {});
233
554
  if (!type)
234
555
  return 400; // Bad request
235
556
  const fieldsMap = parseFields(query);
236
557
  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
558
+ // GATE 0 -- the POST existence oracle.
559
+ //
560
+ // The duplicate check runs before the filter and `store.find` sees hidden
561
+ // records, so POST leaks existence through its STATUS. A previous revision
562
+ // filtered the collision status (403 when the colliding record is denied,
563
+ // 409 when it is visible) and that is NOT sufficient, because the status
564
+ // of a create is a third outcome. With a payload the caller is permitted
565
+ // to create -- the normative case for a per-tenant filter, and the case an
566
+ // attacker picks -- all three are distinguishable in ONE request per id:
567
+ //
568
+ // POST /animals {id:22, owner:'gina'} -> 403 a HIDDEN record has this id
569
+ // POST /animals {id:9500, owner:'gina'} -> 200 this id is FREE
570
+ // POST /animals {id:8, owner:'gina'} -> 409 a VISIBLE record has this id
571
+ //
572
+ // Filtering only the collision status narrows that to callers who cannot
573
+ // create a record they are allowed to see. It does not close it.
574
+ //
575
+ // It cannot be closed while a caller both chooses the id and learns
576
+ // whether the create succeeded: a successful create must answer
577
+ // differently from a refused one. So when a per-record filter is in force
578
+ // the caller does not get to choose the id at all. The refusal is
579
+ // UNCONDITIONAL and happens BEFORE any store lookup, so no status, and no
580
+ // lookup cost, can depend on whether that id exists. 403 -- the same
581
+ // status as a denied create -- so the two cannot be separated either.
582
+ //
583
+ // BOTH HALVES OF THAT ARE PINNED, because both were once asserted here and
584
+ // pinned by nothing:
585
+ //
586
+ // status -- assertion 22 sweeps payload x id x id-type, plus `null`.
587
+ // latency -- assertion 41 asserts NO `store.find` is issued on this
588
+ // path. Moving the refusal to after a lookup and returning
589
+ // the same 403 left the suite green while re-opening a
590
+ // hit-versus-miss timing difference on every id-bearing POST,
591
+ // which is what would turn #197 from a ~0.06ms post-fetch
592
+ // residual into a live timing oracle on create.
593
+ //
594
+ // AND THE GUARANTEE IS ONLY AS WIDE AS THE CHANNELS IT COVERS. It reads on
595
+ // the `id` member of the resource object, so it holds only while that is
596
+ // the ONLY way a caller id can reach `createRecord`. It was not: the
597
+ // relationships loop below re-admitted one under `key === "id"` and the
598
+ // gate never fired. Both strips -- `attributes.id` and `relationships.id`
599
+ // -- are therefore part of THIS gate, not tidiness, and assertion 39 pins
600
+ // them. Adding a third channel without a strip re-opens the oracle.
601
+ //
602
+ // Scoped to function-style `access` because that is exactly the population
603
+ // the oracle exists for: with no per-record filter there are no hidden
604
+ // records, and 409 discloses nothing GET /:id does not already.
605
+ //
606
+ // RESIDUALS, stated rather than implied.
607
+ //
608
+ // - a caller can still learn that a collection HAS a per-record filter
609
+ // (403 rather than 409/200 for an id-bearing POST). That discloses a
610
+ // configuration fact, not a record.
611
+ // - this gate is about ids arriving on THIS model's create route. It
612
+ // says nothing about a write to ANOTHER collection: a `POST /owners`
613
+ // carrying `relationships: {pets: {data: {id: 21}}}` -- or
614
+ // `attributes: {pets: [21, 22]}`, which never enters the
615
+ // relationships loop at all -- re-parents hidden animal 21 onto an
616
+ // owner the caller may write, which changes the very field the
617
+ // animals predicate reads and DE-HIDES it. Blocking that needs animal
618
+ // 21 checked against the ANIMAL model's predicate while servicing an
619
+ // OWNERS route, i.e. cross-model access resolution: abofs/stonyx-orm
620
+ // #207, blocked on #202 (`access` receives the model structurally)
621
+ // and #196 (setup-rest-server discards the model->predicate map at
622
+ // boot). NOT closed here, and no comment in this file may say it is.
623
+ //
624
+ // See README `### Known limitations`.
625
+ if (id !== undefined) {
626
+ if (typeof filter === 'function')
627
+ return 403; // Forbidden
628
+ // `normalizeBodyId`, not the raw value: a string-typed id misses the
629
+ // store's numeric key, which skipped this check entirely.
630
+ const existing = await store.find(model, normalizeBodyId(id));
631
+ if (existing)
632
+ return 409; // Conflict
633
+ }
240
634
  const { id: _ignoredId, ...sanitizedAttributes } = attributes || {};
241
- // Extract relationship IDs from JSON:API relationships object
635
+ // Extract relationship IDs from JSON:API relationships object.
636
+ //
637
+ // `key` comes VERBATIM from the request body, so `id` is stripped here for
638
+ // exactly the same reason it is stripped from `attributes` on the line
639
+ // above -- and it must be, or GATE 0 is walked around by moving one field:
640
+ //
641
+ // POST /animals {"id":21, ...} -> 403 GATE 0 fires
642
+ // POST /animals {"relationships":{"id":{"data":{"id":21}}},
643
+ // "attributes":{"owner":"gina"}} -> 200 BYPASS
644
+ //
645
+ // Top-level `id` stayed `undefined`, so GATE 0 never fired and the
646
+ // collision lookup never ran; `createRecord` took its last-entry-wins
647
+ // branch, overwrote hidden record 21 in place and reset its `owner` to a
648
+ // value the caller chose -- de-hiding it permanently. That is #190 itself,
649
+ // on the create surface. Pinned by assertion 39.
650
+ //
651
+ // The `id` member of the resource object is now the ONLY channel a caller
652
+ // id can arrive on FOR THIS MODEL'S OWN CREATE ROUTE, which is what makes
653
+ // GATE 0's guarantee checkable rather than merely asserted. It is not a
654
+ // statement about the record's reachability in general -- a relationship
655
+ // write on another collection reaches it without ever touching this
656
+ // handler (abofs/stonyx-orm#207). INHERITED from `dev`, which carries this
657
+ // loop verbatim; the general form -- the loop accepts any key, not just
658
+ // `id`, so a body key that is not a declared relationship is still
659
+ // mass-assigned -- is abofs/stonyx-orm#204.
242
660
  if (rels) {
243
661
  for (const [key, value] of Object.entries(rels)) {
662
+ if (key === 'id')
663
+ continue;
244
664
  const relData = value?.data;
245
665
  if (relData && relData.id !== undefined) {
246
666
  sanitizedAttributes[key] = relData.id;
@@ -248,16 +668,91 @@ export default class OrmRequest extends Request {
248
668
  }
249
669
  }
250
670
  const recordAttributes = id !== undefined ? { id, ...sanitizedAttributes } : sanitizedAttributes;
671
+ // Slot count BEFORE the write. `createRecord` writes to the store before
672
+ // the predicate can run, and the rollback below must be able to prove the
673
+ // slot it removes is one THIS REQUEST created. Identity alone cannot
674
+ // prove it: when `assignRecordId` lands on an occupied id, `createRecord`
675
+ // mutates the existing OrmRecord IN PLACE, so `store.get(...) === record`
676
+ // is true for a record the request did not create. The map's size is the
677
+ // only O(1) signal that distinguishes an insert from an overwrite.
678
+ const slotsBefore = store.get(model)?.size ?? 0;
251
679
  const created = createRecord(model, recordAttributes, { serialize: false, _skipAutoPersist: true });
252
680
  const record = isOrmRecord(created) ? created : null;
253
681
  if (!record)
254
682
  return 500;
683
+ const createdNewSlot = (store.get(model)?.size ?? 0) > slotsBefore;
684
+ // 403 here, NOT 404. The oracle argument does not apply to create: there
685
+ // is no pre-existing record whose existence could leak, the caller
686
+ // supplied the attributes, and 404 on a mounted collection route is
687
+ // indistinguishable from "model not mounted" -- a genuinely different
688
+ // failure a developer needs to diagnose.
689
+ //
690
+ // The rollback is not optional. createRecord writes to the store BEFORE
691
+ // the predicate can run, so returning 403 alone would leave the record
692
+ // behind: a worse bug than the bypass being fixed.
693
+ if (isDenied(filter, record)) {
694
+ // ROLL BACK BY IDENTITY, NEVER BY ID. `store.remove(model, record.id)`
695
+ // on its own is a write primitive keyed by a value the caller may have
696
+ // supplied: with the raw-id collision bypass above, a denied
697
+ // `POST {"id":"21"}` answered 403 and DELETED hidden record 21 -- an
698
+ // unauthenticated deletion primitive across the whole id space, created
699
+ // by adding a rollback to a lookup that could be skipped.
700
+ //
701
+ // Both conditions are required and neither implies the other:
702
+ // createdNewSlot -- the store grew, so this request inserted rather
703
+ // than overwrote. Guards `assignRecordId` picking an
704
+ // id that is already taken (it returns
705
+ // last-INSERTED + 1, not max + 1, so a store whose
706
+ // insertion order is not ascending collides) -- see
707
+ // abofs/stonyx-orm#203.
708
+ // identity -- the slot still holds the object we just created,
709
+ // so nothing between createRecord and here replaced
710
+ // it. Deleting this half SURVIVES the suite, and it
711
+ // is kept anyway. WHY IT IS REDUNDANT: there is no
712
+ // `await` anywhere between `slotsBefore` and
713
+ // `store.remove` -- the whole window is synchronous,
714
+ // so it is atomic under Node's event loop; before-
715
+ // `create` hooks run BEFORE the handler
716
+ // (`_withHooks` runs its hook loop ahead of
717
+ // `await handler(...)`), and a consumer predicate
718
+ // inside `isDenied` runs AFTER `createdNewSlot` is
719
+ // computed and cannot flip it. That is a property of
720
+ // THIS function, not of GATE 0 -- an earlier note
721
+ // credited GATE 0, which was both wrong (a caller id
722
+ // reached createRecord through the relationships
723
+ // loop, #204) and the wrong kind of reason: a guard
724
+ // justified on code sixty lines upstream gets
725
+ // silently re-armed when that code moves.
726
+ // SO IT BECOMES REACHABLE IF AN `await` IS
727
+ // INTRODUCED HERE, which is the change a future
728
+ // editor would actually make. Stated here rather
729
+ // than by reference: `docs/` is not in `files`, so
730
+ // a pointer into it resolves to nothing for anyone
731
+ // who installed this package. README carries the
732
+ // consumer-facing half.
733
+ if (createdNewSlot && store.get(model, record.id) === record) {
734
+ store.remove(model, record.id, { _skipAutoPersist: true });
735
+ }
736
+ return 403;
737
+ }
255
738
  return { data: record.toJSON?.({ fields: modelFields }) };
256
739
  };
257
- const updateHandler = async ({ body, params }) => {
740
+ const updateHandler = async ({ body, params }, { filter }) => {
258
741
  const found = await store.find(model, getId(params));
259
742
  if (!found || !isOrmRecord(found))
260
743
  return 404;
744
+ // Checked BEFORE any attribute is applied. 404 rather than 403 for the
745
+ // same reason as GET /:id -- 403 would disclose both that the record
746
+ // exists and that this caller specifically is excluded.
747
+ //
748
+ // NOT redundant behind GATE 1, and not defence in depth either: GATE 1's
749
+ // verdict is computed BEFORE the before-hook loop runs, and a before-hook
750
+ // is a published extension point that can change the answer -- by
751
+ // mutating the record, or against a predicate that closes over
752
+ // per-request state. This is the only re-evaluation after that window.
753
+ // Pinned by assertion 32; deleting it turns a 404 into an applied update.
754
+ if (isDenied(filter, found))
755
+ return 404;
261
756
  const record = found;
262
757
  const { attributes, relationships: rels } = (body?.data || {});
263
758
  if (!attributes && !rels)
@@ -277,6 +772,19 @@ export default class OrmRequest extends Request {
277
772
  if (rels) {
278
773
  const relUpdates = {};
279
774
  for (const [key, value] of Object.entries(rels)) {
775
+ // The same missing key filter as createHandler's, and as the
776
+ // attribute loop directly above -- which already had it, while this
777
+ // loop did not. A PATCH carrying
778
+ // `relationships:{"id":{"data":{"id":9101}}}` reached `updateRecord`
779
+ // and RE-KEYED the record: the object held under store key 9102 then
780
+ // reported id 9101, so a visible record claimed a hidden record's
781
+ // identity on every surface that reads `record.id` rather than the map
782
+ // key. Gated by GATE 1 on the addressed record, so it is store
783
+ // corruption rather than a filter bypass -- but it is the same one-line
784
+ // omission two handlers apart. Pinned by assertion 40; INHERITED from
785
+ // `dev`; abofs/stonyx-orm#204.
786
+ if (key === 'id')
787
+ continue;
280
788
  const relData = value?.data;
281
789
  if (relData && relData.id !== undefined) {
282
790
  relUpdates[key] = relData.id;
@@ -288,8 +796,31 @@ export default class OrmRequest extends Request {
288
796
  }
289
797
  return { data: record.toJSON?.() };
290
798
  };
291
- const deleteHandler = ({ params }) => {
292
- store.remove(model, getId(params));
799
+ const deleteHandler = async ({ params }, { filter }) => {
800
+ // Coerced ONCE. `getId(params)` was evaluated twice here -- once to find
801
+ // the record and once to remove it -- and a coercion evaluated repeatedly
802
+ // is a coercion that can be edited in one place and not the other, which
803
+ // is the defect `coerceId` exists to prevent.
804
+ const recordId = getId(params);
805
+ const record = await store.find(model, recordId);
806
+ // BEHAVIOUR CHANGE (#190): a DELETE of a record that never existed
807
+ // returned 204 before this change. It now returns 404, matching the
808
+ // denied case below. This is deliberate and load-bearing -- if a denied
809
+ // delete returned 404 while a missing one returned 204, the pair would be
810
+ // a perfect existence oracle and the whole fix would be worthless.
811
+ // Returning 204 for a denied delete was rejected instead: it falsely
812
+ // reports success for a request that changed nothing.
813
+ if (!record)
814
+ return 404;
815
+ // Re-evaluated after the before-hook loop, exactly as in updateHandler --
816
+ // GATE 1 decided before the hooks ran. Pinned by assertion 33; deleting it
817
+ // turns a 404 into a destroyed record.
818
+ if (isDenied(filter, record))
819
+ return 404;
820
+ // Removed by the id of the record actually fetched, not by re-deriving it
821
+ // from the params a second time: the record the filter tested and the
822
+ // record removed are then provably the same one.
823
+ store.remove(model, record.id, { _skipAutoPersist: true });
293
824
  return 204;
294
825
  };
295
826
  // Wrap handlers with hooks
@@ -314,9 +845,63 @@ export default class OrmRequest extends Request {
314
845
  };
315
846
  }
316
847
  }
317
- // Wraps a handler with before/after hook execution
848
+ // Wraps a handler with before/after hook execution.
849
+ //
850
+ // ===========================================================================
851
+ // TWO AUTHORIZATION GATES, AND EVERY EXECUTOR SITS BEHIND ONE OF THEM (#190)
852
+ //
853
+ // The defect this function was fixed for is NOT "a delete persists past a
854
+ // 404". It is that _withHooks has SEVERAL executors downstream of the
855
+ // handler, and originally the handler's response gated none of them. Three
856
+ // exist today:
857
+ //
858
+ // 1. sqlDb.persist -- issues real SQL against the backing store
859
+ // 2. the after-hook pipeline -- the PUBLISHED consumer extension point;
860
+ // a cascade delete, a webhook, a search-index
861
+ // purge. `context.recordId` and
862
+ // `context.oldState` are populated for it.
863
+ // 3. Orm.db.save() -- a full serialize-and-write of the store
864
+ //
865
+ // Gating them one at a time is how this keeps regressing, so the rule is:
866
+ // compute denial ONCE at each point where it becomes knowable, and keep every
867
+ // executor downstream of a gate. If you add a fourth executor to this
868
+ // function, it goes below GATE 2 or it is a security bug.
869
+ //
870
+ // GATE 1 (pre-handler) is required because before-hooks and `context.oldState`
871
+ // run/are built BEFORE the handler can consult the filter. Without it a denied
872
+ // DELETE still handed the hidden record's full contents to consumer code.
873
+ // GATE 2 (post-handler) covers everything the handler's status can reach.
874
+ // ===========================================================================
318
875
  _withHooks(operation, handler) {
319
876
  return async (request, state) => {
877
+ // `|| {}` so this function behaves like the relationship routes below,
878
+ // which declare `state` with a `= {}` default. It is unkillable through
879
+ // the rest-server dispatcher, which always passes `getState(req)`; it is
880
+ // listed as such in the guards-redundant-by-construction table rather
881
+ // than left silently unkillable, and it defends the WHOLE function (the
882
+ // context, the snapshot and the handler call all read `callState`) rather
883
+ // than one destructure that the next line would throw past anyway.
884
+ const callState = (state || {});
885
+ // ---------------------------------------------------------------------
886
+ // THE AUTHORIZATION SNAPSHOT. Read ONCE, here, before any consumer code
887
+ // can run.
888
+ //
889
+ // `callState` is the object `auth()` planted the filter in, and it is
890
+ // also handed to every before-hook as `context.state` -- a published,
891
+ // WRITABLE extension point. So `state.filter` is an INPUT to the
892
+ // authorization decision, not only an output channel, and re-reading it
893
+ // after the hook loop lets a consumer hook disarm the filter:
894
+ //
895
+ // beforeHook('get', 'animal', ctx => { delete ctx.state.filter })
896
+ // -> GET /animals/21 turned 404 into 200
897
+ // -> GET /animals turned 20 records into 22
898
+ //
899
+ // GATE 1 already used this snapshot, so writes held; the READ handlers
900
+ // re-destructured `filter` from the live bag and did not. Everything
901
+ // downstream now reads `filter` from here, and the handler is handed
902
+ // `handlerState` below -- never `callState`.
903
+ // ---------------------------------------------------------------------
904
+ const { filter } = callState;
320
905
  // Build context object for hooks
321
906
  const context = {
322
907
  model: this.model,
@@ -325,11 +910,35 @@ export default class OrmRequest extends Request {
325
910
  params: request.params,
326
911
  body: request.body,
327
912
  query: request.query,
328
- state,
913
+ // Deliberately the LIVE object: `redirect` and `pipe` are read back off
914
+ // it by @stonyx/rest-server after the handler returns, so hooks must be
915
+ // able to write to it. What must not happen is the authorization
916
+ // decision reading it back, which is what the snapshot above prevents.
917
+ state: callState,
329
918
  };
330
919
  // Capture old state for operations that modify data
331
920
  if (operation === 'update' || operation === 'delete') {
332
921
  const existingRecord = await store.find(this.model, getId(request.params));
922
+ // GATE 1 -- pre-handler. This record fetch already happened for
923
+ // oldState, so the check is free.
924
+ //
925
+ // Returning here rather than letting updateHandler/deleteHandler
926
+ // produce the same 404 is the point: everything between here and there
927
+ // is an executor the caller is not authorized to reach.
928
+ // - context.oldState is a deep copy of the HIDDEN RECORD'S CONTENTS.
929
+ // Building it and handing it to a before-hook discloses exactly what
930
+ // the filter exists to hide.
931
+ // - context.recordId is populated for delete BEFORE the handler runs,
932
+ // which is the same shape as the sqlDb landmine one layer up:
933
+ // `afterHook('delete', ctx => cascadeDelete(ctx.recordId))` destroys
934
+ // children behind a correct 404.
935
+ // - a before-hook may return a value and short-circuit, which would
936
+ // otherwise return a response without the filter ever executing.
937
+ //
938
+ // 404, not 403, for the same reason as getSingleHandler: the status for
939
+ // "exists but filtered out" must equal "does not exist".
940
+ if (existingRecord && isDenied(filter, existingRecord))
941
+ return 404;
333
942
  if (existingRecord) {
334
943
  // Deep copy the record's data to preserve old state
335
944
  context.oldState = JSON.parse(JSON.stringify(existingRecord.__data || existingRecord));
@@ -347,10 +956,49 @@ export default class OrmRequest extends Request {
347
956
  }
348
957
  }
349
958
  // 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)
959
+ // The handler receives the SNAPSHOT, never the live bag. `filter` is
960
+ // assigned LAST so it wins over anything a before-hook wrote to
961
+ // `callState.filter` -- including a `delete`, which the spread would
962
+ // otherwise carry through as an absent key. Every other key a hook adds
963
+ // is still visible to the handler; only the authorization input is
964
+ // pinned.
965
+ const handlerState = { ...callState, filter };
966
+ const response = await handler(request, handlerState);
967
+ // Set context.record for update BEFORE persist so SQL drivers can read it
968
+ if (operation === 'update' && response?.data) {
969
+ context.record = store.get(this.model, getId(request.params));
970
+ }
971
+ // GATE 2 -- post-handler. A denied or failed handler returns a bare status
972
+ // integer, and no executor below may run for one.
973
+ //
974
+ // `>= 400` deliberately covers every failure status, not just the
975
+ // authorization ones: a 400 (POST with no `type`) and a 409 (duplicate id)
976
+ // are equally requests in which nothing happened, and a persist or a
977
+ // cascade hook for one of them is just as wrong.
978
+ // `Number.isInteger` is a TYPE guard, not a behaviour guard, and it is
979
+ // unkillable TODAY: the only non-integer a handler in this file can
980
+ // return is a `{ data, links }` object, and `{} >= 400` is `false` by JS
981
+ // coercion, so dropping it changes no reachable outcome. It is kept
982
+ // because `>=` coerces rather than rejects, and the shapes it coerces
983
+ // are not obvious -- `[500] >= 400` is TRUE, so a handler that one day
984
+ // returned an array would have every response read as a denial. Listed
985
+ // as an equivalent mutant rather than left to read as coverage; it
986
+ // becomes killable the moment a handler returns anything array-like or
987
+ // numeric-string-like.
988
+ const denied = Number.isInteger(response) && response >= 400;
989
+ // EXECUTOR 1 -- SQL persistence, for all write operations.
990
+ //
991
+ // `response` is passed to sqlDb.persist below, but it is dropped at the
992
+ // driver boundary: _persistDelete(modelName, context) never receives it
993
+ // and guards only on context.recordId -- which _withHooks set above,
994
+ // BEFORE the handler ran. Without this gate a correct 404 still issues
995
+ // DELETE FROM ... WHERE id = ? on every SQL backend.
996
+ //
997
+ // No file-backed test can observe that, because Orm.instance.sqlDb is
998
+ // null in file/directory mode. See the stubbed-sqlDb assertions in
999
+ // test/unit/access-filter-enforcement-test.ts.
352
1000
  const sqlDb = Orm.instance.sqlDb;
353
- if (sqlDb && (operation === 'create' || operation === 'update')) {
1001
+ if (sqlDb && WRITE_OPERATIONS.has(operation) && !denied) {
354
1002
  await sqlDb.persist(operation, this.model, context, response);
355
1003
  }
356
1004
  // Add response and relevant records to context
@@ -364,22 +1012,44 @@ export default class OrmRequest extends Request {
364
1012
  else if (operation === 'create' && response?.data && (response.data.id)) {
365
1013
  // For create, get the record from store using the ID from the response
366
1014
  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));
1015
+ // `normalizeBodyId`, not a copy of its body. This line WAS
1016
+ // `isNaN(id) ? id : parseInt(id)` -- `coerceId` inlined verbatim, a
1017
+ // third coercion feeding a store lookup, sitting under a docblock that
1018
+ // said neither surface had a copy. Equivalent on every input that can
1019
+ // reach this truthy-guarded branch (`21`->`21`, `'21'`->`21`,
1020
+ // `'angela'`->`'angela'`; `''` and `0` cannot reach it), so this is a
1021
+ // de-duplication rather than a behaviour change -- and that is the
1022
+ // point: the two that disagreed were equivalent on every input anyone
1023
+ // checked, too.
1024
+ context.record = store.get(this.model, normalizeBodyId(responseData.id));
372
1025
  }
373
1026
  else if (operation === 'delete') {
374
1027
  // For delete, the record may no longer exist, but we have oldState
375
1028
  context.recordId = getId(request.params);
376
1029
  }
377
- // Run after hooks sequentially
378
- for (const hook of getAfterHooks(operation, this.model)) {
379
- await hook(context);
1030
+ // EXECUTOR 2 -- the after-hook pipeline. This is the published consumer
1031
+ // extension point (`afterHook` is exported from @stonyx/orm and from
1032
+ // ./hooks), so it is the executor with the widest possible blast radius:
1033
+ // a cascade delete, a webhook, a token revocation, a search-index purge.
1034
+ //
1035
+ // BEHAVIOUR CHANGE (#190): after-hooks no longer fire for a request that
1036
+ // failed. Previously `afterHook('delete', ...)` ran with a populated
1037
+ // context.recordId on a 404, so a consumer cascade destroyed children for
1038
+ // a request that deleted nothing. Firing a hook named "after<operation>"
1039
+ // for an operation that did not occur is a booby trap, and the denied case
1040
+ // is unreachable-before-#190 while the missing case is inherited debt --
1041
+ // both are closed by the same gate. `context.response` therefore only ever
1042
+ // carries a success status into a hook.
1043
+ if (!denied) {
1044
+ for (const hook of getAfterHooks(operation, this.model)) {
1045
+ await hook(context);
1046
+ }
380
1047
  }
381
- // Auto-save DB after write operations when configured
382
- if (config.orm.db.autosave === 'onUpdate' && WRITE_OPERATIONS.has(operation)) {
1048
+ // EXECUTOR 3 -- file/directory autosave. Ungated this let an
1049
+ // unauthenticated caller force a full serialize-and-write of the entire
1050
+ // store on every DELETE of any id, with no record touched: amplification
1051
+ // rather than corruption, but the same root cause and the same fix.
1052
+ if (config.orm.db.autosave === 'onUpdate' && WRITE_OPERATIONS.has(operation) && !denied) {
383
1053
  await Orm.db.save();
384
1054
  }
385
1055
  return response;
@@ -391,10 +1061,21 @@ export default class OrmRequest extends Request {
391
1061
  // Dasherize the relationship name for URL paths (e.g., accessLinks -> access-links)
392
1062
  const dasherizedName = camelCaseToKebabCase(relationshipName);
393
1063
  // Related resource route: GET /:id/{relationship}
394
- routes[`/:id/${dasherizedName}`] = async (request) => {
1064
+ //
1065
+ // These generated routes are not wrapped by _withHooks, which is why they
1066
+ // were the least obvious two of the seven unguarded surfaces in #190.
1067
+ // They are still dispatched by @stonyx/rest-server as
1068
+ // `handler(req, getState(req))`, so `state` -- and therefore the filter
1069
+ // planted by auth() -- has always been available here; it was simply
1070
+ // never declared or read.
1071
+ routes[`/:id/${dasherizedName}`] = async (request, { filter } = {}) => {
395
1072
  const record = await store.find(model, getId(request.params));
396
1073
  if (!record)
397
1074
  return 404;
1075
+ // Filtering the PARENT: a caller who may not see the record may not see
1076
+ // what it is related to either.
1077
+ if (isDenied(filter, record))
1078
+ return 404;
398
1079
  const relatedData = record.__relationships[relationshipName];
399
1080
  const baseUrl = getBaseUrl(request);
400
1081
  let data;
@@ -413,10 +1094,12 @@ export default class OrmRequest extends Request {
413
1094
  };
414
1095
  };
415
1096
  // Relationship linkage route: GET /:id/relationships/{relationship}
416
- routes[`/:id/relationships/${dasherizedName}`] = async (request) => {
1097
+ routes[`/:id/relationships/${dasherizedName}`] = async (request, { filter } = {}) => {
417
1098
  const record = await store.find(model, getId(request.params));
418
1099
  if (!record)
419
1100
  return 404;
1101
+ if (isDenied(filter, record))
1102
+ return 404;
420
1103
  const relatedData = record.__relationships[relationshipName];
421
1104
  const baseUrl = getBaseUrl(request);
422
1105
  let data;
@@ -445,31 +1128,95 @@ export default class OrmRequest extends Request {
445
1128
  };
446
1129
  };
447
1130
  }
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
- };
1131
+ // Catch-alls for invalid relationship names. Every valid relationship was
1132
+ // registered above, so reaching either of these means the relationship does
1133
+ // not exist and the answer is 404 regardless of the record.
1134
+ //
1135
+ // These deliberately carry NO access check and no store lookup. An earlier
1136
+ // revision of #190 added `if (isDenied(filter, record)) return 404` here for
1137
+ // symmetry with the seven real surfaces, but both branches returned 404, so
1138
+ // the guard was unobservable by construction -- a mutation deleting it
1139
+ // survived the entire suite because no test that could distinguish it can
1140
+ // exist. Unkillable code in an authorization diff reads as coverage and is
1141
+ // not, so it is gone; skipping the lookup also removes the timing difference
1142
+ // between an existing and a missing parent.
1143
+ //
1144
+ // IF THIS ROUTE EVER RETURNS ANYTHING OTHER THAN A CONSTANT 404, it becomes
1145
+ // the eighth surface and must filter the parent first, exactly like
1146
+ // `/:id/{relationship}` above.
1147
+ routes[`/:id/:relationship`] = async () => 404;
1148
+ routes[`/:id/relationships/:relationship`] = async () => 404;
463
1149
  return routes;
464
1150
  }
465
1151
  auth(request, state) {
466
- const access = this.access(request);
1152
+ // A consumer `access()` that throws is a DENIAL, matching `isDenied` one
1153
+ // layer down. Unguarded it propagates to express's default handler, which
1154
+ // answers 500 -- and the documented sample itself can throw
1155
+ // (`request.originalUrl.split(...)` when originalUrl is absent), so the
1156
+ // failure mode is reachable by following the docs.
1157
+ // -------------------------------------------------------------------------
1158
+ // #202 -- hand the consumer the STRUCTURAL facts, not just the transport.
1159
+ //
1160
+ // Both members are already in hand here. `model` is `this.model`, the name
1161
+ // setup-rest-server mounted this route for; `operation` is the SAME
1162
+ // `methodAccessMap` lookup the permission-array branch at the bottom of
1163
+ // this method performs, so the predicate form and the array form cannot
1164
+ // answer differently about the same request.
1165
+ //
1166
+ // NEITHER IS DERIVED FROM THE REQUEST TARGET, and that is the whole point.
1167
+ // Deriving `model` here from `request.baseUrl` (or from the mounted route
1168
+ // name, or from `getPluralName(this.model)`) would move all five fail-open
1169
+ // variants listed in this file's header OUT of the consumer and INTO the
1170
+ // framework, where every consumer inherits them at once. `this.model` is
1171
+ // assigned once at mount time and no request can influence it.
1172
+ //
1173
+ // `operation` is left UNDEFINED for a method with no entry in
1174
+ // `methodAccessMap`, rather than defaulted. Express delivers HEAD to the
1175
+ // GET handler, so an unmapped method really does reach this line; a
1176
+ // `?? 'read'` here would hand the consumer a fabricated authorisation fact
1177
+ // and turn an unclassified request into an authorised one. Undefined is
1178
+ // the honest answer.
1179
+ //
1180
+ // `record` is deliberately absent -- see `AccessContext` in
1181
+ // src/types/orm-types.ts. Nothing is fetched at this point and adding a
1182
+ // lookup here would put a store read in the middle of an authorization
1183
+ // path. The function return shape below IS the per-record hook.
1184
+ // -------------------------------------------------------------------------
1185
+ const context = {
1186
+ model: this.model,
1187
+ operation: methodAccessMap[request.method],
1188
+ };
1189
+ let access;
1190
+ try {
1191
+ access = this.access(request, context);
1192
+ }
1193
+ catch (error) {
1194
+ // Same reasoning as `isDenied`: fail closed, but say so. An `access()`
1195
+ // that throws denies EVERY request to the collection, and a silent 403
1196
+ // wall is the hardest possible thing to diagnose from the outside.
1197
+ log.error?.(`[@stonyx/orm] access() threw for model "${this.model}" -- denying. ${error instanceof Error ? error.message : String(error)}`);
1198
+ return 403; // Forbidden
1199
+ }
467
1200
  if (!access)
468
1201
  return 403;
469
- if (Array.isArray(access) && !access.includes(methodAccessMap[request.method]))
470
- return 403;
471
- if (typeof access === 'function')
1202
+ if (typeof access === 'function') {
472
1203
  state.filter = access;
1204
+ return undefined;
1205
+ }
1206
+ if (access === true)
1207
+ return undefined;
1208
+ // `AccessMethod` declares `string` legal and it fell through every branch
1209
+ // above, returning undefined -- i.e. FULL CRUD, no filter. `return 'read'`
1210
+ // is the natural reading of a type that lists `string` first, and it
1211
+ // granted DELETE. A bare string is one permission, not a grant of all four.
1212
+ const permitted = typeof access === 'string' ? [access] : access;
1213
+ // Anything that is not a permission array by this point -- an object, a
1214
+ // number, a Symbol -- is a consumer mistake, and the only safe reading of a
1215
+ // shape the contract does not define is a denial. Fail CLOSED.
1216
+ if (!Array.isArray(permitted))
1217
+ return 403;
1218
+ if (!permitted.includes(methodAccessMap[request.method]))
1219
+ return 403;
473
1220
  return undefined;
474
1221
  }
475
1222
  }