@stonyx/orm 0.3.2-alpha.5 → 0.3.2-alpha.51

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 (48) hide show
  1. package/README.md +395 -10
  2. package/config/environment.js +99 -12
  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/main.js +10 -0
  13. package/dist/manage-record.js +34 -3
  14. package/dist/mysql/connection.d.ts +1 -0
  15. package/dist/mysql/mysql-db.d.ts +8 -0
  16. package/dist/mysql/mysql-db.js +44 -10
  17. package/dist/orm-request.d.ts +60 -0
  18. package/dist/orm-request.js +634 -47
  19. package/dist/postgres/connection.d.ts +1 -0
  20. package/dist/postgres/connection.js +8 -6
  21. package/dist/postgres/postgres-db.d.ts +8 -0
  22. package/dist/postgres/postgres-db.js +44 -10
  23. package/dist/record.js +7 -5
  24. package/dist/relationships.js +1 -1
  25. package/dist/serializer.js +38 -2
  26. package/dist/store.d.ts +13 -1
  27. package/dist/store.js +65 -6
  28. package/dist/types/orm-types.d.ts +11 -0
  29. package/package.json +16 -7
  30. package/src/commands.ts +43 -0
  31. package/src/dynamodb/connection.ts +50 -0
  32. package/src/dynamodb/dynamodb-db.ts +811 -0
  33. package/src/dynamodb/operation-builder.ts +202 -0
  34. package/src/dynamodb/type-map.ts +54 -0
  35. package/src/main.ts +10 -0
  36. package/src/manage-record.ts +41 -9
  37. package/src/mysql/connection.ts +1 -0
  38. package/src/mysql/mysql-db.ts +44 -12
  39. package/src/orm-request.ts +644 -45
  40. package/src/postgres/connection.ts +10 -6
  41. package/src/postgres/postgres-db.ts +44 -12
  42. package/src/record.ts +8 -5
  43. package/src/relationships.ts +1 -1
  44. package/src/serializer.ts +39 -2
  45. package/src/store.ts +68 -6
  46. package/src/types/orm-types.ts +12 -0
  47. package/src/types/stonyx.d.ts +7 -1
  48. package/config/environment.ts +0 -91
@@ -1,3 +1,63 @@
1
+ /**
2
+ * REST request handling and access enforcement for @stonyx/orm.
3
+ *
4
+ * ---------------------------------------------------------------------------
5
+ * DO NOT RECONSTRUCT THE REQUEST PATH INSIDE `access()`.
6
+ * ---------------------------------------------------------------------------
7
+ * `auth()` below hands your `access(request)` a raw transport artifact and asks
8
+ * you to work out which collection it addresses. Every attempt to do that by
9
+ * parsing the request target has failed OPEN. Five distinct variants of the
10
+ * same three-line example have now been found, each after the previous was
11
+ * fixed, by five different people:
12
+ *
13
+ * 1. `request.url` is mount-relative under `RestServer.mountRoute`, so a
14
+ * prefix match against it is ALWAYS false.
15
+ * 2. `request.originalUrl` carries the query string, so an anchored equality
16
+ * check misses `/owners?filter[age]=30`.
17
+ * 3. The router is a bare `express()` (`caseSensitive: false`) while a
18
+ * hand-written matcher is case-SENSITIVE, so `GET /OwNeRs/angela` walks
19
+ * past it. Router-side: abofs/stonyx-rest-server#47.
20
+ * 4. Under a configured `ORM_REST_ROUTE` a hard-coded `/owners` matches
21
+ * nothing -- environment-specifically, which is worse.
22
+ * 5. HTTP/1.1 permits an ABSOLUTE-FORM request-target. Express routes on
23
+ * `parseurl(req).pathname`, but `originalUrl` is the raw target, so
24
+ * `GET http://anything.example/owners/angela` reaches the handler with
25
+ * `originalUrl === 'http://anything.example/owners/angela'`. A `/owners`
26
+ * prefix match is false, `access()` falls through to whatever it returns
27
+ * last, and the record comes back in full. It walks past a hard
28
+ * `return false` deny the same way.
29
+ *
30
+ * The fix is not a sixth rule. It is to stop parsing:
31
+ *
32
+ * `request.baseUrl` is the mount Express ACTUALLY MATCHED when it dispatched
33
+ * the request. It carries no query string, it is not mount-relative, it is
34
+ * unaffected by absolute-form, and it already includes the configured
35
+ * `ORM_REST_ROUTE` prefix -- so there is nothing to derive and nothing to
36
+ * join. Compare it lower-cased (the router matched case-insensitively) and
37
+ * fail CLOSED when it is absent. Use `request.path` -- mount-relative and
38
+ * query-free -- if you need to distinguish sub-paths.
39
+ *
40
+ * `?? ''` is not a defence. It converts an absent request target into an empty
41
+ * string, which matches no collection, which falls through to the permission
42
+ * array -- a total grant. An input you cannot identify must DENY.
43
+ *
44
+ * THAT IS STILL A STOPGAP. `baseUrl` closes all five variants, but it is a
45
+ * transport artifact being asked to stand in for a structural fact.
46
+ * THE REAL FIX IS abofs/stonyx-orm#202: `access()` should receive the model,
47
+ * the operation and the record. Prefer the array shape (`['read']`) or `false`
48
+ * until #202 lands; the function shape is what requires any matching at all.
49
+ *
50
+ * The enforcement gates in this file (GATE 0/1/2, the create rollback, the
51
+ * per-handler `isDenied` re-checks) are correct independently of that -- they
52
+ * enforce whatever predicate you return. The stopgap is the part where YOU have
53
+ * to work out which predicate to return.
54
+ *
55
+ * AND A PREDICATE IS NOT A GUARANTEE THAT A HIDDEN RECORD CANNOT BE MODIFIED.
56
+ * It is evaluated against the record the route is ADDRESSED TO, on that model
57
+ * only. A write to a DIFFERENT collection can still re-parent a hidden record
58
+ * and de-hide it -- abofs/stonyx-orm#207, which is blocked on #202 and #196.
59
+ * See `### Known limitations` in README.
60
+ */
1
61
  import { Request } from '@stonyx/rest-server';
2
62
  import Orm, { store, createRecord, updateRecord } from '@stonyx/orm';
3
63
  import { camelCaseToKebabCase } from '@stonyx/utils/string';
