@web-ts-toolkit/access-router 0.60.0 → 0.62.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
@@ -21,6 +21,7 @@ ACL-aware Express routers and in-memory data services for Mongoose-backed APIs.
21
21
 
22
22
  **Migration:** [Removed overrides](#breaking-release-service-overrides-migration) ·
23
23
  [Server-owned hydration](#breaking-release-server-owned-hydration) ·
24
+ [Target-owned populate flags](#breaking-release-populate-policy-migration) ·
24
25
  [Named helpers](#breaking-release-named-helpers-and-default-behavior) ·
25
26
  [Distinct values](#distinct-whole-value-request-authorization) ·
26
27
  [Numeric grouped counts](#numeric-grouped-count-service-api-breaking-migration) ·
@@ -126,9 +127,9 @@ package-managed execution, falling back to `defaultRuntime` outside it.
126
127
 
127
128
  | Layer / public type | Where to put it | Scope and examples |
128
129
  | ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
129
- | Runtime/global — `GlobalOptions` | `api.setGlobalOptions({...})`, `api.setGlobalOption(key, value)`; `api.set` is an alias for these forms | That runtime's request grants (`globalPermissions`, `requestPermissionField`), logger, registered-populate/private-input read policy and `requestComplexity`. |
130
- | Model defaults — `DefaultModelRouterOptions` | `api.setDefaultModelOptions({...})`, `api.setDefaultModelOption(path, value)` | Shared model starting values such as `listHardLimit`, IDs, route segments, `operationAccess`, `hydration` and metadata posture. Data/root routers do not inherit them. |
131
- | Model router — `ModelRouterOptions<Model, Virtuals>` | `api.createRouter(Model, {...})`, then `router.setOptions`, `router.setOption` / `router.set` | One registered model's guards, `permissionSchema`, hooks, virtuals, request schemas, `hydration` and method defaults. Routers for the same model/runtime share its stored options. |
130
+ | Runtime/global — `GlobalOptions` | `api.setGlobalOptions({...})`, `api.setGlobalOption(key, value)`; `api.set` is an alias for these forms | That runtime's request grants (`globalPermissions`, `requestPermissionField`), logger and `requestComplexity`. |
131
+ | Model defaults — `DefaultModelRouterOptions` | `api.setDefaultModelOptions({...})`, `api.setDefaultModelOption(path, value)` | Inherited values such as IDs, `operationAccess`, `hydration`, metadata posture and the two populate operation flags. Data/root routers do not inherit them. |
132
+ | Model router — `ModelRouterOptions<Model, Virtuals>` | `api.setModelOptions(name, {...})`, `api.createRouter(Model, {...})`, then router setters | One registered model's guards, `permissionSchema`, hooks, virtuals, `hydration`, method defaults and target-owned populate flags. Routers for the same model/runtime share stored options. |
132
133
  | Data router — `DataRouterOptions<Data>` | `api.createDataRouter(name, {...})`, its setters, or `api.runtime.setDataOptions` / `setDataOption` | Owned in-memory `data`, list/read guards, request-only fields/filters and decorators. No model `defaults` or model authorization policy. Set `idParam` and `idField` explicitly for data identifier routes. |
133
134
  | Root router — `RootRouterOptions` | Single-argument `api.createRouter({ basePath, operationAccess, ... })` | The batch endpoint's scalar guard and batch/order/whole-operation limits; each target keeps its own policy. |
134
135
  | Per-method defaults — `Defaults<Model>` from `/advanced` | `ModelRouterOptions.defaults`, e.g. `defaults.publicListArgs` or `defaults.findOptions` | Query/presentation defaults for the **named method**, not hydration, global settings or trusted authority. Public wrappers and internal methods have separate buckets. |
@@ -140,9 +141,10 @@ package-managed execution, falling back to `defaultRuntime` outside it.
140
141
  1. **Assignment is shallow.** Object setters replace each supplied top-level value
141
142
  and keep other top-level keys. `setOptions({ operationAccess: { read: true } })`
142
143
  replaces the whole stored guard object; it does not merge its old siblings.
143
- Model option assignment is `{ ...runtimeModelDefaults, ...storedModelOptions,
144
- ...suppliedOptions }`. Changing runtime defaults does not broadcast over values
145
- already stored on a model. Data assignment has no model-default layer.
144
+ Unspecified model options inherit live runtime model defaults; supplied model values
145
+ are explicit overrides. The **two populate operation flags** resolve target override →
146
+ captured runtime model default → true. Explicit `undefined` restores inheritance;
147
+ omission retains an override. Data assignment has no model-default layer.
146
148
  2. **Dotted setters update one path copy-on-write.** Use
147
149
  `router.setOption('operationAccess.basicRead', false)` to keep sibling rules,
148
150
  or pass `undefined` to restore lookup fallback. Property helpers such as
@@ -203,13 +205,32 @@ const options = {
203
205
  ```
204
206
 
205
207
  `router.options` is a frozen **construction-time snapshot**. Runtime option getters
206
- return frozen stored snapshots; read them again for current values. Ordinary plain
208
+ return frozen effective snapshots; read them again for current values. Ordinary plain
207
209
  option containers are copied/frozen; hook functions, Mongoose models and other
208
210
  non-plain handles keep their identities, and the logger is retained by reference.
209
211
  Data has the stronger
210
212
  [data-specific ownership contract](#in-memory-data-ownership), including detached
211
213
  native-valued getter copies.
212
214
 
215
+ Model options inherit `setDefaultModelOptions()` values unless explicitly overridden.
216
+ Later default changes apply to unspecified model options for new work, including on
217
+ already-created models. Explicit `false`, `null`, empty arrays and empty objects win;
218
+ model `undefined` restores inheritance. Nested objects replace shallowly. For example,
219
+ model `hydration: { find: 'lean' }` replaces the default hydration object rather than
220
+ inheriting its other method keys. Default changes are validated before publication.
221
+ Authorization exception: explicitly setting model `operationAccess: undefined`
222
+ retains its existing **exact-key-only** runtime-default fallback; it does not inherit
223
+ a runtime bare or `.default` catch-all guard. An omitted model `operationAccess`
224
+ inherits normally. Existing route guard specificity rules otherwise remain unchanged.
225
+
226
+ For populate flags, `getModelOptions()` and `router.options` retain raw overrides:
227
+ an unset value can be `undefined`. `getModelOption()` resolves the live default, and
228
+ an old `router.options` never becomes a live effective-policy view.
229
+ Operations resolve the strict pair separately, capturing runtime flag defaults before
230
+ source/target option reads and the first await. Each target combines those defaults
231
+ with its own captured options. In-flight nested/include/embedded/dedicated-child
232
+ stages retain that capture; later top-level calls on the same service refresh it.
233
+
213
234
  Route guards and request-schema lookups read live policy. A retained model service
214
235
  reads its originating runtime's current presentation options/defaults on each call;
215
236
  model authorization calls capture
@@ -239,16 +260,20 @@ behavior rather than route shape.
239
260
 
240
261
  ### Temporary unsafe read/list-performance switches
241
262
 
242
- **Both default to off (snapshot checks enabled).** These independent server-only
243
- settings temporarily skip repeated source snapshot comparisons on one registered model:
263
+ **All default to off (snapshot checks enabled).** Six independent server-only
264
+ settings temporarily skip specific comparisons on one registered model:
244
265
 
245
- | Flag | Applies to |
246
- | -------------------------------------- | -------------------------------------------------------------------------------------------------------------- |
247
- | `unsafeSkipListDocumentSnapshotChecks` | Top-level `find`, generated public lists and root-list responses |
248
- | `unsafeSkipReadDocumentSnapshotChecks` | Top-level `findOne`, `findById`, public identifier/filter reads and root reads, including read-to-list retries |
266
+ | LIST flag | READ flag | Comparisons skipped |
267
+ | -------------------------------------------- | -------------------------------------------- | --------------------------------------------------------------------------------- |
268
+ | `unsafeSkipListDocumentSnapshotChecks` | `unsafeSkipReadDocumentSnapshotChecks` | Repeated source comparisons for the top-level document stage |
269
+ | `unsafeSkipListOutputSnapshotChecks` | `unsafeSkipReadOutputSnapshotChecks` | Output-value comparisons for the root and its embedded/populated/included outputs |
270
+ | `unsafeSkipListNestedDocumentSnapshotChecks` | `unsafeSkipReadNestedDocumentSnapshotChecks` | Repeated source comparisons for embedded/populated/included document stages |
249
271
 
250
- A read-to-list retry follows the **read flag**, because the initiating operation
251
- is still a single read. Changing one flag does not change the other.
272
+ LIST means top-level `find`, generated public lists and root-list entries. READ
273
+ means `findOne`, `findById`, public identifier/filter reads and root-read entries.
274
+ A read-to-list retry follows the **read flags**, because the initiating operation
275
+ is still a single read, even when its effective field access is `list`. Changing
276
+ one flag does not change any other flag.
252
277
 
253
278
  <!-- doc-example: partial -->
254
279
 
@@ -259,38 +284,136 @@ import acl from '@web-ts-toolkit/access-router';
259
284
  // TODO: revisit/remove this temporary workaround after query-performance remediation.
260
285
  acl.setModelOptions('User', {
261
286
  unsafeSkipReadDocumentSnapshotChecks: true,
262
- unsafeSkipListDocumentSnapshotChecks: false, // lists stay protected
287
+ unsafeSkipReadOutputSnapshotChecks: true,
288
+ unsafeSkipReadNestedDocumentSnapshotChecks: true,
289
+ // All three LIST flags remain false unless separately enabled.
263
290
  });
264
291
  ```
265
292
 
266
- Set either flag to `false` with `setModelOption` to roll back for new calls.
267
- Both flags can be set in `createRouter(Model, { ... })` or `setDefaultModelOptions`
268
- before model-router creation. Starting defaults do not overwrite existing models'
269
- stored settings; a per-model `false` overrides a starting default of `true`.
293
+ Set any flag to `false` with `setModelOption` to roll back for new calls.
294
+ All flags can be set in `createRouter(Model, { ... })` or `setDefaultModelOptions`.
295
+ An unspecified model flag inherits the current default, even when defaults change
296
+ after router/model setup. Explicit per-model `false` overrides default `true`;
297
+ setting a model flag to `undefined` restores inheritance. This precedence applies
298
+ to all default-model options, not only unsafe flags. Object/array options replace
299
+ shallowly rather than deep-merging. Retained call/handle snapshots do not change.
270
300
  Prefer per-model opt-in rather than enabling it for every model. Use the owning
271
301
  `createAccessRuntime()` API instead of default `acl` for an isolated runtime.
272
302
  Only literal boolean `true` enables each flag. Enabling emits a logger warning once
273
- per model/flag transition, not per row/request. Neither is a global, per-call, HTTP/root
303
+ per effective model/flag transition, including inherited enablement on an existing
304
+ model. Setting defaults before model setup warns when applied to that model, not
305
+ when the defaults alone are stored. No warning repeats per row/request. None is a global, per-call, HTTP/root
274
306
  entry, `options.authorization`, or `service.defaults` option.
275
307
 
276
- - **Skipped:** repeated comparisons of the retained projected document with its
277
- authorization snapshot on the enabled operation. List/read-origin handles and
278
- captured read-to-list retries retain their mode in later work and helper picks.
308
+ - **Independent scopes:** root-source flags do not relax descendant source checks;
309
+ nested-source flags do not relax root source or output checks; output flags do
310
+ not relax source checks. Nested flags do **not** prune child values from parent
311
+ snapshots: a still-strict parent comparison can detect child mutation.
312
+ - **Propagation:** output/nested flags use the **initiating model's captured mode**
313
+ recursively through embedded scopes, ordinary public population and includes
314
+ (including correlated includes). A target model's own flags cannot relax a
315
+ strict parent or override that captured mode. Independent service calls made
316
+ inside hooks use their own settings, not ambient parent authority.
279
317
  - **Still enforced:** row filters, document/field rules, operation gates, exact
280
- request/runtime/model/stage ownership, output-mutation/provenance checks and bounds.
281
- Initial snapshots and detached callback/grant/output copies (including native values)
282
- remain. Writes (including read-like output), dedicated subdocument operations,
283
- embedded/related stages and fresh standalone output helpers stay strict. An
284
- operation without its own opt-out stays protected.
285
- - **Risk:** source changes during callbacks or awaits will no longer invalidate
286
- cached grants/decisions. Output may be authorized using stale data even though
287
- normal permission rules run. This is a deliberate weakening of mutation protection,
288
- **not a security-equivalent fast mode**. Use only with trusted, non-mutating hooks;
289
- review your application and measure a staged rollout before production opt-in.
318
+ request/runtime/model/scope/access/stage binding, handle/output associations,
319
+ output graph identities and structural bounds on initial snapshots. Initial
320
+ source snapshots and detached callback/grant/output copies remain. Initial output
321
+ snapshots also remain unless the separate copy flags below are active. Equal
322
+ replacement objects, forged handles and unrelated rows/calls still reject;
323
+ package-created output-copy transfers still authenticate their source.
324
+ - **Strict boundaries:** writes (including read-like output), dedicated subdocument
325
+ operations and fresh standalone output helpers remain strict. Helpers using an
326
+ originating handle retain that handle's captured mode.
327
+ - **Risk:** source mutation during callbacks/awaits can leave stale grants/decisions.
328
+ Output flags additionally allow changed scalar values, in-place Date/Buffer/BSON
329
+ mutations and other value changes that graph-identity checks cannot detect to
330
+ reuse earlier decisions. This can expose incorrectly authorized output, even
331
+ though permission rules still run. This is **not a security-equivalent fast mode**.
332
+ Use only with trusted, non-mutating hooks and output consumers; review your
333
+ application and measure a staged rollout before production opt-in.
290
334
 
291
335
  Each call captures the setting before awaits. Turning it off protects new calls,
292
- not in-flight calls, retries or existing handles. These switches do not eliminate
293
- all cloning or promise v0.51.0 performance. Restore `false` as soon as possible.
336
+ not in-flight calls, later descendants of captured calls, retries or existing
337
+ handles. These switches do not eliminate all cloning or promise v0.51.0 performance.
338
+ Measure each separately on your workload; restore `false` as soon as possible.
339
+
340
+ ### Temporary unsafe initial output-snapshot copy switches
341
+
342
+ Two **additional**, default-false server model/default-model options can omit the
343
+ initial snapshot stored when finalized output is associated with its private
344
+ authorization handle. They do not change the six comparison flags above:
345
+
346
+ | Copy option | Required comparison option |
347
+ | ----------------------------------------- | ------------------------------------------ |
348
+ | `unsafeSkipListInitialOutputSnapshotCopy` | `unsafeSkipListOutputSnapshotChecks: true` |
349
+ | `unsafeSkipReadInitialOutputSnapshotCopy` | `unsafeSkipReadOutputSnapshotChecks: true` |
350
+
351
+ | Matching comparison skip | Copy skip | Effective behavior |
352
+ | ------------------------ | --------- | ---------------------------------------------------------------------------------- |
353
+ | false | false | Copy and compare output snapshots |
354
+ | true | false | Copy snapshots; skip comparisons (existing behavior) |
355
+ | false | true | Dormant: still copy and compare; warn about the prerequisite |
356
+ | true | true | Omit eligible initial output snapshots; retain structural admission and identities |
357
+
358
+ Only literal boolean `true` enables either option. They follow the same server-only
359
+ inheritance and capture rules as comparison flags: explicit model false wins, model
360
+ undefined restores inheritance, and later default updates affect new calls. Never
361
+ derive them from client input or put them in method defaults/per-call authorization.
362
+ READ-to-list retries follow READ settings. Authenticated embedded/populated/included
363
+ outputs and package-created transfers inherit the initiating model's mode; target
364
+ flags cannot override it. Writes, dedicated subdocument operations and fresh helpers
365
+ stay strict. An originating handle keeps its mode after runtime rollback.
366
+
367
+ **This removes protection, not just an allocation.** The omitted pass no longer
368
+ normalizes Date/RegExp/Buffer/BSON leaves or runs BSON wire validation/hooks. Lost
369
+ observations can change exceptions, side effects and subsequent permission outcomes,
370
+ including changing a denial into an allowance. The prerequisite already allows
371
+ scalar/native mutation to reuse stale decisions. Do not call this security-equivalent
372
+ to copying, or assume that matching benchmark output proves it safe for your app.
373
+
374
+ Eligible ordinary records/arrays retain clone-free bounded structural admission:
375
+ 20,000 visited nodes (including repeated aliases), depth 100, array length 20,000,
376
+ safe keys, data descriptors, supported containers and cycle rejection. Exact output
377
+ root/descendant identities, request/runtime/model/scope/access/stage binding and
378
+ permission evaluation remain. Standard native leaves are allowed without their copy
379
+ normalization; invalid/forged BSON leaf contents are **not** wire-validated by this
380
+ pass. Proxies, Map/Set graphs, unproven native subclasses and unsupported objects use
381
+ the original copier/identity fallback and may still reject. Accessor/proxy ownership
382
+ bindings also use that fallback; graph admission is not retained across binding
383
+ callbacks. A requested skip does
384
+ not guarantee zero copying for every graph.
385
+
386
+ Source snapshots, detached document/field callback inputs and grants, captured
387
+ configuration, getter isolation, metadata and actual output/response copies remain.
388
+ This is **not a general deep-clone opt-out**. Enable only per model with trusted,
389
+ stable data and hooks after a measured staged rollout; the remaining query costs can
390
+ still dominate and no v0.51.0 parity is promised. Warnings distinguish active copying
391
+ omission from dormant requests, occur on effective model/operation transitions and
392
+ do not repeat per row/request. Failed option publication does not activate a warning.
393
+
394
+ <!-- doc-example: partial -->
395
+
396
+ ```ts
397
+ import mongoose from 'mongoose';
398
+ import { createAccessRuntime } from '@web-ts-toolkit/access-router';
399
+
400
+ const api = createAccessRuntime();
401
+ const User = mongoose.model('InitialCopyUser', new mongoose.Schema({ name: String }));
402
+ api.registerModelInstance(User.modelName, User);
403
+ // TEMPORARY UNSAFE: separately enable only the two intended LIST settings.
404
+ api.setModelOptions(User.modelName, {
405
+ unsafeSkipListOutputSnapshotChecks: true,
406
+ unsafeSkipListInitialOutputSnapshotCopy: true,
407
+ });
408
+ // Rollback for new calls; existing handles/calls retain their captured settings.
409
+ api.setModelOption(User.modelName, 'unsafeSkipListInitialOutputSnapshotCopy', false);
410
+ api.setModelOption(User.modelName, 'unsafeSkipListOutputSnapshotChecks', false);
411
+ ```
412
+
413
+ Keep all READ, root-source and nested-source flags off unless independently selected.
414
+ Monitor authorization failures, unexpected callback/native behavior and latency/CPU;
415
+ restore false promptly and revisit/remove this temporary workaround. No release or
416
+ configuration migration automatically enables it.
294
417
 
295
418
  ### Wire placement and option names
296
419
 
@@ -396,7 +519,7 @@ export async function findThings(req: ModelRequest) {
396
519
  ```
397
520
 
398
521
  Supported writers are model construction/router setters,
399
- `api.runtime.setModelOptions` / `setModelOption`, and starting defaults through
522
+ `api.runtime.setModelOptions` / `setModelOption`, and inherited defaults through
400
523
  `api.setDefaultModelOptions` / `setDefaultModelOption` (also on `api.runtime`).
401
524
  `GlobalOptions`, data/root router options, method `defaults`, `service.defaults`
402
525
  and client defaults are not hydration scopes. Decorator applications use the same
@@ -405,16 +528,17 @@ record through `@Router`, per-model/default `@RouterOptions`, `@ModelOption` and
405
528
  for its compiling configuration example.
406
529
  No dedicated hydration decorator is needed.
407
530
 
408
- Assignment follows `{ ...runtimeStartingDefaults, ...storedModelOptions,
409
- ...incomingModelOptions }`: a supplied hydration record **replaces** the previous
410
- record, not individual members. Omitted/undefined entries use the matrix's
531
+ An unspecified model hydration record inherits current runtime model defaults.
532
+ A supplied model record **replaces** the inherited/previous record, not individual
533
+ members. Omitted/undefined entries within that record use the matrix's
411
534
  built-ins, never an older record's members or generic nested `.default` lookup.
412
535
  For example, replacing `{ publicList: 'hydrated' }` with `{ find: 'lean' }`
413
536
  restores public lists to their built-in lean mode. The five exact
414
537
  `hydration.<entry>` setters change one stored member; member `undefined` clears
415
- that override and whole-record `undefined` clears the setting. Starting-default
416
- changes do not broadcast over an existing stored record. Default providers obey
417
- the same shallow semantics and existing decorator precedence.
538
+ that member override. Whole-model-record `undefined` restores default-model
539
+ inheritance; whole-default-record `undefined` clears the default. Later default
540
+ updates apply to inherited records, but never overwrite explicit model records.
541
+ Default providers obey the same shallow semantics and existing decorator precedence.
418
542
 
419
543
  Only plain records with those five keys and mode strings (or `undefined`) are
420
544
  valid; scalars, null, arrays, unknown keys and invalid modes throw a path-bearing
@@ -2648,8 +2772,12 @@ The source ref is retained automatically; repeating it in local `dependsOn` is u
2648
2772
 
2649
2773
  #### Runtime populate operation policies
2650
2774
 
2651
- `GlobalOptions` exposes exactly two independent populate operation flags, both
2652
- defaulting to **true**. Only **literal boolean false** disables their respective gate:
2775
+ `ModelRouterOptions` and `DefaultModelRouterOptions` expose exactly two optional
2776
+ booleans, owned by the **actual target model**, both with built-in **true**.
2777
+ For `Project.documentIds → Document`, Document's Q/D pair governs the reads.
2778
+ If a Document virtual declares private User inputs, **User's D** applies; Project's
2779
+ or Document's bypass cannot relax User. Different Document/User/Report pairs can
2780
+ coexist in one runtime and request. Only **primitive boolean false** disables a gate:
2653
2781
 
2654
2782
  - `requireOperationAccessForPopulateQueries`: ordinary caller population requires
2655
2783
  the target's effective operation (`read` normally, supported `list` or trusted custom
@@ -2662,7 +2790,7 @@ defaulting to **true**. Only **literal boolean false** disables their respective
2662
2790
  virtual's own output authorization and request-mode `baseFilter.read`,
2663
2791
  `overrideFilter.read` and original IDs remain mandatory. No private read-to-list fallback.
2664
2792
 
2665
- For a registered target whose relevant public operation and base read are denied,
2793
+ For **each registered target independently**, when its relevant public operation and base read are denied,
2666
2794
  with selected/permitted source refs and otherwise eligible fields/rows:
2667
2795
 
2668
2796
  | Query flag | Dependency flag | Requested ordinary population | Authorized private virtual |
@@ -2679,34 +2807,62 @@ Neither flag grants standalone target access, fields, rows or writes.
2679
2807
  <!-- doc-example: partial -->
2680
2808
 
2681
2809
  ```ts
2682
- import { createAccessRuntime, type GlobalOptions } from '@web-ts-toolkit/access-router';
2810
+ import mongoose from 'mongoose';
2811
+ import { createAccessRuntime, type DefaultModelRouterOptions } from '@web-ts-toolkit/access-router';
2683
2812
 
2684
2813
  const api = createAccessRuntime();
2685
- api.setGlobalOptions({
2814
+ api.setDefaultModelOptions({
2686
2815
  requireOperationAccessForPopulateQueries: true,
2816
+ requireOperationAccessForPopulateDependencies: true,
2817
+ });
2818
+ const Document = mongoose.model('Document', new mongoose.Schema({ name: String }));
2819
+ const User = mongoose.model('User', new mongoose.Schema({ name: String }));
2820
+ for (const model of [Document, User]) api.registerModelInstance(model.modelName, model);
2821
+ api.setModelOptions(Document.modelName, {
2822
+ operationAccess: { read: false, list: false },
2823
+ permissionSchema: { name: true },
2824
+ requireOperationAccessForPopulateQueries: false,
2687
2825
  requireOperationAccessForPopulateDependencies: false,
2688
2826
  });
2689
- // The exact setter and api.set(key, value)/api.set(options) aliases are also typed.
2690
- api.setGlobalOption('requireOperationAccessForPopulateQueries', false);
2691
- const snapshot: GlobalOptions = api.getGlobalOptions();
2692
- const mode: boolean | undefined = api.getGlobalOption('requireOperationAccessForPopulateDependencies');
2827
+ api.setModelOptions(User.modelName, {
2828
+ operationAccess: { read: false, list: false },
2829
+ permissionSchema: {}, // explicit closed business fields
2830
+ requireOperationAccessForPopulateQueries: true,
2831
+ requireOperationAccessForPopulateDependencies: true,
2832
+ });
2833
+ // Exact setters also accept undefined to restore this target's live inheritance.
2834
+ api.setModelOption(Document.modelName, 'requireOperationAccessForPopulateDependencies', undefined);
2835
+ api.setDefaultModelOption('requireOperationAccessForPopulateDependencies', false);
2836
+ const snapshot: DefaultModelRouterOptions = api.getDefaultModelOptions();
2837
+ const mode: boolean | undefined = api.getModelOption(
2838
+ Document.modelName,
2839
+ 'requireOperationAccessForPopulateDependencies',
2840
+ );
2693
2841
  void [snapshot, mode];
2694
2842
  ```
2695
2843
 
2696
- Missing/undefined or malformed JavaScript values (`'false'`, `0`, null, objects)
2697
- use the conservative true mode; typed setters accept only boolean/undefined. An
2698
- omitted property in a shallow object setter preserves the current setting. The
2699
- flags are captured with source/target configuration and query intent **before the first
2700
- await**. Nested related/embedded/subdocument output retains that call's modes; later
2701
- calls see updates. Separate runtimes remain isolated.
2702
-
2703
- These are **server/runtime configuration**, not model defaults, service query options,
2704
- HTTP/root/client control or persisted capability. Business fields with the same
2705
- spelling keep ordinary data semantics. Actual runtime registration and an effective
2706
- object `permissionSchema` are mandatory in **all four combinations**; private targets
2707
- also require eagerly validated static declarations. `api.getGlobalOptions()` returns
2708
- a frozen snapshot; read it again to observe later setters. The named root exports
2709
- `getGlobalOptions`/`getGlobalOption` refer to the shared default runtime.
2844
+ Each flag resolves **explicit target override → captured runtime model default →
2845
+ built-in true**. Explicit `undefined` clears an override; omission keeps it. Clearing
2846
+ a runtime default falls back to true. Malformed non-undefined JavaScript values
2847
+ (`'false'`, `0`, null, objects, boxed booleans) are conservatively true; typed setters
2848
+ accept boolean/undefined. Unrelated model updates, router construction and repeated
2849
+ decorator setup keep inheritance live. Other model options also inherit live defaults,
2850
+ with shallow replacement of nested objects.
2851
+
2852
+ Valid writers are model/default bulk and exact setters, model construction and
2853
+ `router.setOptions` / `setOption` / `set`. `GlobalOptions`, `api.setGlobal*` and global
2854
+ `api.set` placements reject with migration diagnostics pointing to `setModelOptions`
2855
+ and `setDefaultModelOptions`; there is no global alias/broadcast. Service query,
2856
+ method defaults, HTTP/root/client options gain no capability. Business fields with
2857
+ these names remain legitimate filter/select/mutation data.
2858
+
2859
+ Defaults are captured once **before source/target option reads and the first await**;
2860
+ each actual target contributes its own captured options. Nested related/include/
2861
+ embedded/dedicated-child stages retain the originating pair/default capture. Later
2862
+ top-level calls on existing services observe administrative default changes when the
2863
+ target has no override. `getModelOptions()` and `router.options` retain raw flag
2864
+ overrides, not effective policy; even an unset `undefined` resolves strictly to true
2865
+ when neither layer supplies a value. Runtime isolation remains intact.
2710
2866
 
2711
2867
  There is **no additional target-base-read reference-visibility gate**. Adding a virtual
2712
2868
  does not change ordinary ref shape. Without admitted public population, selected/
@@ -2715,7 +2871,21 @@ failure or deferred virtual denial. Only parent field denial/unselection omits t
2715
2871
  Actual admitted population misses yield scalar null or filtered arrays, never restored
2716
2872
  IDs. See [reconstruction](#target-authority-selection-and-reconstruction).
2717
2873
 
2718
- Missing target configuration/schema raises a controlled service result with
2874
+ Every used target must have an actual model registered/configured in the owning
2875
+ runtime and an effective **object `permissionSchema`**, including closed `{}` or a
2876
+ schema supplied by model defaults. There is no raw passthrough in any Q/D pair.
2877
+ Static string refs resolve on the **source model's Mongoose connection** and must
2878
+ match the exact runtime-configured instance. Missing or same-named mismatched models
2879
+ fail before target I/O or initiating writes. Explicit **Model-valued schema refs**
2880
+ can cross connections when that exact target is registered/configured in the same
2881
+ runtime; the narrower private-declaration limit is described below. The validated
2882
+ model and captured target policy stay pinned together through in-flight population,
2883
+ including a later `db.models` replacement. `Populate` wire descriptors accept no
2884
+ caller-supplied `model` or authority.
2885
+ Dynamic callback/refPath refs reject with a controlled diagnostic because no static
2886
+ actual target can be bound before I/O.
2887
+
2888
+ Missing/mismatched target configuration/schema raises a controlled service result with
2719
2889
  `code: 'bad_request'` and actionable `errors[].detail` (HTTP 400); direct helpers and
2720
2890
  configuration setters throw with the same controlled `result`. Private declaration
2721
2891
  validation is eager/atomic. Ordinary required operation-hook errors propagate; bypass
@@ -2726,8 +2896,9 @@ omit the virtual with structural-only logging, preserving permitted parent IDs.
2726
2896
 
2727
2897
  Save as `private-populate-example.mts` and run with Node 22.18+ or compile with
2728
2898
  TypeScript/NodeNext. Install the package, Express and Mongoose as above. This
2729
- self-contained example creates/removes a uniquely named database, registers the
2730
- configuration-only `Document` **before** the source, and checks all four modes,
2899
+ self-contained example creates/removes a uniquely named database, registers
2900
+ configuration-only `Document` and `User` **before** the source, and checks mixed
2901
+ targets in one request, all four Document modes, live default inheritance/clearing,
2731
2902
  selection/field denial, exact IDs, population misses and standalone denial. The example
2732
2903
  tenant is server-owned; real applications derive it from their authenticated actor.
2733
2904
 
@@ -2748,13 +2919,20 @@ interface DocumentRecord {
2748
2919
  balance: number;
2749
2920
  creditLimit: number;
2750
2921
  tenantId: string;
2922
+ owner: mongoose.Types.ObjectId | null;
2923
+ }
2924
+ interface UserRecord {
2925
+ name: string;
2926
+ riskCode: number;
2751
2927
  }
2752
2928
  interface Order {
2753
2929
  total: number;
2754
2930
  account: mongoose.Types.ObjectId | null; // stays a persisted ref, not a DocumentRecord
2931
+ user: mongoose.Types.ObjectId | null;
2755
2932
  }
2756
2933
  interface OrderVirtuals {
2757
2934
  canPlaceOrder: boolean;
2935
+ knowsUser: boolean;
2758
2936
  }
2759
2937
 
2760
2938
  async function runPrivatePopulateExample() {
@@ -2767,6 +2945,22 @@ async function runPrivatePopulateExample() {
2767
2945
  try {
2768
2946
  const api = createAccessRuntime();
2769
2947
  api.setGlobalOptions({ globalPermissions: () => [] });
2948
+ api.setDefaultModelOptions({
2949
+ requireOperationAccessForPopulateQueries: true,
2950
+ requireOperationAccessForPopulateDependencies: true,
2951
+ });
2952
+ const UserModel = connection.model<UserRecord>(
2953
+ 'User',
2954
+ new mongoose.Schema<UserRecord>({ name: String, riskCode: Number }),
2955
+ );
2956
+ api.registerModelInstance(UserModel.modelName, UserModel);
2957
+ api.setModelOptions(UserModel.modelName, {
2958
+ operationAccess: { read: false, list: false },
2959
+ permissionSchema: { name: true, riskCode: false },
2960
+ requireOperationAccessForPopulateQueries: true,
2961
+ requireOperationAccessForPopulateDependencies: true,
2962
+ stripPermissionsField: true,
2963
+ });
2770
2964
  const DocumentModel = connection.model<DocumentRecord>(
2771
2965
  'Document',
2772
2966
  new mongoose.Schema<DocumentRecord>({
@@ -2774,14 +2968,27 @@ async function runPrivatePopulateExample() {
2774
2968
  balance: { type: Number, select: false },
2775
2969
  creditLimit: Number,
2776
2970
  tenantId: String,
2971
+ owner: { type: mongoose.Schema.Types.ObjectId, ref: UserModel.modelName },
2777
2972
  }),
2778
2973
  );
2779
2974
  // Both the actual model instance and its options must exist in this runtime first.
2780
2975
  api.registerModelInstance(DocumentModel.modelName, DocumentModel);
2781
- api.setModelOptions(DocumentModel.modelName, {
2976
+ let ownerCalls = 0;
2977
+ const ownerLabel: ModelVirtualDescriptor<DocumentRecord, string, { owner: UserRecord }> = {
2978
+ dependsOnPopulate: [{ path: 'owner', select: 'name -_id' }],
2979
+ get(doc, _permissions, _context, populated = {}) {
2980
+ ownerCalls++;
2981
+ assert.equal(JSON.stringify(doc).includes('riskCode'), false);
2982
+ return populated.owner?.name;
2983
+ },
2984
+ };
2985
+ api.setModelOptions<DocumentRecord, { ownerLabel: string }>(DocumentModel.modelName, {
2782
2986
  operationAccess: { read: false, list: false },
2783
2987
  baseFilter: { read: () => ({ tenantId: 'shop-a' }) },
2784
- permissionSchema: { name: true, balance: false, creditLimit: false },
2988
+ permissionSchema: { name: true, balance: false, creditLimit: false, owner: true, ownerLabel: true },
2989
+ requireOperationAccessForPopulateQueries: false,
2990
+ requireOperationAccessForPopulateDependencies: false,
2991
+ virtuals: { ownerLabel }, // This private ref is governed by User's D, not Document's.
2785
2992
  stripPermissionsField: true,
2786
2993
  });
2787
2994
  const OrderModel = connection.model<Order>(
@@ -2789,6 +2996,7 @@ async function runPrivatePopulateExample() {
2789
2996
  new mongoose.Schema<Order>({
2790
2997
  total: Number,
2791
2998
  account: { type: mongoose.Schema.Types.ObjectId, ref: DocumentModel.modelName },
2999
+ user: { type: mongoose.Schema.Types.ObjectId, ref: UserModel.modelName },
2792
3000
  }),
2793
3001
  );
2794
3002
  // Explicit target map: an ObjectId alone cannot infer its related model.
@@ -2802,20 +3010,42 @@ async function runPrivatePopulateExample() {
2802
3010
  return doc.total <= account.balance + account.creditLimit;
2803
3011
  },
2804
3012
  };
3013
+ let userCalls = 0;
3014
+ const knowsUser: ModelVirtualDescriptor<Order, boolean, { user: UserRecord }> = {
3015
+ dependsOnPopulate: [{ path: 'user', select: 'riskCode -_id' }],
3016
+ get(doc, _permissions, context, populated = {}) {
3017
+ userCalls++;
3018
+ assert.equal(Object.hasOwn(context, 'populated'), false);
3019
+ assert.equal(JSON.stringify(doc).includes('riskCode'), false);
3020
+ return populated.user?.riskCode === undefined ? undefined : populated.user.riskCode === 7;
3021
+ },
3022
+ };
2805
3023
  const orders = api.createRouter<Order, OrderVirtuals>(OrderModel, {
2806
3024
  basePath: '/orders',
2807
3025
  operationAccess: { read: true },
2808
- permissionSchema: { total: false, account: true, canPlaceOrder: true },
2809
- virtuals: { canPlaceOrder }, // assign the separately typed descriptor normally
3026
+ // Source flags never flow into either target, including targets' own virtuals.
3027
+ requireOperationAccessForPopulateQueries: false,
3028
+ requireOperationAccessForPopulateDependencies: false,
3029
+ permissionSchema: { total: false, account: true, user: true, canPlaceOrder: true, knowsUser: true },
3030
+ virtuals: { canPlaceOrder, knowsUser },
2810
3031
  stripPermissionsField: true,
2811
3032
  });
2812
- const account = await DocumentModel.create({ name: 'Main', balance: 80, creditLimit: 20, tenantId: 'shop-a' });
2813
- const order = await OrderModel.create({ total: 90, account: account._id });
3033
+ const user = await UserModel.create({ name: 'Ada', riskCode: 7 });
3034
+ const account = await DocumentModel.create({
3035
+ name: 'Main',
3036
+ balance: 80,
3037
+ creditLimit: 20,
3038
+ tenantId: 'shop-a',
3039
+ owner: user._id,
3040
+ });
3041
+ const order = await OrderModel.create({ total: 90, account: account._id, user: user._id });
2814
3042
  // Check standalone base admission without constructing target HTTP routes.
2815
3043
  orders.router.post('/verify-target', async (req, res) => {
2816
3044
  const core = (req as ModelRequest).macl;
2817
3045
  assert.equal(await core.isAllowed(DocumentModel.modelName, 'read'), false);
2818
3046
  assert.equal(await core.isAllowed(DocumentModel.modelName, 'list'), false);
3047
+ assert.equal(await core.isAllowed(UserModel.modelName, 'read'), false);
3048
+ assert.equal(await core.isAllowed(UserModel.modelName, 'list'), false);
2819
3049
  res.json({ ok: true });
2820
3050
  });
2821
3051
  const root = api.createRouter({ basePath: '/batch', operationAccess: true });
@@ -2841,7 +3071,7 @@ async function runPrivatePopulateExample() {
2841
3071
  const populate = [{ path: 'account', select: 'name balance -_id' }];
2842
3072
  for (const queries of [true, false]) {
2843
3073
  for (const dependencies of [true, false]) {
2844
- api.setGlobalOptions({
3074
+ api.setModelOptions(DocumentModel.modelName, {
2845
3075
  requireOperationAccessForPopulateQueries: queries,
2846
3076
  requireOperationAccessForPopulateDependencies: dependencies,
2847
3077
  });
@@ -2857,6 +3087,51 @@ async function runPrivatePopulateExample() {
2857
3087
  orders.permissionSchema('account', true);
2858
3088
  }
2859
3089
  }
3090
+ const mixedSelect = ['account', 'user', 'canPlaceOrder', 'knowsUser', '-_id'];
3091
+ const mixedPopulate = [
3092
+ { path: 'account', select: 'name owner ownerLabel -_id' },
3093
+ { path: 'user', select: 'name riskCode -_id' },
3094
+ ];
3095
+ // Same request/runtime: Document permits public/private work; User remains strict.
3096
+ assert.deepEqual(await read({ select: mixedSelect, populate: mixedPopulate }), {
3097
+ account: { name: 'Main', owner: String(user._id) },
3098
+ user: String(user._id),
3099
+ canPlaceOrder: true,
3100
+ });
3101
+ assert.equal(ownerCalls, 0); // Document's bypass cannot admit its private User ref.
3102
+ assert.equal(userCalls, 0); // Nor can the source's bypass admit User.
3103
+ api.setModelOption(UserModel.modelName, 'requireOperationAccessForPopulateDependencies', false);
3104
+ assert.deepEqual(await read({ select: mixedSelect, populate: mixedPopulate }), {
3105
+ account: { name: 'Main', owner: String(user._id), ownerLabel: 'Ada' },
3106
+ user: String(user._id), // User Q still true: private admission doesn't populate this ref.
3107
+ canPlaceOrder: true,
3108
+ knowsUser: true,
3109
+ });
3110
+ assert.equal(ownerCalls, 1);
3111
+ assert.equal(userCalls, 1);
3112
+ api.setModelOption(UserModel.modelName, 'requireOperationAccessForPopulateDependencies', true);
3113
+
3114
+ // Administrative model/default updates affect later calls, never caller authority.
3115
+ api.setModelOptions(DocumentModel.modelName, {
3116
+ requireOperationAccessForPopulateQueries: undefined,
3117
+ requireOperationAccessForPopulateDependencies: undefined,
3118
+ });
3119
+ const stored = api.getModelOptions(DocumentModel.modelName);
3120
+ const defaults = api.getDefaultModelOptions();
3121
+ assert.equal(stored.requireOperationAccessForPopulateQueries, undefined);
3122
+ assert.deepEqual(await read({ select, populate }), { account: String(account._id) }); // inherits true
3123
+ api.setDefaultModelOptions({
3124
+ requireOperationAccessForPopulateQueries: false,
3125
+ requireOperationAccessForPopulateDependencies: false,
3126
+ });
3127
+ api.setModelOptions(DocumentModel.modelName, { stripPermissionsField: true }); // keeps inheritance live
3128
+ assert.deepEqual(await read({ select: mixedSelect, populate: mixedPopulate }), {
3129
+ account: { name: 'Main', owner: String(user._id) },
3130
+ user: String(user._id),
3131
+ canPlaceOrder: true,
3132
+ });
3133
+ assert.equal(defaults.requireOperationAccessForPopulateQueries, true); // old frozen snapshot
3134
+ assert.equal(api.getModelOptions(DocumentModel.modelName).requireOperationAccessForPopulateQueries, undefined);
2860
3135
  // Both false: readable-but-unrequested private fetch inputs still cannot widen the public mask.
2861
3136
  api.setModelOption(DocumentModel.modelName, 'permissionSchema', { name: true, balance: true, creditLimit: false });
2862
3137
  assert.deepEqual(await read({ select, populate: [{ path: 'account', select: 'name -_id' }] }), {
@@ -2881,6 +3156,8 @@ async function runPrivatePopulateExample() {
2881
3156
  body: JSON.stringify([
2882
3157
  { target: 'model', name: DocumentModel.modelName, op: 'read', id: String(account._id) },
2883
3158
  { target: 'model', name: DocumentModel.modelName, op: 'list' },
3159
+ { target: 'model', name: UserModel.modelName, op: 'read', id: String(user._id) },
3160
+ { target: 'model', name: UserModel.modelName, op: 'list' },
2884
3161
  ]),
2885
3162
  });
2886
3163
  assert.equal(batch.status, 200);
@@ -3069,10 +3346,15 @@ is no longer supported, including with both new flags false.
3069
3346
 
3070
3347
  Choose `requireOperationAccessForPopulateQueries` and
3071
3348
  `requireOperationAccessForPopulateDependencies` explicitly from the matrix above;
3072
- both default true. Migrate a deliberate private operation bypass to the new dependency
3073
- name, then review the query policy independently. Changing a registration setting is
3074
- not a boolean-to-new-policy migration. Keep configuration in the owning runtime, not
3075
- model defaults, per-call options or clients.
3349
+ both default true **per target**. Move previous `setGlobalOptions`, `setGlobalOption`
3350
+ or `api.set` usage to `setDefaultModelOptions` / `setDefaultModelOption` for inheritance,
3351
+ then use model setters for deliberate Document/User overrides. Scoped decorators use
3352
+ `ModelOption` / `DefaultModelOption`, never `GlobalOption` or module `options`.
3353
+ Stale global placements fail with actionable migration errors, without rebroadcast.
3354
+ Explicit undefined restores live inheritance; defaults changed administratively
3355
+ affect later calls on existing unoverridden models, not in-flight captures. Move a
3356
+ deliberate old private bypass to the current dependency name at this model/default
3357
+ scope and review Q independently. Per-call options and clients do not own this policy.
3076
3358
 
3077
3359
  The former PPR whole-reference omission rule is superseded: selected/permitted parent
3078
3360
  IDs survive denied ordinary/private admission and private failure. Source-field denial