@stonyx/orm 0.3.2-alpha.8 → 0.3.2-alpha.80

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 (65) hide show
  1. package/README.md +1137 -11
  2. package/config/environment.js +8 -0
  3. package/dist/access-verdict.d.ts +85 -0
  4. package/dist/access-verdict.js +284 -0
  5. package/dist/commands.js +34 -0
  6. package/dist/dynamodb/connection.d.ts +31 -0
  7. package/dist/dynamodb/connection.js +28 -0
  8. package/dist/dynamodb/dynamodb-db.d.ts +142 -0
  9. package/dist/dynamodb/dynamodb-db.js +596 -0
  10. package/dist/dynamodb/operation-builder.d.ts +76 -0
  11. package/dist/dynamodb/operation-builder.js +116 -0
  12. package/dist/dynamodb/type-map.d.ts +31 -0
  13. package/dist/dynamodb/type-map.js +48 -0
  14. package/dist/hooks.d.ts +15 -1
  15. package/dist/index.d.ts +3 -0
  16. package/dist/index.js +8 -0
  17. package/dist/main.d.ts +116 -0
  18. package/dist/main.js +129 -0
  19. package/dist/manage-record.js +268 -12
  20. package/dist/mysql/connection.d.ts +1 -0
  21. package/dist/mysql/mysql-db.d.ts +8 -0
  22. package/dist/mysql/mysql-db.js +44 -10
  23. package/dist/orm-request.d.ts +264 -3
  24. package/dist/orm-request.js +1138 -61
  25. package/dist/postgres/connection.d.ts +1 -0
  26. package/dist/postgres/connection.js +8 -6
  27. package/dist/postgres/postgres-db.d.ts +8 -0
  28. package/dist/postgres/postgres-db.js +44 -10
  29. package/dist/record.d.ts +16 -0
  30. package/dist/record.js +154 -6
  31. package/dist/relationships.js +1 -1
  32. package/dist/serializer.js +38 -2
  33. package/dist/setup-rest-server.js +51 -5
  34. package/dist/standalone-db.js +17 -5
  35. package/dist/store.d.ts +13 -1
  36. package/dist/store.js +65 -6
  37. package/dist/types/orm-types.d.ts +234 -0
  38. package/dist/utils.d.ts +44 -0
  39. package/dist/utils.js +47 -0
  40. package/package.json +16 -7
  41. package/src/access-verdict.ts +312 -0
  42. package/src/commands.ts +43 -0
  43. package/src/dynamodb/connection.ts +50 -0
  44. package/src/dynamodb/dynamodb-db.ts +811 -0
  45. package/src/dynamodb/operation-builder.ts +202 -0
  46. package/src/dynamodb/type-map.ts +54 -0
  47. package/src/hooks.ts +15 -1
  48. package/src/index.ts +10 -0
  49. package/src/main.ts +133 -0
  50. package/src/manage-record.ts +294 -18
  51. package/src/mysql/connection.ts +1 -0
  52. package/src/mysql/mysql-db.ts +44 -12
  53. package/src/orm-request.ts +1159 -63
  54. package/src/postgres/connection.ts +10 -6
  55. package/src/postgres/postgres-db.ts +44 -12
  56. package/src/record.ts +182 -6
  57. package/src/relationships.ts +1 -1
  58. package/src/serializer.ts +39 -2
  59. package/src/setup-rest-server.ts +59 -6
  60. package/src/standalone-db.ts +17 -6
  61. package/src/store.ts +68 -6
  62. package/src/types/orm-types.ts +242 -1
  63. package/src/types/stonyx-rest-server.d.ts +14 -1
  64. package/src/types/stonyx.d.ts +7 -1
  65. package/src/utils.ts +50 -0
package/README.md CHANGED
@@ -13,7 +13,7 @@ A lightweight ORM for Stonyx projects, featuring model definitions, serializers,
13
13
  - **Models**: Define attributes with type-safe proxies (`attr`) and relationships (`hasMany`, `belongsTo`).
14
14
  - **Serializers**: Map raw data into model-friendly structures, including nested properties.
15
15
  - **Transforms**: Apply custom transformations on data values automatically.
16
- - **DB Integration**: Optional file-based persistence with auto-save support, or MySQL for production workloads.
16
+ - **DB Integration**: Optional file-based persistence with auto-save support, or MySQL/PostgreSQL/TimescaleDB/DynamoDB for production workloads.
17
17
  - **REST Server Integration**: Automatic route setup with customizable access control.
18
18
  - **Lifecycle Hooks**: Middleware-based before/after hooks for validation, authorization, side effects, and auditing.
19
19
 
@@ -65,13 +65,16 @@ const {
65
65
  MYSQL_DATABASE,
66
66
  MYSQL_CONNECTION_LIMIT,
67
67
  MYSQL_MIGRATIONS_DIR,
68
+ DYNAMODB_REGION,
69
+ DYNAMODB_ENDPOINT,
70
+ DYNAMODB_TABLE_PREFIX,
68
71
  } = process.env;
69
72
 