@@ -5,6 +65,7 @@ import { getPluralName } from './plural-registry.js';
5
65
  import { getBeforeHooks, getAfterHooks } from './hooks.js';
6
66
  import type { HookContext } from './hooks.js';
7
67
  import config from 'stonyx/config';
68
+ import log from 'stonyx/log';
8
69
  import type { OrmRecord } from './types/orm-types.js';
9
70
  import { isOrmRecord } from './utils.js';
10
71
 
@@ -84,12 +145,109 @@ function getBaseUrl(request: OrmRequest$): string {
84
145
  return `${protocol}://${host}`;
85
146
  }
86
147
 
148
+ /**
149
+ * The ONE coercion from a caller-supplied id to the key the store holds it
150
+ * under. Every id-bearing surface in this file goes through it, and none has a
151
+ * copy: `getId()` (URL params), `normalizeBodyId()` (JSON body), and the
152
+ * post-create `context.record` lookup in `_withHooks`.
153
+ *
154
+ * WHY IT IS SHARED RATHER THAN DUPLICATED. `getId()` and `normalizeBodyId()`
155
+ * each had their own arithmetic, and they disagreed: `parseInt(id)` versus
156
+ * `parseInt(id, 10)`. On a hex-shaped id that is a two-record difference --
157
+ *
158
+ * GET /animals/0x2391 -> record 9105 (getId -> parseInt('0x2391') = 9105)
159
+ * POST /animals {"id":"0x2391"} -> lookup under 0 (normalize -> parseInt('0x2391',10) = 0)
160
+ * -> a MISS, so the duplicate check was skipped and
161
+ * createRecord OVERWROTE 9105 in place, answering 200
162
+ *
163
+ * -- a narrower form of the raw-versus-normalised divergence that the body-id
164
+ * normalisation was added to close, reintroduced by the fix for it. Two
165
+ * coercions that must agree cannot be kept in agreement by review; they have to
166
+ * be one function. Pinned by assertion 43.
167
+ *
168
+ * The third copy was found later and in a quieter place: `_withHooks` populated
169
+ * `context.record` for `create` with `isNaN(id) ? id : parseInt(id)` -- this
170
+ * function's body, inlined verbatim, feeding `store.get`. It was equivalent on
171
+ * every input reachable there, which is exactly what the two that DID diverge
172
+ * looked like until someone tried a hex id.
173
+ *
174
+ * `parseInt` and not `Number`, deliberately, and the anchor is NOT `getId`.
175
+ * It is `src/transforms.ts:7` -- `number: (value) => parseInt(value as string)`,
176
+ * also radix-less -- because that transform is what actually produces the store
177
+ * KEY a record is filed under. `getId` merely agrees with it. They differ from
178
+ * `Number` on `'1e3'` (1 vs 1000) and `'9105.5'` (9105 vs 9105.5), so switching
179
+ * this function to `Number` would make the lookup key disagree with the landing
180
+ * key on those shapes.
181
+ *
182
+ * THE CHANGE THAT WOULD BREAK THIS: adding a radix to `transforms.number`
183
+ * (`parseInt(value, 10)`). That is a one-word edit in a file with no connection
184
+ * to authorization, it would silently reopen the hex divergence in the other
185
+ * direction, and this comment would still read as correct. Assertion 45 pins
186
+ * the transform's radix-less shape directly, so that edit turns a test red
187
+ * rather than shipping.
188
+ *
189
+ * The reason `parseInt` is safe here is the `isNaN` gate in front of it:
190
+ * `parseInt('9105h')` is `9105`, and truncating a partially-valid id into a
191
+ * DIFFERENT VALID key is exactly how a collision lookup gets skipped. The gate
192
+ * rejects it as a string instead, so nothing is ever truncated. That gate, not
193
+ * the parser, is the load-bearing half -- assertion 43 pins it.
194
+ */
195
+ function coerceId(id: string): string | number {
196
+ if (isNaN(id as unknown as number)) return id;
197
+
198
+ return parseInt(id);
199
+ }
200
+
87
201
  function getId(params: { id?: string; [key: string]: unknown }): string | number {
88
202
  const id = params.id;
89
203
  if (!id) return '';
90
- if (isNaN(id as unknown as number)) return id;
91
204
 
92
- return parseInt(id);
205
+ return coerceId(id);
206
+ }
207
+
208
+ /**
209
+ * Normalise a caller-supplied BODY id to the key the store will hold it under.
210
+ *
211
+ * `getId()` above is params-shaped: it takes `{ id?: string }` off the URL,
212
+ * where the value is always a string and a falsy one means "no id". A JSON body
213
+ * id is neither -- it can arrive as a number, and `0` is a legitimate id that
214
+ * `getId()` would flatten to `''`.
215
+ *
216
+ * WHY THIS EXISTS AT ALL. createHandler used to look the collision up with the
217
+ * RAW body value while every other surface normalised through `getId()`. The
218
+ * store is a Map keyed by the coerced value, so `store.find(model, '21')` misses
219
+ * the entry held under `21` and the duplicate check is skipped by typing the id
220
+ * as a string. On `dev` that silently overwrote the colliding record and
221
+ * answered 200; combined with the denied-create rollback added for #190 it
222
+ * became an unauthenticated DELETE of any id. Normalising here is half of that
223
+ * fix -- see the rollback in createHandler for the other half.
224
+ *
225
+ * It shares `coerceId` with `getId` so the two surfaces cannot drift apart
226
+ * again, and differs from `getId` in exactly ONE place, below.
227
+ */
228
+ function normalizeBodyId(id: string | number): string | number {
229
+ // Non-strings pass through untouched: a JSON body id can arrive as a number,
230
+ // and `getId`'s falsy-flatten must NOT apply to it -- `0` is a legitimate id
231
+ // and `getId` would turn it into `''`. (assertion 30 sweeps id `0`.)
232
+ if (typeof id !== 'string') return id;
233
+
234
+ // THE ONE DIVERGENCE FROM `getId`, and it mirrors rather than contradicts it:
235
+ // `getId` maps a falsy param to `''`, and `''` is the only string a body can
236
+ // carry that means "no id" -- `createRecord` treats it as absent and assigns a
237
+ // server id. Coercing it instead would make it address a real slot, because
238
+ // `parseInt('')` is `NaN` and a record CAN be held under `NaN` (a truthy but
239
+ // non-numeric id such as `' '` survives `assignRecordId`'s falsy guard and
240
+ // then NaNs in the id transform). So `POST {"id":""}` would answer 409 against
241
+ // an unrelated record it never named. Pinned by assertion 44.
242
+ //
243
+ // Note what is deliberately NOT special-cased here any more: whitespace.
244
+ // `id.trim() === ''` used to short-circuit `' '` as well, which made the
245
+ // body surface DISAGREE with the URL surface -- `getId({id:' '})` is `NaN`,
246
+ // so `' '` addresses the NaN slot on every other route while the collision
247
+ // lookup missed it. Same class of bug as the hex divergence above.
248
+ if (id === '') return id;
249
+
250
+ return coerceId(id);
93
251
  }
