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

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 +137 -11
  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 +154 -17
  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,3 +1,181 @@
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';
@@ -5,7 +183,8 @@ import { getPluralName } from './plural-registry.js';
5
183
  import { getBeforeHooks, getAfterHooks } from './hooks.js';
6
184
  import type { HookContext } from './hooks.js';
7
185
  import config from 'stonyx/config';
8
- import type { OrmRecord } from './types/orm-types.js';
186
+ import log from 'stonyx/log';
187
+ import type { OrmRecord, AccessContext, AccessFunction, AccessMethod, AccessOperation } from './types/orm-types.js';
9
188
  import { isOrmRecord } from './utils.js';
10
189
 
11
190
  interface OrmRequest$ extends Request {
@@ -33,10 +212,9 @@ interface JsonApiResponse {
33
212
  included?: unknown[];
34
213
  }
35
214
 
36
- type AccessMethod = string | boolean | string[] | ((record: unknown) => boolean);
37
215
  type HandlerFn = (request: OrmRequest$, state: { [key: string]: unknown }) => unknown | Promise<unknown>;
38
216
 
39
- const methodAccessMap: { [key: string]: string } = {
217
+ const methodAccessMap: { [key: string]: AccessOperation } = {
40
218
  GET: 'read',
41
219
  POST: 'create',
42
220
  DELETE: 'delete',
@@ -84,12 +262,119 @@ function getBaseUrl(request: OrmRequest$): string {
84
262
  return `${protocol}://${host}`;
85
263
  }
86
264
 
265
+ /**
266
+ * The ONE coercion from a caller-supplied id to the key the store holds it
267
+ * under. Every id-bearing surface in this file goes through it, and none has a
268
+ * copy: `getId()` (URL params), `normalizeBodyId()` (JSON body), and the
269
+ * post-create `context.record` lookup in `_withHooks`.
270
+ *
271
+ * WHY IT IS SHARED RATHER THAN DUPLICATED. `getId()` and `normalizeBodyId()`
272
+ * each had their own arithmetic, and they disagreed: `parseInt(id)` versus
273
+ * `parseInt(id, 10)`. On a hex-shaped id that is a two-record difference --
274
+ *
275
+ * GET /animals/0x2391 -> record 9105 (getId -> parseInt('0x2391') = 9105)
276
+ * POST /animals {"id":"0x2391"} -> lookup under 0 (normalize -> parseInt('0x2391',10) = 0)
277
+ * -> a MISS, so the duplicate check was skipped and
278
+ * createRecord OVERWROTE 9105 in place, answering 200
279
+ *
280
+ * -- a narrower form of the raw-versus-normalised divergence that the body-id
281
+ * normalisation was added to close, reintroduced by the fix for it. Two
282
+ * coercions that must agree cannot be kept in agreement by review; they have to
283
+ * be one function. Pinned by assertion 43.
284
+ *
285
+ * The third copy was found later and in a quieter place: `_withHooks` populated
286
+ * `context.record` for `create` with `isNaN(id) ? id : parseInt(id)` -- this
287
+ * function's body, inlined verbatim, feeding `store.get`. It was equivalent on
288
+ * every input reachable there, which is exactly what the two that DID diverge
289
+ * looked like until someone tried a hex id.
290
+ *
291
+ * SHARING IT IS NOT THE SAME AS IT BEING RIGHT EVERYWHERE. On a model declaring
292
+ * `id = attr('string')` a numeric-looking id is filed under the STRING key, so
293
+ * this coercion resolves `'9107'` to `9107` and the post-create lookup misses:
294
+ * `context.record` is `undefined` for an after-`create` hook. Inherited -- the
295
+ * inlined copy computed the same thing -- and NOT fixed here, because picking
296
+ * the right coercion needs the model's declared id type, which is the same
297
+ * structural information abofs/stonyx-orm#202 is about. Filed as
298
+ * abofs/stonyx-orm#209 and pinned by assertion 50, so closing it turns a test
299
+ * red rather than passing silently.
300
+ *
301
+ * `parseInt` and not `Number`, deliberately, and the anchor is NOT `getId`.
302
+ * It is `src/transforms.ts:7` -- `number: (value) => parseInt(value as string)`,
303
+ * also radix-less -- because that transform is what actually produces the store
304
+ * KEY a record is filed under. `getId` merely agrees with it. They differ from
305
+ * `Number` on `'1e3'` (1 vs 1000) and `'9105.5'` (9105 vs 9105.5), so switching
306
+ * this function to `Number` would make the lookup key disagree with the landing
307
+ * key on those shapes.
308
+ *
309
+ * THE CHANGE THAT WOULD BREAK THIS: adding a radix to `transforms.number`
310
+ * (`parseInt(value, 10)`). That is a one-word edit in a file with no connection
311
+ * to authorization, it would silently reopen the hex divergence in the other
312
+ * direction, and this comment would still read as correct. Assertion 45 pins
313
+ * the transform's radix-less shape directly, so that edit turns a test red
314
+ * rather than shipping.
315
+ *
316
+ * The reason `parseInt` is safe here is the `isNaN` gate in front of it:
317
+ * `parseInt('9105h')` is `9105`, and truncating a partially-valid id into a
318
+ * DIFFERENT VALID key is exactly how a collision lookup gets skipped. The gate
319
+ * rejects it as a string instead, so nothing is ever truncated. That gate, not
320
+ * the parser, is the load-bearing half -- assertion 43 pins it.
321
+ */
322
+ function coerceId(id: string): string | number {
323
+ if (isNaN(id as unknown as number)) return id;
324
+
325
+ return parseInt(id);
326
+ }
327
+
87
328
  function getId(params: { id?: string; [key: string]: unknown }): string | number {
88
329
  const id = params.id;
89
330
  if (!id) return '';
90
- if (isNaN(id as unknown as number)) return id;
91
331
 
92
- return parseInt(id);
332
+ return coerceId(id);
333
+ }
334
+
335
+ /**
336
+ * Normalise a caller-supplied BODY id to the key the store will hold it under.
337
+ *
338
+ * `getId()` above is params-shaped: it takes `{ id?: string }` off the URL,
339
+ * where the value is always a string and a falsy one means "no id". A JSON body
340
+ * id is neither -- it can arrive as a number, and `0` is a legitimate id that
341
+ * `getId()` would flatten to `''`.
342
+ *
343
+ * WHY THIS EXISTS AT ALL. createHandler used to look the collision up with the
344
+ * RAW body value while every other surface normalised through `getId()`. The
345
+ * store is a Map keyed by the coerced value, so `store.find(model, '21')` misses
346
+ * the entry held under `21` and the duplicate check is skipped by typing the id
347
+ * as a string. On `dev` that silently overwrote the colliding record and
348
+ * answered 200; combined with the denied-create rollback added for #190 it
349
+ * became an unauthenticated DELETE of any id. Normalising here is half of that
350
+ * fix -- see the rollback in createHandler for the other half.
351
+ *
352
+ * It shares `coerceId` with `getId` so the two surfaces cannot drift apart
353
+ * again, and differs from `getId` in exactly ONE place, below.
354
+ */
355
+ function normalizeBodyId(id: string | number): string | number {
356
+ // Non-strings pass through untouched: a JSON body id can arrive as a number,
357
+ // and `getId`'s falsy-flatten must NOT apply to it -- `0` is a legitimate id
358
+ // and `getId` would turn it into `''`. (assertion 30 sweeps id `0`.)
359
+ if (typeof id !== 'string') return id;
360
+
361
+ // THE ONE DIVERGENCE FROM `getId`, and it mirrors rather than contradicts it:
362
+ // `getId` maps a falsy param to `''`, and `''` is the only string a body can
363
+ // carry that means "no id" -- `createRecord` treats it as absent and assigns a
364
+ // server id. Coercing it instead would make it address a real slot, because
365
+ // `parseInt('')` is `NaN` and a record CAN be held under `NaN` (a truthy but
366
+ // non-numeric id such as `' '` survives `assignRecordId`'s falsy guard and
367
+ // then NaNs in the id transform). So `POST {"id":""}` would answer 409 against
368
+ // an unrelated record it never named. Pinned by assertion 44.
369
+ //
370
+ // Note what is deliberately NOT special-cased here any more: whitespace.
371
+ // `id.trim() === ''` used to short-circuit `' '` as well, which made the
372
+ // body surface DISAGREE with the URL surface -- `getId({id:' '})` is `NaN`,
373
+ // so `' '` addresses the NaN slot on every other route while the collision
374
+ // lookup missed it. Same class of bug as the hex divergence above.
375
+ if (id === '') return id;
376
+
377
+ return coerceId(id);
93
378
  }
94
379
 
95
380
  function buildResponse(
@@ -251,12 +536,46 @@ function createFilterPredicate(filters: Filter[]): ((record: { [key: string]: un
251
536
  });
252
537
  }
253
538
 
539
+ /**
540
+ * A function-style `access` return is a per-record predicate, and it is only
541
+ * meaningful if every surface that can hand a record to a caller consults it.
542
+ * Before #190 exactly one of seven did.
543
+ *
544
+ * Enforcement is deliberately post-fetch. `access` returns an opaque JS
545
+ * predicate and `store.findAll(model, conditions)` accepts only an equality
546
+ * conditions object that the SQL drivers translate to a WHERE clause, so
547
+ * query-layer enforcement would require a breaking change to the published
548
+ * `access` contract. That belongs in #197, not in a security patch. Six of the
549
+ * seven surfaces fetch by primary key anyway, so this costs exactly one row.
550
+ */
551
+ function isDenied(filter: unknown, record: unknown): boolean {
552
+ if (typeof filter !== 'function') return false;
553
+
554
+ // A predicate that throws is treated as a denial. Unguarded, a throw escapes
555
+ // to express's default handler, which answers 500 (with a stack trace outside
556
+ // NODE_ENV=production) while a missing id still answers 404 -- so a
557
+ // record-dependent throw re-separates "hidden" from "does not exist" and
558
+ // hands back the oracle this whole change exists to close.
559
+ try {
560
+ return !(filter as (record: unknown) => boolean)(record);
561
+ } catch (error) {
562
+ // Denied, but not silently. A consumer predicate that throws on every
563
+ // record turns the whole collection into a 404 wall, and with no
564
+ // diagnostic that is indistinguishable from an empty database. `stonyx/log`
565
+ // is the module convention (see setup-rest-server.ts); optional-call
566
+ // because a consumer may not have configured the log types.
567
+ log.error?.(`[@stonyx/orm] access filter threw for model -- denying. ${error instanceof Error ? error.message : String(error)}`);
568
+
569
+ return true;
570
+ }
571
+ }
572
+
254
573
  export default class OrmRequest extends Request {
255
574
  model: string;
256
- access: (request: unknown) => AccessMethod;
575
+ access: AccessFunction;
257
576
  handlers: { [key: string]: { [key: string]: HandlerFn } };
258
577
 
259
- constructor({ model, access }: { model: string; access: (request: unknown) => AccessMethod }) {
578
+ constructor({ model, access }: { model: string; access: AccessFunction }) {
260
579
  super(...arguments as unknown as unknown[]);
261
580
 
262
581
  this.model = model;
@@ -287,9 +606,13 @@ export default class OrmRequest extends Request {
287
606
  });
288
607
  };
289
608
 
290
- const getSingleHandler: HandlerFn = async (request) => {
609
+ const getSingleHandler: HandlerFn = async (request, { filter }) => {
291
610
  const record = await store.find(model, getId(request.params)) as OrmRecord | undefined;
292
611
  if (!record) return 404;
612
+ // 404, never 403: the status for "exists but filtered out" must be
613
+ // identical to "does not exist", or the fix trades an authorization
614
+ // bypass for a narrower existence oracle.
615
+ if (isDenied(filter, record)) return 404;
293
616
 
294
617
  const fieldsMap = parseFields(request.query);
295
618
  const modelFields = fieldsMap.get(pluralizedModel) || fieldsMap.get(model);
@@ -301,7 +624,7 @@ export default class OrmRequest extends Request {
301
624
  });
302
625
  };
303
626
 
304
- const createHandler: HandlerFn = async ({ body, query }) => {
627
+ const createHandler: HandlerFn = async ({ body, query }, { filter }) => {
305
628
  const { type, id, attributes, relationships: rels } = (body?.data || {}) as {
306
629
  type?: string;
307
630
  id?: string | number;
@@ -314,14 +637,113 @@ export default class OrmRequest extends Request {
314
637
  const fieldsMap = parseFields(query);
315
638
  const modelFields = fieldsMap.get(pluralizedModel) || fieldsMap.get(model);
316
639
 
317
- // Check for duplicate ID
318
- if (id !== undefined && await store.find(model, id)) return 409; // Conflict
640
+ // GATE 0 -- the POST existence oracle.
641
+ //
642
+ // The duplicate check runs before the filter and `store.find` sees hidden
643
+ // records, so POST leaks existence through its STATUS. A previous revision
644
+ // filtered the collision status (403 when the colliding record is denied,
645
+ // 409 when it is visible) and that is NOT sufficient, because the status
646
+ // of a create is a third outcome. With a payload the caller is permitted
647
+ // to create -- the normative case for a per-tenant filter, and the case an
648
+ // attacker picks -- all three are distinguishable in ONE request per id:
649
+ //
650
+ // POST /animals {id:22, owner:'gina'} -> 403 a HIDDEN record has this id
651
+ // POST /animals {id:9500, owner:'gina'} -> 200 this id is FREE
652
+ // POST /animals {id:8, owner:'gina'} -> 409 a VISIBLE record has this id
653
+ //
654
+ // Filtering only the collision status narrows that to callers who cannot
655
+ // create a record they are allowed to see. It does not close it.
656
+ //
657
+ // It cannot be closed while a caller both chooses the id and learns
658
+ // whether the create succeeded: a successful create must answer
659
+ // differently from a refused one. So when a per-record filter is in force
660
+ // the caller does not get to choose the id at all. The refusal is
661
+ // UNCONDITIONAL and happens BEFORE any store lookup, so no status, and no
662
+ // lookup cost, can depend on whether that id exists. 403 -- the same
663
+ // status as a denied create -- so the two cannot be separated either.
664
+ //
665
+ // BOTH HALVES OF THAT ARE PINNED, because both were once asserted here and
666
+ // pinned by nothing:
667
+ //
668
+ // status -- assertion 22 sweeps payload x id x id-type, plus `null`.
669
+ // latency -- assertion 41 asserts NO `store.find` is issued on this
670
+ // path. Moving the refusal to after a lookup and returning
671
+ // the same 403 left the suite green while re-opening a
672
+ // hit-versus-miss timing difference on every id-bearing POST,
673
+ // which is what would turn #197 from a ~0.06ms post-fetch
674
+ // residual into a live timing oracle on create.
675
+ //
676
+ // AND THE GUARANTEE IS ONLY AS WIDE AS THE CHANNELS IT COVERS. It reads on
677
+ // the `id` member of the resource object, so it holds only while that is
678
+ // the ONLY way a caller id can reach `createRecord`. It was not: the
679
+ // relationships loop below re-admitted one under `key === "id"` and the
680
+ // gate never fired. Both strips -- `attributes.id` and `relationships.id`
681
+ // -- are therefore part of THIS gate, not tidiness, and assertion 39 pins
682
+ // them. Adding a third channel without a strip re-opens the oracle.
683
+ //
684
+ // Scoped to function-style `access` because that is exactly the population
685
+ // the oracle exists for: with no per-record filter there are no hidden
686
+ // records, and 409 discloses nothing GET /:id does not already.
687
+ //
688
+ // RESIDUALS, stated rather than implied.
689
+ //
690
+ // - a caller can still learn that a collection HAS a per-record filter
691
+ // (403 rather than 409/200 for an id-bearing POST). That discloses a
692
+ // configuration fact, not a record.
693
+ // - this gate is about ids arriving on THIS model's create route. It
694
+ // says nothing about a write to ANOTHER collection: a `POST /owners`
695
+ // carrying `relationships: {pets: {data: {id: 21}}}` -- or
696
+ // `attributes: {pets: [21, 22]}`, which never enters the
697
+ // relationships loop at all -- re-parents hidden animal 21 onto an
698
+ // owner the caller may write, which changes the very field the
699
+ // animals predicate reads and DE-HIDES it. Blocking that needs animal
700
+ // 21 checked against the ANIMAL model's predicate while servicing an
701
+ // OWNERS route, i.e. cross-model access resolution: abofs/stonyx-orm
702
+ // #207, blocked on #202 (`access` receives the model structurally)
703
+ // and #196 (setup-rest-server discards the model->predicate map at
704
+ // boot). NOT closed here, and no comment in this file may say it is.
705
+ //
706
+ // See README `### Known limitations`.
707
+ if (id !== undefined) {
708
+ if (typeof filter === 'function') return 403; // Forbidden
709
+
710
+ // `normalizeBodyId`, not the raw value: a string-typed id misses the
711
+ // store's numeric key, which skipped this check entirely.
712
+ const existing = await store.find(model, normalizeBodyId(id));
713
+ if (existing) return 409; // Conflict
714
+ }
319
715
 
320
716
  const { id: _ignoredId, ...sanitizedAttributes } = attributes || {};
321
717
 
322
- // Extract relationship IDs from JSON:API relationships object
718
+ // Extract relationship IDs from JSON:API relationships object.
719
+ //
720
+ // `key` comes VERBATIM from the request body, so `id` is stripped here for
721
+ // exactly the same reason it is stripped from `attributes` on the line
722
+ // above -- and it must be, or GATE 0 is walked around by moving one field:
723
+ //
724
+ // POST /animals {"id":21, ...} -> 403 GATE 0 fires
725
+ // POST /animals {"relationships":{"id":{"data":{"id":21}}},
726
+ // "attributes":{"owner":"gina"}} -> 200 BYPASS
727
+ //
728
+ // Top-level `id` stayed `undefined`, so GATE 0 never fired and the
729
+ // collision lookup never ran; `createRecord` took its last-entry-wins
730
+ // branch, overwrote hidden record 21 in place and reset its `owner` to a
731
+ // value the caller chose -- de-hiding it permanently. That is #190 itself,
732
+ // on the create surface. Pinned by assertion 39.
733
+ //
734
+ // The `id` member of the resource object is now the ONLY channel a caller
735
+ // id can arrive on FOR THIS MODEL'S OWN CREATE ROUTE, which is what makes
736
+ // GATE 0's guarantee checkable rather than merely asserted. It is not a
737
+ // statement about the record's reachability in general -- a relationship
738
+ // write on another collection reaches it without ever touching this
739
+ // handler (abofs/stonyx-orm#207). INHERITED from `dev`, which carries this
740
+ // loop verbatim; the general form -- the loop accepts any key, not just
741
+ // `id`, so a body key that is not a declared relationship is still
742
+ // mass-assigned -- is abofs/stonyx-orm#204.
323
743
  if (rels) {
324
744
  for (const [key, value] of Object.entries(rels)) {
745
+ if (key === 'id') continue;
746
+
325
747
  const relData = value?.data;
326
748
  if (relData && relData.id !== undefined) {
327
749
  (sanitizedAttributes as { [key: string]: unknown })[key] = relData.id;
@@ -330,16 +752,95 @@ export default class OrmRequest extends Request {
330
752
  }
331
753
 
332
754
  const recordAttributes = id !== undefined ? { id, ...sanitizedAttributes } : sanitizedAttributes;
755
+
756
+ // Slot count BEFORE the write. `createRecord` writes to the store before
757
+ // the predicate can run, and the rollback below must be able to prove the
758
+ // slot it removes is one THIS REQUEST created. Identity alone cannot
759
+ // prove it: when `assignRecordId` lands on an occupied id, `createRecord`
760
+ // mutates the existing OrmRecord IN PLACE, so `store.get(...) === record`
761
+ // is true for a record the request did not create. The map's size is the
762
+ // only O(1) signal that distinguishes an insert from an overwrite.
763
+ const slotsBefore = store.get(model)?.size ?? 0;
764
+
333
765
  const created = createRecord(model, recordAttributes as { [key: string]: unknown }, { serialize: false, _skipAutoPersist: true });
334
766
  const record = isOrmRecord(created) ? created : null;
335
767
  if (!record) return 500;
336
768
 
769
+ const createdNewSlot = (store.get(model)?.size ?? 0) > slotsBefore;
770
+
771
+ // 403 here, NOT 404. The oracle argument does not apply to create: there
772
+ // is no pre-existing record whose existence could leak, the caller
773
+ // supplied the attributes, and 404 on a mounted collection route is
774
+ // indistinguishable from "model not mounted" -- a genuinely different
775
+ // failure a developer needs to diagnose.
776
+ //
777
+ // The rollback is not optional. createRecord writes to the store BEFORE
778
+ // the predicate can run, so returning 403 alone would leave the record
779
+ // behind: a worse bug than the bypass being fixed.
780
+ if (isDenied(filter, record)) {
781
+ // ROLL BACK BY IDENTITY, NEVER BY ID. `store.remove(model, record.id)`
782
+ // on its own is a write primitive keyed by a value the caller may have
783
+ // supplied: with the raw-id collision bypass above, a denied
784
+ // `POST {"id":"21"}` answered 403 and DELETED hidden record 21 -- an
785
+ // unauthenticated deletion primitive across the whole id space, created
786
+ // by adding a rollback to a lookup that could be skipped.
787
+ //
788
+ // Both conditions are required and neither implies the other:
789
+ // createdNewSlot -- the store grew, so this request inserted rather
790
+ // than overwrote. Guards `assignRecordId` picking an
791
+ // id that is already taken (it returns
792
+ // last-INSERTED + 1, not max + 1, so a store whose
793
+ // insertion order is not ascending collides) -- see
794
+ // abofs/stonyx-orm#203.
795
+ // identity -- the slot still holds the object we just created,
796
+ // so nothing between createRecord and here replaced
797
+ // it. Deleting this half SURVIVES the suite, and it
798
+ // is kept anyway. WHY IT IS REDUNDANT: there is no
799
+ // `await` anywhere between `slotsBefore` and
800
+ // `store.remove` -- the whole window is synchronous,
801
+ // so it is atomic under Node's event loop; before-
802
+ // `create` hooks run BEFORE the handler
803
+ // (`_withHooks` runs its hook loop ahead of
804
+ // `await handler(...)`), and a consumer predicate
805
+ // inside `isDenied` runs AFTER `createdNewSlot` is
806
+ // computed and cannot flip it. That is a property of
807
+ // THIS function, not of GATE 0 -- an earlier note
808
+ // credited GATE 0, which was both wrong (a caller id
809
+ // reached createRecord through the relationships
810
+ // loop, #204) and the wrong kind of reason: a guard
811
+ // justified on code sixty lines upstream gets
812
+ // silently re-armed when that code moves.
813
+ // SO IT BECOMES REACHABLE IF AN `await` IS
814
+ // INTRODUCED HERE, which is the change a future
815
+ // editor would actually make. Stated here rather
816
+ // than by reference: `docs/` is not in `files`, so
817
+ // a pointer into it resolves to nothing for anyone
818
+ // who installed this package. README carries the
819
+ // consumer-facing half.
820
+ if (createdNewSlot && store.get(model, record.id as string | number) === record) {
821
+ store.remove(model, record.id as string | number, { _skipAutoPersist: true });
822
+ }
823
+
824
+ return 403;
825
+ }
826
+
337
827
  return { data: record.toJSON?.({ fields: modelFields }) };
338
828
  };
339
829
 
340
- const updateHandler: HandlerFn = async ({ body, params }) => {
830
+ const updateHandler: HandlerFn = async ({ body, params }, { filter }) => {
341
831
  const found = await store.find(model, getId(params));
342
832
  if (!found || !isOrmRecord(found)) return 404;
833
+ // Checked BEFORE any attribute is applied. 404 rather than 403 for the
834
+ // same reason as GET /:id -- 403 would disclose both that the record
835
+ // exists and that this caller specifically is excluded.
836
+ //
837
+ // NOT redundant behind GATE 1, and not defence in depth either: GATE 1's
838
+ // verdict is computed BEFORE the before-hook loop runs, and a before-hook
839
+ // is a published extension point that can change the answer -- by
840
+ // mutating the record, or against a predicate that closes over
841
+ // per-request state. This is the only re-evaluation after that window.
842
+ // Pinned by assertion 32; deleting it turns a 404 into an applied update.
843
+ if (isDenied(filter, found)) return 404;
343
844
  const record = found;
344
845
  const { attributes, relationships: rels } = (body?.data || {}) as {
345
846
  attributes?: { [key: string]: unknown };
@@ -362,6 +863,19 @@ export default class OrmRequest extends Request {
362
863
  if (rels) {
363
864
  const relUpdates: { [key: string]: unknown } = {};
364
865
  for (const [key, value] of Object.entries(rels)) {
866
+ // The same missing key filter as createHandler's, and as the
867
+ // attribute loop directly above -- which already had it, while this
868
+ // loop did not. A PATCH carrying
869
+ // `relationships:{"id":{"data":{"id":9101}}}` reached `updateRecord`
870
+ // and RE-KEYED the record: the object held under store key 9102 then
871
+ // reported id 9101, so a visible record claimed a hidden record's
872
+ // identity on every surface that reads `record.id` rather than the map
873
+ // key. Gated by GATE 1 on the addressed record, so it is store
874
+ // corruption rather than a filter bypass -- but it is the same one-line
875
+ // omission two handlers apart. Pinned by assertion 40; INHERITED from
876
+ // `dev`; abofs/stonyx-orm#204.
877
+ if (key === 'id') continue;
878
+
365
879
  const relData = value?.data;
366
880
  if (relData && relData.id !== undefined) {
367
881
  relUpdates[key] = relData.id;
@@ -375,8 +889,31 @@ export default class OrmRequest extends Request {
375
889
  return { data: record.toJSON?.() };
376
890
  };
377
891
 
378
- const deleteHandler: HandlerFn = ({ params }) => {
379
- store.remove(model, getId(params));
892
+ const deleteHandler: HandlerFn = async ({ params }, { filter }) => {
893
+ // Coerced ONCE. `getId(params)` was evaluated twice here -- once to find
894
+ // the record and once to remove it -- and a coercion evaluated repeatedly
895
+ // is a coercion that can be edited in one place and not the other, which
896
+ // is the defect `coerceId` exists to prevent.
897
+ const recordId = getId(params);
898
+ const record = await store.find(model, recordId) as OrmRecord | undefined;
899
+
900
+ // BEHAVIOUR CHANGE (#190): a DELETE of a record that never existed
901
+ // returned 204 before this change. It now returns 404, matching the
902
+ // denied case below. This is deliberate and load-bearing -- if a denied
903
+ // delete returned 404 while a missing one returned 204, the pair would be
904
+ // a perfect existence oracle and the whole fix would be worthless.
905
+ // Returning 204 for a denied delete was rejected instead: it falsely
906
+ // reports success for a request that changed nothing.
907
+ if (!record) return 404;
908
+ // Re-evaluated after the before-hook loop, exactly as in updateHandler --
909
+ // GATE 1 decided before the hooks ran. Pinned by assertion 33; deleting it
910
+ // turns a 404 into a destroyed record.
911
+ if (isDenied(filter, record)) return 404;
912
+
913
+ // Removed by the id of the record actually fetched, not by re-deriving it
914
+ // from the params a second time: the record the filter tested and the
915
+ // record removed are then provably the same one.
916
+ store.remove(model, record.id as string | number, { _skipAutoPersist: true });
380
917
  return 204;
381
918
  };
382
919
 
@@ -405,9 +942,65 @@ export default class OrmRequest extends Request {
405
942
  }
406
943
  }
407
944
 
408
- // Wraps a handler with before/after hook execution
945
+ // Wraps a handler with before/after hook execution.
946
+ //
947
+ // ===========================================================================
948
+ // TWO AUTHORIZATION GATES, AND EVERY EXECUTOR SITS BEHIND ONE OF THEM (#190)
949
+ //
950
+ // The defect this function was fixed for is NOT "a delete persists past a
951
+ // 404". It is that _withHooks has SEVERAL executors downstream of the
952
+ // handler, and originally the handler's response gated none of them. Three
953
+ // exist today:
954
+ //
955
+ // 1. sqlDb.persist -- issues real SQL against the backing store
956
+ // 2. the after-hook pipeline -- the PUBLISHED consumer extension point;
957
+ // a cascade delete, a webhook, a search-index
958
+ // purge. `context.recordId` and
959
+ // `context.oldState` are populated for it.
960
+ // 3. Orm.db.save() -- a full serialize-and-write of the store
961
+ //
962
+ // Gating them one at a time is how this keeps regressing, so the rule is:
963
+ // compute denial ONCE at each point where it becomes knowable, and keep every
964
+ // executor downstream of a gate. If you add a fourth executor to this
965
+ // function, it goes below GATE 2 or it is a security bug.
966
+ //
967
+ // GATE 1 (pre-handler) is required because before-hooks and `context.oldState`
968
+ // run/are built BEFORE the handler can consult the filter. Without it a denied
969
+ // DELETE still handed the hidden record's full contents to consumer code.
970
+ // GATE 2 (post-handler) covers everything the handler's status can reach.
971
+ // ===========================================================================
409
972
  private _withHooks(operation: string, handler: HandlerFn): HandlerFn {
410
973
  return async (request: OrmRequest$, state: { [key: string]: unknown }) => {
974
+ // `|| {}` so this function behaves like the relationship routes below,
975
+ // which declare `state` with a `= {}` default. It is unkillable through
976
+ // the rest-server dispatcher, which always passes `getState(req)`; it is
977
+ // listed as such in the guards-redundant-by-construction table rather
978
+ // than left silently unkillable, and it defends the WHOLE function (the
979
+ // context, the snapshot and the handler call all read `callState`) rather
980
+ // than one destructure that the next line would throw past anyway.
981
+ const callState = (state || {}) as { [key: string]: unknown };
982
+
983
+ // ---------------------------------------------------------------------
984
+ // THE AUTHORIZATION SNAPSHOT. Read ONCE, here, before any consumer code
985
+ // can run.
986
+ //
987
+ // `callState` is the object `auth()` planted the filter in, and it is
988
+ // also handed to every before-hook as `context.state` -- a published,
989
+ // WRITABLE extension point. So `state.filter` is an INPUT to the
990
+ // authorization decision, not only an output channel, and re-reading it
991
+ // after the hook loop lets a consumer hook disarm the filter:
992
+ //
993
+ // beforeHook('get', 'animal', ctx => { delete ctx.state.filter })
994
+ // -> GET /animals/21 turned 404 into 200
995
+ // -> GET /animals turned 20 records into 22
996
+ //
997
+ // GATE 1 already used this snapshot, so writes held; the READ handlers
998
+ // re-destructured `filter` from the live bag and did not. Everything
999
+ // downstream now reads `filter` from here, and the handler is handed
1000
+ // `handlerState` below -- never `callState`.
1001
+ // ---------------------------------------------------------------------
1002
+ const { filter } = callState as { filter?: unknown };
1003
+
411
1004
  // Build context object for hooks
412
1005
  const context: HookContext = {
413
1006
  model: this.model,
@@ -416,12 +1009,37 @@ export default class OrmRequest extends Request {
416
1009
  params: request.params,
417
1010
  body: request.body,
418
1011
  query: request.query,
419
- state,
1012
+ // Deliberately the LIVE object: `redirect` and `pipe` are read back off
1013
+ // it by @stonyx/rest-server after the handler returns, so hooks must be
1014
+ // able to write to it. What must not happen is the authorization
1015
+ // decision reading it back, which is what the snapshot above prevents.
1016
+ state: callState,
420
1017
  };
421
1018
 
422
1019
  // Capture old state for operations that modify data
423
1020
  if (operation === 'update' || operation === 'delete') {
424
1021
  const existingRecord = await store.find(this.model, getId(request.params)) as OrmRecord | undefined;
1022
+
1023
+ // GATE 1 -- pre-handler. This record fetch already happened for
1024
+ // oldState, so the check is free.
1025
+ //
1026
+ // Returning here rather than letting updateHandler/deleteHandler
1027
+ // produce the same 404 is the point: everything between here and there
1028
+ // is an executor the caller is not authorized to reach.
1029
+ // - context.oldState is a deep copy of the HIDDEN RECORD'S CONTENTS.
1030
+ // Building it and handing it to a before-hook discloses exactly what
1031
+ // the filter exists to hide.
1032
+ // - context.recordId is populated for delete BEFORE the handler runs,
1033
+ // which is the same shape as the sqlDb landmine one layer up:
1034
+ // `afterHook('delete', ctx => cascadeDelete(ctx.recordId))` destroys
1035
+ // children behind a correct 404.
1036
+ // - a before-hook may return a value and short-circuit, which would
1037
+ // otherwise return a response without the filter ever executing.
1038
+ //
1039
+ // 404, not 403, for the same reason as getSingleHandler: the status for
1040
+ // "exists but filtered out" must equal "does not exist".
1041
+ if (existingRecord && isDenied(filter, existingRecord)) return 404;
1042
+
425
1043
  if (existingRecord) {
426
1044
  // Deep copy the record's data to preserve old state
427
1045
  context.oldState = JSON.parse(JSON.stringify(existingRecord.__data || existingRecord));
@@ -441,11 +1059,52 @@ export default class OrmRequest extends Request {
441
1059
  }
442
1060
 
443
1061
  // Execute main handler
444
- const response = await handler(request, state);
1062
+ // The handler receives the SNAPSHOT, never the live bag. `filter` is
1063
+ // assigned LAST so it wins over anything a before-hook wrote to
1064
+ // `callState.filter` -- including a `delete`, which the spread would
1065
+ // otherwise carry through as an absent key. Every other key a hook adds
1066
+ // is still visible to the handler; only the authorization input is
1067
+ // pinned.
1068
+ const handlerState = { ...callState, filter };
1069
+ const response = await handler(request, handlerState);
1070
+
1071
+ // Set context.record for update BEFORE persist so SQL drivers can read it
1072
+ if (operation === 'update' && (response as JsonApiResponse)?.data) {
1073
+ context.record = store.get(this.model, getId(request.params));
1074
+ }
445
1075
 
446
- // Persist to SQL database for create/update (delete is handled by store.remove auto-persist)
1076
+ // GATE 2 -- post-handler. A denied or failed handler returns a bare status
1077
+ // integer, and no executor below may run for one.
1078
+ //
1079
+ // `>= 400` deliberately covers every failure status, not just the
1080
+ // authorization ones: a 400 (POST with no `type`) and a 409 (duplicate id)
1081
+ // are equally requests in which nothing happened, and a persist or a
1082
+ // cascade hook for one of them is just as wrong.
1083
+ // `Number.isInteger` is a TYPE guard, not a behaviour guard, and it is
1084
+ // unkillable TODAY: the only non-integer a handler in this file can
1085
+ // return is a `{ data, links }` object, and `{} >= 400` is `false` by JS
1086
+ // coercion, so dropping it changes no reachable outcome. It is kept
1087
+ // because `>=` coerces rather than rejects, and the shapes it coerces
1088
+ // are not obvious -- `[500] >= 400` is TRUE, so a handler that one day
1089
+ // returned an array would have every response read as a denial. Listed
1090
+ // as an equivalent mutant rather than left to read as coverage; it
1091
+ // becomes killable the moment a handler returns anything array-like or
1092
+ // numeric-string-like.
1093
+ const denied = Number.isInteger(response) && (response as number) >= 400;
1094
+
1095
+ // EXECUTOR 1 -- SQL persistence, for all write operations.
1096
+ //
1097
+ // `response` is passed to sqlDb.persist below, but it is dropped at the
1098
+ // driver boundary: _persistDelete(modelName, context) never receives it
1099
+ // and guards only on context.recordId -- which _withHooks set above,
1100
+ // BEFORE the handler ran. Without this gate a correct 404 still issues
1101
+ // DELETE FROM ... WHERE id = ? on every SQL backend.
1102
+ //
1103
+ // No file-backed test can observe that, because Orm.instance.sqlDb is
1104
+ // null in file/directory mode. See the stubbed-sqlDb assertions in
1105
+ // test/unit/access-filter-enforcement-test.ts.
447
1106
  const sqlDb = Orm.instance.sqlDb;
448
- if (sqlDb && (operation === 'create' || operation === 'update')) {
1107
+ if (sqlDb && WRITE_OPERATIONS.has(operation) && !denied) {
449
1108
  await sqlDb.persist(operation, this.model, context, response);
450
1109
  }
451
1110
 
@@ -459,22 +1118,45 @@ export default class OrmRequest extends Request {
459
1118
  } else if (operation === 'create' && (response as JsonApiResponse)?.data && ((response as { data: { id?: unknown } }).data.id)) {
460
1119
  // For create, get the record from store using the ID from the response
461
1120
  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));
1121
+ // `normalizeBodyId`, not a copy of its body. This line WAS
1122
+ // `isNaN(id) ? id : parseInt(id)` -- `coerceId` inlined verbatim, a
1123
+ // third coercion feeding a store lookup, sitting under a docblock that
1124
+ // said neither surface had a copy. Equivalent on every input that can
1125
+ // reach this truthy-guarded branch (`21`->`21`, `'21'`->`21`,
1126
+ // `'angela'`->`'angela'`; `''` and `0` cannot reach it), so this is a
1127
+ // de-duplication rather than a behaviour change -- and that is the
1128
+ // point: the two that disagreed were equivalent on every input anyone
1129
+ // checked, too.
1130
+ context.record = store.get(this.model, normalizeBodyId(responseData.id) as string | number);
466
1131
  } else if (operation === 'delete') {
467
1132
  // For delete, the record may no longer exist, but we have oldState
468
1133
  context.recordId = getId(request.params);
469
1134
  }
470
1135
 
471
- // Run after hooks sequentially
472
- for (const hook of getAfterHooks(operation, this.model)) {
473
- await hook(context);
1136
+ // EXECUTOR 2 -- the after-hook pipeline. This is the published consumer
1137
+ // extension point (`afterHook` is exported from @stonyx/orm and from
1138
+ // ./hooks), so it is the executor with the widest possible blast radius:
1139
+ // a cascade delete, a webhook, a token revocation, a search-index purge.
1140
+ //
1141
+ // BEHAVIOUR CHANGE (#190): after-hooks no longer fire for a request that
1142
+ // failed. Previously `afterHook('delete', ...)` ran with a populated
1143
+ // context.recordId on a 404, so a consumer cascade destroyed children for
1144
+ // a request that deleted nothing. Firing a hook named "after<operation>"
1145
+ // for an operation that did not occur is a booby trap, and the denied case
1146
+ // is unreachable-before-#190 while the missing case is inherited debt --
1147
+ // both are closed by the same gate. `context.response` therefore only ever
1148
+ // carries a success status into a hook.
1149
+ if (!denied) {
1150
+ for (const hook of getAfterHooks(operation, this.model)) {
1151
+ await hook(context);
1152
+ }
474
1153
  }
475
1154
 
476
- // Auto-save DB after write operations when configured
477
- if (config.orm.db.autosave === 'onUpdate' && WRITE_OPERATIONS.has(operation)) {
1155
+ // EXECUTOR 3 -- file/directory autosave. Ungated this let an
1156
+ // unauthenticated caller force a full serialize-and-write of the entire
1157
+ // store on every DELETE of any id, with no record touched: amplification
1158
+ // rather than corruption, but the same root cause and the same fix.
1159
+ if (config.orm.db.autosave === 'onUpdate' && WRITE_OPERATIONS.has(operation) && !denied) {
478
1160
  await (Orm.db as { save(): Promise<void> }).save();
479
1161
  }
480
1162
 
@@ -494,9 +1176,19 @@ export default class OrmRequest extends Request {
494
1176
  const dasherizedName = camelCaseToKebabCase(relationshipName);
495
1177
 
496
1178
  // Related resource route: GET /:id/{relationship}
497
- routes[`/:id/${dasherizedName}`] = async (request: OrmRequest$) => {
1179
+ //
1180
+ // These generated routes are not wrapped by _withHooks, which is why they
1181
+ // were the least obvious two of the seven unguarded surfaces in #190.
1182
+ // They are still dispatched by @stonyx/rest-server as
1183
+ // `handler(req, getState(req))`, so `state` -- and therefore the filter
1184
+ // planted by auth() -- has always been available here; it was simply
1185
+ // never declared or read.
1186
+ routes[`/:id/${dasherizedName}`] = async (request: OrmRequest$, { filter }: { [key: string]: unknown } = {}) => {
498
1187
  const record = await store.find(model, getId(request.params)) as OrmRecord | undefined;
499
1188
  if (!record) return 404;
1189
+ // Filtering the PARENT: a caller who may not see the record may not see
1190
+ // what it is related to either.
1191
+ if (isDenied(filter, record)) return 404;
500
1192
 
501
1193
  const relatedData = record.__relationships[relationshipName];
502
1194
  const baseUrl = getBaseUrl(request);
@@ -518,9 +1210,10 @@ export default class OrmRequest extends Request {
518
1210
  };
519
1211
 
520
1212
  // Relationship linkage route: GET /:id/relationships/{relationship}
521
- routes[`/:id/relationships/${dasherizedName}`] = async (request: OrmRequest$) => {
1213
+ routes[`/:id/relationships/${dasherizedName}`] = async (request: OrmRequest$, { filter }: { [key: string]: unknown } = {}) => {
522
1214
  const record = await store.find(model, getId(request.params)) as OrmRecord | undefined;
523
1215
  if (!record) return 404;
1216
+ if (isDenied(filter, record)) return 404;
524
1217
 
525
1218
  const relatedData = record.__relationships[relationshipName];
526
1219
  const baseUrl = getBaseUrl(request);
@@ -551,32 +1244,98 @@ export default class OrmRequest extends Request {
551
1244
  };
552
1245
  }
553
1246
 
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;
558
-
559
- // If we reach here, relationship doesn't exist (valid ones were registered above)
560
- return 404;
561
- };
562
-
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;
567
-
568
- return 404;
569
- };
1247
+ // Catch-alls for invalid relationship names. Every valid relationship was
1248
+ // registered above, so reaching either of these means the relationship does
1249
+ // not exist and the answer is 404 regardless of the record.
1250
+ //
1251
+ // These deliberately carry NO access check and no store lookup. An earlier
1252
+ // revision of #190 added `if (isDenied(filter, record)) return 404` here for
1253
+ // symmetry with the seven real surfaces, but both branches returned 404, so
1254
+ // the guard was unobservable by construction -- a mutation deleting it
1255
+ // survived the entire suite because no test that could distinguish it can
1256
+ // exist. Unkillable code in an authorization diff reads as coverage and is
1257
+ // not, so it is gone; skipping the lookup also removes the timing difference
1258
+ // between an existing and a missing parent.
1259
+ //
1260
+ // IF THIS ROUTE EVER RETURNS ANYTHING OTHER THAN A CONSTANT 404, it becomes
1261
+ // the eighth surface and must filter the parent first, exactly like
1262
+ // `/:id/{relationship}` above.
1263
+ routes[`/:id/:relationship`] = async () => 404;
1264
+ routes[`/:id/relationships/:relationship`] = async () => 404;
570
1265
 
571
1266
  return routes;
572
1267
  }
573
1268
 
574
1269
  auth(request: OrmRequest$, state: { [key: string]: unknown }): number | undefined {
575
- const access = this.access(request);
1270
+ // A consumer `access()` that throws is a DENIAL, matching `isDenied` one
1271
+ // layer down. Unguarded it propagates to express's default handler, which
1272
+ // answers 500 -- and the documented sample itself can throw
1273
+ // (`request.originalUrl.split(...)` when originalUrl is absent), so the
1274
+ // failure mode is reachable by following the docs.
1275
+ // -------------------------------------------------------------------------
1276
+ // #202 -- hand the consumer the STRUCTURAL facts, not just the transport.
1277
+ //
1278
+ // Both members are already in hand here. `model` is `this.model`, the name
1279
+ // setup-rest-server mounted this route for; `operation` is the SAME
1280
+ // `methodAccessMap` lookup the permission-array branch at the bottom of
1281
+ // this method performs, so the predicate form and the array form cannot
1282
+ // answer differently about the same request.
1283
+ //
1284
+ // NEITHER IS DERIVED FROM THE REQUEST TARGET, and that is the whole point.
1285
+ // Deriving `model` here from `request.baseUrl` (or from the mounted route
1286
+ // name, or from `getPluralName(this.model)`) would move all five fail-open
1287
+ // variants listed in this file's header OUT of the consumer and INTO the
1288
+ // framework, where every consumer inherits them at once. `this.model` is
1289
+ // assigned once at mount time and no request can influence it.
1290
+ //
1291
+ // `operation` is left UNDEFINED for a method with no entry in
1292
+ // `methodAccessMap`, rather than defaulted. Express delivers HEAD to the
1293
+ // GET handler, so an unmapped method really does reach this line; a
1294
+ // `?? 'read'` here would hand the consumer a fabricated authorisation fact
1295
+ // and turn an unclassified request into an authorised one. Undefined is
1296
+ // the honest answer.
1297
+ //
1298
+ // `record` is deliberately absent -- see `AccessContext` in
1299
+ // src/types/orm-types.ts. Nothing is fetched at this point and adding a
1300
+ // lookup here would put a store read in the middle of an authorization
1301
+ // path. The function return shape below IS the per-record hook.
1302
+ // -------------------------------------------------------------------------
1303
+ const context: AccessContext = {
1304
+ model: this.model,
1305
+ operation: methodAccessMap[request.method],
1306
+ };
1307
+
1308
+ let access: AccessMethod;
1309
+ try {
1310
+ access = this.access(request, context);
1311
+ } catch (error) {
1312
+ // Same reasoning as `isDenied`: fail closed, but say so. An `access()`
1313
+ // that throws denies EVERY request to the collection, and a silent 403
1314
+ // wall is the hardest possible thing to diagnose from the outside.
1315
+ log.error?.(`[@stonyx/orm] access() threw for model "${this.model}" -- denying. ${error instanceof Error ? error.message : String(error)}`);
1316
+
1317
+ return 403; // Forbidden
1318
+ }
576
1319
 
577
1320
  if (!access) return 403;
578
- if (Array.isArray(access) && !access.includes(methodAccessMap[request.method])) return 403;
579
- if (typeof access === 'function') state.filter = access;
1321
+ if (typeof access === 'function') {
1322
+ state.filter = access;
1323
+ return undefined;
1324
+ }
1325
+ if (access === true) return undefined;
1326
+
1327
+ // `AccessMethod` declares `string` legal and it fell through every branch
1328
+ // above, returning undefined -- i.e. FULL CRUD, no filter. `return 'read'`
1329
+ // is the natural reading of a type that lists `string` first, and it
1330
+ // granted DELETE. A bare string is one permission, not a grant of all four.
1331
+ const permitted = typeof access === 'string' ? [access] : access;
1332
+
1333
+ // Anything that is not a permission array by this point -- an object, a
1334
+ // number, a Symbol -- is a consumer mistake, and the only safe reading of a
1335
+ // shape the contract does not define is a denial. Fail CLOSED.
1336
+ if (!Array.isArray(permitted)) return 403;
1337
+ if (!permitted.includes(methodAccessMap[request.method])) return 403;
1338
+
580
1339
  return undefined;
581
1340
  }
582
1341
  }