70
73
  export default {
71
74
  orm: {
72
75
  logColor: 'white',
73
76
  logMethod: 'db',
74
-
77
+
75
78
  db: {
76
79
  autosave: DB_AUTO_SAVE ?? 'false',
77
80
  file: DB_FILE ?? 'db.json',
@@ -95,6 +98,12 @@ export default {
95
98
  connectionLimit: parseInt(MYSQL_CONNECTION_LIMIT ?? '10'),
96
99
  migrationsDir: MYSQL_MIGRATIONS_DIR ?? 'migrations',
97
100
  migrationsTable: '__migrations',
101
+ autoMigrate: AUTO_MIGRATE === 'true' ? true : AUTO_MIGRATE === 'false' ? false : undefined,
102
+ } : undefined,
103
+ dynamodb: DYNAMODB_REGION ? {
104
+ region: DYNAMODB_REGION,
105
+ endpoint: DYNAMODB_ENDPOINT, // optional, for DynamoDB Local
106
+ tablePrefix: DYNAMODB_TABLE_PREFIX, // optional table name prefix
98
107
  } : undefined,
99
108
  restServer: {
100
109
  enabled: ORM_USE_REST_SERVER ?? 'true',
@@ -243,6 +252,31 @@ Set the `MYSQL_HOST` environment variable to enable MySQL persistence. The ORM l
243
252
  | `stonyx db:migrate` | Apply pending migrations |
244
253
  | `stonyx db:migrate:rollback` | Rollback the most recent migration |
245
254
  | `stonyx db:migrate:status` | Show migration status |
255
+ | `stonyx db:sync` | Sync DynamoDB table definitions to match current model schemas |
256
+
257
+ ### DynamoDB Mode
258
+
259
+ Set the `DYNAMODB_REGION` environment variable to enable DynamoDB persistence. Tables are created with PAY_PER_REQUEST (on-demand) billing. Global Secondary Indexes (GSIs) are auto-provisioned at startup based on model `belongsTo` relationships — each FK column gets a GSI. `findAll()` with conditions routes to a GSI Query when the condition key matches a GSI partition key; non-indexed attribute conditions fall back to Scan + FilterExpression (expensive for large tables). ULID generation replaces auto-increment for numeric-ID models.
260
+
261
+ ```javascript
262
+ dynamodb: {
263
+ region: 'us-east-1',
264
+ endpoint: 'http://localhost:8000', // optional, for DynamoDB Local
265
+ tablePrefix: 'myapp-', // optional table name prefix
266
+ }
267
+ ```
268
+
269
+ Environment variables:
270
+
271
+ * `DYNAMODB_REGION`: AWS region for DynamoDB (e.g., `'us-east-1'`).
272
+ * `DYNAMODB_ENDPOINT`: Optional custom endpoint URL, useful for DynamoDB Local during development.
273
+ * `DYNAMODB_TABLE_PREFIX`: Optional prefix prepended to all table names (e.g., `'myapp-'` yields `'myapp-animals'`).
274
+
275
+ **Peer dependencies:** `@aws-sdk/client-dynamodb` and `@aws-sdk/lib-dynamodb` must be installed when using the DynamoDB driver. The AWS SDK is dynamically imported and only loaded when the DynamoDB driver is selected.
276
+
277
+ ```bash
278
+ npm install @aws-sdk/client-dynamodb @aws-sdk/lib-dynamodb
279
+ ```
246
280
 
247
281
  ### Running MySQL Tests
248
282
 
@@ -275,19 +309,1058 @@ import setupRestServer from '@stonyx/orm/setup-rest-server';
275
309
  await setupRestServer('/', './access');
276
310
  ```
277
311
 
278
- Access classes define models and provide custom filtering/authorization logic:
312
+ Access classes define models and provide custom filtering/authorization logic.
313
+
314
+ > **Do not reconstruct the request path inside `access()`. Read
315
+ > [Identifying the collection](#identifying-the-collection) before copying this.**
316
+ > Every attempt to identify the collection by parsing the request target has
317
+ > failed **open** — five distinct variants of this same example, each found only
318
+ > after the previous was fixed, by five different people. That section is now a
319
+ > record of what not to do, not a matching recipe: the sample below reads `model`
320
+ > from [the access context](#the-access-context-second-argument) and never looks
321
+ > at the mount at all, so variants 1, 2, 4 and 5 are **unconstructible** against
322
+ > it rather than merely handled. **Variant 3 survives.** It is the general shape
323
+ > "a hand-written matcher normalises differently from the router", and the
324
+ > migrated sample still runs one string comparison — the `/archived` sub-path
325
+ > deny — which folds case but does not decode, so `GET /owners/%61rchived` steps
326
+ > past it ([#228](https://github.com/abofs/stonyx-orm/issues/228)).
327
+ >
328
+ > **Superseded 2026-09-01 by [#236](https://github.com/abofs/stonyx-orm/issues/236) /
329
+ > [#237](https://github.com/abofs/stonyx-orm/issues/237), and left standing rather
330
+ > than rewritten.** Both claims above are now false: `#228` is **closed**, and the
331
+ > one string comparison variant 3 lived in is gone — the sample below compares the
332
+ > **decoded `recordId`** the access context supplies, so there is no comparison
333
+ > left to step around. The paragraph about `request.path` further down is
334
+ > superseded the same way. Nothing here is deleted because the same "variant 3
335
+ > survives" wording sits at four sites (this file twice, `src/orm-request.ts`, and
336
+ > the test fixture) and retiring one of four leaves the shipped copies
337
+ > contradicting each other; retiring all four **with the measurement that retires
338
+ > them** is [#238](https://github.com/abofs/stonyx-orm/issues/238), which also owns
339
+ > this blockquote and the reference section below.
340
+ >
341
+ > That is still a stopgap. **The real fix is
342
+ > [#202](https://github.com/abofs/stonyx-orm/issues/202)** — `access()` should
343
+ > receive the model, the operation and the record, so there is nothing to
344
+ > identify. Until it lands, prefer the array shape (`['read']`) or `false` where
345
+ > you can: the **function** shape is the one that requires any matching at all.
346
+ >
347
+ > The one read of argument **one** that survives is `request.path`, for the
348
+ > `/archived` sub-path deny — and it has to. The context names which model and
349
+ > which verb, not which route, so that deny **cannot be expressed from the
350
+ > context alone** and a context-only rewrite would silently turn it into an
351
+ > allow.
352
+ >
353
+ > **Superseded 2026-09-01 by [#236](https://github.com/abofs/stonyx-orm/issues/236) /
354
+ > [#237](https://github.com/abofs/stonyx-orm/issues/237)** — see the dated note
355
+ > above. No read of argument **one** survives in the sample below: the context
356
+ > carries `recordId`, the decoded route-parameter id, so the `/archived` deny **is**
357
+ > expressible from the context alone. It still must not be dropped — expressible is
358
+ > not optional. Retirement of this wording:
359
+ > [#238](https://github.com/abofs/stonyx-orm/issues/238).
360
+ >
361
+ > The same warning is repeated at the top of `src/orm-request.ts`, which ships;
362
+ > the longer write-up in `docs/usage-patterns.md` does **not** ship, so this
363
+ > README and that source header are the two copies a consumer sees.
364
+ >
365
+ > This sample is the same code as the shipped test fixture, and a test asserts
366
+ > the two `access()` bodies are identical line for line. For four rounds they
367
+ > were two independently written copies — and the fifth fail-open variant was
368
+ > found in the one nothing was mutating.
279
369
 
280
370
  ```js
281
371
  export default class GlobalAccess {
282
372
  models = ['owner', 'animal'];
283
373
 
284
- access(request) {
285
- if (request.url.endsWith('/owner/angela')) return false;
374
+ access(request, { model, operation, recordId }) {
375
+ // `model` is the model this route was mounted for. It is assigned once, at
376
+ // mount time, and no request can influence it — not a mount prefix, not a
377
+ // query string, not a case-varied path, not an absolute-form request
378
+ // target. `recordId` is the record this route was ADDRESSED TO, decoded by
379
+ // the router and coerced to the key the store lookup uses. Nothing below
380
+ // parses anything, and since abofs/stonyx-orm#236 nothing below reads
381
+ // argument one AT ALL. Variants 1, 2, 4 and 5 were already unconstructible;
382
+ // the sub-path STRING COMPARISON that variant 3 lived in is gone too,
383
+ // replaced by a comparison against the decoded id. Retiring the "variant 3
384
+ // survives" wording at the four sites that still carry it — with the
385
+ // measurement that retires it, rather than by deletion — is
386
+ // abofs/stonyx-orm#238.
387
+ //
388
+ // `operation` is destructured to name the whole contract at the point of
389
+ // use. This sample's rules are per-model and per-record rather than
390
+ // per-verb, so it does not branch on it; the permission array at the bottom
391
+ // is where the verb is answered.
392
+
393
+ // FAIL CLOSED ON AN UNIDENTIFIABLE MODEL. `model` is absent for any caller
394
+ // that resolved this predicate without supplying the context, and a request
395
+ // this function cannot identify DENIES rather than falling through to the
396
+ // CRUD grant at the bottom. An unidentifiable input must never be the
397
+ // permissive path.
398
+ if (typeof model !== 'string' || model === '') return false;
399
+
400
+ if (model === 'owner') {
401
+ // FAIL CLOSED ON AN ABSENT `recordId` TOO, AND `undefined` IS THE ONLY
402
+ // SPELLING OF ABSENT. `auth()` ALWAYS sets the key — `null` on a
403
+ // collection route, which is addressed to no record — so `undefined`
404
+ // means the context did not come from `auth()`: it was hand-assembled by
405
+ // a caller resolving this predicate through the documented
406
+ // `Orm.instance.getAccess()` path. Letting that through would fall
407
+ // straight to the per-record filter below, which is a DENY becoming an
408
+ // ALLOW. This is the same rule the old guard on `request.path` enforced,
409
+ // moved to the argument this predicate now actually reads.
410
+ if (recordId === undefined) return false;
411
+
412
+ // THE `/archived` DENY, EXPRESSED AGAINST THE DECODED ID. It used to be
413
+ // `request.path.toLowerCase()` compared against `'/archived'`, and that
414
+ // was wrong in both directions at once.
415
+ //
416
+ // TOO PERMISSIVE: express sets `request.path` from the RAW pathname while
417
+ // the router DECODES `:id`, so `GET /owners/%61rchived` reached the
418
+ // comparison as `/%61rchived`, walked past the deny and was dispatched as
419
+ // the record `archived` — 200 with the record in full, and DELETE
420
+ // answered 204 with the record DESTROYED, unauthenticated. 255
421
+ // non-canonical spellings of that 8-character id decode to the same key,
422
+ // so no deny-list of spellings was ever going to close it.
423
+ //
424
+ // TOO STRICT: a record id is a VALUE, not a literal route segment, and
425
+ // express's `case sensitive routing` governs literal segments only. With
426
+ // a distinct owner seeded at `ARCHIVED`, the `.toLowerCase()` 403'd
427
+ // `GET /owners/ARCHIVED` — the wrong record — while still admitting
428
+ // `GET /owners/%41RCHIVED`, the same record encoded.
429
+ //
430
+ // SO DO NOT NORMALISE `recordId`. It is already decoded, exactly ONCE,
431
+ // which is what a route parameter means: `/owners/%2561rchived` is the
432
+ // legitimate id `%61rchived`, and decoding until stable would deny it. Do
433
+ // not case-fold it. Do not rebuild it from `request.path` — decoding the
434
+ // whole path decodes THEN splits while the router splits THEN decodes,
435
+ // which over-denies the distinct record at `/owners/archived%2fx`.
436
+ //
437
+ // THE DENY IS NOW EXPRESSIBLE FROM THE CONTEXT ALONE, which is exactly
438
+ // what `recordId` bought — and it still must not be dropped. Deleting it
439
+ // does not remove a rule loudly, it turns a deny into an ALLOW, silently.
440
+ if (recordId === 'archived') return false;
441
+
442
+ // Returning a function plugs it in as a per-record filter, and it is
443
+ // enforced on every surface addressed to one of these records:
444
+ // /owners, /owners/:id, /owners/:id/pets, /owners/:id/relationships/pets
445
+ // A rejected record is 404 on record routes — the same status as a record
446
+ // that does not exist — so the filter is not an existence oracle.
447
+ return record => record.id !== 'angela' && record.id !== 'restricted';
448
+ }
449
+
450
+ // `record.owner` resolves to an OrmRecord, not to the owner's id string —
451
+ // comparing it directly against a string is the bug that made this predicate
452
+ // inert. Deliberately NO `?? record.owner` fallback: accepting the raw
453
+ // shape as well as the resolved one would absorb a resolution regression
454
+ // silently, which is exactly what blinded this fixture before.
455
+ if (model === 'animal') return record => record.owner?.id !== 'restricted';
456
+
457
+ // Allows full access to all calls that don't match any of the above conditions
286
458
  return ['read', 'create', 'update', 'delete'];
287
459
  }
288
460
  }
289
461
  ```
290
462
 
463
+
464
+ ### The access context (second argument)
465
+
466
+ `access()` is called with **two** arguments:
467
+
468
+ ```js
469
+ access(request, { model, operation })
470
+ ```
471
+
472
+ The second is the **access context** — the structural facts about the request,
473
+ which the framework already holds at authorization time. Read these instead of
474
+ parsing anything.
475
+
476
+ | Key | Value |
477
+ |---|---|
478
+ | `model` | The model this route was mounted for, as a **model name**: kebab-case, exactly as declared under `config.orm.paths.model` and keyed in the store — `'owner'`, `'animal'`, `'phone-number'`. **Not** the pluralized, dasherized, mount-prefixed *route* name. |
479
+ | `operation` | One of **`'read'`, `'create'`, `'update'`, `'delete'`** — and no second vocabulary *on this path*. Never an HTTP method name like `'GET'`, and **not** the hook vocabulary either (see [below](#operation-is-not-the-hook-operation)). `undefined` when the dispatched method has no entry in the framework's method map. |
480
+
481
+ So a predicate can be written without reference to any URL:
482
+
483
+ ```js
484
+ export default class OwnerAccess {
485
+ models = ['owner'];
486
+
487
+ access(request, { model, operation }) {
488
+ if (model === 'owner' && operation === 'read') {
489
+ return record => record.id !== 'angela';
490
+ }
491
+
492
+ return ['read'];
493
+ }
494
+ }
495
+ ```
496
+
497
+ There is no string to parse, no variant to miss, and no way to fail open through
498
+ a URL shape nobody anticipated. `model` is fixed at mount time and no request
499
+ can influence it — not a mount prefix, not a query string, not a case-varied
500
+ path, not an absolute-form request target.
501
+
502
+ #### What the context does not tell you: which surface
503
+
504
+ It names **which model and which verb**, not **which route**. Measured over the
505
+ live router, six surfaces produce one identical context:
506
+
507
+ ```
508
+ GET /owners { model: 'owner', operation: 'read' }
509
+ GET /owners/gina { model: 'owner', operation: 'read' }
510
+ GET /owners/gina/pets { model: 'owner', operation: 'read' }
511
+ GET /owners/gina/relationships/pets { model: 'owner', operation: 'read' }
512
+ GET /owners/archived { model: 'owner', operation: 'read' }
513
+ GET /owners/gina?include=pets { model: 'owner', operation: 'read' }
514
+ ```
515
+
516
+ So a rule that depends on the **sub-path** still needs `request.path` —
517
+ mount-relative and query-free, and the one read of argument one that
518
+ [Identifying the collection](#identifying-the-collection) sanctions. The sample
519
+ access class shipped with this repo has such a rule: its `/archived` deny
520
+ **cannot be expressed from the context alone**, and a predicate migrated to
521
+ context-only would silently drop it — a deny becoming an allow.
522
+
523
+ **Superseded 2026-09-01 by [#236](https://github.com/abofs/stonyx-orm/issues/236) /
524
+ [#237](https://github.com/abofs/stonyx-orm/issues/237).** The context also carries
525
+ `recordId` — the record this route was addressed to, already decoded — so the
526
+ `/archived` deny **is** expressible from the context alone, and the shipped sample
527
+ no longer reads `request.path`. The full contract is `AccessContext.recordId` in
528
+ `src/types/orm-types.ts`, which ships. This section — the signature, the key table
529
+ and this paragraph — is corrected by
530
+ [#238](https://github.com/abofs/stonyx-orm/issues/238); the pointer is here because
531
+ what it currently says is an instruction, and the instruction is wrong.
532
+
533
+ Note also that the related-resource and `?include=` surfaces serve *another
534
+ model's* records under `model: 'owner'`, and the context gives a predicate no
535
+ signal that it is authorizing a related-resource route. That is
536
+ [#196](https://github.com/abofs/stonyx-orm/issues/196).
537
+
538
+ #### `operation` is not the hook `operation`
539
+
540
+ This module exposes a **second** `operation` vocabulary, on an identically-named
541
+ key of an identically-shaped context object:
542
+ [hook contexts](#hook-context-object) carry `list` / `get` / `create` /
543
+ `update` / `delete`. The access vocabulary collapses `list` and `get` into
544
+ `'read'`, so for one `GET /animals/1` a hook sees `'get'` while `access()` sees
545
+ `'read'` — and a predicate cannot distinguish a collection read from a
546
+ record read.
547
+
548
+ "No second vocabulary" above is a statement about the **access path**, where
549
+ both the context and the permission array come from one method map. It is not a
550
+ statement about the module. Writing `operation === 'get'` in a predicate never
551
+ matches, and a predicate that stops matching falls through to the permission
552
+ array — so the misreading is fail-open shaped. In TypeScript the exported
553
+ `AccessOperation` union makes it a compile error.
554
+
555
+ The four `operation` values are the same four strings the permission-array
556
+ return shape is written in (`['read', 'create', 'update', 'delete']`), because
557
+ both come from one method map inside the framework. The two forms cannot
558
+ disagree about the same request.
559
+
560
+ **`operation` is `undefined`, never defaulted, for an unmapped method.** Express
561
+ delivers `HEAD` to the `GET` handler, so this is reachable. It is deliberately
562
+ not defaulted to `'read'`: a fabricated operation would turn an unclassified
563
+ request into an authorized one. Treat `undefined` as *not classified* and deny.
564
+
565
+ **The second argument is additive.** JavaScript ignores extra arguments, so an
566
+ existing `access(request)` predicate keeps working exactly as it did. Nothing
567
+ needs to be migrated to keep running — but note that argument **one** is still
568
+ the raw request, so the warning in
569
+ [Identifying the collection](#identifying-the-collection) still applies to any
570
+ predicate that reads it.
571
+
572
+ #### `record` is not in the context
573
+
574
+ Deliberately, and it is not an oversight. `auth()` runs after route matching but
575
+ **before any handler executes**, so nothing has been fetched yet. Supplying a
576
+ record would force a pre-fetch on every request — a second store hit, a new
577
+ failure mode, and an ordering change in the middle of an authorization path.
578
+
579
+ It is also unnecessary: the **function** return shape already *is* the
580
+ per-record hook. Return `(record) => boolean` and the handlers apply it to every
581
+ record the request touches. Auth-time and record-time are separate decision
582
+ points, and the contract keeps them separate.
583
+
584
+ #### Reaching another model's predicate
585
+
586
+ The model → predicate map is published on the ORM instance at boot, before any
587
+ route is mounted, so a predicate can be resolved by model name and asked about a
588
+ request routed to a *different* model:
589
+
590
+ ```js
591
+ import Orm from '@stonyx/orm';
592
+
593
+ const predicate = Orm.instance.getAccess('animal');
594
+ if (!predicate) return deny;
595
+
596
+ const verdict = predicate(request, { model: 'animal', operation: 'read' });
597
+ ```
598
+
599
+ **`undefined` means no predicate could be resolved — not that the model is
600
+ unrestricted. Treat it as deny.** It covers a model with no access class *and* a
601
+ model whose access class failed to **load**: a load failure is caught and warned
602
+ about, and the partial map is published anyway, so a missing key is not evidence
603
+ of an unrestricted model. This is the same rule as `operation === undefined`
604
+ above, and for the same reason.
605
+
606
+ The raw map is `Orm.instance.accessFunctions`, keyed by model name; prefer
607
+ `getAccess()` — it is guarded against inherited `Object.prototype` members and a
608
+ direct index is not. Note that it maps a model name to the predicate of the
609
+ access *class* that claims it, which may claim many models: against this repo's
610
+ sample, `getAccess('owner') === getAccess('animal')`.
611
+
612
+ #### Passing the context makes a model-correct answer *possible*
613
+
614
+ It does not make the answer model-correct on its own. **The resolved predicate
615
+ has to read the context.** Against a predicate that ignores it the failure is
616
+ measurable. On a request Express dispatched to `GET /owners/angela`, asked about
617
+ **animals**, the sample as it shipped before
618
+ [#222](https://github.com/abofs/stonyx-orm/issues/222) answered:
619
+
620
+ ```
621
+ getAccess('animal')(ownersRequest, { model: 'animal', operation: 'read' })
622
+ -> record => record.id !== 'angela' && record.id !== 'restricted'
623
+ ```
624
+
625
+ That is the **owners** filter, and it returns `true` for animal 21 — the record
626
+ hidden on every animal surface. Under a mount such a predicate recognizes
627
+ neither way it is worse still: it falls through to
628
+ `['read', 'create', 'update', 'delete']`, a full CRUD grant. Either way the
629
+ context was supplied and the answer is not the animal answer, and it is wrong in
630
+ the direction that **grants** — because that predicate was single-argument and
631
+ identified its collection from the request, so it answered about the collection
632
+ the request was *addressed to* while being asked about another one.
633
+
634
+ The sample shipped with this repo has since been migrated to read the context,
635
+ and the same call now answers with the **animal** filter:
636
+
637
+ ```
638
+ getAccess('animal')(ownersRequest, { model: 'animal', operation: 'read' })
639
+ -> record => record.owner?.id !== 'restricted'
640
+ ```
641
+
642
+ A single-argument predicate remains the default in every consumer tree, and a
643
+ caller has no supported way to tell which kind it resolved. The boot-time arity
644
+ warning that surfaces one is
645
+ [#221](https://github.com/abofs/stonyx-orm/issues/221).
646
+
647
+ So: pass the context, and do not treat a resolved predicate's answer as
648
+ model-specific until that predicate has been migrated to read it.
649
+
650
+ ### Return values
651
+
652
+ | `access()` returns | Effect |
653
+ |---|---|
654
+ | `false` (or any falsy value) | `403` for the whole request |
655
+ | `true` | full access, no filter |
656
+ | `['read', 'create', 'update', 'delete']` | the listed operations only; anything else is `403` |
657
+ | `'read'` (a bare string) | **one** permission, equivalent to `['read']` |
658
+ | a function | a per-record filter — see below |
659
+ | anything else | `403` — unknown shapes fail **closed** |
660
+
661
+ A `throw` inside `access()` is a **denial**, not a 500.
662
+
663
+ ### Filter functions
664
+
665
+ A function return value is a **per-record predicate**, and it is enforced on
666
+ every endpoint that is addressed to a record — not only on the collection.
667
+
668
+ It is evaluated against the record the route is *addressed to*, **on that model
669
+ only**. It is not a guarantee that a hidden record cannot be reached or modified:
670
+ a write to a *different* collection can still re-parent one. See
671
+ [Known limitations](#known-limitations) and
672
+ [#207](https://github.com/abofs/stonyx-orm/issues/207).
673
+
674
+ | Endpoint | A record the predicate rejects |
675
+ |---|---|
676
+ | `GET /:models` | omitted from the collection |
677
+ | `GET /:models/:id` | `404` |
678
+ | `GET /:models/:id/{relationship}` | `404` — the **addressed** record is filtered, not the related one |
679
+ | `GET /:models/:id/relationships/{relationship}` | `404` — same |
680
+ | `PATCH /:models/:id` | `404`, no attribute is applied |
681
+ | `DELETE /:models/:id` | `404`, the record is not removed and no SQL `DELETE` is issued |
682
+ | `POST /:models` | `403`, and a record **this request inserted** is rolled back — see [Known limitations](#known-limitations) for why the rollback is conditional |
683
+
684
+ **Denied record-level requests return 404, not 403.** This is deliberate and it
685
+ is the property most easily "improved" away. 403 would confirm that the record
686
+ exists to a caller who is not allowed to know that, which turns the filter into
687
+ an existence oracle: `404` means "no such record", `403` means "there is one and
688
+ it is not yours". Every status on a record route must therefore be identical for
689
+ "filtered out" and "does not exist" — including `DELETE`, which is why deleting
690
+ a record that never existed also returns 404 rather than 204.
691
+
692
+ `POST` is the one exception and returns **403**, because 404 on a mounted
693
+ collection route is indistinguishable from "model not mounted" — a genuinely
694
+ different failure a developer needs to diagnose.
695
+
696
+ **A client-supplied `id` on `POST` is refused with `403` whenever a function
697
+ filter is in force.** This is the part that keeps `POST` from being an
698
+ enumeration oracle, and it is worth understanding rather than working around.
699
+ The duplicate-id check has to run before the filter, and it sees records the
700
+ filter hides, so the *status* of a `POST` otherwise leaks whether an id is
701
+ taken:
702
+
703
+ | `POST /animals` with a payload the caller may create | before | now |
704
+ |---|---|---|
705
+ | an id held by a record the filter **hides** | `403` | `403` |
706
+ | an id that is **free** | `200` | `403` |
707
+ | an id held by a record the caller **can see** | `409` | `403` |
708
+
709
+ Three outcomes, one request per id, the whole id space. Filtering only the
710
+ *collision* status narrows that to callers who cannot create a record they are
711
+ allowed to see; it does not close it. It cannot be closed while a caller both
712
+ chooses the id and learns whether the create succeeded — so under a filter the
713
+ caller does not choose the id. The refusal happens before any store lookup, so
714
+ neither the status nor the response time depends on whether the id exists.
715
+
716
+ Let the server assign the id and read it back from the response — and read it
717
+ back rather than predicting it, because the value it returns is documented but
718
+ not stable across model kinds: a numeric-id model gets `max + 1` (or, at the
719
+ numeric ceiling, the lowest free integer), and a string-id model gets
720
+ `<model>-<n>`. See breaking change 8.
721
+
722
+ **What a server-assigned id is not.** It is not a secret. On a string-id
723
+ collection it is dense and enumerable from `1`, where previously it inherited
724
+ whatever entropy the last-inserted id happened to carry — a UUID-seeded store
725
+ answered a UUID-derived key. If a collection has **no** `access` config its
726
+ record-level routes are ungated, so the id was the only thing standing between
727
+ an unauthenticated caller and `GET`/`PATCH`/`DELETE` on a record. That was never
728
+ a control and must not become one; configure `access`.
729
+
730
+ **And the id itself is an occupancy signal — on both model kinds.**
731
+ `assignRecordId` reads the whole store, not the caller's filtered view — it
732
+ never sees `state.filter` — so the id it returns is a function of records the
733
+ caller may not be permitted to read. **This applies to numeric-id collections
734
+ as well as string-id ones**, and the conditions differ, so read both:
735
+
736
+ - **String-id collections, always.** The assigned `n` is the smallest positive
737
+ integer whose landing key is free, which tells the caller that every key
738
+ below it is taken, hidden or not.
739
+ - **Numeric-id collections, once one record sits at the numeric ceiling.** The
740
+ normal answer is `max + 1`, which discloses only the maximum. But `max + 1`
741
+ is not representable at or above 2^53, so the walk restarts from `1` (see
742
+ breaking change 8) and the assigned id becomes the smallest free integer —
743
+ the same occupancy predicate, now over arbitrary low keys. Each subsequent
744
+ no-id `POST` names the next free one, so a caller can enumerate the holes in
745
+ a range it cannot read.
746
+
747
+ **A ceiling record reaches a filter-protected collection even though `POST`
748
+ refuses caller ids on one.** Breaking change 3 makes
749
+ `POST /animals {"id": 9007199254740992}` answer `403`, but the same id lands
750
+ through a *relationship write on another collection* —
751
+ `POST /owners` carrying `attributes: { pets: [{ "id": 9007199254740992 }] }`
752
+ creates the animal under that key
753
+ ([#207](https://github.com/abofs/stonyx-orm/issues/207), the same channel the
754
+ **Known limitations** re-parenting note describes). So the precondition is
755
+ reachable by an unauthenticated caller on exactly the collections `access`
756
+ exists to protect. Measured on the sample fixture, with every animal hidden by
757
+ the `/animals` predicate and keys 4 and 7 deleted:
758
+
759
+ ```
760
+ GET /animals -> 200 [] (nothing visible)
761
+ GET /animals/4 -> 404 (free — indistinguishable from hidden)
762
+ POST /animals {"id":4} -> 403 (breaking change 3)
763
+ POST /owners {... pets:[{"id":9007199254740992}]} -> 200 (#207 plants the ceiling record)
764
+ POST /animals (no id) -> 200 id=4 <- names a hole in the hidden range
765
+ POST /animals (no id) -> 200 id=7 <- and the other one
766
+ POST /animals (no id) -> 200 id=13
767
+ POST /animals (no id) -> 200 id=14
768
+ ```
769
+
770
+ Closing this requires the assignment to be filter-aware, which is a change to
771
+ the `access` contract rather than a fix; it is stated here rather than left to
772
+ be discovered. Callers with no function-style filter are unaffected — there are
773
+ no hidden records to disclose.
774
+
775
+ ### Identifying the collection
776
+
777
+ **Do not reconstruct the request path — and since
778
+ [#202](https://github.com/abofs/stonyx-orm/issues/202) you do not have to
779
+ identify the collection at all.** Read `model` from
780
+ [the access context](#the-access-context-second-argument): it is fixed at mount
781
+ time, no request can influence it, and there is nothing left to parse.
782
+
783
+ **Everything below is the record of what happened when this sample did parse
784
+ it.** It is kept as history, not as a recipe — none of these matching strategies
785
+ should be written into a new predicate. Every version of this sample that tried
786
+ to identify the collection from the request target failed **open**, and each
787
+ variant was found only after the previous one was fixed:
788
+
789
+ | # | Variant | Why it fails open |
790
+ |---|---|---|
791
+ | 1 | match `request.url` | `RestServer.mountRoute` mounts each model as an Express **sub-app**, so `url` is mount-relative — `GET /owners/angela` arrives as `/angela`. A `/owners` prefix match is **always false**, so the branch never fires and `access()` falls through to whatever it returns last. |
792
+ | 2 | anchored match on a raw `request.originalUrl` | `originalUrl` carries the query string, so `=== '/owners'` misses `/owners?filter[age]=30` and that collection comes back unfiltered. `endsWith('/owners')` is the older half of the same trap: it leaves every record route unguarded. |
793
+ | 3 | case-sensitive matcher | `RestServer` mounts with a bare `express()`, whose default is `caseSensitive: false`. A matcher stricter than the router that dispatched the request can simply be stepped around: `GET /owners/angela` → 404 but `GET /OwNeRs/angela` → 200 in full, and `DELETE /ANIMALS/22` destroyed a hidden record. Router-side fix: [stonyx-rest-server#47](https://github.com/abofs/stonyx-rest-server/issues/47). |
794
+ | 4 | hard-coded `/owners` | With `ORM_REST_ROUTE=/api` every url becomes `/api/owners/...` and the sample matches nothing — environment-specifically, which is harder to notice than failing everywhere. The remediation this document used to give was itself broken: `` `${config.orm.restServer.route}owners` `` evaluates to **`/apiowners`**, so a reader who followed the correction exactly still failed open and believed they had handled it. |
795
+ | 5 | any match on `originalUrl` at all | HTTP/1.1 permits an **absolute-form** request-target. Express routes on `parseurl(req).pathname`, so the request dispatches normally — but `originalUrl` is the raw target. `GET http://anything.example/owners/angela` yields `originalUrl === 'http://anything.example/owners/angela'`, which has no `/owners` prefix. Measured: the record came back in full, `DELETE` succeeded, and it walked past a hard `return false` deny the same way. |
796
+
797
+ **The fix is not a sixth rule, and it is not a better string to match.** It is
798
+ to stop identifying the collection at all. That is a statement about
799
+ **identifying the collection**, and it is not a statement about the sample as a
800
+ whole: the `/archived` sub-path rule *is* still a string match, and
801
+ [#228](https://github.com/abofs/stonyx-orm/issues/228) is a sixth spelling that
802
+ gets past it. Sub-path rules are the residue this fix does not cover, which is
803
+ why they must normalise the way the router does.
804
+
805
+ An intermediate revision read **`request.baseUrl`** — the mount Express
806
+ *actually matched*. That closed all five variants: it carries no query string
807
+ (variant 2), it is not mount-relative (variant 1), it already contains the
808
+ configured `ORM_REST_ROUTE` prefix (variant 4 — there is nothing left to derive,
809
+ so `/apiowners` is unconstructible), and it is unaffected by an absolute-form
810
+ target (variant 5). It was still a transport artifact standing in for a
811
+ structural fact, and it is **no longer what the sample does**: the sample reads
812
+ `model`, so variants 1, 2, 4 and 5 are unconstructible against it rather than
813
+ handled. **Variant 3 survives**, in the one string comparison the migration
814
+ leaves behind: the `/archived` sub-path deny folds case but does not decode
815
+ ([#228](https://github.com/abofs/stonyx-orm/issues/228)). The table below is
816
+ retained as the measured evidence behind the five variants, not because any of
817
+ these values should be matched on:
818
+
819
+ | request | `request.url` | `request.originalUrl` | `request.baseUrl` | `request.path` |
820
+ |---|---|---|---|---|
821
+ | `GET /owners` | `/` | `/owners` | `/owners` | `/` |
822
+ | `GET /owners/angela` | `/angela` | `/owners/angela` | `/owners` | `/angela` |
823
+ | `GET /owners/angela?filter[age]=30` | `/angela?filter[age]=30` | `/owners/angela?filter[age]=30` | `/owners` | `/angela` |
824
+ | `GET /OwNeRs/angela` | `/angela` | `/OwNeRs/angela` | `/OwNeRs` | `/angela` |
825
+ | `GET http://anything.example/owners/angela` | `http://anything.example/angela` | `http://anything.example/owners/angela` | `/owners` | `/angela` |
826
+ | `GET /api/animals/22` (`ORM_REST_ROUTE=/api`) | `/22` | `/api/animals/22` | `/api/animals` | `/22` |
827
+
828
+ **Superseded 2026-09-01 by [#236](https://github.com/abofs/stonyx-orm/issues/236) /
829
+ [#237](https://github.com/abofs/stonyx-orm/issues/237) — "Variant 3 survives" above,
830
+ and the two paragraphs below, are no longer true.** The access context now carries
831
+ `recordId`, the **decoded** route-parameter id, and the sample compares against it:
832
+ the one string comparison variant 3 lived in is gone, `#228` is **closed**, and no
833
+ read of argument one survives in the sample. The wording is left standing rather
834
+ than deleted because it appears at four sites (this file twice,
835
+ `src/orm-request.ts`, and the test fixture) and retiring one of four leaves the
836
+ shipped copies contradicting each other; retiring all four **with the measurement
837
+ that retires them** is [#238](https://github.com/abofs/stonyx-orm/issues/238).
838
+
839
+ **One read of argument one survives, and it must: `request.path`.** It is
840
+ mount-relative and query-free, and it is for rules that distinguish **sub-paths**
841
+ beneath the mount — as the `/archived` deny in the sample above does. The context
842
+ names which model and which verb, **not which route**, so that deny *cannot be
843
+ expressed from the context alone*, and a context-only rewrite would silently turn
844
+ it into an allow.
845
+
846
+ **Normalise the way the router that dispatched the request does — and
847
+ case-folding alone does not.** A matcher stricter than the router can be stepped
848
+ around, so the sample lower-cases before comparing (the router matched
849
+ case-insensitively). That closes the case gap and **it is not the whole rule**:
850
+ Express sets `request.path` from the **raw, undecoded** pathname while the router
851
+ **decodes** `:id`, so `GET /owners/%61rchived` reaches a `path === '/archived'`
852
+ comparison as `/%61rchived`, walks past the deny, and is dispatched as the record
853
+ `archived`. That gap is live in the sample above and is tracked as
854
+ [#228](https://github.com/abofs/stonyx-orm/issues/228) — **do not read the
855
+ `.toLowerCase()` there as a complete normalisation recipe.** Record ids are
856
+ case-sensitive and must be compared at their real case.
857
+
858
+ **Do not follow the two paragraphs above — superseded 2026-09-01 by
859
+ [#236](https://github.com/abofs/stonyx-orm/issues/236) /
860
+ [#237](https://github.com/abofs/stonyx-orm/issues/237).** They are *instructions*,
861
+ not merely stale observations, which is why this note is louder than a date. The
862
+ sample no longer reads `request.path` and no longer calls `.toLowerCase()` on
863
+ anything it compares: `.toLowerCase()` was measured wrong in **both directions at
864
+ once** — with a distinct owner seeded at `ARCHIVED`, `GET /owners/ARCHIVED` was a
865
+ false **deny** on the wrong record and `GET /owners/%41RCHIVED` a false **allow**
866
+ on that same record. Compare `recordId` **as it arrives**: do not case-fold it, do
867
+ not decode it, do not derive it from `request.path`. The contract is
868
+ `AccessContext.recordId` in `src/types/orm-types.ts`, which ships and says "Do NOT
869
+ case-fold it". Retirement of this wording, with its measurement:
870
+ [#238](https://github.com/abofs/stonyx-orm/issues/238).
871
+
872
+ **Fail closed on anything you cannot identify — on *either* argument.**
873
+ `String(request.originalUrl ?? '')` was once added here to stop a `TypeError`,
874
+ and it traded fail-closed for fail-**open**: an empty string matched no
875
+ collection, so `access()` fell through to the permission array and granted full
876
+ CRUD. The same rule applies to the context — the sample returns `false` for an
877
+ absent `model` rather than falling through. Since #202 the guard and the read can
878
+ sit on **different objects**, and a guard on argument two does not protect a read
879
+ of argument one: the sample therefore also returns `false` when `request.path` is
880
+ absent or is not a string, rather than letting `?? ''` fall through to the
881
+ per-record filter. An input you cannot identify must **deny**.
882
+
883
+ ### Known limitations
884
+
885
+ - **A function-style filter is not a guarantee that a hidden record cannot be
886
+ modified.** A write to a *different* collection can re-parent one and de-hide
887
+ it: `POST /owners` (or `PATCH /owners/{id}`) carrying
888
+ `relationships: { pets: { data: { id: 21 } } }` — or
889
+ `attributes: { pets: [21, 22] } `, which never enters the relationships loop at
890
+ all — re-parents animal 21 onto an owner the caller is permitted to write. The
891
+ animal's `owner` is the field the `/animals` predicate reads, so the record
892
+ stops being rejected: it becomes readable through `GET /animals/21` and
893
+ deletable through `DELETE /animals/21`. **Reachable unauthenticated** wherever
894
+ one collection is writable and another is filtered on a field the first can
895
+ set. Blocking it requires checking animal 21 against the **animal** model's
896
+ predicate while servicing an **owners** route — cross-model access resolution,
897
+ which the contract could not express before
898
+ [#202](https://github.com/abofs/stonyx-orm/issues/202): `access()` never
899
+ received the model structurally and `setup-rest-server.ts` discarded the
900
+ model→predicate map at boot. **#202 has landed and both halves now exist** —
901
+ see [The access context](#the-access-context-second-argument):
902
+ `Orm.instance.getAccess(modelName)` makes another model's predicate
903
+ **reachable**, and `context.model` makes a **model-correct answer possible** —
904
+ possible, not guaranteed: the resolved predicate has to read the context. The
905
+ sample shipped with this repo now does
906
+ ([#222](https://github.com/abofs/stonyx-orm/issues/222)), so
907
+ `getAccess('animal')` answers with the animal filter; a predicate that ignores
908
+ the second argument still answers about the collection the request is
909
+ addressed to, and the boot-time warning that surfaces one is
910
+ [#221](https://github.com/abofs/stonyx-orm/issues/221). **The mechanism
911
+ exists; the ORM does not yet use it on this path.** The re-parenting write above is still
912
+ **not refused** — that enforcement is
913
+ [#196](https://github.com/abofs/stonyx-orm/issues/196) and
914
+ [#207](https://github.com/abofs/stonyx-orm/issues/207), which were blocked on
915
+ #202 and are now free to proceed. Until they land, do not rely on a filter to
916
+ keep a record unmodifiable; keep the *writable* collections' predicates as tight as
917
+ the hidden ones.
918
+ - **Authorization by identifying the collection is a consumer-side
919
+ reconstruction of information the framework already holds.** `access()`
920
+ receives a transport artifact and is asked to work out which model, which
921
+ operation and which record the request addresses. The five variants above are
922
+ the five ways that has been observed to fail open so far. Tracked as
923
+ [#202](https://github.com/abofs/stonyx-orm/issues/202).
924
+ - **Related and included records are not filtered.** The predicate is evaluated
925
+ against the record the route is *addressed to*. `GET /animals/1/owner`,
926
+ `GET /animals/1/relationships/owner` and `?include=owner` all serialize the
927
+ related record without resolving that model's own access class, so a filter on
928
+ `/owners` does not hide an owner reached through `/animals`. Tracked as
929
+ [#196](https://github.com/abofs/stonyx-orm/issues/196), which covers
930
+ `include=`, related-resource routes and relationship-linkage routes. This is
931
+ **membership** — whether the related resource is served at all — and it is a
932
+ different question from which ids a document may *name*, immediately below.
933
+ - **Relationship linkage is filtered on every request-bound surface that
934
+ serializes a record — the reads, the two writes, and `included`.** A
935
+ document's `relationships.*.data` used to publish the id of every related
936
+ record unconditionally, so a record hidden on every one of its own surfaces
937
+ was still named inside another model's document — with no `include=`, no
938
+ relationship route and no query string
939
+ ([#234](https://github.com/abofs/stonyx-orm/issues/234)). The ORM now resolves
940
+ the **related** model's own access class on `GET /:models`, `GET /:models/:id`,
941
+ both `GET /:models/:id/{relationship}` shapes, the `POST /:models` and
942
+ `PATCH /:models/:id` **response documents**, and every record inside an
943
+ `?include=` **`included`** array
944
+ ([#235](https://github.com/abofs/stonyx-orm/issues/235)), and asks it
945
+ `{ model: <related>, operation: 'read' }`. **`operation` is `'read'` even on a
946
+ write route, and that is correct rather than an oversight** — the question
947
+ asked of the *related* model is "may this caller **read** this id", not "may
948
+ they update it". An access class that grants `['create']` but not `['read']`
949
+ on the related model therefore denies that linkage on its own `POST`
950
+ response; that is the fail-closed direction. Do **not** wire these handlers to
951
+ `methodAccessMap[request.method]`: it would ask a different question on a
952
+ write route than on a read route, which is the two-vocabularies failure
953
+ `createLinkageFilter` exists to prevent. An unresolvable class
954
+ (`getAccess()` → `undefined`) and a predicate that throws both **deny**.
955
+
956
+ **What the two write surfaces cost before #235, measured rather than
957
+ described:** one HTTP verb defeated the filter on the same record. On
958
+ `dev @ 8dda5d6`, seconds apart, with no query string and no relationship
959
+ route, `GET /animals/1` returned `owner.data: null` while `PATCH /animals/1`
960
+ returned **200 naming angela**. Any caller who could read a record could also
961
+ write it and be handed the id the read withheld. That consequence is kept here
962
+ after the fix, and stated as a measurement, because **naming the two handlers
963
+ is not a substitute for it** — a reader who is told only that `POST` and
964
+ `PATCH` are now covered cannot tell what was wrong, and a reviewer cannot tell
965
+ whether the fix addressed it. A
966
+ filtered-out relationship is **indistinguishable from a genuinely empty one** —
967
+ an emptied `hasMany` is `data: []` and an emptied `belongsTo` is `data: null`,
968
+ both **keeping their `links`**, which are built from the serialized record's
969
+ own id and never from the related one. On the two **write** surfaces there are
970
+ no `links` to keep: neither handler passes a `baseUrl`, so a filtered and a
971
+ genuinely-empty relationship are both a bare `{ "data": … }` there. That is
972
+ pre-existing and deliberate — adding `baseUrl` to the write handlers would be
973
+ an unrelated change to their response shape. Nothing errors and no status changes,
974
+ because throwing here would be an existence oracle *and* would throw out of
975
+ the enclosing `JSON.stringify`.
976
+
977
+ **That resolves the right class; it does not guarantee a model-correct
978
+ answer, and the failure direction is not the safe one.** Only a predicate that
979
+ *reads* `context.model` can answer about the model it was asked about — see
980
+ [Passing the context makes a model-correct answer *possible*](#passing-the-context-makes-a-model-correct-answer-possible)
981
+ above. A **single-argument predicate remains the default in every consumer
982
+ tree**, it identifies its collection from the request, and asked about
983
+ `owner` on a request dispatched to `/animals` it answers about **animals**.
984
+ Measured against this repo's own fixture with an arity-1 predicate registered
985
+ for `owner`: `GET /owners` correctly returns `["gina","michael","bob"]` while
986
+ `GET /animals/1` returns `owner.data {"type":"owner","id":"angela"}` — the
987
+ #234 defect, on the #234 surface, after the #234 fix. This is not a
988
+ regression (the id was published unconditionally before), it cannot be fixed
989
+ from this side, and the signal that surfaces such a predicate is
990
+ [#221](https://github.com/abofs/stonyx-orm/issues/221) /
991
+ [#213](https://github.com/abofs/stonyx-orm/issues/213). **Migrate your
992
+ predicates to read the context before relying on this filter.** A migrated,
993
+ context-reading predicate degrades the other way — it can over-deny a
994
+ *permitted* related record, which is recorded in the release notes as a
995
+ breaking change.
996
+
997
+ **Not yet covered by #235. Each still publishes ids the surfaces above
998
+ withhold, except where its own owning issue has since closed it — the first
999
+ entry names an issue that is in flight as this is written:**
1000
+
1001
+ - **`GET /:models/:id/relationships/{relationship}`, and its state is #232's
1002
+ to report rather than this entry's.**
1003
+ [#232](https://github.com/abofs/stonyx-orm/issues/232) owns the
1004
+ relationships-linkage route. Its *primary data* is linkage,
1005
+ so filtering it is a **membership** decision — which is why it is the filed
1006
+ child of [#196](https://github.com/abofs/stonyx-orm/issues/196) and not of
1007
+ #234. The route builds its `{type, id}` objects by hand and never calls
1008
+ `toJSON`, so the `linkage` **option** never reaches it; whatever that route
1009
+ filters, it filters itself. Measured **on `dev @ 8dda5d6`**, the commit
1010
+ #235 branched from: `GET /animals/1/relationships/owner` answered
1011
+ `{"type":"owner","id":"angela"}` while `GET /owners/angela` was `404`. That
1012
+ measurement is pinned to a commit on purpose, so that it does not quietly
1013
+ become a false claim about `dev`. **PR
1014
+ [#247](https://github.com/abofs/stonyx-orm/pull/247) is in flight against
1015
+ this entry**; if it has landed, this route is covered and the bullet #247
1016
+ adds above supersedes this one.
1017
+ - **Whether a related resource appears in `included` at all.**
1018
+ [#233](https://github.com/abofs/stonyx-orm/issues/233) owns whether a
1019
+ related resource appears in `included`. #235 filters what a record
1020
+ *already in* `included` may **name**; a hidden record is still a
1021
+ **member** of that array. The two are different questions and neither closes
1022
+ the other: after #235, `GET /animals/1?include=owner,owner.pets` returns
1023
+ `owner.data: null` on every permitted animal it sideloads **and still
1024
+ includes the hidden owner as a resource**.
1025
+ - **A computed attribute that interpolates a related record's id.**
1026
+ [#245](https://github.com/abofs/stonyx-orm/issues/245) owns this channel,
1027
+ and **it is open as this is written**. `relationships.*.data` is a structure
1028
+ this module builds, so it can be filtered; a computed property is arbitrary
1029
+ consumer code returning an arbitrary value. Whether that makes the channel a
1030
+ **framework defect** the ORM should close — by handing computed getters a
1031
+ verdict, or by refusing to run them while a filter is in force — or a
1032
+ **consumer contract** the ORM should only document, is the question #245
1033
+ must decide. **This README does not decide it; neither reading should be
1034
+ read out of the text here.** Measured on this repo's own fixture, where the
1035
+ `animal` model has a `get tag()` that interpolates `owner.id`: **every**
1036
+ animal document on **every** surface — including the ones above — carries
1037
+ `attributes.tag: "angela's small dog"` for an owner that answers `404`. That
1038
+ measurement is where #245 starts, and it holds whichever way the decision
1039
+ lands. Until it lands, if your access rules hide a record, audit your
1040
+ computed properties for its identifiers.
1041
+ - **A bare `toJSON()` still emits unfiltered linkage, and that is deliberate.**
1042
+ `Record.toJSON()` **applies** a verdict; it never **resolves** one. It has no
1043
+ request, and the documented `access()` contract permits a predicate to read
1044
+ one — the sample in this README does, for its sub-path rule — so a filter
1045
+ resolved inside `toJSON()` denies *permitted* records rather than hidden ones
1046
+ (measured: 967 → 964, all three failures over-denials). `toJSON` is also the
1047
+ `JSON.stringify` hook, so `JSON.stringify(record)`, `res.json(record)` and
1048
+ `console.log(JSON.stringify(record))` reach it with a **string** in the
1049
+ options slot and have no syntactic place to pass a verdict. The no-argument
1050
+ call therefore returns the pre-#234 document unchanged. Fail-closed by default
1051
+ is not available either: `Orm.instance.accessFunctions` is `{}` in any process
1052
+ that never ran `setup-rest-server` — a CLI, an SQL-only process, a test — so
1053
+ it would empty every relationship on every document in processes with no REST
1054
+ surface to protect. Closing the residual means moving JSON:API serialization
1055
+ **off** the `toJSON` name, tracked as
1056
+ [#230](https://github.com/abofs/stonyx-orm/issues/230). If you hand a `Record`
1057
+ to an untrusted consumer, serialize it through the REST layer, or resolve a
1058
+ verdict with the **exported** `createLinkageFilter(request)` and pass it as
1059
+ the `linkage` option — do not write your own reading of `access()`. This is a
1060
+ consumer obligation with no signal when it lapses; it is stated once, in full,
1061
+ under [Consumer Contracts](#consumer-contracts) below.
1062
+ - **`format()` and `serialize()` are deliberately not filtered, and must stay
1063
+ that way.** `format()` is the **persistence** path — its output is what
1064
+ `Orm.db.save()` writes to disk — so applying an access filter there would
1065
+ write a truncated database. That is **data loss**, not disclosure prevention.
1066
+ Neither method appears anywhere in the REST response path.
1067
+ - **A before-hook that returns a value short-circuits the request.** On write
1068
+ operations addressed to a record the filter is consulted first, so a hook
1069
+ cannot answer for a record the caller may not see. On reads it is not, so a
1070
+ `beforeHook('get', ...)` read-through cache can answer past the filter.
1071
+ - **`beforeHook('create', ...)` still runs for a `POST` that is denied.** For
1072
+ `create` there is no record to test until the handler has built one, so the
1073
+ denial is not knowable in time. Every *after*-hook is gated, and every
1074
+ before-hook on `update` and `delete` is gated; before-`create` is the one
1075
+ exception. A before-`create` hook must not assume the create will succeed.
1076
+ - **A caller can still learn that a collection *has* a per-record filter**, by
1077
+ observing `403` rather than `409`/`200` for an id-bearing `POST`. That
1078
+ discloses a configuration fact, not the existence of any record.
1079
+ - **Enforcement is post-fetch.** The record is loaded and then tested, which
1080
+ leaves a small timing difference between a hidden record and one that never
1081
+ existed. Tracked as [#197](https://github.com/abofs/stonyx-orm/issues/197).
1082
+ - **A `relationships` key that is not a declared relationship is still applied
1083
+ to the record.** The key comes verbatim from the request body and is checked
1084
+ against nothing except `id`, which is stripped. On a `POST` that makes an
1085
+ undeclared key a mass-assigned attribute; on a `PATCH` it is passed to
1086
+ `updateRecord`. `id` is stripped in both handlers because it defeats breaking
1087
+ change 3 above; the general form is tracked as
1088
+ [#204](https://github.com/abofs/stonyx-orm/issues/204).
1089
+ - **A `POST` body `id` that the duplicate check cannot resolve can still
1090
+ overwrite a different record on an unfiltered collection.** The lookup is
1091
+ correct and deliberately does not coerce: `"9105h"` is rejected as a string
1092
+ rather than truncated, and `9105.5`, `[9105]` and `true` are passed through as
1093
+ themselves. The model's id transform then coerces anyway — a bare `parseInt`
1094
+ with no such guard — so the create lands on `9105` (or on `NaN`) and
1095
+ overwrites whatever is there. **This is not string-only**: any body id whose
1096
+ transform output differs from its lookup key is the same defect. Filtered
1097
+ collections are unaffected — breaking change 3 refuses any client-supplied id
1098
+ — so this reaches consumers with **no** function-style filter. Tracked as
1099
+ [#205](https://github.com/abofs/stonyx-orm/issues/205). Its sibling
1100
+ [#203](https://github.com/abofs/stonyx-orm/issues/203) — a **server-assigned**
1101
+ id landing on an occupied slot — is **fixed**; see breaking change 8. #205 is
1102
+ the client-supplied half and is still open.
1103
+ - **`context.record` is `undefined` for an after-`create` hook when a string-id
1104
+ model is given a numeric-looking id.** The post-create lookup uses the same id
1105
+ coercion as every other surface, which resolves `'9107'` to the number `9107`,
1106
+ while a model declaring `id = attr('string')` files the record under the string
1107
+ key. The create itself succeeds and `context.response.data` is correct; only
1108
+ the hook's view of the record is wrong, and it is wrong *silently*. Tracked as
1109
+ [#209](https://github.com/abofs/stonyx-orm/issues/209).
1110
+ - **A denied `POST` rolls back only a record it *inserted*.** The rollback
1111
+ requires the store to have grown, because removing by id alone is a write
1112
+ primitive keyed by a caller-supplied value. **The reachability condition this
1113
+ bullet used to state is gone**: it was
1114
+ [#203](https://github.com/abofs/stonyx-orm/issues/203) — `assignRecordId`
1115
+ returned last-*inserted* + 1, so a server-assigned id could land on an
1116
+ occupied slot and `createRecord` would update it in place — and #203 is fixed
1117
+ (breaking change 8). A server-assigned create can no longer overwrite, so on a
1118
+ collection whose only id channel is `createHandler` this guard has no
1119
+ observable effect today. It is kept because a caller-supplied id reaching
1120
+ `createRecord` from another route — a relationship write,
1121
+ [#207](https://github.com/abofs/stonyx-orm/issues/207) — puts the condition
1122
+ back, and without the guard a denied `403` would delete a record the request
1123
+ did not create.
1124
+
1125
+ ### Consumer Contracts
1126
+
1127
+ Obligations this package **cannot enforce**, where nothing fails, warns or
1128
+ changes shape when a consumer omits them. One place, findable, per
1129
+ `quality.md` rule 2 — if you are relying on `@stonyx/orm` for access control,
1130
+ read all of these.
1131
+
1132
+ #### `Record.toJSON()` does not filter relationship linkage unless you pass a verdict
1133
+
1134
+ **The framework resolves a verdict for you on every request-bound surface that
1135
+ serializes a record through `toJSON()`. You own it everywhere else.**
1136
+
1137
+ Those surfaces are `GET /:models`, `GET /:models/:id`, both shapes of
1138
+ `GET /:models/:id/{relationship}`, the `POST /:models` and `PATCH /:models/:id`
1139
+ **response documents**, and every record inside an `?include=` **`included`**
1140
+ array ([#234](https://github.com/abofs/stonyx-orm/issues/234) for the four
1141
+ reads, [#235](https://github.com/abofs/stonyx-orm/issues/235) for the two
1142
+ writes and `included`). Each resolves a linkage verdict and passes it to
1143
+ `toJSON()` for you.
1144
+
1145
+ **`GET /:models/:id/relationships/{relationship}` is not on that list, and its
1146
+ state is not this section's to report.** It builds its `{ type, id }` objects by
1147
+ hand instead of calling `toJSON()`, so the `linkage` **option** never reaches it
1148
+ — whatever that route filters, it filters itself. And because its linkage *is*
1149
+ its primary data, filtering it is a **membership** decision rather than a
1150
+ linkage one. Membership on both relationship route families is owned by
1151
+ [#232](https://github.com/abofs/stonyx-orm/issues/232) (PR
1152
+ [#247](https://github.com/abofs/stonyx-orm/pull/247), in flight as this is
1153
+ written); read that issue for its state rather than inferring it here, because
1154
+ this section describes only what `toJSON()` filters.
1155
+
1156
+ Any other path to a document — `JSON.stringify(record)`, `res.json(record)`,
1157
+ `console.log(record)`, a custom route, a queue payload, a websocket frame —
1158
+ calls `toJSON()` with no verdict, and **the no-verdict document names every
1159
+ related id, including records hidden on every one of their own surfaces**
1160
+ ([#234](https://github.com/abofs/stonyx-orm/issues/234)). That default is
1161
+ deliberate and cannot be inverted; the reasons are in
1162
+ [Known limitations](#known-limitations) above.
1163
+
1164
+ **There is no signal when you omit it.** `linkage` is optional, absent is the
1165
+ default, the default is the unfiltered document, and a filtered relationship is
1166
+ byte-identical to a genuinely empty one — so nothing on the wire distinguishes
1167
+ "filtered" from "forgotten".
1168
+
1169
+ Do this:
1170
+
1171
+ ```js
1172
+ import { createLinkageFilter } from '@stonyx/orm';
1173
+
1174
+ // `request` is the live request the caller was authorised against. The verdict
1175
+ // is REQUEST-SCOPED: build one per request and never cache it across requests,
1176
+ // or a second caller is answered with the first caller's authorization.
1177
+ const linkage = createLinkageFilter(request);
1178
+
1179
+ res.json({ data: record.toJSON({ baseUrl, linkage }) });
1180
+ ```
1181
+
1182
+ Not this:
1183
+
1184
+ ```js
1185
+ // A second, unreviewed reading of access(). It will drift from the one in
1186
+ // src/access-verdict.ts, and it will drift in consumer code where no reviewer
1187
+ // of this repository will ever see it.
1188
+ const linkage = (type, r) => Orm.instance.getAccess(type)?.(request)?.(r) ?? true;
1189
+ ```
1190
+
1191
+ **`createLinkageFilter` requires a live request, and there is no safe call
1192
+ without one.** `request` is the only authorization input the filter has — it is
1193
+ handed straight to your `access()` predicates, and a predicate that does not
1194
+ *read* it cannot fail closed when it is missing. Passing `undefined`, `null` or
1195
+ any non-object therefore denies **all** linkage and logs, once, at construction.
1196
+ Measured before that guard existed, `createLinkageFilter(undefined)` granted
1197
+ four of the five models in this repository's own fixture, silently.
1198
+
1199
+ **This is the catch for the request-less contexts named above.** In a queue
1200
+ consumer or a websocket handler there is no live request, so there is nothing to
1201
+ authorize against and nothing this package can resolve for you. Either carry the
1202
+ originating request through to the point of serialization, or publish no linkage
1203
+ at all — `record.toJSON({ linkage: () => false })` emits the document with every
1204
+ relationship empty. A stand-in is **not** a substitute: `{}` is an object
1205
+ and passes the guard, and any predicate that ignores its request will grant.
1206
+
1207
+ **`linkage` itself is validated, and an unusable value DENIES.** `undefined`
1208
+ means "no verdict supplied" and emits today's document. Anything else must be a
1209
+ **synchronous function that answers with a boolean**. Each of the following
1210
+ drops **all** linkage on that document and logs once:
1211
+
1212
+ - **A non-function** — `null`, `0`, `false`, `''`, `true`, a string, an object.
1213
+ `null` is the natural return of a resolver that could not resolve a session:
1214
+ it used to be read as "absent" and emit the full document silently.
1215
+ - **An `async` function, a generator function, or any predicate that returns a
1216
+ promise or thenable.** `toJSON` is the `JSON.stringify` hook and cannot await
1217
+ a verdict, and **an `async` resolver returns a promise, a promise is
1218
+ truthy**, so every related id was published, silently, exactly as if this fix
1219
+ were not here. If your
1220
+ authorization lookup is asynchronous, `await` it *before* you serialize and
1221
+ close over the result.
1222
+ - **Any answer that is not a boolean** — `{}`, `'no'`, `1`, `undefined`. A
1223
+ non-boolean is a resolver that did not answer, and a truthy one granted.
1224
+ - **A predicate that throws**, including a `class` passed by mistake. It is
1225
+ caught and denied; it used to escape the enclosing `JSON.stringify` and take
1226
+ the rest of that serialization down with it.
1227
+
1228
+ #### A predicate that ignores `context.model` makes cross-model resolution GRANT
1229
+
1230
+ The linkage filter above asks the **related** model's access class the
1231
+ model-correct question, but only a predicate that *reads*
1232
+ [`context.model`](#the-access-context-second-argument) can give a model-correct
1233
+ answer. A single-argument predicate identifies its collection from the request
1234
+ and therefore answers about the collection the request was *addressed to* —
1235
+ which is the direction that **grants**. Measured, and worked through in
1236
+ [Known limitations](#known-limitations). There is no boot-time warning yet
1237
+ ([#221](https://github.com/abofs/stonyx-orm/issues/221)). **Migrate your
1238
+ predicates to the two-argument contract.**
1239
+
1240
+ #### `format()` and `serialize()` are never filtered, by design
1241
+
1242
+ They are the persistence path. Do not hand their output to an untrusted
1243
+ consumer, and do not add a filter to them — `Orm.db.save()` writes `format()`
1244
+ output to disk, so filtering there is data loss rather than disclosure
1245
+ prevention.
1246
+
1247
+ ### Breaking changes
1248
+
1249
+ These land in the next published build. There is no changelog or release-notes channel yet
1250
+ ([stonyx-workflows#17](https://github.com/abofs/stonyx-workflows/issues/17)), so
1251
+ they are recorded here.
1252
+
1253
+ 1. **`DELETE /{collection}/{id}` on a record that does not exist returns `404`
1254
+ instead of `204`.** This affects **every** consumer issuing a DELETE against
1255
+ any mounted collection, whether or not an access filter is configured, and
1256
+ `models: '*'` mounts every model by default. It is not optional: if a denied
1257
+ delete returned 404 while a missing one returned 204, the pair would be a
1258
+ perfect existence oracle and the filter would be worthless.
1259
+ 2. **After-hooks no longer fire for a request that failed** — denied, missing,
1260
+ `400` or `409`. The gate is on the handler's status, not on the operation, so
1261
+ it covers reads as well: a `GET /:id` that answers 404 runs no after-`get`
1262
+ hook either. Previously `afterHook('delete', ...)` ran with a populated
1263
+ `context.recordId` on a request that deleted nothing, so a consumer cascade
1264
+ destroyed children behind a 404.
1265
+ 3. **`POST` with a client-supplied `id` returns `403` when a function-style
1266
+ `access` filter is in force**, whatever the payload and whether or not the id
1267
+ exists, and *before* any store lookup — so neither the status nor the lookup
1268
+ cost can depend on whether that id exists. Only affects function-style
1269
+ `access` users. See [Filter functions](#filter-functions) for why, and let the
1270
+ server assign the id instead. `409`-on-duplicate is unchanged for everyone
1271
+ else.
1272
+
1273
+ "Whatever the payload" is a statement about the **`id` member of the resource
1274
+ object**, and it holds only because that is the sole channel a caller id can
1275
+ arrive on. It was not always: a caller id moved into
1276
+ `relationships: {"id": {"data": {"id": 21}}}` reached `createRecord` past this
1277
+ refusal and overwrote a hidden record in place. Both strips — `attributes.id`
1278
+ and `relationships.id` — are part of this behaviour, not tidiness. A future
1279
+ change that adds a third channel without stripping it re-opens the oracle;
1280
+ see [#204](https://github.com/abofs/stonyx-orm/issues/204).
1281
+ 4. **Function-style `access` is now enforced on all seven surfaces.** Records
1282
+ previously reachable by id despite being filtered from the collection now
1283
+ return 404. Only affects function-style `access` users, for whom the old
1284
+ behaviour was the bypass.
1285
+
1286
+ "Seven surfaces" means the seven endpoints of **the filtered model**. A write
1287
+ to another collection can still reach one of its records through a
1288
+ relationship — [#207](https://github.com/abofs/stonyx-orm/issues/207), which
1289
+ is **not** closed here.
1290
+ 5. **A predicate that throws is treated as a denial** rather than propagating to
1291
+ Express's default 500 handler. So is an `access()` that throws.
1292
+ 6. **`access()` returning a bare string is one permission, not full access.**
1293
+ `AccessMethod` declares `string` legal, and it previously fell through every
1294
+ branch and granted all four operations — `return 'read'` allowed `DELETE`.
1295
+ It is now equivalent to `['read']`. Any other unrecognised shape (an object,
1296
+ a number) now returns `403` rather than granting full access.
1297
+ 7. **`POST` with a client-supplied `id` normalises the body id before the
1298
+ duplicate check**, so an id shape that previously *missed* the store's key
1299
+ now finds it. `POST {"id":"0x2391"}` and `POST {"id":" 21 "}` answer `409`
1300
+ where they answered `200`, and the `200` was not a success: the lookup missed,
1301
+ the duplicate check was skipped, and `createRecord` overwrote the colliding
1302
+ record in place. **This one reaches consumers with no filter at all** — the
1303
+ population breaking changes 3 and 4 explicitly exempt. If you were relying on
1304
+ a hex-shaped or whitespace-padded id creating a second record, it never did.
1305
+
1306
+ 8. **Server-assigned ids change value on string-id models, numeric ids stop
1307
+ being monotonic at the numeric ceiling, and the create route gains a
1308
+ `409`.** Three consumer-visible changes from
1309
+ [#203](https://github.com/abofs/stonyx-orm/issues/203).
1310
+
1311
+ **The value.** A `POST` with no `id` against a model declaring
1312
+ `id = attr('string')` previously produced the *last-inserted* id with `1`
1313
+ concatenated onto it — an owner store holding `['gina', 'bob']` answered
1314
+ `'bob1'`. It now answers `'owner-1'`: the model name, a hyphen, and the
1315
+ lowest positive integer whose landing key is free. **No test in this repo
1316
+ pinned the old value**, so a consumer relying on it gets no failing test, no
1317
+ deprecation and no other signal — which is why it is recorded here. Numeric
1318
+ id models (`id = attr('number')`, the default) are unaffected in shape: they
1319
+ still get an integer, but it is now the **maximum** existing id plus one
1320
+ rather than the last-inserted id plus one, which is the defect #203 is about.
1321
+ They are **not** unaffected in *sequence* — see the monotonicity half below.
1322
+
1323
+ The value is deliberately **not** numeric-looking, and that is not cosmetic.
1324
+ Every id-bearing surface resolves a numeric-looking string id to a **number**
1325
+ (`GET /owners/1` looks up `1`), while a string-id model files its records
1326
+ under the **string** key `'1'`. A server-assigned `'1'` would therefore be a
1327
+ record that was created successfully and could not be fetched, updated or
1328
+ deleted by id, and whose after-`create` hook received
1329
+ `context.record === undefined`
1330
+ ([#209](https://github.com/abofs/stonyx-orm/issues/209)).
1331
+
1332
+ **Numeric ids are no longer monotonic, and deleted ids can be re-issued.**
1333
+ The precondition is narrow but it is reachable, and there is no signal when
1334
+ it is met: **one record filed at or above 2^53** (`9007199254740992`). `max
1335
+ + 1` is not representable there, so assignment restarts from `1` and walks
1336
+ up to the lowest free key — which means the id of a *deleted* record is
1337
+ handed to the next `POST`. Both `dev` and every prior release were strictly
1338
+ monotonic and never re-issued a numeric id, so a consumer that relied on
1339
+ that — audit rows, cursors, cached authorization decisions, external
1340
+ references keyed on the id — now has a stale reference that silently points
1341
+ at a **different record, created by a different caller**, rather than at a
1342
+ deleted one. Nothing fails; the reference simply resolves to the wrong
1343
+ record.
1344
+
1345
+ The restart is deliberate and is not itself optional: without it, one record
1346
+ at the ceiling made every subsequent server-assigned create on that
1347
+ collection fail permanently. Re-use is the cost of keeping the collection
1348
+ writable. **If you need monotonic ids, assign them yourself** rather than
1349
+ letting the server assign, and note that a ceiling record can be planted by
1350
+ an unauthenticated caller — see *And the id itself is an occupancy signal*
1351
+ under [Filter functions](#filter-functions) for the reachability path.
1352
+ String-id models are unaffected by this half: their keys are
1353
+ `<model>-<n>` and were never monotonic over an integer sequence.
1354
+
1355
+ **The status.** `POST /{collection}` can now answer `409` for a reason other
1356
+ than a duplicate id: the server could not derive a free id. That requires a
1357
+ **non-injective** id transform — one that maps distinct candidates onto the
1358
+ same store key, such as `boolean`, or anything you registered on
1359
+ `Orm.instance.transforms` and named as an id type. It is a configuration
1360
+ fault rather than a request fault; the message is logged through
1361
+ `stonyx/log`. Previously this case threw out of the handler and express
1362
+ answered `500` with a stack trace.
1363
+
291
1364
  ### Include Parameter (Sideloading Relationships)
292
1365
 
293
1366
  The ORM supports JSON API-compliant relationship sideloading via the `include` query parameter. This reduces the need for multiple API requests by embedding related records in a single response.
@@ -380,6 +1453,15 @@ GET /animals/1
380
1453
  #### Limitations
381
1454
 
382
1455
  - Only available on GET endpoints (not POST/PATCH)
1456
+ - **`included` is access-filtered on one of the two questions, not both.** What
1457
+ a record already in `included` may **name** in its own
1458
+ `relationships.*.data` is filtered
1459
+ ([#235](https://github.com/abofs/stonyx-orm/issues/235)) — `?include=` no
1460
+ longer republishes ids the primary document withholds. Whether a resource
1461
+ appears in `included` **at all** is *membership* and is still unfiltered
1462
+ ([#233](https://github.com/abofs/stonyx-orm/issues/233)): a record that is
1463
+ 404 on its own routes is still served as an `included` resource, attributes
1464
+ and all. See [Consumer Contracts](#consumer-contracts).
383
1465
 
384
1466
  ## Lifecycle Hooks
385
1467
 
@@ -434,6 +1516,16 @@ Each hook receives a context object with comprehensive information:
434
1516
  - It contains a deep copy of the record's state **before** the operation executes (captured before the `before` hook fires)
435
1517
  - The deep copy is created via JSON serialization (`JSON.parse(JSON.stringify())`) to ensure complete isolation
436
1518
  - For `delete` operations, `recordId` is provided in after hooks since the record may no longer exist in the store
1519
+ - **`context.recordId` here is NOT `AccessContext.recordId`.** Same name, same-shaped
1520
+ object, different coverage: `_withHooks` sets this key **only** under
1521
+ `operation === 'delete'`, so on `get` / `list` / `create` / `update` the key is
1522
+ **absent** — `beforeHook('update', 'owner', ctx => ctx.recordId === 'archived' ? 403 : undefined)`
1523
+ never fires (measured: `PATCH /owners/{id}` → 200 with `ctx.recordId === undefined`
1524
+ and the id sitting in `ctx.params`). The access context, by contrast, carries
1525
+ `recordId` on every route it classifies and spells absence as `null`, never
1526
+ `undefined`. Tracked as
1527
+ [#242](https://github.com/abofs/stonyx-orm/issues/242); see
1528
+ `AccessContext.recordId` in `src/types/orm-types.ts` for the other side.
437
1529
  - `oldState` is captured as a deep copy of the record's data before the operation, providing access to the previous field values
438
1530
 
439
1531
  ### Usage Examples
@@ -561,7 +1653,19 @@ afterHook('delete', 'animal', async (context) => {
561
1653
  // Additional access control - halt with 403 if unauthorized
562
1654
  beforeHook('delete', 'animal', (context) => {
563
1655
  const user = context.state.currentUser;
564
- const animal = store.get('animal', context.params.id);
1656
+
1657
+ // `context.oldState` — NOT a store lookup. For `update` and `delete` the ORM
1658
+ // has already fetched the record (and already applied the access filter to
1659
+ // it) before this hook runs, so re-fetching it here is a fourth id coercion
1660
+ // that has to agree with three others.
1661
+ //
1662
+ // And it would not agree. `context.params.id` is the raw url segment, always
1663
+ // a string, while the store keys numeric-id models by NUMBER — so
1664
+ // `store.get('animal', '21')` misses the record held under `21`, and so does
1665
+ // `store.find('animal', '21')`: neither coerces. The miss reads as "no such
1666
+ // record", which in an authorization hook fails whichever way your code
1667
+ // happens to handle a null.
1668
+ const animal = context.oldState;
565
1669
 
566
1670
  if (animal.owner !== user.id && !user.isAdmin) {
567
1671
  return 403; // Forbidden
@@ -569,6 +1673,10 @@ beforeHook('delete', 'animal', (context) => {
569
1673
  });
570
1674
  ```
571
1675
 
1676
+ > If you do need a lookup for some *other* model inside a hook, coerce the id
1677
+ > yourself to the type that model's `id` attribute declares — the store is a
1678
+ > `Map` and `'21'` and `21` are different keys.
1679
+
572
1680
  #### Auditing
573
1681
 
574
1682
  ```javascript
@@ -702,11 +1810,29 @@ beforeHook('create', 'post', (context) => {
702
1810
 
703
1811
  ### Hook Execution Order
704
1812
 
705
- 1. **Before hooks** fire first (sequentially, in registration order)
706
- 2. **Main operation** executes (if no before hook halted)
707
- 3. **After hooks** fire last (sequentially, in registration order)
708
-
709
- Before hooks can halt the operation by returning a value. After hooks run after completion and cannot halt.
1813
+ 1. **Authorization is evaluated first for `update` and `delete`.** A record the
1814
+ access filter rejects returns `404` **before any before-hook runs**, so a
1815
+ hook never sees a record or a `context.oldState` — that the caller is not
1816
+ allowed to read. `create` is the exception: there is no record to test until
1817
+ the handler has built one, so `beforeHook('create', ...)` **does** fire for a
1818
+ `POST` that goes on to answer `403`.
1819
+ 2. **Before hooks** fire next (sequentially, in registration order).
1820
+ 3. **Main operation** executes (if no before hook halted).
1821
+ 4. **After hooks** fire last (sequentially, in registration order) — **only if
1822
+ the request succeeded.**
1823
+
1824
+ Before hooks can halt the operation by returning a value, and that value becomes
1825
+ the response.
1826
+
1827
+ **After hooks do not run for a failed request.** Any status `>= 400` — denied,
1828
+ missing, `400`, `409` — skips the entire after-hook pipeline, along with SQL
1829
+ persistence and `onUpdate` autosave. This is a behaviour change; see
1830
+ [Breaking changes](#breaking-changes). It applies to the samples above: the
1831
+ `afterHook('delete', ...)` auditing hook writes **no** audit row for a `DELETE`
1832
+ that answered `404`, and the `afterHook('update', ...)` change-tracking hook
1833
+ writes none for a `PATCH` that answered `404` or `400`. If you need a record of
1834
+ refused requests, log them from a before-hook or from your own middleware —
1835
+ `after<operation>` fires only for an operation that actually happened.
710
1836
 
711
1837
  ### Best Practices
712
1838