94
252
 
95
253
  function buildResponse(
@@ -251,6 +409,40 @@ function createFilterPredicate(filters: Filter[]): ((record: { [key: string]: un
251
409
  });
252
410
  }
253
411
 
412
+ /**
413
+ * A function-style `access` return is a per-record predicate, and it is only
414
+ * meaningful if every surface that can hand a record to a caller consults it.
415
+ * Before #190 exactly one of seven did.
416
+ *
417
+ * Enforcement is deliberately post-fetch. `access` returns an opaque JS
418
+ * predicate and `store.findAll(model, conditions)` accepts only an equality
419
+ * conditions object that the SQL drivers translate to a WHERE clause, so
420
+ * query-layer enforcement would require a breaking change to the published
421
+ * `access` contract. That belongs in #197, not in a security patch. Six of the
422
+ * seven surfaces fetch by primary key anyway, so this costs exactly one row.
423
+ */
424
+ function isDenied(filter: unknown, record: unknown): boolean {
425
+ if (typeof filter !== 'function') return false;
426
+
427
+ // A predicate that throws is treated as a denial. Unguarded, a throw escapes
428
+ // to express's default handler, which answers 500 (with a stack trace outside
429
+ // NODE_ENV=production) while a missing id still answers 404 -- so a
430
+ // record-dependent throw re-separates "hidden" from "does not exist" and
431
+ // hands back the oracle this whole change exists to close.
432
+ try {
433
+ return !(filter as (record: unknown) => boolean)(record);
434
+ } catch (error) {
435
+ // Denied, but not silently. A consumer predicate that throws on every
436
+ // record turns the whole collection into a 404 wall, and with no
437
+ // diagnostic that is indistinguishable from an empty database. `stonyx/log`
438
+ // is the module convention (see setup-rest-server.ts); optional-call
439
+ // because a consumer may not have configured the log types.
440
+ log.error?.(`[@stonyx/orm] access filter threw for model -- denying. ${error instanceof Error ? error.message : String(error)}`);
441
+
442
+ return true;
443
+ }
444
+ }
445
+
254
446
  export default class OrmRequest extends Request {
255
447
  model: string;
256
448
  access: (request: unknown) => AccessMethod;
@@ -287,9 +479,13 @@ export default class OrmRequest extends Request {
287
479
  });
288
480
  };
289
481
 
290
- const getSingleHandler: HandlerFn = async (request) => {
482
+ const getSingleHandler: HandlerFn = async (request, { filter }) => {
291
483
  const record = await store.find(model, getId(request.params)) as OrmRecord | undefined;
292
484
  if (!record) return 404;
485
+ // 404, never 403: the status for "exists but filtered out" must be
486
+ // identical to "does not exist", or the fix trades an authorization
487
+ // bypass for a narrower existence oracle.
488
+ if (isDenied(filter, record)) return 404;
293
489
 
294
490
  const fieldsMap = parseFields(request.query);
295
491
  const modelFields = fieldsMap.get(pluralizedModel) || fieldsMap.get(model);
@@ -301,7 +497,7 @@ export default class OrmRequest extends Request {
301
497
  });
302
498
  };
303
499
 
