@stonyx/orm 0.3.2-beta.15 → 0.3.2-beta.151

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 +402 -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 +644 -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 +654 -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,9 +1,70 @@
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';
4
64
  import { getPluralName } from './plural-registry.js';
5
65
  import { getBeforeHooks, getAfterHooks } from './hooks.js';
6
66
  import config from 'stonyx/config';
67
+ import log from 'stonyx/log';
7
68
  import { isOrmRecord } from './utils.js';
8
69
  const methodAccessMap = {
9
70
  GET: 'read',
@@ -48,13 +109,117 @@ function getBaseUrl(request) {
48
109
  const host = request.get('host');
49
110
  return `${protocol}://${host}`;
50
111
  }
112
+ /**
113
+ * The ONE coercion from a caller-supplied id to the key the store holds it
114
+ * under. Every id-bearing surface in this file goes through it, and none has a
115
+ * copy: `getId()` (URL params), `normalizeBodyId()` (JSON body), and the
116
+ * post-create `context.record` lookup in `_withHooks`.
117
+ *
118
+ * WHY IT IS SHARED RATHER THAN DUPLICATED. `getId()` and `normalizeBodyId()`
119
+ * each had their own arithmetic, and they disagreed: `parseInt(id)` versus
120
+ * `parseInt(id, 10)`. On a hex-shaped id that is a two-record difference --
121
+ *
122
+ * GET /animals/0x2391 -> record 9105 (getId -> parseInt('0x2391') = 9105)
123
+ * POST /animals {"id":"0x2391"} -> lookup under 0 (normalize -> parseInt('0x2391',10) = 0)
124
+ * -> a MISS, so the duplicate check was skipped and
125
+ * createRecord OVERWROTE 9105 in place, answering 200
126
+ *
127
+ * -- a narrower form of the raw-versus-normalised divergence that the body-id
128
+ * normalisation was added to close, reintroduced by the fix for it. Two
129
+ * coercions that must agree cannot be kept in agreement by review; they have to
130
+ * be one function. Pinned by assertion 43.
131
+ *
132
+ * The third copy was found later and in a quieter place: `_withHooks` populated
133
+ * `context.record` for `create` with `isNaN(id) ? id : parseInt(id)` -- this
134
+ * function's body, inlined verbatim, feeding `store.get`. It was equivalent on
135
+ * every input reachable there, which is exactly what the two that DID diverge
136
+ * looked like until someone tried a hex id.
137
+ *
138
+ * SHARING IT IS NOT THE SAME AS IT BEING RIGHT EVERYWHERE. On a model declaring
139
+ * `id = attr('string')` a numeric-looking id is filed under the STRING key, so
140
+ * this coercion resolves `'9107'` to `9107` and the post-create lookup misses:
141
+ * `context.record` is `undefined` for an after-`create` hook. Inherited -- the
142
+ * inlined copy computed the same thing -- and NOT fixed here, because picking
143
+ * the right coercion needs the model's declared id type, which is the same
144
+ * structural information abofs/stonyx-orm#202 is about. Filed as
145
+ * abofs/stonyx-orm#209 and pinned by assertion 50, so closing it turns a test
146
+ * red rather than passing silently.
147
+ *
148
+ * `parseInt` and not `Number`, deliberately, and the anchor is NOT `getId`.
149
+ * It is `src/transforms.ts:7` -- `number: (value) => parseInt(value as string)`,
150
+ * also radix-less -- because that transform is what actually produces the store
151
+ * KEY a record is filed under. `getId` merely agrees with it. They differ from
152
+ * `Number` on `'1e3'` (1 vs 1000) and `'9105.5'` (9105 vs 9105.5), so switching
153
+ * this function to `Number` would make the lookup key disagree with the landing
154
+ * key on those shapes.
155
+ *
156
+ * THE CHANGE THAT WOULD BREAK THIS: adding a radix to `transforms.number`
157
+ * (`parseInt(value, 10)`). That is a one-word edit in a file with no connection
158
+ * to authorization, it would silently reopen the hex divergence in the other
159
+ * direction, and this comment would still read as correct. Assertion 45 pins
160
+ * the transform's radix-less shape directly, so that edit turns a test red
161
+ * rather than shipping.
162
+ *
163
+ * The reason `parseInt` is safe here is the `isNaN` gate in front of it:
164
+ * `parseInt('9105h')` is `9105`, and truncating a partially-valid id into a
165
+ * DIFFERENT VALID key is exactly how a collision lookup gets skipped. The gate
166
+ * rejects it as a string instead, so nothing is ever truncated. That gate, not
167
+ * the parser, is the load-bearing half -- assertion 43 pins it.
168
+ */
169
+ function coerceId(id) {
170
+ if (isNaN(id))
171
+ return id;
172
+ return parseInt(id);
173
+ }
51
174
  function getId(params) {
52
175
  const id = params.id;
53
176
  if (!id)
54
177
  return '';
55
- if (isNaN(id))
178
+ return coerceId(id);
179
+ }
180
+ /**
181
+ * Normalise a caller-supplied BODY id to the key the store will hold it under.
182
+ *
183
+ * `getId()` above is params-shaped: it takes `{ id?: string }` off the URL,
184
+ * where the value is always a string and a falsy one means "no id". A JSON body
185
+ * id is neither -- it can arrive as a number, and `0` is a legitimate id that
186
+ * `getId()` would flatten to `''`.
187
+ *
188
+ * WHY THIS EXISTS AT ALL. createHandler used to look the collision up with the
189
+ * RAW body value while every other surface normalised through `getId()`. The
190
+ * store is a Map keyed by the coerced value, so `store.find(model, '21')` misses
191
+ * the entry held under `21` and the duplicate check is skipped by typing the id
192
+ * as a string. On `dev` that silently overwrote the colliding record and
193
+ * answered 200; combined with the denied-create rollback added for #190 it
194
+ * became an unauthenticated DELETE of any id. Normalising here is half of that
195
+ * fix -- see the rollback in createHandler for the other half.
196
+ *
197
+ * It shares `coerceId` with `getId` so the two surfaces cannot drift apart
198
+ * again, and differs from `getId` in exactly ONE place, below.
199
+ */
200
+ function normalizeBodyId(id) {
201
+ // Non-strings pass through untouched: a JSON body id can arrive as a number,
202
+ // and `getId`'s falsy-flatten must NOT apply to it -- `0` is a legitimate id
203
+ // and `getId` would turn it into `''`. (assertion 30 sweeps id `0`.)
204
+ if (typeof id !== 'string')
56
205
  return id;
57
- return parseInt(id);
206
+ // THE ONE DIVERGENCE FROM `getId`, and it mirrors rather than contradicts it:
207
+ // `getId` maps a falsy param to `''`, and `''` is the only string a body can
208
+ // carry that means "no id" -- `createRecord` treats it as absent and assigns a
209
+ // server id. Coercing it instead would make it address a real slot, because
210
+ // `parseInt('')` is `NaN` and a record CAN be held under `NaN` (a truthy but
211
+ // non-numeric id such as `' '` survives `assignRecordId`'s falsy guard and
212
+ // then NaNs in the id transform). So `POST {"id":""}` would answer 409 against
213
+ // an unrelated record it never named. Pinned by assertion 44.
214
+ //
215
+ // Note what is deliberately NOT special-cased here any more: whitespace.
216
+ // `id.trim() === ''` used to short-circuit `' '` as well, which made the
217
+ // body surface DISAGREE with the URL surface -- `getId({id:' '})` is `NaN`,
218
+ // so `' '` addresses the NaN slot on every other route while the collision
219
+ // lookup missed it. Same class of bug as the hex divergence above.
220
+ if (id === '')
221
+ return id;
222
+ return coerceId(id);
58
223
  }
59
224
  function buildResponse(data, includeParam, recordOrRecords, options = {}) {
60
225
  const { links, baseUrl } = options;
@@ -187,6 +352,39 @@ function createFilterPredicate(filters) {
187
352
  return String(current) === value;
188
353
  });
189
354
  }
