@web-ts-toolkit/access-router 0.65.1 → 0.67.0

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.
package/README.md CHANGED
@@ -20,6 +20,7 @@ ACL-aware Express routers and in-memory data services for Mongoose-backed APIs.
20
20
  **Private virtual inputs:** [Populated dependencies and runnable example](#private-populated-dependencies)
21
21
 
22
22
  **Migration:** [Removed overrides](#breaking-release-service-overrides-migration) ·
23
+ [Nested operation rules](MIGRATION.md#breaking-change-nested-operation-access) ·
23
24
  [Server-owned hydration](#breaking-release-server-owned-hydration) ·
24
25
  [Target-owned populate flags](#breaking-release-populate-policy-migration) ·
25
26
  [Named helpers](#breaking-release-named-helpers-and-default-behavior) ·
@@ -146,10 +147,9 @@ package-managed execution, falling back to `defaultRuntime` outside it.
146
147
  captured runtime model default → true. Explicit `undefined` restores inheritance;
147
148
  omission retains an override. Data assignment has no model-default layer.
148
149
  2. **Dotted setters update one path copy-on-write.** Use
149
- `router.setOption('operationAccess.basicRead', false)` to keep sibling rules,
150
- or pass `undefined` to restore lookup fallback. Property helpers such as
151
- `router.operationAccess('basicRead', false)` are for defined values; use
152
- `set`/`setOption` for undefined. Updating a path beneath a scalar starts an
150
+ `router.setOption('operationAccess.read.basic', false)` to keep sibling members,
151
+ or pass `undefined` to restore lookup fallback. Two-argument property helpers such as
152
+ `router.operationAccess('read.basic', undefined)` also clear that member. Updating a path beneath a scalar starts an
153
153
  object; use a `default` entry to retain a broad fallback. Dotted keys belong in
154
154
  setter arguments, not flat constructor-object properties.
155
155
  3. **Lookup is not a deep merge.** Generic nested option/hook lookup uses the
@@ -159,9 +159,9 @@ package-managed execution, falling back to `defaultRuntime` outside it.
159
159
  stored parent is also absent. `getExactModelOption` instead checks just the
160
160
  exact stored path, then the same runtime-default path; `getExactDataOption`
161
161
  checks only the stored path. `getDefaultModelOption` is exact. **Route guards
162
- have their own resolver:** exact variant (including exact model-default
163
- fallback) → base exact/`.default`/shorthand. A default variant can therefore
164
- outrank a model's base rule. See the [full precedence](#variant-and-base-fallback),
162
+ have their own resolver:** exact context member (including same-owner exact model-default
163
+ fallback) → operation scalar/`default` → outer `.default`/shorthand → deny. A runtime context member can
164
+ outrank a model's operation default. See the [full precedence](#variant-and-base-fallback),
165
165
  including closed [subdocument rules](#subdocument-field-precedence).
166
166
  4. **Method values resolve with `??`.** At each service resolver a non-nullish
167
167
  supplied property wins over that method's `defaults` bucket, then its built-in
@@ -175,8 +175,10 @@ package-managed execution, falling back to `defaultRuntime` outside it.
175
175
  Public `_upsert` uses the public create or update bucket for its branch; trusted
176
176
  `upsert` has `upsertArgs`/`upsertOptions`. There is no `publicUpsertOptions` bucket.
177
177
  5. **Metadata posture is absolute.** Model `stripPermissionsField: true` removes
178
- the entire output metadata field; `disableFieldPermissions: true` suppresses
179
- `_view`/`_edit` computation. They win over per-call flags and method defaults.
178
+ the entire output metadata field; `disableFieldPermissions` defaults to `true`
179
+ and suppresses `_view`/`_edit` computation and output, including placeholders. They win over
180
+ per-call flags and method defaults. Set `disableFieldPermissions: false` on a
181
+ model or with `setDefaultModelOptions` to allow field maps.
180
182
  Internal authorization and full document grants still run.
181
183
 
182
184
  The supported `Defaults` buckets are `findArgs`/`findOptions`,
@@ -248,8 +250,9 @@ Express request. This includes scalar counts/distinct, ID lookups, mutations, in
248
250
  populate, subdocuments and field helpers. Services acquired later from a retained core
249
251
  also belong to that core. The request's current `macl` slot still belongs to the new
250
252
  runtime; acquiring a service there uses the new runtime's independent authority.
251
- Output handles remain bound to their original request/runtime/model/scope and cannot
252
- be reused by the replacement runtime.
253
+ Each model authorization call and its private in-flight document stages remain owned
254
+ by the originating request/runtime/model/scope. Published DTOs and diagnostic contexts
255
+ are ordinary data, not reusable authority for either runtime.
253
256
 
254
257
  Route-shape keys (`modelName`/`dataName`, `basePath`, `parentPath`, `idParam`,
255
258
  `queryRouteSegment`, and model `mutationRouteSegment`) are fixed at construction;
@@ -258,467 +261,92 @@ Express routes. `parentPath` supplies the external prefix for route metadata/log
258
261
  mount that prefix in Express yourself. Live `idField`/`resolveIdFilter` change lookup
259
262
  behavior rather than route shape.
260
263
 
261
- ### Temporary unsafe read/list-performance switches
264
+ ### Owned authorization modes
262
265
 
263
- **All default to off (snapshot checks enabled).** Six independent server-only
264
- settings temporarily skip specific comparisons on one registered model:
266
+ One document-stage engine has four independent server model/default-model settings,
267
+ all `AuthorizationMode = 'isolated' | 'trusted'`, default **isolated**:
265
268
 
266
- The retained-copy/graph guarantees in this section and the initial-copy section
267
- below apply with the matching **authorization fast-path flag OFF (or dormant)**.
268
- The separately opted-in [active trusted path](#experimental-unsafe-readlist-authorization-fast-paths)
269
- has a deliberately weaker contract; it does not change these original six/two groups.
269
+ | Setting | Current scope |
270
+ | ------------------------- | -------------------------------------------------------------------------------------------------- |
271
+ | `readAuthorizationMode` | Root READ output; READ-to-LIST retry retains this capture. |
272
+ | `listAuthorizationMode` | Root LIST output. |
273
+ | `createAuthorizationMode` | Post-persistence/lifecycle CREATE output, including bulk rows and UPSERT's executed create branch. |
274
+ | `updateAuthorizationMode` | Post-persistence/lifecycle UPDATE output and UPSERT's executed update branch. |
270
275
 
271
- | LIST flag | READ flag | Comparisons skipped |
272
- | -------------------------------------------- | -------------------------------------------- | --------------------------------------------------------------------------------- |
273
- | `unsafeSkipListDocumentSnapshotChecks` | `unsafeSkipReadDocumentSnapshotChecks` | Repeated source comparisons for the top-level document stage |
274
- | `unsafeSkipListOutputSnapshotChecks` | `unsafeSkipReadOutputSnapshotChecks` | Output-value comparisons for the root and its embedded/populated/included outputs |
275
- | `unsafeSkipListNestedDocumentSnapshotChecks` | `unsafeSkipReadNestedDocumentSnapshotChecks` | Repeated source comparisons for embedded/populated/included document stages |
276
-
277
- LIST means top-level `find`, generated public lists and root-list entries. READ
278
- means `findOne`, `findById`, public identifier/filter reads and root-read entries.
279
- A read-to-list retry follows the **read flags**, because the initiating operation
280
- is still a single read, even when its effective field access is `list`. Changing
281
- one flag does not change any other flag.
282
-
283
- <!-- doc-example: partial -->
284
-
285
- ```ts
286
- import acl from '@web-ts-toolkit/access-router';
287
-
288
- // User must already be registered on this runtime. Never take this value from a request.
289
- // TODO: revisit/remove this temporary workaround after query-performance remediation.
290
- acl.setModelOptions('User', {
291
- unsafeSkipReadDocumentSnapshotChecks: true,
292
- unsafeSkipReadOutputSnapshotChecks: true,
293
- unsafeSkipReadNestedDocumentSnapshotChecks: true,
294
- // All three LIST flags remain false unless separately enabled.
295
- });
296
- ```
297
-
298
- Set any flag to `false` with `setModelOption` to roll back for new calls.
299
- All flags can be set in `createRouter(Model, { ... })` or `setDefaultModelOptions`.
300
- An unspecified model flag inherits the current default, even when defaults change
301
- after router/model setup. Explicit per-model `false` overrides default `true`;
302
- setting a model flag to `undefined` restores inheritance. This precedence applies
303
- to all default-model options, not only unsafe flags. Object/array options replace
304
- shallowly rather than deep-merging. Retained call/handle snapshots do not change.
305
- Prefer per-model opt-in rather than enabling it for every model. Use the owning
306
- `createAccessRuntime()` API instead of default `acl` for an isolated runtime.
307
- Only literal boolean `true` enables each flag. Enabling emits a logger warning once
308
- per effective model/flag transition, including inherited enablement on an existing
309
- model. Setting defaults before model setup warns when applied to that model, not
310
- when the defaults alone are stored. No warning repeats per row/request. None is a global, per-call, HTTP/root
311
- entry, `options.authorization`, or `service.defaults` option.
312
-
313
- - **Independent scopes:** root-source flags do not relax descendant source checks;
314
- nested-source flags do not relax root source or output checks; output flags do
315
- not relax source checks. Nested flags do **not** prune child values from parent
316
- snapshots: a still-strict parent comparison can detect child mutation.
317
- - **Propagation:** output/nested flags use the **initiating model's captured mode**
318
- recursively through embedded scopes, ordinary public population and includes
319
- (including correlated includes). A target model's own flags cannot relax a
320
- strict parent or override that captured mode. Independent service calls made
321
- inside hooks use their own settings, not ambient parent authority.
322
- - **Still enforced:** row filters, document/field rules, operation gates, exact
323
- request/runtime/model/scope/access/stage binding, handle/output associations,
324
- output graph identities and structural bounds on initial snapshots. Initial
325
- source snapshots and detached callback/grant/output copies remain. Initial output
326
- snapshots also remain unless the separate copy flags below are active. Equal
327
- replacement objects, forged handles and unrelated rows/calls still reject;
328
- package-created output-copy transfers still authenticate their source.
329
- - **Strict boundaries:** writes (including read-like output), dedicated subdocument
330
- operations and fresh standalone output helpers remain strict. Helpers using an
331
- originating handle retain that handle's captured mode.
332
- - **Risk:** source mutation during callbacks/awaits can leave stale grants/decisions.
333
- Output flags additionally allow changed scalar values, in-place Date/Buffer/BSON
334
- mutations and other value changes that graph-identity checks cannot detect to
335
- reuse earlier decisions. This can expose incorrectly authorized output, even
336
- though permission rules still run. This is **not a security-equivalent fast mode**.
337
- Use only with trusted, non-mutating hooks and output consumers; review your
338
- application and measure a staged rollout before production opt-in.
339
-
340
- Each call captures the setting before awaits. Turning it off protects new calls,
341
- not in-flight calls, later descendants of captured calls, retries or existing
342
- handles. These switches do not eliminate all cloning or promise v0.51.0 performance.
343
- Measure each separately on your workload; restore `false` as soon as possible.
344
-
345
- ### Temporary unsafe initial output-snapshot copy switches
346
-
347
- Two **additional**, default-false server model/default-model options can omit the
348
- initial snapshot stored when finalized output is associated with its private
349
- authorization handle. They do not change the six comparison flags above:
350
-
351
- | Copy option | Required comparison option |
352
- | ----------------------------------------- | ------------------------------------------ |
353
- | `unsafeSkipListInitialOutputSnapshotCopy` | `unsafeSkipListOutputSnapshotChecks: true` |
354
- | `unsafeSkipReadInitialOutputSnapshotCopy` | `unsafeSkipReadOutputSnapshotChecks: true` |
355
-
356
- | Matching comparison skip | Copy skip | Effective behavior |
357
- | ------------------------ | --------- | ---------------------------------------------------------------------------------- |
358
- | false | false | Copy and compare output snapshots |
359
- | true | false | Copy snapshots; skip comparisons (existing behavior) |
360
- | false | true | Dormant: still copy and compare; warn about the prerequisite |
361
- | true | true | Omit eligible initial output snapshots; retain structural admission and identities |
362
-
363
- Only literal boolean `true` enables either option. They follow the same server-only
364
- inheritance and capture rules as comparison flags: explicit model false wins, model
365
- undefined restores inheritance, and later default updates affect new calls. Never
366
- derive them from client input or put them in method defaults/per-call authorization.
367
- READ-to-list retries follow READ settings. Authenticated embedded/populated/included
368
- outputs and package-created transfers inherit the initiating model's mode; target
369
- flags cannot override it. Writes, dedicated subdocument operations and fresh helpers
370
- stay strict. An originating handle keeps its mode after runtime rollback.
371
-
372
- **This removes protection, not just an allocation.** The omitted pass no longer
373
- normalizes Date/RegExp/Buffer/BSON leaves or runs BSON wire validation/hooks. Lost
374
- observations can change exceptions, side effects and subsequent permission outcomes,
375
- including changing a denial into an allowance. The prerequisite already allows
376
- scalar/native mutation to reuse stale decisions. Do not call this security-equivalent
377
- to copying, or assume that matching benchmark output proves it safe for your app.
378
-
379
- Eligible ordinary records/arrays retain clone-free bounded structural admission:
380
- 20,000 visited nodes (including repeated aliases), depth 100, array length 20,000,
381
- safe keys, data descriptors, supported containers and cycle rejection. Exact output
382
- root/descendant identities, request/runtime/model/scope/access/stage binding and
383
- permission evaluation remain. Standard native leaves are allowed without their copy
384
- normalization; invalid/forged BSON leaf contents are **not** wire-validated by this
385
- pass. Proxies, Map/Set graphs, unproven native subclasses and unsupported objects use
386
- the original copier/identity fallback and may still reject. Accessor/proxy ownership
387
- bindings also use that fallback; graph admission is not retained across binding
388
- callbacks. A requested skip does
389
- not guarantee zero copying for every graph.
390
-
391
- Source snapshots, detached document/field callback inputs and grants, captured
392
- configuration, getter isolation, metadata and actual output/response copies remain.
393
- This is **not a general deep-clone opt-out**. Enable only per model with trusted,
394
- stable data and hooks after a measured staged rollout; the remaining query costs can
395
- still dominate and no v0.51.0 parity is promised. Warnings distinguish active copying
396
- omission from dormant requests, occur on effective model/operation transitions and
397
- do not repeat per row/request. Failed option publication does not activate a warning.
276
+ The READ/LIST names stay unchanged. There is no fifth UPSERT setting, alternate
277
+ spelling or compatibility alias. The broader names do not authorize input or other
278
+ phase relaxation. See the shipped [migration guide](MIGRATION.md) for the current
279
+ contract, removed unsafe flags and checked workflows.
398
280
 
399
281
  <!-- doc-example: partial -->
400
282
 
401
283
  ```ts
402
- import mongoose from 'mongoose';
403
284
  import { createAccessRuntime } from '@web-ts-toolkit/access-router';
404
-
405
285
  const api = createAccessRuntime();
406
- const User = mongoose.model('InitialCopyUser', new mongoose.Schema({ name: String }));
407
- api.registerModelInstance(User.modelName, User);
408
- // TEMPORARY UNSAFE: separately enable only the two intended LIST settings.
409
- api.setModelOptions(User.modelName, {
410
- unsafeSkipListOutputSnapshotChecks: true,
411
- unsafeSkipListInitialOutputSnapshotCopy: true,
286
+ api.setDefaultModelOptions({
287
+ readAuthorizationMode: 'isolated',
288
+ listAuthorizationMode: 'isolated',
289
+ createAuthorizationMode: 'isolated',
290
+ updateAuthorizationMode: 'isolated',
412
291
  });
413
- // Rollback for new calls; existing handles/calls retain their captured settings.
414
- api.setModelOption(User.modelName, 'unsafeSkipListInitialOutputSnapshotCopy', false);
415
- api.setModelOption(User.modelName, 'unsafeSkipListOutputSnapshotChecks', false);
416
- ```
417
-
418
- Keep all READ, root-source and nested-source flags off unless independently selected.
419
- Monitor authorization failures, unexpected callback/native behavior and latency/CPU;
420
- restore false promptly and revisit/remove this temporary workaround. No release or
421
- configuration migration automatically enables it.
422
-
423
- An unshipped output-publication fusion experiment was withdrawn after failing its
424
- performance-and-regression gate. **No publication-fusion options are available**;
425
- the six comparison and two initial-copy switches above are unchanged.
426
-
427
- ### Experimental unsafe READ/LIST authorization fast paths
428
-
429
- `unsafeUseListAuthorizationFastPath?: boolean` and
430
- `unsafeUseReadAuthorizationFastPath?: boolean` are a **third independent** group,
431
- both default `false`. This is experimental, performance-first reduced authorization
432
- bookkeeping, **not** publication fusion, a full ACL bypass, or a security-equivalent
433
- optimization. Benchmark your workload and review application hooks/data before
434
- opting in; no universal speedup or v0.51.0 equivalence/performance parity is promised.
435
-
436
- Only literal server model/default-model boolean `true` requests a fast path. It
437
- requires **all four matching prerequisites**, without enabling any automatically:
438
-
439
- | LIST prerequisites | READ prerequisites |
440
- | -------------------------------------------- | -------------------------------------------- |
441
- | `unsafeSkipListDocumentSnapshotChecks` | `unsafeSkipReadDocumentSnapshotChecks` |
442
- | `unsafeSkipListOutputSnapshotChecks` | `unsafeSkipReadOutputSnapshotChecks` |
443
- | `unsafeSkipListNestedDocumentSnapshotChecks` | `unsafeSkipReadNestedDocumentSnapshotChecks` |
444
- | `unsafeSkipListInitialOutputSnapshotCopy` | `unsafeSkipReadInitialOutputSnapshotCopy` |
445
-
446
- | Requested fast flag | All four matching skips true | Effective behavior |
447
- | ------------------- | ---------------------------- | ----------------------------------------------------- |
448
- | false/omitted | either | **off**; original flags retain their behavior |
449
- | true | no | **dormant**; original flags retain their behavior |
450
- | true | yes | **active**; eligible rows use the weaker trusted path |
451
-
452
- LIST covers `find`, generated lists and root lists; READ covers `findOne`,
453
- `findById`, public identifier/filter reads and root reads. **READ-to-list retries
454
- remain READ-origin**, even with effective `list` field access. Configuration is
455
- captured at the genuine query origin **before hooks/awaits**. Authenticated
456
- embedded/populated/included descendants inherit that capture, never live target
457
- flags; target operation/row/field policy and target grants remain their own.
458
- Independent calls inside callbacks capture their own settings. Arbitrary parent
459
- provenance, writes/write-derived output, new/create/update/delete/upsert, dedicated
460
- subdocument operations and fresh raw-policy helpers cannot select this path.
461
-
462
- Use `createRouter`, model setters or model-default setters on the owning runtime.
463
- Explicit model `false` overrides a true default; model `undefined` restores
464
- inheritance. Effective activation/dormancy and missing-prerequisite transitions
465
- warn, not every request. Presence in HTTP/root/service per-call/defaults, policy,
466
- helper, include/populate or `$$sq` **control slots rejects**, even if undefined;
467
- same-named ordinary persisted business fields remain inert data.
468
-
469
- #### What active trusted rows actually omit and retain
470
-
471
- - Ordinary lean projected source and document-hook input are **borrowed**, not
472
- detached stage snapshots. Ordinary returned grants are shared across field
473
- decisions, reads and owning embedded children. Diagnostic contexts are shallow;
474
- `originalDocumentSnapshot` is a historical property name, **not an immutable
475
- snapshot promise** here. Captured configuration/scope views are reused; native
476
- configuration and context/grant leaves are not isolated anew per row/callback.
477
- - Actual operation gates, row filters, ordered field rules, original actor,
478
- short-circuiting, document hooks, getters and finite hook concurrency remain.
479
- Modern document hooks run once per root/target regardless of skim/metadata;
480
- embedded children reuse owner grants. Independent rows/targets do not cache
481
- grants/decisions by ID. Modern backend policy, target admission and private
482
- populated inputs remain; this is historical-like bookkeeping, not old skim behavior.
483
- - Selected output is safely constructed once; metadata and include attachments
484
- finish before one root context/association. Authenticated target DTO roots can
485
- be retained directly. Source and produced-attachment lanes remain separate.
486
- Selection/denied fields, metadata stripping/exposure, dotted paths, population,
487
- includes and registered virtual semantics still apply to ordinary stable data.
488
- - Trusted handles retain exact root association and cheap call/stage/request/
489
- runtime/model/name/scope/access checks, **not snapshot or current-descendant
490
- identity walks**. Child lookup means **issued-document membership, not current
491
- reachability**: a removed original child may still be found; a replacement/new
492
- object receives no child handle. Equal values, IDs, spreads, other rows or forged
493
- handles establish no authority. The exact root helper remains usable after
494
- descendant replacement, filtering current values with stale memo/shared grants.
495
- - Public request/query/filter/pagination/work limits remain. New selected
496
- materialization/child/registry algorithms share **20,000 visited slots/issued
497
- roots and depth 100**, safe descriptor writes and controlled cycle errors.
498
- Encountered-key filtering consumes slots even for denied/protected keys; denied
499
- values and their descendants remain unread, not recursively validated.
500
- There is **no full 20,000-node/depth-100 validation guarantee for unvisited
501
- source/grants/context**. Unknown selected proxies/custom objects/functions/
502
- symbols/cycles reject with a controlled authorization error; invalid virtual
503
- returns omit fail-closed rather than publishing partial output.
504
- - Snapshot native/BSON wire/equality passes are omitted, **not every native
505
- observation**. Hydrated inputs normalize once; selected native/value fallbacks,
506
- stable-base/per-getter document views, getter return staging, private populated
507
- argument-four isolation and JSON serialization can still copy/normalize or run
508
- native code. Getter argument-one mutation is still not an implicit output write.
509
- - Selected BSON compatibility first prepares contained/wire-expanded containers
510
- under the **same remaining slot/depth budget**, then performs one BSON wire copy.
511
- Ordinary BSON leaves, `Code.scope`, `DBRef` fields/IDs and nested natives remain
512
- supported; aliases consume work per emitted occurrence. Data-method `toBSON`
513
- runs once per encountered occurrence (its own computation/allocation is not
514
- bounded). Accessor state/hooks, chained hook results, custom serializer overrides,
515
- unknown prototypes and native-as-document scope roots fail closed; BSON-contained
516
- RegExp values use intrinsic state. String/binary storage is scalar, not a
517
- per-byte slot budget. Structural-budget exhaustion fails the complete result,
518
- including when discovered while staging a virtual return; other invalid native
519
- virtual returns retain fail-closed omission.
520
- - Shallow-unproven roots (including proxy/accessor/unsafe-root shapes) use compatible
521
- copied stages before the hook; exotic grants may copy once without rerunning it.
522
- Copied and trusted rows may coexist in one active call. Supported native/value
523
- fallbacks copy once under the selected-output budget. **Active configuration is
524
- not a promise that every row is zero-copy**, nor does a copied row restore all
525
- former context/configuration isolation. No general deep-clone switch is exposed.
526
-
527
- **Accepted risk:** source/grant/context mutation across callbacks/awaits, stale
528
- decisions, descendant replacement and fewer/different native observations or
529
- exceptions can change permission outcomes, **including denial becoming allowance**.
530
- Matching benchmark fingerprints do not prove security equivalence. Use trusted,
531
- stable application code/data and a measured staged rollout; restore false promptly.
532
-
533
- Rollback affects **new calls only**, not in-flight calls, retries, descendants or
534
- retained handles. Turning off a new flag does **not** turn off its original four
535
- skip flags: restore those independently if you want default protections. Retained
536
- trusted-handle helpers keep the weaker behavior after rollback; fresh raw-policy
537
- helpers remain strict and known trimmed DTOs retain unresolved-rule fail-closed behavior.
538
-
539
- #### Runnable LIST/READ prerequisites, rollback and handle warnings
540
-
541
- Save as `authorization-fast-path-example.mts`; run on Node 22.18+ or compile with
542
- TypeScript/NodeNext first. Uses only public package imports, Express and Mongoose.
543
- It creates/drops its own example database (`MONGODB_URL` or local MongoDB), serves
544
- one loopback request and closes all resources. **The deliberate DTO replacements
545
- demonstrate lost protection, not recommended application behavior.** LIST defaults
546
- and READ opt-in below are independent server constants, never request inputs.
547
-
548
- <!-- doc-example: complete-runtime -->
549
-
550
- ```ts
551
- import assert from 'node:assert/strict';
552
- import { randomUUID } from 'node:crypto';
553
- import { once } from 'node:events';
554
- import type { Server } from 'node:http';
555
- import express from 'express';
556
- import mongoose from 'mongoose';
557
- import { createAccessRuntime, type DefaultModelRouterOptions } from '@web-ts-toolkit/access-router';
558
- import type { ModelRequest } from '@web-ts-toolkit/access-router/advanced';
559
-
560
- type Row = { name?: string; owner?: boolean; secret?: string; contacts?: { email?: string; secret?: string }[] };
561
-
562
- async function runAuthorizationFastPathExample() {
563
- const connection = await mongoose
564
- .createConnection(process.env.MONGODB_URL ?? 'mongodb://127.0.0.1:27017', {
565
- dbName: `authorization_fast_example_${randomUUID().replaceAll('-', '')}`,
566
- })
567
- .asPromise();
568
- let server: Server | undefined;
569
- try {
570
- const api = createAccessRuntime();
571
- const listDefaults = {
572
- unsafeSkipListDocumentSnapshotChecks: true,
573
- unsafeSkipListOutputSnapshotChecks: true,
574
- unsafeSkipListNestedDocumentSnapshotChecks: true,
575
- unsafeSkipListInitialOutputSnapshotCopy: true,
576
- unsafeUseListAuthorizationFastPath: true,
577
- } satisfies DefaultModelRouterOptions;
578
- api.setDefaultModelOptions(listDefaults); // no READ flags enabled
579
- const Model = connection.model<Row>(
580
- 'FastPathExampleRow',
581
- new mongoose.Schema<Row>({
582
- name: String,
583
- owner: Boolean,
584
- secret: String,
585
- contacts: [new mongoose.Schema({ email: String, secret: String }, { _id: false })],
586
- }),
587
- );
588
- let documentHooks = 0;
589
- const router = api.createRouter(Model, {
590
- operationAccess: { list: true, read: true },
591
- hydration: { find: 'lean', findOne: 'lean' },
592
- stripPermissionsField: true,
593
- unsafeUseListAuthorizationFastPath: false, // explicit false wins over defaults
594
- alwaysSelectFields: ['owner'],
595
- docPermissions: (doc) => {
596
- documentHooks++;
597
- return { owner: !!doc && typeof doc === 'object' && 'owner' in doc && doc.owner === true };
598
- },
599
- permissionSchema: {
600
- name: 'owner',
601
- secret: false,
602
- contacts: { list: true, read: true, sub: { email: true, secret: false } },
603
- },
604
- virtuals: { contacts: { sub: {} } }, // registered embedded scope, no getters
605
- });
606
- const row = await Model.create({
607
- name: 'Ada',
608
- owner: true,
609
- secret: 'hidden',
610
- contacts: [{ email: 'ada@example.test', secret: 'hidden' }],
611
- });
612
- const selected = { select: ['name', 'contacts', 'secret', '-_id'] };
613
-
614
- async function verify(req: ModelRequest) {
615
- const service = router.getService(req);
616
- const off = await service.find({}, selected);
617
- assert.ok(off.success);
618
- off.data[0].contacts![0] = { email: 'replacement' };
619
- await assert.rejects(
620
- service.pickAllowedFields(off.data[0], 'list', {
621
- documentAuthorization: off.contexts[0].documentAuthorization,
622
- }),
623
- );
624
-
625
- router.setOption('unsafeUseListAuthorizationFastPath', undefined); // inherit true
626
- router.setOption('unsafeSkipListNestedDocumentSnapshotChecks', false); // missing ONE prerequisite
627
- const dormant = await service.find({}, selected);
628
- assert.ok(dormant.success);
629
- dormant.data[0].contacts![0] = { email: 'replacement' };
630
- await assert.rejects(
631
- service.pickAllowedFields(dormant.data[0], 'list', {
632
- documentAuthorization: dormant.contexts[0].documentAuthorization,
633
- }),
634
- );
635
-
636
- router.setOption('unsafeSkipListNestedDocumentSnapshotChecks', undefined); // all FOUR now true
637
- const active = await service.find({}, selected);
638
- assert.ok(active.success);
639
- assert.deepEqual(active.data[0], { name: 'Ada', contacts: [{ email: 'ada@example.test' }] });
640
- const context = active.contexts[0];
641
- const originalChild = active.data[0].contacts![0];
642
- const childHandle = context.getDocumentAuthorization(originalChild);
643
- assert.ok(childHandle);
644
- const replacement = { email: 'replacement', secret: 'must be filtered' };
645
- active.data[0].contacts![0] = replacement;
646
- router.setOption('unsafeUseListAuthorizationFastPath', false); // rollback NEW calls only
647
- assert.equal(context.getDocumentAuthorization(originalChild), childHandle); // removed issued member survives
648
- assert.equal(context.getDocumentAuthorization(replacement), undefined); // membership is not reachability
649
- assert.deepEqual(
650
- await service.pickAllowedFields(active.data[0], 'list', {
651
- documentAuthorization: context.documentAuthorization,
652
- }),
653
- { name: 'Ada', contacts: [{ email: 'replacement' }] },
654
- );
655
- const fresh = await service.pickAllowedFields(active.data[0], 'list');
656
- assert.equal(fresh.name, undefined); // fresh raw helper cannot recover the trimmed owner decision
657
-
658
- const readOptions = {
659
- unsafeSkipReadDocumentSnapshotChecks: true,
660
- unsafeSkipReadOutputSnapshotChecks: true,
661
- unsafeSkipReadNestedDocumentSnapshotChecks: true,
662
- unsafeSkipReadInitialOutputSnapshotCopy: true,
663
- unsafeUseReadAuthorizationFastPath: true,
664
- } satisfies DefaultModelRouterOptions;
665
- api.setModelOptions(Model.modelName, readOptions); // does NOT enable LIST
666
- assert.equal(api.getModelOption(Model.modelName, 'unsafeUseListAuthorizationFastPath'), false);
667
- const read = await service.findOne({ _id: row._id }, selected);
668
- assert.ok(read.success);
669
- read.data.contacts![0] = { email: 'read replacement', secret: 'must be filtered' };
670
- api.setModelOption(Model.modelName, 'unsafeUseReadAuthorizationFastPath', false);
671
- assert.deepEqual(
672
- await service.pickAllowedFields(read.data, 'read', {
673
- documentAuthorization: read.context.documentAuthorization,
674
- }),
675
- { name: 'Ada', contacts: [{ email: 'read replacement' }] },
676
- );
677
- const rolledBack = await service.findOne({ _id: row._id }, selected);
678
- assert.ok(rolledBack.success);
679
- rolledBack.data.contacts![0] = { email: 'replacement' };
680
- await assert.rejects(
681
- service.pickAllowedFields(rolledBack.data, 'read', {
682
- documentAuthorization: rolledBack.context.documentAuthorization,
683
- }),
684
- );
685
- assert.equal(documentHooks, 5); // once per query row, never rerun for retained/trimmed helpers
686
- }
687
-
688
- const app = express();
689
- const initialize = api();
690
- app.use((req, res, next) => initialize(req as ModelRequest, res, next));
691
- app.get('/verify', async (req, res, next) => {
692
- try {
693
- await verify(req as ModelRequest);
694
- res.json({ ok: true });
695
- } catch (error) {
696
- next(error);
697
- }
698
- });
699
- server = app.listen(0, '127.0.0.1');
700
- await once(server, 'listening');
701
- const address = server.address();
702
- assert.ok(address && typeof address !== 'string');
703
- const response = await fetch(`http://127.0.0.1:${address.port}/verify`);
704
- assert.equal(response.status, 200);
705
- assert.deepEqual(await response.json(), { ok: true });
706
- } finally {
707
- if (server)
708
- await new Promise<void>((resolve, reject) => server!.close((error) => (error ? reject(error) : resolve())));
709
- try {
710
- await connection.dropDatabase();
711
- } finally {
712
- await connection.close();
713
- }
714
- }
715
- }
716
- runAuthorizationFastPathExample().catch((error) => {
717
- console.error(error);
718
- process.exitCode = 1;
292
+ api.setModelOptions('Employee', {
293
+ readAuthorizationMode: 'isolated',
294
+ listAuthorizationMode: 'trusted',
295
+ createAuthorizationMode: 'trusted',
296
+ updateAuthorizationMode: 'isolated',
719
297
  });
298
+ api.setModelOptions('Payroll', { readAuthorizationMode: 'isolated', listAuthorizationMode: 'isolated' });
299
+ api.setModelOption('Employee', 'listAuthorizationMode', undefined); // inherit the live default
300
+ api.setModelOption('Employee', 'readAuthorizationMode', 'isolated'); // NEW calls only
720
301
  ```
721
302
 
303
+ Isolated owns bounded detached source and gives document-permission output hooks
304
+ disposable views. Trusted may borrow admitted ordinary source/doc-hook input:
305
+ mutations can affect response values and facts calculated from that source. Only
306
+ **query-origin** trusted output can leave hidden unvisited graphs unbounded.
307
+
308
+ **Both write modes always acquire a full bounded detached post-write source**, including
309
+ mutable native leaves, before output callbacks. Trusted omits only the subsequent
310
+ disposable document-hook view copy; it never lends live write documents, `_doc`, payloads
311
+ or lifecycle snapshots. Conversion failure at this boundary fails output rather than
312
+ borrowing `_doc`. This also applies to write-origin populated targets, even when their
313
+ mode is selected by READ/LIST. A hidden graph can therefore fail write-output admission
314
+ even if a trusted query would not visit it. No source-copy saving is promised; without
315
+ an exposed document hook there may be no copy saving.
316
+
317
+ **Both own actor, private policy and normalized frozen boolean facts**, enforce
318
+ original actor, rows/fields/targets and selected/native 20,000-slot/depth-100 bounds.
319
+ Both retain separate getter views, return staging and private argument-four isolation.
320
+ No sandbox, transaction, rollback, external freshness or blanket security equivalence.
321
+
322
+ Capture precedes hooks/awaits, including both possible UPSERT modes. Selecting the
323
+ executed branch retains initiating `operation: 'upsert'` and branch-specific access;
324
+ it does not re-read settings after saving or turn a write response into a READ call.
325
+ Genuine embedded scopes inherit their owner's mode/facts. Related targets use their
326
+ **own model's captured READ/LIST mode** at effective target access, including genuine
327
+ write-origin populate, with independent policy/facts. Parent mode cannot lower an
328
+ isolated target; a trusted target cannot mutate an isolated parent's source or live
329
+ write graph. Independent nested READ/LIST service calls capture anew.
330
+
331
+ Write-input admission, pre-write grants and the **hydrated pre-write UPDATE hook**,
332
+ validation, preparation, transform/save and lifecycle hooks are unchanged, not newly
333
+ detached or sandboxed. NEW, helpers, dedicated subdocument origins, COUNT, DELETE,
334
+ DISTINCT and unsupported custom origins gain no trusted stage. No implicit save,
335
+ query or rollback is added. **Output authorization can fail after the write commits**;
336
+ reconcile stored business state rather than automatically retrying the write.
337
+
338
+ Only literal enum strings or undefined restoration are valid. Bulk setters reject
339
+ atomically. Retired controls reject by presence, even false/undefined/inherited/
340
+ non-enumerable. Mode/retired selectors are prohibited in HTTP/root/per-call/helper/defaults/
341
+ include/populate/subquery authority slots; same-named business fields remain data.
342
+ Trusted transitions warn once per effective owner/access; logger failures cannot abort.
343
+ Switching to isolated affects new calls, not in-flight captures. Rollback means a tested
344
+ matching application/library revision, never re-adding removed flags or assuming mixed
345
+ rolling compatibility. No timing or universal-speedup claim follows from mode names.
346
+
347
+ The [complete executable migration workflow](MIGRATION.md#complete-public-workflow-facts-helper-costs-and-checked-refresh)
348
+ uses literal facts, both modes, zero-read raw helpers and a checked fresh read.
349
+
722
350
  ### Wire placement and option names
723
351
 
724
352
  | Intent | Basic GET query | Advanced body | Root entry |
@@ -752,7 +380,7 @@ separate from both objects. Root entries keep `target`, `name`, base `op`, `filt
752
380
  | Names | Deliberate distinction |
753
381
  | ----------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
754
382
  | `operationAccess` / `permissionSchema` / `authorization` | Route entry / request field rules / explicit server-only per-call authority. An entry grant does not grant fields or related targets. |
755
- | `select` / `alwaysSelectFields` / virtual `dependsOn` | Desired output / private persisted hook inputs / scoped getter dependencies. Fetching a value grants no output authority. |
383
+ | `select` / `docPermissions.dependsOn` / virtual `dependsOn` | Desired output / private document-hook inputs / scoped getter dependencies. Fetching a value grants no output authority. |
756
384
  | `baseFilter` / `overrideFilter` | Request row scope / ordinary-query transform. Trusted rows replace only the former; the transform still runs once and false stays terminal. |
757
385
  | `idParam` / `idField` / `resolveIdFilter` | Express parameter name / lookup field / custom identifier-to-filter hook. A callable resolver takes precedence over `idField`; otherwise lookup uses that field (model default `_id`). |
758
386
  | `requestPermissionField` / `documentPermissionField` / `docPermissions` | Request grant storage / serialized document metadata path / hook producing full internal document grants. Metadata flags affect exposure, not authority. |
@@ -952,8 +580,9 @@ order input returns BadRequest before entry dispatch.
952
580
 
953
581
  Groups run in ascending order; within a group operations may run concurrently.
954
582
  Results retain input indices/order, with each entry's `statusCode` and public
955
- `result` inside the HTTP 200 batch response. Root entries use base operation guards,
956
- not basic/advanced variant names. Batches are non-transactional: an unexpected
583
+ `result` inside the HTTP 200 batch response. Root entries keep base operation names
584
+ but select target `operation.root`, falling back to its scalar/default. The root's
585
+ own scalar guard is a separate outer admission check. Batches are non-transactional: an unexpected
957
586
  rejection can leave already-committed writes. Hook and persistence work also obey
958
587
  their separate [request/runtime limits](#persistence-concurrency-and-resource-limits).
959
588
 
@@ -968,8 +597,8 @@ reentry bound are separate contracts, documented in their sections.
968
597
  ## Trusted service authorization
969
598
 
970
599
  Use these contracts for tenant-scoped business services, protected input/output,
971
- related targets and same-execution document decisions. For a complete executable
972
- example, see [Runnable authorization and handle reuse](#runnable-authorization-and-handle-reuse).
600
+ related targets and document facts. See [Runnable service authorization](#runnable-service-authorization)
601
+ and the shipped [owned-authorization migration](MIGRATION.md) with executable examples.
973
602
 
974
603
  ### Public request admission and backend options
975
604
 
@@ -1011,10 +640,9 @@ Target output grants remain selection-limited, including schema-hidden fields an
1011
640
  virtuals. Populate match, include filter, ref IDs and join/correlation constraints
1012
641
  remain ANDed with the target scope after query transformation in every row mode.
1013
642
  Populate policies also apply after create/update/upsert. Neither parent nor related
1014
- grants flow into request-controlled `$$sq` queries. For a same-execution target pick,
1015
- use `result.context.getDocumentAuthorization(child)` (or the corresponding list-row
1016
- context) with **that target model's** helper. Private dependencies and join keys do
1017
- not become output grants; related copies retain their own document results.
643
+ grants flow into request-controlled `$$sq` queries. Related output is already-filtered
644
+ DATA; no child handles/lookups remain. A current target-dependent decision needs a
645
+ new normal target read/list. Private dependencies/join keys do not grant output.
1018
646
 
1019
647
  Every requested populate target needs an actual registered Mongoose model and ACL
1020
648
  configuration with an **effective object `permissionSchema`** in the owning runtime.
@@ -1027,6 +655,73 @@ stay false while ordinary population skips only target operation admission with
1027
655
  `requireOperationAccessForPopulateQueries: false`. See the [two-flag policy matrix](#runtime-populate-operation-policies)
1028
656
  and [runnable Document example](#runnable-private-dependency-example).
1029
657
 
658
+ ### Document-permission dependencies (breaking change)
659
+
660
+ `alwaysSelectFields` is removed, including its fluent setter and dotted options.
661
+ Move each private input onto the calculation that uses it: `docPermissions` accepts
662
+ a synchronous/asynchronous function or `{ dependsOn?, get }`, directly or in a
663
+ per-access map. The spelling is **`get`**, like virtuals, not `getter`.
664
+
665
+ <!-- doc-example: partial -->
666
+
667
+ ```ts
668
+ import type {
669
+ ModelDocPermissionsDescriptor,
670
+ ModelDocPermissionsDefinition,
671
+ ModelDocPermissionsAccessRecord,
672
+ ModelRouter,
673
+ ModelRouterOptions,
674
+ } from '@web-ts-toolkit/access-router';
675
+
676
+ interface Order {
677
+ ownerId: string;
678
+ profile: { tenantId: string };
679
+ }
680
+ const owner: ModelDocPermissionsDescriptor<Order> = {
681
+ dependsOn: ['ownerId', 'profile'], // whole top-level container for nested input
682
+ get(doc, permissions, context) {
683
+ void [this.macl, context.operation]; // original request this; unchanged hook arguments
684
+ return {
685
+ owner:
686
+ permissions.has('admin') ||
687
+ (doc !== null && typeof doc === 'object' && 'ownerId' in doc && doc.ownerId === 'alice'),
688
+ };
689
+ },
690
+ };
691
+ const definition: ModelDocPermissionsDefinition<Order> = owner;
692
+ const accesses: ModelDocPermissionsAccessRecord<Order> = {
693
+ default: definition,
694
+ read: owner,
695
+ list: async () => ({ owner: false }), // function: no additional fetch inputs
696
+ inspection: owner, // trusted custom access
697
+ };
698
+ const direct: ModelRouterOptions<Order> = { docPermissions: definition };
699
+ const mapped: ModelRouterOptions<Order> = { docPermissions: accesses };
700
+ declare const router: ModelRouter<Order>;
701
+ router.docPermissions(owner).docPermissions('read', owner);
702
+ router.setOption('docPermissions.inspection', owner); // replace the entire definition
703
+ void [direct, mapped];
704
+ ```
705
+
706
+ Dependencies use model-local **top-level persisted schema keys**, like virtuals.
707
+ Dotted, unsafe, unknown and virtual names reject; declare `profile`, not
708
+ `profile.tenantId`. `dependsOn` absent/empty adds no fetch inputs. A missing or
709
+ undefined value **never skips the document hook** (unlike virtual dependency
710
+ skipping). Declared inputs remain private when unrequested, excluded or denied;
711
+ they grant no output authority and do not select a virtual.
712
+
713
+ The active **`docPermissionsAccess`** selects the exact definition, then `default`
714
+ when the exact entry is undefined; a direct function/descriptor applies to every
715
+ access. Hook and dependencies are captured together before awaits. Dependencies
716
+ are **not unioned** with output/virtual access or inherited from a different entry.
717
+ `get`/`dependsOn` are reserved descriptor members, not custom access names.
718
+ Dotted access setters replace whole definitions; partial `.get`/`.dependsOn` edits
719
+ reject. Malformed definitions (including null/false or mixed descriptor/access keys)
720
+ reject instead of silently disabling calculation. Embedded scopes inherit owning-document facts; populate/include targets
721
+ resolve their own definitions. Dedicated subdocument routes still prepare the
722
+ owning parent. Pre-write and post-write stages are independent. Raw output helpers
723
+ perform no hidden query or document-hook calculation.
724
+
1030
725
  ### Selection, grants and document results
1031
726
 
1032
727
  For business fields, output is **selected AND (request-authorized OR explicitly
@@ -1058,7 +753,8 @@ scalar value when that root is selected.
1058
753
 
1059
754
  Planning defers document-dependent rules and never runs permission functions or
1060
755
  virtual getters. Document hooks receive projected input: configure additional
1061
- persisted hook dependencies with `alwaysSelectFields`. Internal dependency fetches
756
+ persisted hook dependencies with `docPermissions.dependsOn` (on the applicable
757
+ definition). Internal dependency fetches
1062
758
  do not grant output, even when the same path is also a private include join key.
1063
759
  Captured row/document hooks retain exact-access → `.default` → bare-hook resolution;
1064
760
  only an undefined entry falls through. Omitted/undefined helper options now use the
@@ -1074,29 +770,15 @@ start fresh request-mode output evaluation. `genAllowedFields` defaults to
1074
770
  purpose. It reports **existing output paths**, not a schema/input allowlist. Null or
1075
771
  undefined documents yield `[]` (pick/trim preserve the nullish value) without hooks.
1076
772
 
1077
- The shared finalizer now consumes retained authorization plans and privately
1078
- memoizes full document grants and field decisions. For a subsequent same-execution
1079
- pick, use `{ documentAuthorization }` with the package-issued output context's
1080
- handle, rather than resupplying the raw policy. Default/copied handles validate the
1081
- unchanged output graph; active trusted handles validate exact root association and
1082
- issued membership, not current descendants. All retain request/runtime/model, scope,
1083
- access and document-stage checks; caller
1084
- spreads, matching IDs and `_permissions` are not provenance. Raw policy on a known
1085
- trimmed output retains unconditional request fields and explicit grants, but does
1086
- not rerun the document hook or recover document-dependent decisions. Metadata
1087
- stripping/exposure switches are independent of internal grants. Target models
1088
- require their own authorization; parent grants cover the relationship only.
1089
-
1090
- Internal `findOne`/`findById`/`find`, `create`, `updateOne`/`updateById`, `upsert`
1091
- and `new` now consume the captured call policy throughout output finalization.
1092
- Single results expose `context.documentAuthorization`; list/create results expose
1093
- one `contexts[index]` per row. These opaque handles are non-enumerable context
1094
- properties, never attached to `data`. `context.getDocumentAuthorization(value)`
1095
- looks up an unchanged registered output in a default/copied result's graph. In the
1096
- [active trusted path](#experimental-unsafe-readlist-authorization-fast-paths), it
1097
- instead looks up issued document-root membership: removed original children may
1098
- remain discoverable, replacements are not issued, and an exact root's helper can
1099
- filter changed descendants using stale decisions/shared grants after rollback.
773
+ The finalizer owns a private stage, resolves boolean `DocumentGrants` once and
774
+ memoizes field decisions only until publication. Each row/call/target/pre-/post-write
775
+ stage is independent; genuine embedded scopes reuse their owner's facts. Returned
776
+ DTOs carry **no capability**, hidden authority symbol or reusable document handle.
777
+
778
+ Single results have a frozen diagnostic `context`; list/create results have aligned
779
+ `contexts[index]`. These are `ModelOutputContext` diagnostics, not source/model/
780
+ lifecycle aliases or authority. Their exact allowlist and removed-member replacements
781
+ are in [MIGRATION.md](MIGRATION.md#m2-replace-output-context-mutation-with-explicit-business-work).
1100
782
 
1101
783
  <!-- doc-example: partial -->
1102
784
 
@@ -1110,40 +792,30 @@ const result = await service.findOne(
1110
792
  { select: ['status', 'internalNote'] },
1111
793
  { authorization: { outputFields: { mode: 'grant', paths: ['internalNote'] } } },
1112
794
  );
1113
- if (result.success) {
1114
- const picked = await service.pickAllowedFields(result.data, 'read', {
1115
- documentAuthorization: result.context.documentAuthorization,
1116
- });
1117
- console.log(picked);
1118
- }
795
+ if (!result.success) throw new Error(`Read failed: ${result.code}`);
796
+ console.log({ internalNote: result.data.internalNote }); // presentation subset, no new authorization
797
+ const current = await service.findById(orderId, { select: ['status', 'internalNote'] });
798
+ if (!current.success) throw new Error(`Refresh failed: ${current.code}`);
799
+ console.log(current.data); // new normal row/document authorization; adds a read/hook
1119
800
  ```
1120
801
 
1121
- The selected stored note survives false/missing request rules; `status` still
1122
- requires normal request authorization. Ordinary document grants now apply even
1123
- under `skim` and metadata-disabled/stripped postures. Declare private hook inputs
1124
- with `alwaysSelectFields`; later handle picks reuse the original results after
1125
- those inputs are removed. Metadata describes request permissions, not backend grants.
1126
-
1127
- Mutations use ordinary `args.select`. Output grants never admit protected writes;
1128
- validation, prepare/transform/afterPersist/change hooks and save semantics remain.
1129
- Update admission and post-write output have separate document stages. Upsert keeps
1130
- its initiating operation with create/update branch accesses. `new()` continues to
1131
- ignore `select`, including empty/exclusion projections. Trusted presentation hooks
1132
- run after finalization and may intentionally remove/construct output. There is no
1133
- automatic second authorization pass; arbitrary mutations/replacements do not acquire
1134
- provenance. For an unchanged output, use its handle at the **output access**: `read`
1135
- for ordinary reads/create/update/upsert output, `list` for lists or reads using list
1136
- access, and `create` for `new()`.
1137
-
1138
- The immutable **call policy** captures authority once for planning and execution.
1139
- Each document/scope/access stage separately owns its hook grants and field decisions;
1140
- two list rows never share those results. Reusing the same raw policy is fresh
1141
- evaluation, not a substitute for a document handle. A fresh unassociated input must
1142
- contain the projected hook dependencies; a recognized trimmed output cannot rerun
1143
- the hook to reconstruct lost decisions. Use either `authorization` or
1144
- `documentAuthorization` in a named helper, never both. When extracting policy from a
1145
- full call, construct `{ outputFields: policy.outputFields }` for output-only helpers;
1146
- `create` accepts input/output/related, and `new` accepts output only.
802
+ Raw output helpers use captured global permissions + frozen **empty document facts**
803
+ and explicit output-only server policy. They perform zero DB operations/document hooks,
804
+ no row checks, virtuals or omitted-value recovery. `!facts.suspended` may be true on
805
+ empty facts; that is not current-document proof. Metadata (`getDocPermissions` included)
806
+ is DATA, not authority. Never replace a retired handle with unrestricted/client grants.
807
+
808
+ For current document-dependent authorization use a new normal read/list with suitable
809
+ selection and private `docPermissions.dependsOn` hook inputs. For presentation just use the
810
+ already-filtered DTO: no extra query, but no claim of current checks. See the executable
811
+ guide for exact **0/0 helper** versus **+1 read/+1 hook** refresh counts.
812
+
813
+ Mutations retain ordinary `args.select`, independent input admission, validation,
814
+ prepare/transform/save/afterPersist/change roles and separate pre-/post-write facts.
815
+ `new()` still ignores select. Presentation callbacks run after stage closure and may
816
+ construct data, with no automatic second filtering pass. Extract only
817
+ `{ outputFields: policy.outputFields }` for output helpers; full row/input/related
818
+ policies reject. There is no helper handle option or child lookup.
1147
819
 
1148
820
  ### Independent mutation input authority
1149
821
 
@@ -1360,7 +1032,7 @@ for public adapters. Keep policies as server constants, not spreads of request
1360
1032
  options. Positional helper overloads are removed; see the named-helper migration
1361
1033
  and request-only data compatibility contract below.
1362
1034
 
1363
- ### Runnable authorization and handle reuse
1035
+ ### Runnable service authorization
1364
1036
 
1365
1037
  This complete example uses an installed package, Express and MongoDB. Save it as
1366
1038
  `authorization-example.mts` and run `node authorization-example.mts` on Node 22.18+
@@ -1446,11 +1118,13 @@ async function runServiceAuthorizationExample() {
1446
1118
  return filter;
1447
1119
  },
1448
1120
  },
1449
- alwaysSelectFields: { read: ['ownerId'] }, // private projected document-hook input
1450
1121
  docPermissions: {
1451
- read: (doc) => {
1452
- documentHookCalls++;
1453
- return { owner: doc !== null && typeof doc === 'object' && 'ownerId' in doc && doc.ownerId === 'alice' };
1122
+ read: {
1123
+ dependsOn: ['ownerId'], // private projected document-hook input
1124
+ get: (doc) => {
1125
+ documentHookCalls++;
1126
+ return { owner: doc !== null && typeof doc === 'object' && 'ownerId' in doc && doc.ownerId === 'alice' };
1127
+ },
1454
1128
  },
1455
1129
  },
1456
1130
  permissionSchema: { status: { read: 'owner' }, internalNote: false, summary: false },
@@ -1489,10 +1163,9 @@ async function runServiceAuthorizationExample() {
1489
1163
  const result = await service.findOne({ _id: rows[0]._id }, selected, { ...quiet, authorization });
1490
1164
  assert.ok(result.success);
1491
1165
  assert.deepEqual(result.data, { status: 'ready', internalNote: 'server note' });
1492
- // ownerId and _permissions are absent, yet this handle retains both decisions.
1493
- const reuse = { documentAuthorization: result.context.documentAuthorization };
1494
- const picked = await service.pickAllowedFields(result.data, 'read', reuse);
1495
- assert.deepEqual(await service.trimOutputFields(picked, 'read', reuse), result.data);
1166
+ // Already-filtered DTO is usable DATA, not current-document authority.
1167
+ const subset = { status: result.data.status };
1168
+ assert.deepEqual(subset, { status: 'ready' });
1496
1169
  assert.equal(documentHookCalls, 1);
1497
1170
  const fresh = await service.pickAllowedFields(result.data, 'read', { authorization: output });
1498
1171
  assert.deepEqual(fresh, { internalNote: 'server note' }); // no original owner decision
@@ -1555,13 +1228,10 @@ async function runServiceAuthorizationExample() {
1555
1228
  assert.equal(related.data.contacts?.[0].ssn, undefined);
1556
1229
  const child: unknown = Reflect.get(related.data, 'customer');
1557
1230
  assert.ok(child && typeof child === 'object');
1558
- const childHandle = related.context.getDocumentAuthorization(child);
1559
- assert.ok(childHandle);
1560
- const childPick = await customerRouter
1561
- .getService(req)
1562
- .pickAllowedFields(child, 'read', { documentAuthorization: childHandle });
1563
- assert.equal(Reflect.get(childPick, 'billingEmail'), 'billing@example.test');
1564
- assert.equal(Reflect.get(childPick, 'tenantId'), undefined);
1231
+ assert.equal(Reflect.get(child, 'billingEmail'), 'billing@example.test');
1232
+ assert.equal(Reflect.get(child, 'tenantId'), undefined);
1233
+ const targetRaw = await customerRouter.getService(req).pickAllowedFields(child, 'read');
1234
+ assert.equal(Reflect.get(targetRaw, 'billingEmail'), undefined); // no retained target authority
1565
1235
 
1566
1236
  // Input authority is independent: patch the existing first contact, preserve ssn,
1567
1237
  // persist the denied note, and grant neither field in the mutation response.
@@ -1776,7 +1446,7 @@ adapter or alternate legacy authority path.
1776
1446
  | `overrides.idFilter: { slug }` | `findOne({ slug }, args, options)` / `updateOne({ slug }, data, args, options)` with explicit row policy when needed. By-ID calls always use normal identifier resolution. |
1777
1447
  | `overrides.effectiveSelect: ['status']` | `create(data, { select: ['status'] }, options)` / `updateOne(query, data, { select: ['status'] }, options)` / `upsert(query, data, { select: ['status'] }, options)`. Public `returningAll: false` computes this ordinary selection once. |
1778
1448
  | `overrides.operation: 'upsert'` | Call `upsert(query, data, args, options)`. Private execution retains initiating `upsert` while create/update branch accesses govern getters, output and document grants. |
1779
- | `pickAllowedFields(doc, 'read', ['internalNote'])` using helper `baseFields` as visibility authority | `pickAllowedFields(doc, 'read', { authorization: { outputFields: { mode: 'grant', paths: ['internalNote'] } } })`, or reuse the original `documentAuthorization` handle for same-execution document decisions. |
1449
+ | `pickAllowedFields(doc, 'read', ['internalNote'])` using helper `baseFields` as visibility authority | `pickAllowedFields(doc, 'read', { authorization: { outputFields: { mode: 'grant', paths: ['internalNote'] } } })`. For document-dependent decisions, use a new normal service query; presentation can use the already-filtered DTO. |
1780
1450
  | `genSelect('read', select, true)` using helper `skipChecks` for provisional fetching | `genSelect('read', select, { authorization: { outputFields: { mode: 'request' } } })` / `genQuerySelect(...)`. Named planning defers document-dependent rules; use an explicit output grant when backend visibility is required. |
1781
1451
 
1782
1452
  The helper overloads in the last two rows are also **removed in this next breaking
@@ -1832,9 +1502,13 @@ hook, losing otherwise allowed persisted fields. Full internal document grants
1832
1502
  are now resolved once per projected document/access stage regardless of `skim`,
1833
1503
  `includePermissions`, `includeFieldPermissions`, stripping or exposed-key limits.
1834
1504
  Only serialized metadata changes with those settings. Configure required private
1835
- hook inputs with `alwaysSelectFields`; same-execution handle picks retain the
1836
- original decisions after those inputs and `_permissions` are removed. Temporary
1837
- backend grants do not forge request-user `_view`/`_edit` or document-hook metadata.
1505
+ hook inputs with `docPermissions.dependsOn`; the published DTO is data, not an authorization
1506
+ certificate after those inputs and `_permissions` are removed. A later raw helper pick
1507
+ uses captured global permissions, frozen empty document facts and explicit output-only
1508
+ server policy, not retained document decisions. For current document-dependent facts,
1509
+ issue a new normal read/list with suitable selection/private hook inputs. This adds
1510
+ read/hook work; raw picks perform no hidden refresh. Temporary backend grants do not
1511
+ forge request-user `_view`/`_edit` or document-hook metadata.
1838
1512
 
1839
1513
  Output grants cannot write protected fields. Explicit model mutation `inputFields`
1840
1514
  and dedicated parent/child/visibility policies are independent opt-in capabilities;
@@ -1848,12 +1522,13 @@ valid under ordinary rules.
1848
1522
  Model `Base`/`Service`/`PublicService` expose these finite signatures; Core prepends
1849
1523
  `modelName`. The option types are exported from both the root and `/advanced`:
1850
1524
 
1851
- | Helper | Supported final argument / default |
1852
- | ------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
1853
- | `genSelect(access, select?, options?)`, `genQuerySelect(...)` | `OutputPlanningOptions<TModel, TVirtuals>`, defaults to `{}` |
1854
- | `pickAllowedFields(doc, access, options?)`, `trimOutputFields(...)` | `OutputFieldOptions<TModel, TVirtuals>`, defaults to `{}` |
1855
- | `genAllowedFields(doc, access, options?)` | `AllowedOutputFieldOptions<TModel, TVirtuals>`, defaults to `{ purpose: 'output' }`; supplied objects require the purpose |
1856
- | `genPopulate(access?, populate?, options?)` | Request-only `PopulatePlanningOptions`, defaults to `{}`; only `scopePath` is supported |
1525
+ | Helper | Supported final argument / default |
1526
+ | ------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
1527
+ | `genSelect(access, select?, options?)`, `genQuerySelect(...)` | `OutputPlanningOptions<TModel, TVirtuals>`, defaults to `{}` |
1528
+ | `pickAllowedFields(doc, access, options?)`, `trimOutputFields(...)` | `OutputFieldOptions<TModel, TVirtuals>`, defaults to `{}` |
1529
+ | `pickAllowedFieldsMany(rows, access, options?)` | `OutputFieldOptions<TModel, TVirtuals>`, defaults to `{}`; one explicit collection capture, `readonly FilteredOutput<T>[]` result |
1530
+ | `genAllowedFields(doc, access, options?)` | `AllowedOutputFieldOptions<TModel, TVirtuals>`, defaults to `{ purpose: 'output' }`; supplied objects require the purpose |
1531
+ | `genPopulate(access?, populate?, options?)` | Request-only `PopulatePlanningOptions`, defaults to `{}`; only `scopePath` is supported |
1857
1532
 
1858
1533
  **Default model calls changed.** There is no hidden no-option legacy path:
1859
1534
 
@@ -1865,11 +1540,12 @@ Model `Base`/`Service`/`PublicService` expose these finite signatures; Core prep
1865
1540
  that setting, still subject to request rules or explicit policy. It is no grant.
1866
1541
  A fetch projection never proves response or population permission.
1867
1542
  - Pick/trim isolate hydrated or plain inputs rather than mutating persistence
1868
- documents. Fresh raw input runs the document-permissions hook; serialized
1869
- `_permissions` cannot grant fields. Nested/array output rules, private `_id`
1870
- retention and configured metadata posture match named output behavior. On known
1871
- trimmed output, use its handle to retain document-dependent decisions. Unsupported
1872
- scalar/array documents reject. `genAllowedFields` only reports existing paths.
1543
+ documents, using captured globals, frozen empty document facts and explicit server
1544
+ output policy. They run **no document hooks or hidden reads**. Serialized
1545
+ `_permissions` and already-trimmed DTOs carry no authority or reusable handle.
1546
+ Nested/array output rules, private `_id` retention and configured metadata posture
1547
+ still apply. Unsupported scalar/array root documents reject; an array inside a row
1548
+ remains a value. `genAllowedFields` only reports existing paths.
1873
1549
  - Request/input and query-field checks remain separate. Migrate writes to service
1874
1550
  mutations with independent `authorization.inputFields`; output picks never admit
1875
1551
  writes. Distinct/sort and request-user `_view`/`_edit` do not inherit output grants.
@@ -1886,6 +1562,93 @@ backend target authority. The obsolete raw `buildVirtualPlan`/`buildSubVirtualPl
1886
1562
  service builders are removed; use named fetch helpers. Retained plans, private
1887
1563
  identity/metadata/join retention and document-result issuance belong to package execution.
1888
1564
 
1565
+ #### Optional raw collections: one deliberately shared capture
1566
+
1567
+ `service.pickAllowedFieldsMany<T>(rows, access, options?)` returns
1568
+ `Promise<readonly FilteredOutput<T>[]>`. Both `getService` and `getPublicService`
1569
+ inherit it; `req.macl.pickAllowedFieldsMany(modelName, rows, access, options?)`
1570
+ is the Core form. There is no DataService member, generated route, client control,
1571
+ batch alias, reusable preparer or output capability. Existing single-row helpers
1572
+ remain independently fresh, including their weaker `Promise<T>` declarations
1573
+ (which never proved that required fields survived).
1574
+
1575
+ Use this **optional** API for existing backend-held raw records only when the backend
1576
+ deliberately wants **one** initialized actor/model/catalog/configuration/scope/output
1577
+ policy capture before awaits or field predicates. It is **not semantically equivalent**
1578
+ to N fresh independent calls, nor a default handle/H3 migration recommendation.
1579
+ Later actor-view, schema or options changes apply to the next call, not later rows.
1580
+ Changing `req.user` alone does not rerun the initialized permission resolver. Trusted
1581
+ closures, live request properties, external state and native normalization effects
1582
+ are not frozen: this is not an atomic multi-object/database snapshot or sandbox.
1583
+
1584
+ <!-- doc-example: partial -->
1585
+
1586
+ ```ts
1587
+ import type { FilteredOutput, OutputFieldOptions } from '@web-ts-toolkit/access-router';
1588
+ import type { ModelRequest } from '@web-ts-toolkit/access-router/advanced';
1589
+ type Contact = { label: string; email: string; address: { city: string } };
1590
+ type Employee = { contacts: Contact[] };
1591
+ async function filterRawContacts(req: ModelRequest, rows: readonly Contact[]) {
1592
+ // Backend-owned policy, NEVER copied from request body/query/options.
1593
+ const options: OutputFieldOptions<Employee> = {
1594
+ scopePath: ['contacts'],
1595
+ authorization: { outputFields: { mode: 'grant', paths: ['contacts.label'] } },
1596
+ };
1597
+ const result: readonly FilteredOutput<Contact>[] = await req.macl
1598
+ .getService<Employee>('Employee')
1599
+ .pickAllowedFieldsMany(rows, 'list', options);
1600
+ return result.map((row) => row.label?.toUpperCase()); // nested fields can also be omitted
1601
+ }
1602
+ void filterRawContacts;
1603
+ ```
1604
+
1605
+ Scope paths use ordinary response segments; grants remain **model-relative**
1606
+ (`contacts.label`, not `label`). Only output policy is accepted, never row/input/
1607
+ related authority, selection, handles, tokens, `purpose` or mode controls. Every row
1608
+ occurrence gets an independent isolated source/stage/memo in **all modes**, including
1609
+ repeated references. All sources are owned before the **first** field predicate;
1610
+ field evaluations are not shared between rows. The helper uses globals + literal
1611
+ frozen EMPTY facts + explicit output policy: **0 DB operations / 0 document hooks**,
1612
+ no virtuals, row/operation/related checks, reference-provenance recovery or restoration.
1613
+ `!facts.suspended` on EMPTY is not current-document authority. Presentation subsets
1614
+ normally need **zero helpers**; current document facts require a **new normal READ/LIST**
1615
+ with normal row policy/private hook inputs. See the executable alternatives in
1616
+ [M3](MIGRATION.md#m3-remove-handles-choose-presentation-or-a-fresh-normal-query).
1617
+
1618
+ - Outer input: dense ordinary Array, **0–1,000** positions, frozen/readonly accepted,
1619
+ null/undefined positions preserved. Proxies (before traps), subclasses, holes,
1620
+ accessor/non-enumerable indices, extra own string/symbol keys and iterables reject;
1621
+ no iterator is used. Empty calls still validate receiver/controls/model/policy/catalog.
1622
+ - Separate per-row source/fact/view/selected **20,000-slot / depth-100** owners remain;
1623
+ embedded/native/metadata/copy/wire work shares the relevant remainder. One whole-call
1624
+ **200,000 work-unit / 16 MiB cumulative payload** ledger covers **router-controlled
1625
+ admission, staging, traversal and explicit copies**, including preparation and all
1626
+ rows/phases. It never resets per row or internal chunk. Caller chunking creates new
1627
+ fresh operations, not one atomic collection operation.
1628
+ - **Excluded:** opaque Mongoose/native normalization internals and dependency-owned
1629
+ allocations/traversals, arbitrary trusted callback/closure effects and engine
1630
+ enumeration costs. This is **not** a total-memory/RSS, whole-normalization, CPU-operation
1631
+ or sandbox cap. Canonical normalization may copy 17 MiB and discard it into a tiny
1632
+ admitted row; a returned 17 MiB normalized value must reject **before the next explicit
1633
+ router copy**. Explicit router native/wire preparation is still accounted for.
1634
+ - Row work uses the minimum row/scheduler/shared-hook-gate concurrency, preserving
1635
+ FIFO/reentry/depth, stable outer order and each row's field order/sync-until-async
1636
+ behavior; no unbounded Promise.all or persistence permit while waiting. Structural,
1637
+ native or router-budget poison rejects the **whole** operation with controlled 400,
1638
+ even if caught inside a callback. Admission closes, admitted library work drains,
1639
+ private state clears and late work cannot publish. Ordinary predicate-body errors
1640
+ omit their fields. No partial result, side-effect rollback, automatic retry or wait
1641
+ for untracked detached closure work is promised.
1642
+
1643
+ `FilteredOutput<T>` is a **type-only** root/advanced export: recursively optional
1644
+ readonly string properties (including `_id`), nullish array elements without tuple/
1645
+ cardinality inference, string Maps normalized to readonly records, and canonical
1646
+ Date/RegExp/Buffer base types. Other BSON, hydrated documents (including string-ID
1647
+ documents), unknown inputs and recursion at depth eight become `unknown`; narrow or
1648
+ validate them. Readonly does not freeze native methods. The type is not a supported-
1649
+ input validator, exact-selected-field inference or authority certificate. No speedup,
1650
+ old performance-gate substitution or performance acceptance is implied.
1651
+
1889
1652
  #### Request-only data helpers
1890
1653
 
1891
1654
  `DataCore` keeps `genSelect`, `genAllowedFields`, and `pickAllowedFields` with a
@@ -1898,8 +1661,11 @@ Selection, input document and resulting field paths are relative to that scope.
1898
1661
 
1899
1662
  These helpers retain the **request-only data evaluator**: no Mongoose registration
1900
1663
  or catalog, model document hooks, virtual computation, or DataService authorization.
1901
- Permission functions receive the original request as `this` and only its permissions
1902
- argument. Allowed-fields returns a schema allowlist even with a null/empty document;
1664
+ Field permission functions receive the original request as `this` and
1665
+ `(permissions, grants)`: `grants` is the built-in frozen empty document-facts record. Request-only
1666
+ means no model document facts, not a one-argument field callback. Operation `GuardHook`
1667
+ remains separate: it receives only `permissions`, with the original request as `this`.
1668
+ Allowed-fields returns a schema allowlist even with a null/empty document;
1903
1669
  pick/trim select existing values from it. An allowed container remains a whole value;
1904
1670
  use a scoped helper to filter a child. `_id` and metadata require ordinary data-field
1905
1671
  rules, with no automatic retention.
@@ -2061,10 +1827,16 @@ query params; only `includePermissions`/`includeFieldPermissions`/`populateAcces
2061
1827
 
2062
1828
  ## Basic and advanced operation access
2063
1829
 
2064
- Configure generated endpoint guards in `operationAccess`. A base rule such as `read`
2065
- covers both variants unless an exact `basicRead` or `advancedRead` rule overrides it.
2066
- Variants authorize **route entry**; field grants remain in `permissionSchema` under
2067
- base names such as `read` and `list`.
1830
+ Configure generated endpoint guards in `operationAccess`. Each operation accepts a
1831
+ scalar `Validation` or `{ default?, basic?, advanced?, root? }`, with a `Validation`
1832
+ at each member. `basic`, `advanced` and `root` independently authorize **entry**;
1833
+ `default` supplies context-free base checks and entry fallback. Field grants remain
1834
+ in `permissionSchema` under base names such as `read` and `list`.
1835
+
1836
+ This is a hard breaking replacement of the former flat API, not an alias or
1837
+ translation layer. See the shipped [migration and seven mapping pairs](MIGRATION.md#breaking-change-nested-operation-access).
1838
+ Public `OperationAccessContext`, `OperationAccessVariants` and `OperationAccessRule`
1839
+ are exported from root and `./advanced`.
2068
1840
 
2069
1841
  <!-- doc-example: partial -->
2070
1842
 
@@ -2080,20 +1852,20 @@ const baseOnly = {
2080
1852
  // Among top-level routes, deny GET /users/:id only; both advanced read POSTs inherit read: true.
2081
1853
  const advancedReadsOnly = {
2082
1854
  basePath: '/users',
2083
- operationAccess: { list: true, read: true, basicRead: false },
1855
+ operationAccess: { list: true, read: { default: true, basic: false } },
2084
1856
  permissionSchema: { name: true },
2085
1857
  } satisfies ModelRouterOptions;
2086
1858
 
2087
1859
  // Keep GET /users, deny POST /users/__query.
2088
1860
  const basicListsOnly = {
2089
1861
  basePath: '/users',
2090
- operationAccess: { list: true, read: true, advancedList: false },
1862
+ operationAccess: { list: { default: true, advanced: false }, read: true },
2091
1863
  permissionSchema: { name: true },
2092
1864
  } satisfies ModelRouterOptions;
2093
1865
  // Pass one of these objects to acl.createRouter(UserModel, options).
2094
1866
  ```
2095
1867
 
2096
- `basicRead: false` does not affect list, new, count, distinct, or mutation routes;
1868
+ `read.basic: false` does not affect list, new, count, distinct, or mutation routes;
2097
1869
  their own guards still apply. Subdocument reads follow the field precedence below.
2098
1870
  Denied operations return **HTTP 401 Unauthorized**
2099
1871
  before validation/service dispatch. Every route stays registered in
@@ -2107,55 +1879,61 @@ Paths are relative to `basePath`, with model defaults `idParam: 'id'`,
2107
1879
  Changing those route-shape options changes paths, not guard names. For data routers,
2108
1880
  set `idParam: 'id'` explicitly to use the illustrated identifier paths.
2109
1881
 
2110
- | Base guard | Basic endpoint → override | Advanced endpoint → override |
2111
- | ----------------- | ------------------------------------------------ | -------------------------------------------------------------- |
2112
- | `list` | `GET /` → `basicList` | `POST /__query` → `advancedList` |
2113
- | `read` | `GET /:id` → `basicRead` | `POST /__query/:id`, `POST /__query/__filter` → `advancedRead` |
2114
- | `create` | `POST /` → `basicCreate` | `POST /__mutation` → `advancedCreate` |
2115
- | `update` | `PATCH /:id` → `basicUpdate` | `PATCH /__mutation/:id` → `advancedUpdate` |
2116
- | `upsert` | `PUT /` → `basicUpsert` | `PUT /__mutation` → `advancedUpsert` |
2117
- | `count` | `GET /count` → `basicCount` | `POST /count` → `advancedCount` |
2118
- | `distinct` | `GET /distinct/:field` → `basicDistinct` | `POST /distinct/:field` → `advancedDistinct` |
2119
- | `subs.<sub>.list` | `GET /:id/<sub>` → `subs.<sub>.basicList` | `POST /:id/<sub>/__query` → `subs.<sub>.advancedList` |
2120
- | `subs.<sub>.read` | `GET /:id/<sub>/:subId` → `subs.<sub>.basicRead` | `POST /:id/<sub>/:subId/__query` → `subs.<sub>.advancedRead` |
2121
-
2122
- Model routers support all fourteen top-level keys. Data routers implement only
2123
- list/read: `basicList`, `advancedList`, `basicRead`, and `advancedRead`, including
2124
- both advanced read paths. Each model subdocument field supports four nested
2125
- list/read keys. Filtered count/distinct POSTs are advanced even without `__query`.
2126
-
2127
- Unpaired routes retain their base guards:
2128
-
2129
- | Endpoint | Guard |
2130
- | --------------------------------------------- | ------------------- |
2131
- | `GET /new` | `new` |
2132
- | `DELETE /:id` | `delete` |
2133
- | `POST /:id/<sub>` | `subs.<sub>.create` |
2134
- | `PATCH /:id/<sub>`, `PATCH /:id/<sub>/:subId` | `subs.<sub>.update` |
2135
- | `DELETE /:id/<sub>/:subId` | `subs.<sub>.delete` |
1882
+ | Operation | Basic endpoint → member | Advanced endpoint → member | Root entry member |
1883
+ | ----------------- | ------------------------------------------------- | --------------------------------------------------------------- | ---------------------- |
1884
+ | `list` | `GET /` → `list.basic` | `POST /__query` → `list.advanced` | `list.root` |
1885
+ | `read` | `GET /:id` → `read.basic` | `POST /__query/:id`, `POST /__query/__filter` → `read.advanced` | `read.root` |
1886
+ | `create` | `POST /` → `create.basic` | `POST /__mutation` → `create.advanced` | `create.root` |
1887
+ | `update` | `PATCH /:id` → `update.basic` | `PATCH /__mutation/:id` → `update.advanced` | `update.root` |
1888
+ | `upsert` | `PUT /` → `upsert.basic` | `PUT /__mutation` → `upsert.advanced` | `upsert.root` |
1889
+ | `count` | `GET /count` → `count.basic` | `POST /count` → `count.advanced` | `count.root` |
1890
+ | `distinct` | `GET /distinct/:field` → `distinct.basic` | `POST /distinct/:field` → `distinct.advanced` | `distinct.root` |
1891
+ | `subs.<sub>.list` | `GET /:id/<sub>` → `subs.<sub>.list.basic` | `POST /:id/<sub>/__query` → `subs.<sub>.list.advanced` | `subs.<sub>.list.root` |
1892
+ | `subs.<sub>.read` | `GET /:id/<sub>/:subId` → `subs.<sub>.read.basic` | `POST /:id/<sub>/:subId/__query` → `subs.<sub>.read.advanced` | `subs.<sub>.read.root` |
1893
+
1894
+ Data routers implement list/read with the same members, including both advanced
1895
+ read paths. Filtered count/distinct POSTs are advanced even without `__query`.
1896
+ Context is explicit server-owned dispatch metadata, never inferred from method or
1897
+ caller-supplied selectors. Root POST does not select advanced.
1898
+
1899
+ Unpaired routes also use operation objects; direct entry selects basic:
1900
+
1901
+ | Endpoint | Guard |
1902
+ | --------------------------------------------- | ------------------------- |
1903
+ | `GET /new` | `new.basic` |
1904
+ | `DELETE /:id` | `delete.basic` |
1905
+ | `POST /:id/<sub>` | `subs.<sub>.create.basic` |
1906
+ | `PATCH /:id/<sub>`, `PATCH /:id/<sub>/:subId` | `subs.<sub>.update.basic` |
1907
+ | `DELETE /:id/<sub>/:subId` | `subs.<sub>.delete.basic` |
1908
+
1909
+ Their root counterparts select `root`; both `subUpdate` and `subBulkUpdate` use
1910
+ `subs.<sub>.update.root`. An `advanced` member does not create an unpaired endpoint.
2136
1911
 
2137
1912
  ### Variant and base fallback
2138
1913
 
2139
- 1. Read the exact variant from the owning runtime (model lookup includes the
2140
- runtime's exact model-default path).
2141
- 2. Only if that value is `undefined`, use the existing base operation resolution:
2142
- exact base rule → `operationAccess.default` → scalar `operationAccess` shorthand.
2143
- If no valid guard resolves, deny.
1914
+ 1. Select the exact operation context member, e.g. `read.advanced`. Model lookup
1915
+ checks the model, then its owning runtime's same exact model-default path.
1916
+ 2. Only if undefined, select the operation's scalar rule or its object's `default`.
1917
+ 3. If still undefined, use outer `operationAccess.default` or scalar shorthand.
1918
+ 4. With no applicable valid guard, deny. An empty top-level operation object can
1919
+ use the outer fallback; malformed defined JavaScript values deny without fallback.
2144
1920
 
2145
1921
  The selected variant **replaces** the base guard; the two are not combined or both
2146
1922
  evaluated. Explicit false, an empty array, or a guard returning false is terminal.
2147
1923
  Omitted and explicit undefined variants inherit. With no runtime-default variants
2148
1924
  or other fallback configured:
2149
1925
 
2150
- | Rules | Basic list | Advanced list | Root list entry |
2151
- | ---------------------------------- | ---------- | ------------- | --------------- |
2152
- | `list: true` | allowed | allowed | allowed |
2153
- | `list: false` | denied | denied | denied |
2154
- | `list: true, basicList: false` | denied | allowed | allowed |
2155
- | `list: true, advancedList: false` | allowed | denied | allowed |
2156
- | `list: false, basicList: true` | allowed | denied | denied |
2157
- | only `basicList: true` | allowed | denied | denied |
2158
- | `list: true, basicList: undefined` | allowed | allowed | allowed |
1926
+ | Rules | Basic list | Advanced list | Root list entry |
1927
+ | ------------------------------------------- | ---------- | ------------- | --------------- |
1928
+ | `list: true` | allowed | allowed | allowed |
1929
+ | `list: false` | denied | denied | denied |
1930
+ | `list: { default: true, basic: false }` | denied | allowed | allowed |
1931
+ | `list: { default: true, advanced: false }` | allowed | denied | allowed |
1932
+ | `list: { default: false, basic: true }` | allowed | denied | denied |
1933
+ | `list: { basic: true }` | allowed | denied | denied |
1934
+ | `list: { default: true, basic: undefined }` | allowed | allowed | allowed |
1935
+ | `list: { default: false, root: true }` | denied | denied | allowed |
1936
+ | `list: { default: true, root: false }` | allowed | allowed | denied |
2159
1937
 
2160
1938
  All rule values use `Validation`: `boolean | string | string[] | GuardHook`.
2161
1939
  Space-separated permission strings AND their names; arrays OR their entries.
@@ -2181,12 +1959,12 @@ acl.setGlobalOptions({
2181
1959
  });
2182
1960
  const permissionBased = {
2183
1961
  operationAccess: {
2184
- list: true,
2185
- read: true,
2186
- advancedList: 'isAdmin',
2187
- advancedRead: ['canReadDetails', 'isAdmin'],
2188
- advancedUpdate: async function (permissions) {
2189
- return permissions.has('isAdmin') && this.headers['x-write-mode'] === 'advanced';
1962
+ list: { default: true, advanced: 'isAdmin' },
1963
+ read: { default: true, advanced: ['canReadDetails', 'isAdmin'], root: false },
1964
+ update: {
1965
+ advanced: async function (permissions) {
1966
+ return permissions.has('isAdmin') && this.headers['x-write-mode'] === 'advanced';
1967
+ },
2190
1968
  },
2191
1969
  },
2192
1970
  permissionSchema: { name: { list: true, read: true } },
@@ -2205,26 +1983,28 @@ import acl, { type ModelRouterOptions } from '@web-ts-toolkit/access-router';
2205
1983
 
2206
1984
  const shorthand = { operationAccess: 'canUseApi' } satisfies ModelRouterOptions;
2207
1985
  const withDefault = {
2208
- operationAccess: { default: 'canUseApi', list: true, basicRead: false },
1986
+ operationAccess: { default: 'canUseApi', list: true, read: { basic: false } },
2209
1987
  } satisfies ModelRouterOptions;
2210
1988
 
2211
1989
  acl.setDefaultModelOptions({ operationAccess: { list: true, read: true } });
2212
- acl.setDefaultModelOption('operationAccess.advancedRead', 'isAdmin');
2213
- const defaultRead = acl.getDefaultModelOption('operationAccess.advancedRead');
1990
+ acl.setDefaultModelOption('operationAccess.read', { default: true, advanced: 'isAdmin' });
1991
+ const defaultRead = acl.getDefaultModelOption('operationAccess.read.advanced');
2214
1992
  const defaultsSnapshot = acl.getDefaultModelOptions();
2215
1993
  ```
2216
1994
 
2217
1995
  Model options use shallow assignment. Supplying an `operationAccess` object
2218
1996
  replaces that stored object rather than recursively merging default siblings.
2219
- Exact variant lookup separately falls back to the runtime's **same exact path**:
2220
- a runtime-default `advancedRead` can therefore outrank a model's `read`, `default`,
2221
- or scalar shorthand unless the model defines its own `advancedRead`.
2222
-
2223
- Defaults copied into a model's stored options stay there until updated. Changing
2224
- runtime defaults does not broadcast replacements to existing model values;
2225
- setting a stored variant to undefined can expose a live runtime-default variant
2226
- before base fallback. `getDefaultModelOption` reads the requested path exactly;
2227
- it does not resolve variant/base aliases or `operationAccess.default`.
1997
+ Exact context lookup separately falls back to the runtime's **same exact path**:
1998
+ a runtime-default `read.advanced` can outrank a model's scalar `read` or
1999
+ `read.default` unless the model defines its own `read.advanced`. This does not
2000
+ recursively merge defaults: model `read: {}` never independently inherits a runtime
2001
+ `read.default`. A whole operation inherited through existing base lookup can supply
2002
+ its own default. Clearing a context member can expose the live exact runtime default.
2003
+
2004
+ Omitted model `operationAccess` inherits configured model defaults; without grants,
2005
+ the built-in model policy denies. Explicit whole-model `operationAccess: undefined`
2006
+ permits runtime exact-operation fallback, but not a runtime bare/outer `.default`
2007
+ catch-all. `getDefaultModelOption` reads the requested path exactly, not an entry decision.
2228
2008
  `getDefaultModelOptions()` returns a frozen snapshot. Data routers use only their
2229
2009
  own options and never inherit model defaults.
2230
2010
 
@@ -2232,16 +2012,15 @@ own options and never inherit model defaults.
2232
2012
 
2233
2013
  For a basic list of `comments`, resolve:
2234
2014
 
2235
- 1. Exact `subs.comments.basicList`.
2236
- 2. Exact `subs.comments.list`.
2237
- 3. Defined `subs.comments`: evaluate a scalar guard; an object without the
2238
- applicable key **denies**, even if top-level list/variants allow.
2239
- 4. Only for an absent field rule, top-level exact `basicList`.
2240
- 5. Existing top-level base `list` fallback.
2015
+ 1. Exact `subs.comments.list.basic`, including the same-owner exact runtime default.
2016
+ 2. The field operation's scalar rule or nested `list.default`.
2017
+ 3. A field scalar supplies its operation fallback. A defined field object with no
2018
+ applicable operation/default **denies**, even if top-level list/outer default allow.
2019
+ 4. Only for an absent field rule, use the corresponding top-level operation/context.
2241
2020
 
2242
- The same ordering applies to advanced list and both read variants. No nested
2243
- `.default` fallback is introduced. Exact field lookups retain model-default
2244
- specificity; an inherited defined field also stays closed. The legacy scalar `subs` umbrella is still
2021
+ The same ordering applies to advanced/root and all field operations. Exact runtime
2022
+ specificity precedes scalar fallback. Empty field operation objects stay closed;
2023
+ `subs.comments.default` is not a field wildcard. The legacy scalar `subs` umbrella is still
2245
2024
  accepted, but **does not guard absent fields**; their fallback bypasses it and
2246
2025
  uses top-level rules. Use explicit per-field rules to guard a field.
2247
2026
 
@@ -2255,7 +2034,7 @@ const subdocumentRules = {
2255
2034
  list: true,
2256
2035
  read: true,
2257
2036
  subs: {
2258
- comments: { list: true, read: true, basicList: false, advancedRead: 'isAdmin' },
2037
+ comments: { list: { default: true, basic: false }, read: { default: true, advanced: 'isAdmin', root: false } },
2259
2038
  // Closed object: both items list routes are denied despite top-level list: true.
2260
2039
  items: { read: true },
2261
2040
  attachments: 'isAdmin',
@@ -2276,36 +2055,36 @@ import acl from '@web-ts-toolkit/access-router';
2276
2055
  // User must already be registered with this runtime.
2277
2056
  const router = acl.createRouter('User', {
2278
2057
  basePath: '/users',
2279
- operationAccess: { list: true, read: true },
2058
+ operationAccess: { list: { default: true }, read: { default: true } },
2280
2059
  permissionSchema: { name: true },
2281
2060
  });
2282
2061
 
2283
- router.operationAccess('basicRead', false); // Update one key, keep list/read rules.
2284
- router.operationAccess('subs.comments.basicRead', false);
2285
- router.set('operationAccess.advancedList', 'isAdmin');
2286
- router.setOption('operationAccess.basicRead', undefined); // Restore inheritance.
2287
- acl.setModelOption('User', 'operationAccess.basicRead', false);
2062
+ router.operationAccess('read.basic', false); // Update one member, keep list/read defaults.
2063
+ router.operationAccess('subs.comments.read.basic', false);
2064
+ router.set('operationAccess.list.advanced', 'isAdmin');
2065
+ router.setOption('operationAccess.read.basic', undefined); // Restore fallback.
2066
+ acl.setModelOption('User', 'operationAccess.read.root', false);
2288
2067
 
2289
2068
  // All object forms replace the whole operationAccess object, not a deep merge.
2290
- router.operationAccess({ list: true, read: true, basicRead: false });
2291
- router.setOptions({ operationAccess: { list: true, read: true, advancedList: false } });
2069
+ router.operationAccess({ list: true, read: { default: true, basic: false } });
2070
+ router.setOptions({ operationAccess: { list: { default: true, advanced: false }, read: true } });
2292
2071
 
2293
2072
  const current = router.runtime.getModelOptions('User');
2294
- const exactVariant = router.runtime.getExactModelOption('User', 'operationAccess.basicRead');
2073
+ const exactVariant = router.runtime.getExactModelOption('User', 'operationAccess.read.basic');
2295
2074
  ```
2296
2075
 
2297
2076
  `set({ operationAccess: ... })` and `setOption('operationAccess', ...)` have the
2298
2077
  same shallow replacement semantics. Dotted paths are setter arguments, not flat
2299
2078
  properties in constructor options. Updating a nested path under a scalar shorthand
2300
2079
  starts an object; retain a `default` rule if you want the prior broad fallback.
2301
- Use `set`/`setOption` with undefined to clear a variant; the two-argument property
2302
- helper is intended for defined values.
2080
+ Use any two-argument member setter with undefined to clear that member. Whole-operation
2081
+ setters accept a scalar or a rule object, e.g. `operationAccess('read', { default: true, root: false })`.
2303
2082
 
2304
2083
  `router.options` is the frozen **construction-time** snapshot. Options getter
2305
2084
  results are also frozen snapshots; data native-valued properties return detached copies
2306
2085
  on access as described above. Fetch again for current stored values. Ordinary
2307
2086
  `getModelOption`/`getDataOption` use generic nested-option fallback, not the
2308
- route-specific variant-to-base resolver. Exact getters inspect the variant path
2087
+ final nested operation-entry resolver and can return a raw operation object. Exact getters inspect a member path
2309
2088
  (including exact model-default fallback). Request guards read live runtime values.
2310
2089
  Data router setters use the same forms; its owning runtime provides
2311
2090
  `setDataOption`, `getDataOptions`, and `getExactDataOption`.
@@ -2316,22 +2095,26 @@ Data router setters use the same forms; its owning runtime provides
2316
2095
  checks retain base accesses. A variant grant does not grant fields or bypass
2317
2096
  target authorization.
2318
2097
  - Model `_read`/`_readFilter` misses with `tryList: true` still require **base
2319
- `list`** to retry. `list: false, advancedList: true` cannot grant retry;
2320
- `list: true, basicList: false` cannot block it. Forbidden/BadRequest never retry.
2321
- - Upsert keeps its create/update branch policy; authorizing `advancedUpsert` does
2322
- not also require `advancedCreate` or `advancedUpdate`.
2098
+ `list` scalar/default** to retry. `list: { default: false, advanced: true }` cannot grant retry;
2099
+ `list: { default: true, basic: false }` cannot block it. Forbidden/BadRequest never retry.
2100
+ - Upsert keeps its create/update branch policy; authorizing `upsert.advanced` does
2101
+ not also require `create.advanced` or `update.advanced`.
2323
2102
  - Subdocument mutation-response visibility uses base parent/subdocument read/list
2324
2103
  checks. Disabling basic reads does not hide otherwise readable output. Base
2325
2104
  response denial can still yield a successful null/empty response after a write
2326
2105
  (see [Subdocument writes with hidden responses](#subdocument-writes-with-hidden-responses)).
2327
- - Root batches use existing operation names and target base entry checks, with
2328
- entry 401 inside the HTTP 200 batch envelope. Variants are not new root `op`
2106
+ - Root batches use existing operation names and target `root` entry checks, with
2107
+ entry 401 inside the HTTP 200 batch envelope. Context members are not new root `op`
2329
2108
  values. Direct service calls remain trusted application calls with their
2330
- existing checks; they do not infer basic/advanced access from `req.method`.
2109
+ existing checks; they do not infer entry context from `req.method` or gain blanket entry guards.
2110
+ - Existing populate/include/private-dependency checks use operation scalar/default
2111
+ when target flags require admission. A target `{ default: false, root: true }`
2112
+ grants root entry only, not context-free related admission. Flags and trusted-service
2113
+ bypasses remain unchanged; secondary checks never implicitly choose transport members.
2331
2114
 
2332
2115
  **Populate selectors:** wire `options.populateAccess` and descriptor `access`
2333
2116
  accept only `'list' | 'read'` (`PopulateAccess` from `/advanced`). The shared Core
2334
- populate boundary also rejects all fourteen reserved variant names in effective
2117
+ populate boundary also rejects retired flat names and reserved nested context-member paths in effective
2335
2118
  option/descriptor access, including generic options forwarded by legacy includes
2336
2119
  and subqueries, before target persistence. Other trusted, non-reserved custom
2337
2120
  access strings keep their existing runtime behavior. Invalid selectors return
@@ -2341,7 +2124,7 @@ omitting it, so nested invalid selectors cannot disappear from the result.
2341
2124
 
2342
2125
  ### Runnable data-router split
2343
2126
 
2344
- This database-free example exercises the same four data keys after installation:
2127
+ This database-free example exercises nested data read members after installation:
2345
2128
 
2346
2129
  <!-- doc-example: complete-runtime -->
2347
2130
 
@@ -2356,7 +2139,7 @@ const router = runtime.createDataRouter('VariantFruit', {
2356
2139
  idParam: 'id',
2357
2140
  idField: 'id',
2358
2141
  data: [{ id: 'apple', name: 'Apple' }],
2359
- operationAccess: { list: true, read: true, basicRead: false },
2142
+ operationAccess: { list: true, read: { default: true, basic: false } },
2360
2143
  permissionSchema: { id: true, name: true },
2361
2144
  });
2362
2145
  const app = express();
@@ -2377,7 +2160,7 @@ try {
2377
2160
  if (basic.status !== 401 || advanced.status !== 200) throw new Error('Read split failed');
2378
2161
  const fruit = await advanced.json();
2379
2162
  if (fruit.name !== 'Apple') throw new Error('Expected the authorized fruit');
2380
- router.operationAccess('basicRead', true);
2163
+ router.operationAccess('read.basic', true);
2381
2164
  if ((await fetch(`${url}/apple`)).status !== 200) throw new Error('Live update failed');
2382
2165
  } finally {
2383
2166
  await new Promise<void>((resolve, reject) => {
@@ -2404,8 +2187,13 @@ Two router options lock down permission metadata regardless of client input or
2404
2187
  per-operation `defaults`: `stripPermissionsField: true` removes the whole
2405
2188
  permissions field from outputs (equivalent to `includePermissions: false` with
2406
2189
  the field — including its placeholder — deleted; enforcement still runs), and
2407
- `disableFieldPermissions: true` never computes `_view`/`_edit` maps while still
2408
- honoring `includePermissions` for `docPermissions`-hook keys.
2190
+ `disableFieldPermissions: true` (the default) neither computes nor emits
2191
+ `_view`/`_edit` maps (including placeholders) while still honoring `includePermissions` for
2192
+ `docPermissions`-hook keys. When no keys are included, the permissions field is
2193
+ an empty object; use `stripPermissionsField: true` to remove it entirely. This
2194
+ applies to regular model routes, root batch items, and direct service calls. Set
2195
+ `disableFieldPermissions: false` on the model or runtime model defaults to opt in
2196
+ to field maps; `includeFieldPermissions` then controls whether they are requested.
2409
2197
 
2410
2198
  ## Main Exports
2411
2199
 
@@ -2421,11 +2209,11 @@ Root entrypoint (`@web-ts-toolkit/access-router`):
2421
2209
  - `permissionsPlugin` — optional Mongoose metadata alias; [role and usage](#optional-permissions-plugin)
2422
2210
  - logger helpers: `redactFilter`, `redactPayload`, `safeStringify`, `isLevelEnabled` + `OpLogContext` type
2423
2211
  - option helpers: `setGlobalOptions`, `setGlobalOption`, `getGlobalOptions`, `getGlobalOption`, `setModelOptions`, `setModelOption`, `getModelOptions`, `getModelOption`, `getModelNames`, `getModelJsonSchema`, `setDefaultModelOptions`, `setDefaultModelOption`, `getDefaultModelOptions`, `getDefaultModelOption`
2424
- - route-policy types: `OperationAccess`, `SubOperationAccess`, `Validation`, `GuardHook`, `RouteVariantAccess`, `ModelRouterOptions`, `DefaultModelRouterOptions`, `DataRouterOptions`, `ExtendedModelRouterOptions`, `ExtendedDefaultModelRouterOptions`, and `ExtendedDataRouterOptions` for typed setters; `PermissionSchema` / `FieldOperationAccess` are separate base-operation field grants. These types are also available from `/advanced`.
2212
+ - route-policy types: `OperationAccess`, `SubOperationAccess`, `OperationAccessContext`, `OperationAccessVariants`, `OperationAccessRule`, `OperationAccessPaths`, `OperationAccessSetter`, `Validation`, `GuardHook`, `ModelRouterOptions`, `DefaultModelRouterOptions`, `DataRouterOptions`, `ExtendedModelRouterOptions`, `ExtendedDefaultModelRouterOptions`, and `ExtendedDataRouterOptions` for typed setters; `PermissionSchema` / `FieldOperationAccess` are separate base-operation field grants. These types are also available from `/advanced`.
2425
2213
  - fetch configuration types (also `/advanced`): `HydrationMode`, `ModelHydrationOptions` — server-owned model/default configuration, never per-call/wire options.
2426
2214
  - virtual types (also `/advanced`): `ModelVirtualGetter`, `ModelVirtualDescriptor`, `ModelVirtualAccessRecord`, `ModelVirtualLeaf`, `ModelVirtuals`, `ModelVirtualDoc`, `ModelVirtualContext`, `ModelVirtualPopulateDependency`, `ModelVirtualPopulateInputs`. Explicit private target maps type only the fourth getter argument; see [Private populated dependencies](#private-populated-dependencies).
2427
2215
  - trusted service policy types (also `/advanced`): `ServiceAuthorization` (reads), `MutationAuthorization` (update/upsert), `CreateAuthorization`, `InputFieldAuthorization`, `InputFieldPath`, `OutputAuthorization`, `FieldAuthorization`, `RowAuthorization`, `OperationAuthorization`, `RelatedAuthorization`, `OutputFieldPath`. Input paths use persisted types only; output paths also include virtuals. Unknown models have an explicit runtime-validated string fallback; grant arrays may be readonly.
2428
- - named helper/result types (also `/advanced`): `OutputPlanningOptions`, `OutputFieldOptions`, `AllowedOutputFieldOptions`, opaque `DocumentAuthorization`, `ServiceOutputContext`, `ServiceOutputDecorator`, `AuthorizedSingleResult`, `AuthorizedListResult`, `NewArgs`, `NewOptions`. Acquire the service from a router/request; there is no standalone `Service` export or public issuer/execution/prepared API.
2216
+ - named helper/result types (also `/advanced`): `OutputPlanningOptions`, `OutputFieldOptions`, `AllowedOutputFieldOptions`, `DocumentGrants`, `FieldPermissionHook`, `AuthorizationMode`, `ModelOutputContext`, `ModelOutputHook`, `ModelOutputListHook`, `ServiceOutputContext`, `ServiceOutputDecorator`, `AuthorizedSingleResult`, `AuthorizedListResult`, `NewArgs`, `NewOptions`. Acquire the service from a router/request; there is no standalone `Service` export or public issuer/execution/prepared API.
2429
2217
 
2430
2218
  Subpath entrypoints:
2431
2219
 
@@ -2737,9 +2525,11 @@ Include output is tracked separately from the original projected source. Documen
2737
2525
  permission hooks and virtual dependencies see the source values even when a successful
2738
2526
  attachment replaces the same business field (for example, `restricted`). Only results
2739
2527
  actually produced by include execution are attached after source selection and field
2740
- filtering, with the target's own authorization and document handle. A legacy read miss
2741
- or omitted result never turns an existing source value into an attachment: that field
2742
- still requires source selection and permission. Correlated empty results remain explicit
2528
+ filtering using the target's own captured policy, facts and output filtering during
2529
+ private in-flight construction. Attached results are ordinary DTO data, not reusable
2530
+ target authority. A legacy read miss or omitted result never turns an existing source
2531
+ value into an attachment: that field still requires source selection and permission.
2532
+ Correlated empty results remain explicit
2743
2533
  `null`/`[]`/`0` attachments. This separation also applies to nested targets and each list
2744
2534
  row; include output does not mutate fetched persistence documents.
2745
2535
 
@@ -3511,7 +3301,7 @@ view for every getter. Automatically fetched private-only refs are not added the
3511
3301
  an existing local `dependsOn` on that ref keeps its ordinary behavior. Each getter
3512
3302
  sees only its own resolved declarations and target selections in argument four.
3513
3303
  Private maps/raw targets are not implicitly attached to response DTOs, contexts,
3514
- lifecycle snapshots, public permission hooks/metadata, document handles, or ordinary
3304
+ lifecycle snapshots, public permission hooks/metadata, or ordinary
3515
3305
  decorate/decorateAll/task inputs. **Only an authorized getter's deliberate return
3516
3306
  becomes computed output**; this is not a prohibition on returning derived values.
3517
3307
 
@@ -3555,7 +3345,7 @@ missing target IDs, order, duplicates, nulls, empty arrays and own absence. Stri
3555
3345
  private operation denial, private row/query failure, getter omission/failure and deferred
3556
3346
  virtual authorization denial cannot hide permitted IDs. Public list/custom population
3557
3347
  and scoped backend operation grants retain their own admission and target-owned output
3558
- authority. Cleanup runs before output copying/handles and presentation hooks/tasks.
3348
+ authority. Cleanup runs before output publication and presentation hooks/tasks.
3559
3349
 
3560
3350
  #### Supported declarations and validation
3561
3351
 
@@ -3674,6 +3464,31 @@ deny the **source field** instead. Private inputs remain isolated fourth argumen
3674
3464
  and registration, row, static-ref and hydration limitations remain mandatory. Plan this
3675
3465
  as a breaking application upgrade; no release/version automation is changed here.
3676
3466
 
3467
+ ### Model-condition guards
3468
+
3469
+ `guard({ modelName, id, condition })` requires a visible row and fresh document facts
3470
+ from the current actor. It uses the normal public by-ID defaults, query/projection,
3471
+ hydration and hook-source preparation, but **publishes no DTO**. Conditions use global
3472
+ permissions OR literal-true facts with the existing string/array grammar, not metadata.
3473
+
3474
+ Guards do not run output-field callbacks, virtuals, embedded/populated-target DTO
3475
+ finalizers, output-only include attachments, metadata, decoration/tasks or `_read`
3476
+ overrides. Errors/effects solely in that work no longer veto a guard; ordinary DTO
3477
+ reads still perform it. Source/fact/necessary-dependency structural errors remain 400;
3478
+ ordinary missing/denied conditions remain 401. Descriptor preflight and any necessary
3479
+ target-input queries retain target-local admission and private-input masks.
3480
+
3481
+ A visible-row guard normally performs one root read/hook and zero output callbacks.
3482
+ An admitted miss may retry once under captured LIST admission and initiating READ
3483
+ mode; a true/false condition and 400/403 are terminal. Like direct request-only `_read`,
3484
+ this is not the generated HTTP READ-route operation gate. Compose that existing
3485
+ route/global check when needed; generated routes retain their operation admission.
3486
+
3487
+ Put security in operation/row/fact hooks, not output side effects. If a caller needs
3488
+ a DTO or business effects, perform a separate ordinary authorized read, check success
3489
+ and handle errors at its explicit additional read/hook/output cost. See the shipped
3490
+ [guard migration](MIGRATION.md#model-conditions-are-facts-only-not-an-implicit-dto-read).
3491
+
3677
3492
  ### Hook admission and reentrant service calls
3678
3493
 
3679
3494
  `requestComplexity.maxHookConcurrency` (default `10`) limits **independently
@@ -3681,7 +3496,7 @@ admitted hook chains per request/runtime**. Independent services, root-batch
3681
3496
  entries, legacy/correlated includes, populate and embedded/subdocument outputs
3682
3497
  share one private pool. It covers:
3683
3498
 
3684
- - Model `docPermissions`, including pre-write, output-helper and owning-parent stages;
3499
+ - Model `docPermissions`, including pre-write and owning-parent stages (raw output helpers never invoke it);
3685
3500
  - Virtual getters;
3686
3501
  - Model/data `decorate` and `decorateAll` chains and service output decorator callbacks;
3687
3502
  - Data request-field selection/trimming stages (their field rules run sequentially).