304
- const createHandler: HandlerFn = async ({ body, query }) => {
500
+ const createHandler: HandlerFn = async ({ body, query }, { filter }) => {
305
501
  const { type, id, attributes, relationships: rels } = (body?.data || {}) as {
306
502
  type?: string;
307
503
  id?: string | number;
@@ -314,14 +510,113 @@ export default class OrmRequest extends Request {
314
510
  const fieldsMap = parseFields(query);
315
511
  const modelFields = fieldsMap.get(pluralizedModel) || fieldsMap.get(model);
316
512
 
317
- // Check for duplicate ID
318
- if (id !== undefined && await store.find(model, id)) return 409; // Conflict
513
+ // GATE 0 -- the POST existence oracle.
514
+ //
515
+ // The duplicate check runs before the filter and `store.find` sees hidden
516
+ // records, so POST leaks existence through its STATUS. A previous revision
517
+ // filtered the collision status (403 when the colliding record is denied,
518
+ // 409 when it is visible) and that is NOT sufficient, because the status
519
+ // of a create is a third outcome. With a payload the caller is permitted
520
+ // to create -- the normative case for a per-tenant filter, and the case an
521
+ // attacker picks -- all three are distinguishable in ONE request per id:
522
+ //
523
+ // POST /animals {id:22, owner:'gina'} -> 403 a HIDDEN record has this id
524
+ // POST /animals {id:9500, owner:'gina'} -> 200 this id is FREE
525
+ // POST /animals {id:8, owner:'gina'} -> 409 a VISIBLE record has this id
526
+ //
527
+ // Filtering only the collision status narrows that to callers who cannot
528
+ // create a record they are allowed to see. It does not close it.
529
+ //
530
+ // It cannot be closed while a caller both chooses the id and learns
531
+ // whether the create succeeded: a successful create must answer
532
+ // differently from a refused one. So when a per-record filter is in force
533
+ // the caller does not get to choose the id at all. The refusal is
534
+ // UNCONDITIONAL and happens BEFORE any store lookup, so no status, and no
535
+ // lookup cost, can depend on whether that id exists. 403 -- the same
536
+ // status as a denied create -- so the two cannot be separated either.
537
+ //
538
+ // BOTH HALVES OF THAT ARE PINNED, because both were once asserted here and
539
+ // pinned by nothing:
540
+ //
541
+ // status -- assertion 22 sweeps payload x id x id-type, plus `null`.
542
+ // latency -- assertion 41 asserts NO `store.find` is issued on this
543
+ // path. Moving the refusal to after a lookup and returning
544
+ // the same 403 left the suite green while re-opening a
545
+ // hit-versus-miss timing difference on every id-bearing POST,
546
+ // which is what would turn #197 from a ~0.06ms post-fetch
547
+ // residual into a live timing oracle on create.
548
+ //
549
+ // AND THE GUARANTEE IS ONLY AS WIDE AS THE CHANNELS IT COVERS. It reads on
550
+ // the `id` member of the resource object, so it holds only while that is
551
+ // the ONLY way a caller id can reach `createRecord`. It was not: the
552
+ // relationships loop below re-admitted one under `key === "id"` and the
553
+ // gate never fired. Both strips -- `attributes.id` and `relationships.id`
554
+ // -- are therefore part of THIS gate, not tidiness, and assertion 39 pins
555
+ // them. Adding a third channel without a strip re-opens the oracle.
556
+ //
557
+ // Scoped to function-style `access` because that is exactly the population
558
+ // the oracle exists for: with no per-record filter there are no hidden
559
+ // records, and 409 discloses nothing GET /:id does not already.
560
+ //
561
+ // RESIDUALS, stated rather than implied.
562
+ //
563
+ // - a caller can still learn that a collection HAS a per-record filter
564
+ // (403 rather than 409/200 for an id-bearing POST). That discloses a
565
+ // configuration fact, not a record.
566
+ // - this gate is about ids arriving on THIS model's create route. It
567
+ // says nothing about a write to ANOTHER collection: a `POST /owners`
568
+ // carrying `relationships: {pets: {data: {id: 21}}}` -- or
569
+ // `attributes: {pets: [21, 22]}`, which never enters the
570
+ // relationships loop at all -- re-parents hidden animal 21 onto an
571
+ // owner the caller may write, which changes the very field the
572
+ // animals predicate reads and DE-HIDES it. Blocking that needs animal
573
+ // 21 checked against the ANIMAL model's predicate while servicing an
574
+ // OWNERS route, i.e. cross-model access resolution: abofs/stonyx-orm
575
+ // #207, blocked on #202 (`access` receives the model structurally)
576
+ // and #196 (setup-rest-server discards the model->predicate map at
577
+ // boot). NOT closed here, and no comment in this file may say it is.
578
+ //
579
+ // See README `### Known limitations`.
580
+ if (id !== undefined) {
581
+ if (typeof filter === 'function') return 403; // Forbidden
582
+
583
+ // `normalizeBodyId`, not the raw value: a string-typed id misses the
584
+ // store's numeric key, which skipped this check entirely.
585
+ const existing = await store.find(model, normalizeBodyId(id));
586
+ if (existing) return 409; // Conflict
587
+ }
319
588
 
320
589
  const { id: _ignoredId, ...sanitizedAttributes } = attributes || {};
321
590
 
322
- // Extract relationship IDs from JSON:API relationships object
591
+ // Extract relationship IDs from JSON:API relationships object.
592
+ //
593
+ // `key` comes VERBATIM from the request body, so `id` is stripped here for
594
+ // exactly the same reason it is stripped from `attributes` on the line
595
+ // above -- and it must be, or GATE 0 is walked around by moving one field:
596
+ //
597
+ // POST /animals {"id":21, ...} -> 403 GATE 0 fires
598
+ // POST /animals {"relationships":{"id":{"data":{"id":21}}},
599
+ // "attributes":{"owner":"gina"}} -> 200 BYPASS
600
+ //
601
+ // Top-level `id` stayed `undefined`, so GATE 0 never fired and the
602
+ // collision lookup never ran; `createRecord` took its last-entry-wins
603
+ // branch, overwrote hidden record 21 in place and reset its `owner` to a
604
+ // value the caller chose -- de-hiding it permanently. That is #190 itself,
605
+ // on the create surface. Pinned by assertion 39.
606
+ //
607
+ // The `id` member of the resource object is now the ONLY channel a caller
608
+ // id can arrive on FOR THIS MODEL'S OWN CREATE ROUTE, which is what makes
609
+ // GATE 0's guarantee checkable rather than merely asserted. It is not a
610
+ // statement about the record's reachability in general -- a relationship
611
+ // write on another collection reaches it without ever touching this
612
+ // handler (abofs/stonyx-orm#207). INHERITED from `dev`, which carries this
613
+ // loop verbatim; the general form -- the loop accepts any key, not just
614
+ // `id`, so a body key that is not a declared relationship is still
615
+ // mass-assigned -- is abofs/stonyx-orm#204.
323
616
  if (rels) {
324
617
  for (const [key, value] of Object.entries(rels)) {
618
+ if (key === 'id') continue;
619
+
325
620
  const relData = value?.data;
326
621
  if (relData && relData.id !== undefined) {
327
622
  (sanitizedAttributes as { [key: string]: unknown })[key] = relData.id;
@@ -330,16 +625,95 @@ export default class OrmRequest extends Request {
330
625
  }
331
626
 
332
627
  const recordAttributes = id !== undefined ? { id, ...sanitizedAttributes } : sanitizedAttributes;
628
+
629
+ // Slot count BEFORE the write. `createRecord` writes to the store before
630
+ // the predicate can run, and the rollback below must be able to prove the
631
+ // slot it removes is one THIS REQUEST created. Identity alone cannot
632
+ // prove it: when `assignRecordId` lands on an occupied id, `createRecord`
633
+ // mutates the existing OrmRecord IN PLACE, so `store.get(...) === record`
634
+ // is true for a record the request did not create. The map's size is the
635
+ // only O(1) signal that distinguishes an insert from an overwrite.
636
+ const slotsBefore = store.get(model)?.size ?? 0;
637
+
333
638
  const created = createRecord(model, recordAttributes as { [key: string]: unknown }, { serialize: false, _skipAutoPersist: true });
334
639
  const record = isOrmRecord(created) ? created : null;
335
640
  if (!record) return 500;
336
641
 
642
+ const createdNewSlot = (store.get(model)?.size ?? 0) > slotsBefore;
643
+
644
+ // 403 here, NOT 404. The oracle argument does not apply to create: there
645
+ // is no pre-existing record whose existence could leak, the caller
646
+ // supplied the attributes, and 404 on a mounted collection route is
647
+ // indistinguishable from "model not mounted" -- a genuinely different
648
+ // failure a developer needs to diagnose.
649
+ //
650
+ // The rollback is not optional. createRecord writes to the store BEFORE
651
+ // the predicate can run, so returning 403 alone would leave the record
652
+ // behind: a worse bug than the bypass being fixed.
653
+ if (isDenied(filter, record)) {
654
+ // ROLL BACK BY IDENTITY, NEVER BY ID. `store.remove(model, record.id)`
655
+ // on its own is a write primitive keyed by a value the caller may have
656
+ // supplied: with the raw-id collision bypass above, a denied
657
+ // `POST {"id":"21"}` answered 403 and DELETED hidden record 21 -- an
658
+ // unauthenticated deletion primitive across the whole id space, created
659
+ // by adding a rollback to a lookup that could be skipped.
660
+ //
661
+ // Both conditions are required and neither implies the other:
662
+ // createdNewSlot -- the store grew, so this request inserted rather
663
+ // than overwrote. Guards `assignRecordId` picking an
664
+ // id that is already taken (it returns
665
+ // last-INSERTED + 1, not max + 1, so a store whose
666
+ // insertion order is not ascending collides) -- see
667
+ // abofs/stonyx-orm#203.
668
+ // identity -- the slot still holds the object we just created,
669
+ // so nothing between createRecord and here replaced
670
+ // it. Deleting this half SURVIVES the suite, and it
671
+ // is kept anyway. WHY IT IS REDUNDANT: there is no
672
+ // `await` anywhere between `slotsBefore` and
673
+ // `store.remove` -- the whole window is synchronous,
674
+ // so it is atomic under Node's event loop; before-
675
+ // `create` hooks run BEFORE the handler
676
+ // (`_withHooks` runs its hook loop ahead of
677
+ // `await handler(...)`), and a consumer predicate
678
+ // inside `isDenied` runs AFTER `createdNewSlot` is
679
+ // computed and cannot flip it. That is a property of
680
+ // THIS function, not of GATE 0 -- an earlier note
681
+ // credited GATE 0, which was both wrong (a caller id
682
+ // reached createRecord through the relationships
683
+ // loop, #204) and the wrong kind of reason: a guard
684
+ // justified on code sixty lines upstream gets
685
+ // silently re-armed when that code moves.
686
+ // SO IT BECOMES REACHABLE IF AN `await` IS
687
+ // INTRODUCED HERE, which is the change a future
688
+ // editor would actually make. Stated here rather
689
+ // than by reference: `docs/` is not in `files`, so
690
+ // a pointer into it resolves to nothing for anyone
691
+ // who installed this package. README carries the
692
+ // consumer-facing half.
693
+ if (createdNewSlot && store.get(model, record.id as string | number) === record) {
694
+ store.remove(model, record.id as string | number, { _skipAutoPersist: true });
695
+ }
696
+
697
+ return 403;
698
+ }
699
+
337
700
  return { data: record.toJSON?.({ fields: modelFields }) };
338
701
  };
339
702
 
340
- const updateHandler: HandlerFn = async ({ body, params }) => {
703
+ const updateHandler: HandlerFn = async ({ body, params }, { filter }) => {
341
704
  const found = await store.find(model, getId(params));
342
705
  if (!found || !isOrmRecord(found)) return 404;
706
+ // Checked BEFORE any attribute is applied. 404 rather than 403 for the
707
+ // same reason as GET /:id -- 403 would disclose both that the record
708
+ // exists and that this caller specifically is excluded.
709
+ //
710
+ // NOT redundant behind GATE 1, and not defence in depth either: GATE 1's
711
+ // verdict is computed BEFORE the before-hook loop runs, and a before-hook
712
+ // is a published extension point that can change the answer -- by
713
+ // mutating the record, or against a predicate that closes over
714
+ // per-request state. This is the only re-evaluation after that window.
715
+ // Pinned by assertion 32; deleting it turns a 404 into an applied update.
716
+ if (isDenied(filter, found)) return 404;
343
717
  const record = found;
344
718
  const { attributes, relationships: rels } = (body?.data || {}) as {
345
719
  attributes?: { [key: string]: unknown };
@@ -362,6 +736,19 @@ export default class OrmRequest extends Request {
362
736
  if (rels) {
363
737
  const relUpdates: { [key: string]: unknown } = {};
364
738
  for (const [key, value] of Object.entries(rels)) {
739
+ // The same missing key filter as createHandler's, and as the
740
+ // attribute loop directly above -- which already had it, while this
741
+ // loop did not. A PATCH carrying
742
+ // `relationships:{"id":{"data":{"id":9101}}}` reached `updateRecord`
743
+ // and RE-KEYED the record: the object held under store key 9102 then
744
+ // reported id 9101, so a visible record claimed a hidden record's
745
+ // identity on every surface that reads `record.id` rather than the map
746
+ // key. Gated by GATE 1 on the addressed record, so it is store
747
+ // corruption rather than a filter bypass -- but it is the same one-line
748
+ // omission two handlers apart. Pinned by assertion 40; INHERITED from
749
+ // `dev`; abofs/stonyx-orm#204.
750
+ if (key === 'id') continue;
751
+
365
752
  const relData = value?.data;
366
753
  if (relData && relData.id !== undefined) {
367
754
  relUpdates[key] = relData.id;
@@ -375,8 +762,31 @@ export default class OrmRequest extends Request {
375
762
  return { data: record.toJSON?.() };
376
763
  };
377
764
 
378
- const deleteHandler: HandlerFn = ({ params }) => {
379
- store.remove(model, getId(params));
765
+ const deleteHandler: HandlerFn = async ({ params }, { filter }) => {
766
+ // Coerced ONCE. `getId(params)` was evaluated twice here -- once to find
767
+ // the record and once to remove it -- and a coercion evaluated repeatedly
768
+ // is a coercion that can be edited in one place and not the other, which
769
+ // is the defect `coerceId` exists to prevent.
770
+ const recordId = getId(params);
771
+ const record = await store.find(model, recordId) as OrmRecord | undefined;
772
+
773
+ // BEHAVIOUR CHANGE (#190): a DELETE of a record that never existed
774
+ // returned 204 before this change. It now returns 404, matching the
775
+ // denied case below. This is deliberate and load-bearing -- if a denied
776
+ // delete returned 404 while a missing one returned 204, the pair would be
777
+ // a perfect existence oracle and the whole fix would be worthless.
778
+ // Returning 204 for a denied delete was rejected instead: it falsely
779
+ // reports success for a request that changed nothing.
780
+ if (!record) return 404;
781
+ // Re-evaluated after the before-hook loop, exactly as in updateHandler --
782
+ // GATE 1 decided before the hooks ran. Pinned by assertion 33; deleting it
783
+ // turns a 404 into a destroyed record.
784
+ if (isDenied(filter, record)) return 404;
785
+
786
+ // Removed by the id of the record actually fetched, not by re-deriving it
787
+ // from the params a second time: the record the filter tested and the
788
+ // record removed are then provably the same one.
789
+ store.remove(model, record.id as string | number, { _skipAutoPersist: true });
380
790
  return 204;
381
791
  };
382
792
 
@@ -405,9 +815,65 @@ export default class OrmRequest extends Request {
405
815
  }
406
816
  }
407
817
 
408
- // Wraps a handler with before/after hook execution
818
+ // Wraps a handler with before/after hook execution.
819
+ //
820
+ // ===========================================================================
821
+ // TWO AUTHORIZATION GATES, AND EVERY EXECUTOR SITS BEHIND ONE OF THEM (#190)
822
+ //
823
+ // The defect this function was fixed for is NOT "a delete persists past a
824
+ // 404". It is that _withHooks has SEVERAL executors downstream of the
825
+ // handler, and originally the handler's response gated none of them. Three
826
+ // exist today:
827
+ //
828
+ // 1. sqlDb.persist -- issues real SQL against the backing store
829
+ // 2. the after-hook pipeline -- the PUBLISHED consumer extension point;
830
+ // a cascade delete, a webhook, a search-index
831
+ // purge. `context.recordId` and
832
+ // `context.oldState` are populated for it.
833
+ // 3. Orm.db.save() -- a full serialize-and-write of the store
834
+ //
835
+ // Gating them one at a time is how this keeps regressing, so the rule is:
836
+ // compute denial ONCE at each point where it becomes knowable, and keep every
837
+ // executor downstream of a gate. If you add a fourth executor to this
838
+ // function, it goes below GATE 2 or it is a security bug.
839
+ //
840
+ // GATE 1 (pre-handler) is required because before-hooks and `context.oldState`
841
+ // run/are built BEFORE the handler can consult the filter. Without it a denied
842
+ // DELETE still handed the hidden record's full contents to consumer code.
843
+ // GATE 2 (post-handler) covers everything the handler's status can reach.
844
+ // ===========================================================================
409
845
  private _withHooks(operation: string, handler: HandlerFn): HandlerFn {
410
846
  return async (request: OrmRequest$, state: { [key: string]: unknown }) => {
847
+ // `|| {}` so this function behaves like the relationship routes below,
848
+ // which declare `state` with a `= {}` default. It is unkillable through
849
+ // the rest-server dispatcher, which always passes `getState(req)`; it is
850
+ // listed as such in the guards-redundant-by-construction table rather
851
+ // than left silently unkillable, and it defends the WHOLE function (the
852
+ // context, the snapshot and the handler call all read `callState`) rather
853
+ // than one destructure that the next line would throw past anyway.
854
+ const callState = (state || {}) as { [key: string]: unknown };
855
+
856
+ // ---------------------------------------------------------------------
857
+ // THE AUTHORIZATION SNAPSHOT. Read ONCE, here, before any consumer code
858
+ // can run.
859
+ //
860
+ // `callState` is the object `auth()` planted the filter in, and it is
861
+ // also handed to every before-hook as `context.state` -- a published,
862
+ // WRITABLE extension point. So `state.filter` is an INPUT to the
863
+ // authorization decision, not only an output channel, and re-reading it
864
+ // after the hook loop lets a consumer hook disarm the filter:
865
+ //
866
+ // beforeHook('get', 'animal', ctx => { delete ctx.state.filter })
867
+ // -> GET /animals/21 turned 404 into 200
868
+ // -> GET /animals turned 20 records into 22
869
+ //
870
+ // GATE 1 already used this snapshot, so writes held; the READ handlers
871
+ // re-destructured `filter` from the live bag and did not. Everything
872
+ // downstream now reads `filter` from here, and the handler is handed
873
+ // `handlerState` below -- never `callState`.
874
+ // ---------------------------------------------------------------------
875
+ const { filter } = callState as { filter?: unknown };
876
+
411
877
  // Build context object for hooks
412
878
  const context: HookContext = {
413
879
  model: this.model,
@@ -416,12 +882,37 @@ export default class OrmRequest extends Request {
416
882
  params: request.params,
417
883
  body: request.body,
418
884
  query: request.query,
419
- state,
885
+ // Deliberately the LIVE object: `redirect` and `pipe` are read back off
886
+ // it by @stonyx/rest-server after the handler returns, so hooks must be
887
+ // able to write to it. What must not happen is the authorization
888
+ // decision reading it back, which is what the snapshot above prevents.
889
+ state: callState,
420
890
  };
421
891
 
422
892
  // Capture old state for operations that modify data
423
893
  if (operation === 'update' || operation === 'delete') {
424
894
  const existingRecord = await store.find(this.model, getId(request.params)) as OrmRecord | undefined;
895
+
896
+ // GATE 1 -- pre-handler. This record fetch already happened for
897
+ // oldState, so the check is free.
898
+ //
899
+ // Returning here rather than letting updateHandler/deleteHandler
900
+ // produce the same 404 is the point: everything between here and there
901
+ // is an executor the caller is not authorized to reach.
902
+ // - context.oldState is a deep copy of the HIDDEN RECORD'S CONTENTS.
903
+ // Building it and handing it to a before-hook discloses exactly what
904
+ // the filter exists to hide.
905
+ // - context.recordId is populated for delete BEFORE the handler runs,
906
+ // which is the same shape as the sqlDb landmine one layer up:
907
+ // `afterHook('delete', ctx => cascadeDelete(ctx.recordId))` destroys
908
+ // children behind a correct 404.
909
+ // - a before-hook may return a value and short-circuit, which would
910
+ // otherwise return a response without the filter ever executing.
911
+ //
912
+ // 404, not 403, for the same reason as getSingleHandler: the status for
913
+ // "exists but filtered out" must equal "does not exist".
914
+ if (existingRecord && isDenied(filter, existingRecord)) return 404;
915
+
425
916
  if (existingRecord) {
426
917
  // Deep copy the record's data to preserve old state
427
918
  context.oldState = JSON.parse(JSON.stringify(existingRecord.__data || existingRecord));
@@ -441,11 +932,52 @@ export default class OrmRequest extends Request {
441
932
  }
442
933
 
443
934
  // Execute main handler
444
- const response = await handler(request, state);
935
+ // The handler receives the SNAPSHOT, never the live bag. `filter` is
936
+ // assigned LAST so it wins over anything a before-hook wrote to
937
+ // `callState.filter` -- including a `delete`, which the spread would
938
+ // otherwise carry through as an absent key. Every other key a hook adds
939
+ // is still visible to the handler; only the authorization input is
940
+ // pinned.
941
+ const handlerState = { ...callState, filter };
942
+ const response = await handler(request, handlerState);
943
+
944
+ // Set context.record for update BEFORE persist so SQL drivers can read it
945
+ if (operation === 'update' && (response as JsonApiResponse)?.data) {
946
+ context.record = store.get(this.model, getId(request.params));
947
+ }
445
948
 
446
- // Persist to SQL database for create/update (delete is handled by store.remove auto-persist)
949
+ // GATE 2 -- post-handler. A denied or failed handler returns a bare status
950
+ // integer, and no executor below may run for one.
951
+ //
952
+ // `>= 400` deliberately covers every failure status, not just the
953
+ // authorization ones: a 400 (POST with no `type`) and a 409 (duplicate id)
954
+ // are equally requests in which nothing happened, and a persist or a
955
+ // cascade hook for one of them is just as wrong.
956
+ // `Number.isInteger` is a TYPE guard, not a behaviour guard, and it is
957
+ // unkillable TODAY: the only non-integer a handler in this file can
958
+ // return is a `{ data, links }` object, and `{} >= 400` is `false` by JS
959
+ // coercion, so dropping it changes no reachable outcome. It is kept
960
+ // because `>=` coerces rather than rejects, and the shapes it coerces
961
+ // are not obvious -- `[500] >= 400` is TRUE, so a handler that one day
962
+ // returned an array would have every response read as a denial. Listed
963
+ // as an equivalent mutant rather than left to read as coverage; it
964
+ // becomes killable the moment a handler returns anything array-like or
965
+ // numeric-string-like.
966
+ const denied = Number.isInteger(response) && (response as number) >= 400;
967
+
968
+ // EXECUTOR 1 -- SQL persistence, for all write operations.
969
+ //
970
+ // `response` is passed to sqlDb.persist below, but it is dropped at the
971
+ // driver boundary: _persistDelete(modelName, context) never receives it
972
+ // and guards only on context.recordId -- which _withHooks set above,
973
+ // BEFORE the handler ran. Without this gate a correct 404 still issues
974
+ // DELETE FROM ... WHERE id = ? on every SQL backend.
975
+ //
976
+ // No file-backed test can observe that, because Orm.instance.sqlDb is
977
+ // null in file/directory mode. See the stubbed-sqlDb assertions in
978
+ // test/unit/access-filter-enforcement-test.ts.
447
979
  const sqlDb = Orm.instance.sqlDb;
448
- if (sqlDb && (operation === 'create' || operation === 'update')) {
980
+ if (sqlDb && WRITE_OPERATIONS.has(operation) && !denied) {
449
981
  await sqlDb.persist(operation, this.model, context, response);
450
982
  }
451
983
 
@@ -459,22 +991,45 @@ export default class OrmRequest extends Request {
459
991
  } else if (operation === 'create' && (response as JsonApiResponse)?.data && ((response as { data: { id?: unknown } }).data.id)) {
460
992
  // For create, get the record from store using the ID from the response
461
993
  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));
994
+ // `normalizeBodyId`, not a copy of its body. This line WAS
995
+ // `isNaN(id) ? id : parseInt(id)` -- `coerceId` inlined verbatim, a
996
+ // third coercion feeding a store lookup, sitting under a docblock that
997
+ // said neither surface had a copy. Equivalent on every input that can
998
+ // reach this truthy-guarded branch (`21`->`21`, `'21'`->`21`,
999
+ // `'angela'`->`'angela'`; `''` and `0` cannot reach it), so this is a
1000
+ // de-duplication rather than a behaviour change -- and that is the
1001
+ // point: the two that disagreed were equivalent on every input anyone
1002
+ // checked, too.
1003
+ context.record = store.get(this.model, normalizeBodyId(responseData.id) as string | number);
466
1004
  } else if (operation === 'delete') {
467
1005
  // For delete, the record may no longer exist, but we have oldState
468
1006
  context.recordId = getId(request.params);
469
1007
  }
470
1008
 
471
- // Run after hooks sequentially
472
- for (const hook of getAfterHooks(operation, this.model)) {
473
- await hook(context);
1009
+ // EXECUTOR 2 -- the after-hook pipeline. This is the published consumer
1010
+ // extension point (`afterHook` is exported from @stonyx/orm and from
1011
+ // ./hooks), so it is the executor with the widest possible blast radius:
1012
+ // a cascade delete, a webhook, a token revocation, a search-index purge.
1013
+ //
1014
+ // BEHAVIOUR CHANGE (#190): after-hooks no longer fire for a request that
1015
+ // failed. Previously `afterHook('delete', ...)` ran with a populated
1016
+ // context.recordId on a 404, so a consumer cascade destroyed children for
1017
+ // a request that deleted nothing. Firing a hook named "after<operation>"
1018
+ // for an operation that did not occur is a booby trap, and the denied case
1019
+ // is unreachable-before-#190 while the missing case is inherited debt --
1020
+ // both are closed by the same gate. `context.response` therefore only ever
1021
+ // carries a success status into a hook.
1022
+ if (!denied) {
1023
+ for (const hook of getAfterHooks(operation, this.model)) {
1024
+ await hook(context);
1025
+ }
474
1026
  }
475
1027
 
476
- // Auto-save DB after write operations when configured
477
- if (config.orm.db.autosave === 'onUpdate' && WRITE_OPERATIONS.has(operation)) {
1028
+ // EXECUTOR 3 -- file/directory autosave. Ungated this let an
1029
+ // unauthenticated caller force a full serialize-and-write of the entire
1030
+ // store on every DELETE of any id, with no record touched: amplification
1031
+ // rather than corruption, but the same root cause and the same fix.
1032
+ if (config.orm.db.autosave === 'onUpdate' && WRITE_OPERATIONS.has(operation) && !denied) {
478
1033
  await (Orm.db as { save(): Promise<void> }).save();
479
1034
  }
480
1035
 
@@ -494,9 +1049,19 @@ export default class OrmRequest extends Request {
494
1049
  const dasherizedName = camelCaseToKebabCase(relationshipName);
495
1050
 
496
1051
  // Related resource route: GET /:id/{relationship}
497
- routes[`/:id/${dasherizedName}`] = async (request: OrmRequest$) => {
1052
+ //
1053
+ // These generated routes are not wrapped by _withHooks, which is why they
1054
+ // were the least obvious two of the seven unguarded surfaces in #190.
1055
+ // They are still dispatched by @stonyx/rest-server as
1056
+ // `handler(req, getState(req))`, so `state` -- and therefore the filter
1057
+ // planted by auth() -- has always been available here; it was simply
1058
+ // never declared or read.
1059
+ routes[`/:id/${dasherizedName}`] = async (request: OrmRequest$, { filter }: { [key: string]: unknown } = {}) => {
498
1060
  const record = await store.find(model, getId(request.params)) as OrmRecord | undefined;
499
1061
  if (!record) return 404;
1062
+ // Filtering the PARENT: a caller who may not see the record may not see
1063
+ // what it is related to either.
1064
+ if (isDenied(filter, record)) return 404;
500
1065
 
501
1066
  const relatedData = record.__relationships[relationshipName];
502
1067
  const baseUrl = getBaseUrl(request);
@@ -518,9 +1083,10 @@ export default class OrmRequest extends Request {
518
1083
  };
519
1084
 
520
1085
  // Relationship linkage route: GET /:id/relationships/{relationship}
521
- routes[`/:id/relationships/${dasherizedName}`] = async (request: OrmRequest$) => {
1086
+ routes[`/:id/relationships/${dasherizedName}`] = async (request: OrmRequest$, { filter }: { [key: string]: unknown } = {}) => {
522
1087
  const record = await store.find(model, getId(request.params)) as OrmRecord | undefined;
523
1088
  if (!record) return 404;
1089
+ if (isDenied(filter, record)) return 404;
524
1090
 
525
1091
  const relatedData = record.__relationships[relationshipName];
526
1092
  const baseUrl = getBaseUrl(request);
@@ -551,32 +1117,65 @@ export default class OrmRequest extends Request {
551
1117
  };
552
1118
  }
553
1119
 
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
- };
1120
+ // Catch-alls for invalid relationship names. Every valid relationship was
1121
+ // registered above, so reaching either of these means the relationship does
1122
+ // not exist and the answer is 404 regardless of the record.
1123
+ //
1124
+ // These deliberately carry NO access check and no store lookup. An earlier
1125
+ // revision of #190 added `if (isDenied(filter, record)) return 404` here for
1126
+ // symmetry with the seven real surfaces, but both branches returned 404, so
1127
+ // the guard was unobservable by construction -- a mutation deleting it
1128
+ // survived the entire suite because no test that could distinguish it can
1129
+ // exist. Unkillable code in an authorization diff reads as coverage and is
1130
+ // not, so it is gone; skipping the lookup also removes the timing difference
1131
+ // between an existing and a missing parent.
1132
+ //
1133
+ // IF THIS ROUTE EVER RETURNS ANYTHING OTHER THAN A CONSTANT 404, it becomes
1134
+ // the eighth surface and must filter the parent first, exactly like
1135
+ // `/:id/{relationship}` above.
1136
+ routes[`/:id/:relationship`] = async () => 404;
1137
+ routes[`/:id/relationships/:relationship`] = async () => 404;
570
1138
 
571
1139
  return routes;
572
1140
  }
573
1141
 
574
1142
  auth(request: OrmRequest$, state: { [key: string]: unknown }): number | undefined {
575
- const access = this.access(request);
1143
+ // A consumer `access()` that throws is a DENIAL, matching `isDenied` one
1144
+ // layer down. Unguarded it propagates to express's default handler, which
1145
+ // answers 500 -- and the documented sample itself can throw
1146
+ // (`request.originalUrl.split(...)` when originalUrl is absent), so the
1147
+ // failure mode is reachable by following the docs.
1148
+ let access: AccessMethod;
1149
+ try {
1150
+ access = this.access(request);
1151
+ } catch (error) {
1152
+ // Same reasoning as `isDenied`: fail closed, but say so. An `access()`
1153
+ // that throws denies EVERY request to the collection, and a silent 403
1154
+ // wall is the hardest possible thing to diagnose from the outside.
1155
+ log.error?.(`[@stonyx/orm] access() threw for model "${this.model}" -- denying. ${error instanceof Error ? error.message : String(error)}`);
1156
+
1157
+ return 403; // Forbidden
1158
+ }
576
1159
 
577
1160
  if (!access) return 403;
578
- if (Array.isArray(access) && !access.includes(methodAccessMap[request.method])) return 403;
579
- if (typeof access === 'function') state.filter = access;
1161
+ if (typeof access === 'function') {
1162
+ state.filter = access;
1163
+ return undefined;
1164
+ }
1165
+ if (access === true) return undefined;
1166
+
1167
+ // `AccessMethod` declares `string` legal and it fell through every branch
1168
+ // above, returning undefined -- i.e. FULL CRUD, no filter. `return 'read'`
1169
+ // is the natural reading of a type that lists `string` first, and it
1170
+ // granted DELETE. A bare string is one permission, not a grant of all four.
1171
+ const permitted = typeof access === 'string' ? [access] : access;
1172
+
1173
+ // Anything that is not a permission array by this point -- an object, a
1174
+ // number, a Symbol -- is a consumer mistake, and the only safe reading of a
1175
+ // shape the contract does not define is a denial. Fail CLOSED.
1176
+ if (!Array.isArray(permitted)) return 403;
1177
+ if (!permitted.includes(methodAccessMap[request.method])) return 403;
1178
+
580
1179
  return undefined;
581
1180
  }
582
1181
  }