355
+ /**
356
+ * A function-style `access` return is a per-record predicate, and it is only
357
+ * meaningful if every surface that can hand a record to a caller consults it.
358
+ * Before #190 exactly one of seven did.
359
+ *
360
+ * Enforcement is deliberately post-fetch. `access` returns an opaque JS
361
+ * predicate and `store.findAll(model, conditions)` accepts only an equality
362
+ * conditions object that the SQL drivers translate to a WHERE clause, so
363
+ * query-layer enforcement would require a breaking change to the published
364
+ * `access` contract. That belongs in #197, not in a security patch. Six of the
365
+ * seven surfaces fetch by primary key anyway, so this costs exactly one row.
366
+ */
367
+ function isDenied(filter, record) {
368
+ if (typeof filter !== 'function')
369
+ return false;
370
+ // A predicate that throws is treated as a denial. Unguarded, a throw escapes
371
+ // to express's default handler, which answers 500 (with a stack trace outside
372
+ // NODE_ENV=production) while a missing id still answers 404 -- so a
373
+ // record-dependent throw re-separates "hidden" from "does not exist" and
374
+ // hands back the oracle this whole change exists to close.
375
+ try {
376
+ return !filter(record);
377
+ }
378
+ catch (error) {
379
+ // Denied, but not silently. A consumer predicate that throws on every
380
+ // record turns the whole collection into a 404 wall, and with no
381
+ // diagnostic that is indistinguishable from an empty database. `stonyx/log`
382
+ // is the module convention (see setup-rest-server.ts); optional-call
383
+ // because a consumer may not have configured the log types.
384
+ log.error?.(`[@stonyx/orm] access filter threw for model -- denying. ${error instanceof Error ? error.message : String(error)}`);
385
+ return true;
386
+ }
387
+ }
190
388
  export default class OrmRequest extends Request {
191
389
  model;
192
390
  access;
@@ -216,10 +414,15 @@ export default class OrmRequest extends Request {
216
414
  baseUrl
217
415
  });
218
416
  };
219
- const getSingleHandler = async (request) => {
417
+ const getSingleHandler = async (request, { filter }) => {
220
418
  const record = await store.find(model, getId(request.params));
221
419
  if (!record)
222
420
  return 404;
421
+ // 404, never 403: the status for "exists but filtered out" must be
422
+ // identical to "does not exist", or the fix trades an authorization
423
+ // bypass for a narrower existence oracle.
424
+ if (isDenied(filter, record))
425
+ return 404;
223
426
  const fieldsMap = parseFields(request.query);
224
427
  const modelFields = fieldsMap.get(pluralizedModel) || fieldsMap.get(model);
225
428
  const baseUrl = getBaseUrl(request);
@@ -228,19 +431,118 @@ export default class OrmRequest extends Request {
228
431
  baseUrl
229
432
  });
230
433
  };
231
- const createHandler = async ({ body, query }) => {
434
+ const createHandler = async ({ body, query }, { filter }) => {
232
435
  const { type, id, attributes, relationships: rels } = (body?.data || {});
233
436
  if (!type)
234
437
  return 400; // Bad request
235
438
  const fieldsMap = parseFields(query);
236
439
  const modelFields = fieldsMap.get(pluralizedModel) || fieldsMap.get(model);
237
- // Check for duplicate ID
238
- if (id !== undefined && await store.find(model, id))
239
- return 409; // Conflict
440
+ // GATE 0 -- the POST existence oracle.
441
+ //
442
+ // The duplicate check runs before the filter and `store.find` sees hidden
443
+ // records, so POST leaks existence through its STATUS. A previous revision
444
+ // filtered the collision status (403 when the colliding record is denied,
445
+ // 409 when it is visible) and that is NOT sufficient, because the status
446
+ // of a create is a third outcome. With a payload the caller is permitted
447
+ // to create -- the normative case for a per-tenant filter, and the case an
448
+ // attacker picks -- all three are distinguishable in ONE request per id:
449
+ //
450
+ // POST /animals {id:22, owner:'gina'} -> 403 a HIDDEN record has this id
451
+ // POST /animals {id:9500, owner:'gina'} -> 200 this id is FREE
452
+ // POST /animals {id:8, owner:'gina'} -> 409 a VISIBLE record has this id
453
+ //
454
+ // Filtering only the collision status narrows that to callers who cannot
455
+ // create a record they are allowed to see. It does not close it.
456
+ //
457
+ // It cannot be closed while a caller both chooses the id and learns
458
+ // whether the create succeeded: a successful create must answer
459
+ // differently from a refused one. So when a per-record filter is in force
460
+ // the caller does not get to choose the id at all. The refusal is
461
+ // UNCONDITIONAL and happens BEFORE any store lookup, so no status, and no
462
+ // lookup cost, can depend on whether that id exists. 403 -- the same
463
+ // status as a denied create -- so the two cannot be separated either.
464
+ //
465
+ // BOTH HALVES OF THAT ARE PINNED, because both were once asserted here and
466
+ // pinned by nothing:
467
+ //
468
+ // status -- assertion 22 sweeps payload x id x id-type, plus `null`.
469
+ // latency -- assertion 41 asserts NO `store.find` is issued on this
470
+ // path. Moving the refusal to after a lookup and returning
471
+ // the same 403 left the suite green while re-opening a
472
+ // hit-versus-miss timing difference on every id-bearing POST,
473
+ // which is what would turn #197 from a ~0.06ms post-fetch
474
+ // residual into a live timing oracle on create.
475
+ //
476
+ // AND THE GUARANTEE IS ONLY AS WIDE AS THE CHANNELS IT COVERS. It reads on
477
+ // the `id` member of the resource object, so it holds only while that is
478
+ // the ONLY way a caller id can reach `createRecord`. It was not: the
479
+ // relationships loop below re-admitted one under `key === "id"` and the
480
+ // gate never fired. Both strips -- `attributes.id` and `relationships.id`
481
+ // -- are therefore part of THIS gate, not tidiness, and assertion 39 pins
482
+ // them. Adding a third channel without a strip re-opens the oracle.
483
+ //
484
+ // Scoped to function-style `access` because that is exactly the population
485
+ // the oracle exists for: with no per-record filter there are no hidden
486
+ // records, and 409 discloses nothing GET /:id does not already.
487
+ //
488
+ // RESIDUALS, stated rather than implied.
489
+ //
490
+ // - a caller can still learn that a collection HAS a per-record filter
491
+ // (403 rather than 409/200 for an id-bearing POST). That discloses a
492
+ // configuration fact, not a record.
493
+ // - this gate is about ids arriving on THIS model's create route. It
494
+ // says nothing about a write to ANOTHER collection: a `POST /owners`
495
+ // carrying `relationships: {pets: {data: {id: 21}}}` -- or
496
+ // `attributes: {pets: [21, 22]}`, which never enters the
497
+ // relationships loop at all -- re-parents hidden animal 21 onto an
498
+ // owner the caller may write, which changes the very field the
499
+ // animals predicate reads and DE-HIDES it. Blocking that needs animal
500
+ // 21 checked against the ANIMAL model's predicate while servicing an
501
+ // OWNERS route, i.e. cross-model access resolution: abofs/stonyx-orm
502
+ // #207, blocked on #202 (`access` receives the model structurally)
503
+ // and #196 (setup-rest-server discards the model->predicate map at
504
+ // boot). NOT closed here, and no comment in this file may say it is.
505
+ //
506
+ // See README `### Known limitations`.
507
+ if (id !== undefined) {
508
+ if (typeof filter === 'function')
509
+ return 403; // Forbidden
510
+ // `normalizeBodyId`, not the raw value: a string-typed id misses the
511
+ // store's numeric key, which skipped this check entirely.
512
+ const existing = await store.find(model, normalizeBodyId(id));
513
+ if (existing)
514
+ return 409; // Conflict
515
+ }
240
516
  const { id: _ignoredId, ...sanitizedAttributes } = attributes || {};
241
- // Extract relationship IDs from JSON:API relationships object
517
+ // Extract relationship IDs from JSON:API relationships object.
518
+ //
519
+ // `key` comes VERBATIM from the request body, so `id` is stripped here for
520
+ // exactly the same reason it is stripped from `attributes` on the line
521
+ // above -- and it must be, or GATE 0 is walked around by moving one field:
522
+ //
523
+ // POST /animals {"id":21, ...} -> 403 GATE 0 fires
524
+ // POST /animals {"relationships":{"id":{"data":{"id":21}}},
525
+ // "attributes":{"owner":"gina"}} -> 200 BYPASS
526
+ //
527
+ // Top-level `id` stayed `undefined`, so GATE 0 never fired and the
528
+ // collision lookup never ran; `createRecord` took its last-entry-wins
529
+ // branch, overwrote hidden record 21 in place and reset its `owner` to a
530
+ // value the caller chose -- de-hiding it permanently. That is #190 itself,
531
+ // on the create surface. Pinned by assertion 39.
532
+ //
533
+ // The `id` member of the resource object is now the ONLY channel a caller
534
+ // id can arrive on FOR THIS MODEL'S OWN CREATE ROUTE, which is what makes
535
+ // GATE 0's guarantee checkable rather than merely asserted. It is not a
536
+ // statement about the record's reachability in general -- a relationship
537
+ // write on another collection reaches it without ever touching this
538
+ // handler (abofs/stonyx-orm#207). INHERITED from `dev`, which carries this
539
+ // loop verbatim; the general form -- the loop accepts any key, not just
540
+ // `id`, so a body key that is not a declared relationship is still
541
+ // mass-assigned -- is abofs/stonyx-orm#204.
242
542
  if (rels) {
243
543
  for (const [key, value] of Object.entries(rels)) {
544
+ if (key === 'id')
545
+ continue;
244
546
  const relData = value?.data;
245
547
  if (relData && relData.id !== undefined) {
246
548
  sanitizedAttributes[key] = relData.id;
@@ -248,16 +550,91 @@ export default class OrmRequest extends Request {
248
550
  }
249
551
  }
250
552
  const recordAttributes = id !== undefined ? { id, ...sanitizedAttributes } : sanitizedAttributes;
553
+ // Slot count BEFORE the write. `createRecord` writes to the store before
554
+ // the predicate can run, and the rollback below must be able to prove the
555
+ // slot it removes is one THIS REQUEST created. Identity alone cannot
556
+ // prove it: when `assignRecordId` lands on an occupied id, `createRecord`
557
+ // mutates the existing OrmRecord IN PLACE, so `store.get(...) === record`
558
+ // is true for a record the request did not create. The map's size is the
559
+ // only O(1) signal that distinguishes an insert from an overwrite.
560
+ const slotsBefore = store.get(model)?.size ?? 0;
251
561
  const created = createRecord(model, recordAttributes, { serialize: false, _skipAutoPersist: true });
252
562
  const record = isOrmRecord(created) ? created : null;
253
563
  if (!record)
254
564
  return 500;
565
+ const createdNewSlot = (store.get(model)?.size ?? 0) > slotsBefore;
566
+ // 403 here, NOT 404. The oracle argument does not apply to create: there
567
+ // is no pre-existing record whose existence could leak, the caller
568
+ // supplied the attributes, and 404 on a mounted collection route is
569
+ // indistinguishable from "model not mounted" -- a genuinely different
570
+ // failure a developer needs to diagnose.
571
+ //
572
+ // The rollback is not optional. createRecord writes to the store BEFORE
573
+ // the predicate can run, so returning 403 alone would leave the record
574
+ // behind: a worse bug than the bypass being fixed.
575
+ if (isDenied(filter, record)) {
576
+ // ROLL BACK BY IDENTITY, NEVER BY ID. `store.remove(model, record.id)`
577
+ // on its own is a write primitive keyed by a value the caller may have
578
+ // supplied: with the raw-id collision bypass above, a denied
579
+ // `POST {"id":"21"}` answered 403 and DELETED hidden record 21 -- an
580
+ // unauthenticated deletion primitive across the whole id space, created
581
+ // by adding a rollback to a lookup that could be skipped.
582
+ //
583
+ // Both conditions are required and neither implies the other:
584
+ // createdNewSlot -- the store grew, so this request inserted rather
585
+ // than overwrote. Guards `assignRecordId` picking an
586
+ // id that is already taken (it returns
587
+ // last-INSERTED + 1, not max + 1, so a store whose
588
+ // insertion order is not ascending collides) -- see
589
+ // abofs/stonyx-orm#203.
590
+ // identity -- the slot still holds the object we just created,
591
+ // so nothing between createRecord and here replaced
592
+ // it. Deleting this half SURVIVES the suite, and it
593
+ // is kept anyway. WHY IT IS REDUNDANT: there is no
594
+ // `await` anywhere between `slotsBefore` and
595
+ // `store.remove` -- the whole window is synchronous,
596
+ // so it is atomic under Node's event loop; before-
597
+ // `create` hooks run BEFORE the handler
598
+ // (`_withHooks` runs its hook loop ahead of
599
+ // `await handler(...)`), and a consumer predicate
600
+ // inside `isDenied` runs AFTER `createdNewSlot` is
601
+ // computed and cannot flip it. That is a property of
602
+ // THIS function, not of GATE 0 -- an earlier note
603
+ // credited GATE 0, which was both wrong (a caller id
604
+ // reached createRecord through the relationships
605
+ // loop, #204) and the wrong kind of reason: a guard
606
+ // justified on code sixty lines upstream gets
607
+ // silently re-armed when that code moves.
608
+ // SO IT BECOMES REACHABLE IF AN `await` IS
609
+ // INTRODUCED HERE, which is the change a future
610
+ // editor would actually make. Stated here rather
611
+ // than by reference: `docs/` is not in `files`, so
612
+ // a pointer into it resolves to nothing for anyone
613
+ // who installed this package. README carries the
614
+ // consumer-facing half.
615
+ if (createdNewSlot && store.get(model, record.id) === record) {
616
+ store.remove(model, record.id, { _skipAutoPersist: true });
617
+ }
618
+ return 403;
619
+ }
255
620
  return { data: record.toJSON?.({ fields: modelFields }) };
256
621
  };
257
- const updateHandler = async ({ body, params }) => {
622
+ const updateHandler = async ({ body, params }, { filter }) => {
258
623
  const found = await store.find(model, getId(params));
259
624
  if (!found || !isOrmRecord(found))
260
625
  return 404;
626
+ // Checked BEFORE any attribute is applied. 404 rather than 403 for the
627
+ // same reason as GET /:id -- 403 would disclose both that the record
628
+ // exists and that this caller specifically is excluded.
629
+ //
630
+ // NOT redundant behind GATE 1, and not defence in depth either: GATE 1's
631
+ // verdict is computed BEFORE the before-hook loop runs, and a before-hook
632
+ // is a published extension point that can change the answer -- by
633
+ // mutating the record, or against a predicate that closes over
634
+ // per-request state. This is the only re-evaluation after that window.
635
+ // Pinned by assertion 32; deleting it turns a 404 into an applied update.
636
+ if (isDenied(filter, found))
637
+ return 404;
261
638
  const record = found;
262
639
  const { attributes, relationships: rels } = (body?.data || {});
263
640
  if (!attributes && !rels)
@@ -277,6 +654,19 @@ export default class OrmRequest extends Request {
277
654
  if (rels) {
278
655
  const relUpdates = {};
279
656
  for (const [key, value] of Object.entries(rels)) {
657
+ // The same missing key filter as createHandler's, and as the
658
+ // attribute loop directly above -- which already had it, while this
659
+ // loop did not. A PATCH carrying
660
+ // `relationships:{"id":{"data":{"id":9101}}}` reached `updateRecord`
661
+ // and RE-KEYED the record: the object held under store key 9102 then
662
+ // reported id 9101, so a visible record claimed a hidden record's
663
+ // identity on every surface that reads `record.id` rather than the map
664
+ // key. Gated by GATE 1 on the addressed record, so it is store
665
+ // corruption rather than a filter bypass -- but it is the same one-line
666
+ // omission two handlers apart. Pinned by assertion 40; INHERITED from
667
+ // `dev`; abofs/stonyx-orm#204.
668
+ if (key === 'id')
669
+ continue;
280
670
  const relData = value?.data;
281
671
  if (relData && relData.id !== undefined) {
282
672
  relUpdates[key] = relData.id;
@@ -288,8 +678,31 @@ export default class OrmRequest extends Request {
288
678
  }
289
679
  return { data: record.toJSON?.() };
290
680
  };
291
- const deleteHandler = ({ params }) => {
292
- store.remove(model, getId(params));
681
+ const deleteHandler = async ({ params }, { filter }) => {
682
+ // Coerced ONCE. `getId(params)` was evaluated twice here -- once to find
683
+ // the record and once to remove it -- and a coercion evaluated repeatedly
684
+ // is a coercion that can be edited in one place and not the other, which
685
+ // is the defect `coerceId` exists to prevent.
686
+ const recordId = getId(params);
687
+ const record = await store.find(model, recordId);
688
+ // BEHAVIOUR CHANGE (#190): a DELETE of a record that never existed
689
+ // returned 204 before this change. It now returns 404, matching the
690
+ // denied case below. This is deliberate and load-bearing -- if a denied
691
+ // delete returned 404 while a missing one returned 204, the pair would be
692
+ // a perfect existence oracle and the whole fix would be worthless.
693
+ // Returning 204 for a denied delete was rejected instead: it falsely
694
+ // reports success for a request that changed nothing.
695
+ if (!record)
696
+ return 404;
697
+ // Re-evaluated after the before-hook loop, exactly as in updateHandler --
698
+ // GATE 1 decided before the hooks ran. Pinned by assertion 33; deleting it
699
+ // turns a 404 into a destroyed record.
700
+ if (isDenied(filter, record))
701
+ return 404;
702
+ // Removed by the id of the record actually fetched, not by re-deriving it
703
+ // from the params a second time: the record the filter tested and the
704
+ // record removed are then provably the same one.
705
+ store.remove(model, record.id, { _skipAutoPersist: true });
293
706
  return 204;
294
707
  };
295
708
  // Wrap handlers with hooks
@@ -314,9 +727,63 @@ export default class OrmRequest extends Request {
314
727
  };
315
728
  }
316
729
  }
317
- // Wraps a handler with before/after hook execution
730
+ // Wraps a handler with before/after hook execution.
731
+ //
732
+ // ===========================================================================
733
+ // TWO AUTHORIZATION GATES, AND EVERY EXECUTOR SITS BEHIND ONE OF THEM (#190)
734
+ //
735
+ // The defect this function was fixed for is NOT "a delete persists past a
736
+ // 404". It is that _withHooks has SEVERAL executors downstream of the
737
+ // handler, and originally the handler's response gated none of them. Three
738
+ // exist today:
739
+ //
740
+ // 1. sqlDb.persist -- issues real SQL against the backing store
741
+ // 2. the after-hook pipeline -- the PUBLISHED consumer extension point;
742
+ // a cascade delete, a webhook, a search-index
743
+ // purge. `context.recordId` and
744
+ // `context.oldState` are populated for it.
745
+ // 3. Orm.db.save() -- a full serialize-and-write of the store
746
+ //
747
+ // Gating them one at a time is how this keeps regressing, so the rule is:
748
+ // compute denial ONCE at each point where it becomes knowable, and keep every
749
+ // executor downstream of a gate. If you add a fourth executor to this
750
+ // function, it goes below GATE 2 or it is a security bug.
751
+ //
752
+ // GATE 1 (pre-handler) is required because before-hooks and `context.oldState`
753
+ // run/are built BEFORE the handler can consult the filter. Without it a denied
754
+ // DELETE still handed the hidden record's full contents to consumer code.
755
+ // GATE 2 (post-handler) covers everything the handler's status can reach.
756
+ // ===========================================================================
318
757
  _withHooks(operation, handler) {
319
758
  return async (request, state) => {
759
+ // `|| {}` so this function behaves like the relationship routes below,
760
+ // which declare `state` with a `= {}` default. It is unkillable through
761
+ // the rest-server dispatcher, which always passes `getState(req)`; it is
762
+ // listed as such in the guards-redundant-by-construction table rather
763
+ // than left silently unkillable, and it defends the WHOLE function (the
764
+ // context, the snapshot and the handler call all read `callState`) rather
765
+ // than one destructure that the next line would throw past anyway.
766
+ const callState = (state || {});
767
+ // ---------------------------------------------------------------------
768
+ // THE AUTHORIZATION SNAPSHOT. Read ONCE, here, before any consumer code
769
+ // can run.
770
+ //
771
+ // `callState` is the object `auth()` planted the filter in, and it is
772
+ // also handed to every before-hook as `context.state` -- a published,
773
+ // WRITABLE extension point. So `state.filter` is an INPUT to the
774
+ // authorization decision, not only an output channel, and re-reading it
775
+ // after the hook loop lets a consumer hook disarm the filter:
776
+ //
777
+ // beforeHook('get', 'animal', ctx => { delete ctx.state.filter })
778
+ // -> GET /animals/21 turned 404 into 200
779
+ // -> GET /animals turned 20 records into 22
780
+ //
781
+ // GATE 1 already used this snapshot, so writes held; the READ handlers
782
+ // re-destructured `filter` from the live bag and did not. Everything
783
+ // downstream now reads `filter` from here, and the handler is handed
784
+ // `handlerState` below -- never `callState`.
785
+ // ---------------------------------------------------------------------
786
+ const { filter } = callState;
320
787
  // Build context object for hooks
321
788
  const context = {
322
789
  model: this.model,
@@ -325,11 +792,35 @@ export default class OrmRequest extends Request {
325
792
  params: request.params,
326
793
  body: request.body,
327
794
  query: request.query,
328
- state,
795
+ // Deliberately the LIVE object: `redirect` and `pipe` are read back off
796
+ // it by @stonyx/rest-server after the handler returns, so hooks must be
797
+ // able to write to it. What must not happen is the authorization
798
+ // decision reading it back, which is what the snapshot above prevents.
799
+ state: callState,
329
800
  };
330
801
  // Capture old state for operations that modify data
331
802
  if (operation === 'update' || operation === 'delete') {
332
803
  const existingRecord = await store.find(this.model, getId(request.params));
804
+ // GATE 1 -- pre-handler. This record fetch already happened for
805
+ // oldState, so the check is free.
806
+ //
807
+ // Returning here rather than letting updateHandler/deleteHandler
808
+ // produce the same 404 is the point: everything between here and there
809
+ // is an executor the caller is not authorized to reach.
810
+ // - context.oldState is a deep copy of the HIDDEN RECORD'S CONTENTS.
811
+ // Building it and handing it to a before-hook discloses exactly what
812
+ // the filter exists to hide.
813
+ // - context.recordId is populated for delete BEFORE the handler runs,
814
+ // which is the same shape as the sqlDb landmine one layer up:
815
+ // `afterHook('delete', ctx => cascadeDelete(ctx.recordId))` destroys
816
+ // children behind a correct 404.
817
+ // - a before-hook may return a value and short-circuit, which would
818
+ // otherwise return a response without the filter ever executing.
819
+ //
820
+ // 404, not 403, for the same reason as getSingleHandler: the status for
821
+ // "exists but filtered out" must equal "does not exist".
822
+ if (existingRecord && isDenied(filter, existingRecord))
823
+ return 404;
333
824
  if (existingRecord) {
334
825
  // Deep copy the record's data to preserve old state
335
826
  context.oldState = JSON.parse(JSON.stringify(existingRecord.__data || existingRecord));
@@ -347,10 +838,49 @@ export default class OrmRequest extends Request {
347
838
  }
348
839
  }
349
840
  // Execute main handler
350
- const response = await handler(request, state);
351
- // Persist to SQL database for create/update (delete is handled by store.remove auto-persist)
841
+ // The handler receives the SNAPSHOT, never the live bag. `filter` is
842
+ // assigned LAST so it wins over anything a before-hook wrote to
843
+ // `callState.filter` -- including a `delete`, which the spread would
844
+ // otherwise carry through as an absent key. Every other key a hook adds
845
+ // is still visible to the handler; only the authorization input is
846
+ // pinned.
847
+ const handlerState = { ...callState, filter };
848
+ const response = await handler(request, handlerState);
849
+ // Set context.record for update BEFORE persist so SQL drivers can read it
850
+ if (operation === 'update' && response?.data) {
851
+ context.record = store.get(this.model, getId(request.params));
852
+ }
853
+ // GATE 2 -- post-handler. A denied or failed handler returns a bare status
854
+ // integer, and no executor below may run for one.
855
+ //
856
+ // `>= 400` deliberately covers every failure status, not just the
857
+ // authorization ones: a 400 (POST with no `type`) and a 409 (duplicate id)
858
+ // are equally requests in which nothing happened, and a persist or a
859
+ // cascade hook for one of them is just as wrong.
860
+ // `Number.isInteger` is a TYPE guard, not a behaviour guard, and it is
861
+ // unkillable TODAY: the only non-integer a handler in this file can
862
+ // return is a `{ data, links }` object, and `{} >= 400` is `false` by JS
863
+ // coercion, so dropping it changes no reachable outcome. It is kept
864
+ // because `>=` coerces rather than rejects, and the shapes it coerces
865
+ // are not obvious -- `[500] >= 400` is TRUE, so a handler that one day
866
+ // returned an array would have every response read as a denial. Listed
867
+ // as an equivalent mutant rather than left to read as coverage; it
868
+ // becomes killable the moment a handler returns anything array-like or
869
+ // numeric-string-like.
870
+ const denied = Number.isInteger(response) && response >= 400;
871
+ // EXECUTOR 1 -- SQL persistence, for all write operations.
872
+ //
873
+ // `response` is passed to sqlDb.persist below, but it is dropped at the
874
+ // driver boundary: _persistDelete(modelName, context) never receives it
875
+ // and guards only on context.recordId -- which _withHooks set above,
876
+ // BEFORE the handler ran. Without this gate a correct 404 still issues
877
+ // DELETE FROM ... WHERE id = ? on every SQL backend.
878
+ //
879
+ // No file-backed test can observe that, because Orm.instance.sqlDb is
880
+ // null in file/directory mode. See the stubbed-sqlDb assertions in
881
+ // test/unit/access-filter-enforcement-test.ts.
352
882
  const sqlDb = Orm.instance.sqlDb;
353
- if (sqlDb && (operation === 'create' || operation === 'update')) {
883
+ if (sqlDb && WRITE_OPERATIONS.has(operation) && !denied) {
354
884
  await sqlDb.persist(operation, this.model, context, response);
355
885
  }
356
886
  // Add response and relevant records to context
@@ -364,22 +894,44 @@ export default class OrmRequest extends Request {
364
894
  else if (operation === 'create' && response?.data && (response.data.id)) {
365
895
  // For create, get the record from store using the ID from the response
366
896
  const responseData = response.data;
367
- const recordId = isNaN(responseData.id) ? responseData.id : parseInt(responseData.id);
368
- context.record = store.get(this.model, recordId);
369
- }
370
- else if (operation === 'update' && response?.data) {
371
- context.record = store.get(this.model, getId(request.params));
897
+ // `normalizeBodyId`, not a copy of its body. This line WAS
898
+ // `isNaN(id) ? id : parseInt(id)` -- `coerceId` inlined verbatim, a
899
+ // third coercion feeding a store lookup, sitting under a docblock that
900
+ // said neither surface had a copy. Equivalent on every input that can
901
+ // reach this truthy-guarded branch (`21`->`21`, `'21'`->`21`,
902
+ // `'angela'`->`'angela'`; `''` and `0` cannot reach it), so this is a
903
+ // de-duplication rather than a behaviour change -- and that is the
904
+ // point: the two that disagreed were equivalent on every input anyone
905
+ // checked, too.
906
+ context.record = store.get(this.model, normalizeBodyId(responseData.id));
372
907
  }
373
908
  else if (operation === 'delete') {
374
909
  // For delete, the record may no longer exist, but we have oldState
375
910
  context.recordId = getId(request.params);
376
911
  }
377
- // Run after hooks sequentially
378
- for (const hook of getAfterHooks(operation, this.model)) {
379
- await hook(context);
912
+ // EXECUTOR 2 -- the after-hook pipeline. This is the published consumer
913
+ // extension point (`afterHook` is exported from @stonyx/orm and from
914
+ // ./hooks), so it is the executor with the widest possible blast radius:
915
+ // a cascade delete, a webhook, a token revocation, a search-index purge.
916
+ //
917
+ // BEHAVIOUR CHANGE (#190): after-hooks no longer fire for a request that
918
+ // failed. Previously `afterHook('delete', ...)` ran with a populated
919
+ // context.recordId on a 404, so a consumer cascade destroyed children for
920
+ // a request that deleted nothing. Firing a hook named "after<operation>"
921
+ // for an operation that did not occur is a booby trap, and the denied case
922
+ // is unreachable-before-#190 while the missing case is inherited debt --
923
+ // both are closed by the same gate. `context.response` therefore only ever
924
+ // carries a success status into a hook.
925
+ if (!denied) {
926
+ for (const hook of getAfterHooks(operation, this.model)) {
927
+ await hook(context);
928
+ }
380
929
  }
381
- // Auto-save DB after write operations when configured
382
- if (config.orm.db.autosave === 'onUpdate' && WRITE_OPERATIONS.has(operation)) {
930
+ // EXECUTOR 3 -- file/directory autosave. Ungated this let an
931
+ // unauthenticated caller force a full serialize-and-write of the entire
932
+ // store on every DELETE of any id, with no record touched: amplification
933
+ // rather than corruption, but the same root cause and the same fix.
934
+ if (config.orm.db.autosave === 'onUpdate' && WRITE_OPERATIONS.has(operation) && !denied) {
383
935
  await Orm.db.save();
384
936
  }
385
937
  return response;
@@ -391,10 +943,21 @@ export default class OrmRequest extends Request {
391
943
  // Dasherize the relationship name for URL paths (e.g., accessLinks -> access-links)
392
944
  const dasherizedName = camelCaseToKebabCase(relationshipName);
393
945
  // Related resource route: GET /:id/{relationship}
394
- routes[`/:id/${dasherizedName}`] = async (request) => {
946
+ //
947
+ // These generated routes are not wrapped by _withHooks, which is why they
948
+ // were the least obvious two of the seven unguarded surfaces in #190.
949
+ // They are still dispatched by @stonyx/rest-server as
950
+ // `handler(req, getState(req))`, so `state` -- and therefore the filter
951
+ // planted by auth() -- has always been available here; it was simply
952
+ // never declared or read.
953
+ routes[`/:id/${dasherizedName}`] = async (request, { filter } = {}) => {
395
954
  const record = await store.find(model, getId(request.params));
396
955
  if (!record)
397
956
  return 404;
957
+ // Filtering the PARENT: a caller who may not see the record may not see
958
+ // what it is related to either.
959
+ if (isDenied(filter, record))
960
+ return 404;
398
961
  const relatedData = record.__relationships[relationshipName];
399
962
  const baseUrl = getBaseUrl(request);
400
963
  let data;
@@ -413,10 +976,12 @@ export default class OrmRequest extends Request {
413
976
  };
414
977
  };
415
978
  // Relationship linkage route: GET /:id/relationships/{relationship}
416
- routes[`/:id/relationships/${dasherizedName}`] = async (request) => {
979
+ routes[`/:id/relationships/${dasherizedName}`] = async (request, { filter } = {}) => {
417
980
  const record = await store.find(model, getId(request.params));
418
981
  if (!record)
419
982
  return 404;
983
+ if (isDenied(filter, record))
984
+ return 404;
420
985
  const relatedData = record.__relationships[relationshipName];
421
986
  const baseUrl = getBaseUrl(request);
422
987
  let data;
@@ -445,31 +1010,63 @@ export default class OrmRequest extends Request {
445
1010
  };
446
1011
  };
447
1012
  }
448
- // Catch-all for invalid relationship names on related resource route
449
- routes[`/:id/:relationship`] = async (request) => {
450
- const record = await store.find(model, getId(request.params));
451
- if (!record)
452
- return 404;
453
- // If we reach here, relationship doesn't exist (valid ones were registered above)
454
- return 404;
455
- };
456
- // Catch-all for invalid relationship names on relationship linkage route
457
- routes[`/:id/relationships/:relationship`] = async (request) => {
458
- const record = await store.find(model, getId(request.params));
459
- if (!record)
460
- return 404;
461
- return 404;
462
- };
1013
+ // Catch-alls for invalid relationship names. Every valid relationship was
1014
+ // registered above, so reaching either of these means the relationship does
1015
+ // not exist and the answer is 404 regardless of the record.
1016
+ //
1017
+ // These deliberately carry NO access check and no store lookup. An earlier
1018
+ // revision of #190 added `if (isDenied(filter, record)) return 404` here for
1019
+ // symmetry with the seven real surfaces, but both branches returned 404, so
1020
+ // the guard was unobservable by construction -- a mutation deleting it
1021
+ // survived the entire suite because no test that could distinguish it can
1022
+ // exist. Unkillable code in an authorization diff reads as coverage and is
1023
+ // not, so it is gone; skipping the lookup also removes the timing difference
1024
+ // between an existing and a missing parent.
1025
+ //
1026
+ // IF THIS ROUTE EVER RETURNS ANYTHING OTHER THAN A CONSTANT 404, it becomes
1027
+ // the eighth surface and must filter the parent first, exactly like
1028
+ // `/:id/{relationship}` above.
1029
+ routes[`/:id/:relationship`] = async () => 404;
1030
+ routes[`/:id/relationships/:relationship`] = async () => 404;
463
1031
  return routes;
464
1032
  }
465
1033
  auth(request, state) {
466
- const access = this.access(request);
1034
+ // A consumer `access()` that throws is a DENIAL, matching `isDenied` one
1035
+ // layer down. Unguarded it propagates to express's default handler, which
1036
+ // answers 500 -- and the documented sample itself can throw
1037
+ // (`request.originalUrl.split(...)` when originalUrl is absent), so the
1038
+ // failure mode is reachable by following the docs.
1039
+ let access;
1040
+ try {
1041
+ access = this.access(request);
1042
+ }
1043
+ catch (error) {
1044
+ // Same reasoning as `isDenied`: fail closed, but say so. An `access()`
1045
+ // that throws denies EVERY request to the collection, and a silent 403
1046
+ // wall is the hardest possible thing to diagnose from the outside.
1047
+ log.error?.(`[@stonyx/orm] access() threw for model "${this.model}" -- denying. ${error instanceof Error ? error.message : String(error)}`);
1048
+ return 403; // Forbidden
1049
+ }
467
1050
  if (!access)
468
1051
  return 403;
469
- if (Array.isArray(access) && !access.includes(methodAccessMap[request.method]))
470
- return 403;
471
- if (typeof access === 'function')
1052
+ if (typeof access === 'function') {
472
1053
  state.filter = access;
1054
+ return undefined;
1055
+ }
1056
+ if (access === true)
1057
+ return undefined;
1058
+ // `AccessMethod` declares `string` legal and it fell through every branch
1059
+ // above, returning undefined -- i.e. FULL CRUD, no filter. `return 'read'`
1060
+ // is the natural reading of a type that lists `string` first, and it
1061
+ // granted DELETE. A bare string is one permission, not a grant of all four.
1062
+ const permitted = typeof access === 'string' ? [access] : access;
1063
+ // Anything that is not a permission array by this point -- an object, a
1064
+ // number, a Symbol -- is a consumer mistake, and the only safe reading of a
1065
+ // shape the contract does not define is a denial. Fail CLOSED.
1066
+ if (!Array.isArray(permitted))
1067
+ return 403;
1068
+ if (!permitted.includes(methodAccessMap[request.method]))
1069
+ return 403;
473
1070
  return undefined;
474
1071
  }
475
1072
  }