@web-ts-toolkit/access-router 0.65.0 → 0.66.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
@@ -248,8 +248,9 @@ Express request. This includes scalar counts/distinct, ID lookups, mutations, in
248
248
  populate, subdocuments and field helpers. Services acquired later from a retained core
249
249
  also belong to that core. The request's current `macl` slot still belongs to the new
250
250
  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.
251
+ Each model authorization call and its private in-flight document stages remain owned
252
+ by the originating request/runtime/model/scope. Published DTOs and diagnostic contexts
253
+ are ordinary data, not reusable authority for either runtime.
253
254
 
254
255
  Route-shape keys (`modelName`/`dataName`, `basePath`, `parentPath`, `idParam`,
255
256
  `queryRouteSegment`, and model `mutationRouteSegment`) are fixed at construction;
@@ -258,466 +259,50 @@ Express routes. `parentPath` supplies the external prefix for route metadata/log
258
259
  mount that prefix in Express yourself. Live `idField`/`resolveIdFilter` change lookup
259
260
  behavior rather than route shape.
260
261
 
261
- ### Temporary unsafe read/list-performance switches
262
+ ### Owned READ/LIST authorization modes
262
263
 
263
- **All default to off (snapshot checks enabled).** Six independent server-only
264
- settings temporarily skip specific comparisons on one registered model:
265
-
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.
270
-
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.
264
+ There is one document-stage engine and exactly two independent server options:
265
+ `readAuthorizationMode` / `listAuthorizationMode`, each `'isolated' | 'trusted'`,
266
+ default **isolated**. See the shipped [breaking migration guide](MIGRATION.md) for
267
+ before/after examples, all ten removed flags, errors and rollout guidance. No old
268
+ flag combination, dormant mode, output handle or compatibility alias remains.
398
269
 
399
270
  <!-- doc-example: partial -->
400
271
 
401
272
  ```ts
402
- import mongoose from 'mongoose';
403
273
  import { createAccessRuntime } from '@web-ts-toolkit/access-router';
404
-
405
274
  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,
412
- });
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);
275
+ api.setDefaultModelOptions({ readAuthorizationMode: 'isolated', listAuthorizationMode: 'isolated' });
276
+ api.setModelOptions('Employee', { readAuthorizationMode: 'isolated', listAuthorizationMode: 'trusted' });
277
+ api.setModelOptions('Payroll', { readAuthorizationMode: 'isolated', listAuthorizationMode: 'isolated' });
278
+ api.setModelOption('Employee', 'listAuthorizationMode', undefined); // inherit the live default
279
+ api.setModelOption('Employee', 'readAuthorizationMode', 'isolated'); // NEW calls only
416
280
  ```
417
281
 
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;
719
- });
720
- ```
282
+ Isolated owns bounded detached projected source and gives document hooks disposable
283
+ views. Trusted may borrow admitted ordinary projected source/doc-hook input: mutations
284
+ can affect values/calculated facts; hidden unvisited graphs are not whole-document
285
+ bounded. **Both own actor, private policy and normalized frozen boolean facts**, enforce
286
+ original actor, rows/fields/targets and selected/native 20,000-slot/depth-100 bounds.
287
+ Both retain separate getter views, return staging and private argument-four isolation.
288
+ No sandbox, transaction, rollback, external freshness or blanket security equivalence.
289
+
290
+ Capture precedes hooks/awaits. Genuine embedded scopes inherit their owner; related
291
+ targets use their own captured model/access mode and policy, not their parent's mode.
292
+ READ-to-LIST retry keeps initiating READ mode with a fresh stage. Independent service
293
+ calls capture anew. Writes/new/dedicated subdocuments always stay isolated.
294
+
295
+ Only literal enum strings or undefined restoration are valid. Bulk setters reject
296
+ atomically. Retired controls reject by presence, even false/undefined/inherited/
297
+ non-enumerable. New/old selectors are prohibited in HTTP/root/per-call/helper/defaults/
298
+ include/populate/subquery authority slots; same-named business fields remain data.
299
+ Trusted transitions warn once per effective owner/access; logger failures cannot abort.
300
+ Switching to isolated affects new calls, not in-flight captures. Rollback means a tested
301
+ matching application/library revision, never re-adding removed flags or assuming mixed
302
+ rolling compatibility. No timing or universal-speedup claim follows from mode names.
303
+
304
+ The [complete executable migration workflow](MIGRATION.md#complete-public-workflow-facts-helper-costs-and-checked-refresh)
305
+ uses literal facts, both modes, zero-read raw helpers and a checked fresh read.
721
306
 
722
307
  ### Wire placement and option names
723
308
 
@@ -968,8 +553,8 @@ reentry bound are separate contracts, documented in their sections.
968
553
  ## Trusted service authorization
969
554
 
970
555
  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).
556
+ related targets and document facts. See [Runnable service authorization](#runnable-service-authorization)
557
+ and the shipped [owned-authorization migration](MIGRATION.md) with executable examples.
973
558
 
974
559
  ### Public request admission and backend options
975
560
 
@@ -1011,10 +596,9 @@ Target output grants remain selection-limited, including schema-hidden fields an
1011
596
  virtuals. Populate match, include filter, ref IDs and join/correlation constraints
1012
597
  remain ANDed with the target scope after query transformation in every row mode.
1013
598
  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.
599
+ grants flow into request-controlled `$$sq` queries. Related output is already-filtered
600
+ DATA; no child handles/lookups remain. A current target-dependent decision needs a
601
+ new normal target read/list. Private dependencies/join keys do not grant output.
1018
602
 
1019
603
  Every requested populate target needs an actual registered Mongoose model and ACL
1020
604
  configuration with an **effective object `permissionSchema`** in the owning runtime.
@@ -1074,29 +658,15 @@ start fresh request-mode output evaluation. `genAllowedFields` defaults to
1074
658
  purpose. It reports **existing output paths**, not a schema/input allowlist. Null or
1075
659
  undefined documents yield `[]` (pick/trim preserve the nullish value) without hooks.
1076
660
 
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.
661
+ The finalizer owns a private stage, resolves boolean `DocumentGrants` once and
662
+ memoizes field decisions only until publication. Each row/call/target/pre-/post-write
663
+ stage is independent; genuine embedded scopes reuse their owner's facts. Returned
664
+ DTOs carry **no capability**, hidden authority symbol or reusable document handle.
665
+
666
+ Single results have a frozen diagnostic `context`; list/create results have aligned
667
+ `contexts[index]`. These are `ModelOutputContext` diagnostics, not source/model/
668
+ lifecycle aliases or authority. Their exact allowlist and removed-member replacements
669
+ are in [MIGRATION.md](MIGRATION.md#m2-replace-output-context-mutation-with-explicit-business-work).
1100
670
 
1101
671
  <!-- doc-example: partial -->
1102
672
 
@@ -1110,40 +680,30 @@ const result = await service.findOne(
1110
680
  { select: ['status', 'internalNote'] },
1111
681
  { authorization: { outputFields: { mode: 'grant', paths: ['internalNote'] } } },
1112
682
  );
1113
- if (result.success) {
1114
- const picked = await service.pickAllowedFields(result.data, 'read', {
1115
- documentAuthorization: result.context.documentAuthorization,
1116
- });
1117
- console.log(picked);
1118
- }
683
+ if (!result.success) throw new Error(`Read failed: ${result.code}`);
684
+ console.log({ internalNote: result.data.internalNote }); // presentation subset, no new authorization
685
+ const current = await service.findById(orderId, { select: ['status', 'internalNote'] });
686
+ if (!current.success) throw new Error(`Refresh failed: ${current.code}`);
687
+ console.log(current.data); // new normal row/document authorization; adds a read/hook
1119
688
  ```
1120
689
 
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.
690
+ Raw output helpers use captured global permissions + frozen **empty document facts**
691
+ and explicit output-only server policy. They perform zero DB operations/document hooks,
692
+ no row checks, virtuals or omitted-value recovery. `!facts.suspended` may be true on
693
+ empty facts; that is not current-document proof. Metadata (`getDocPermissions` included)
694
+ is DATA, not authority. Never replace a retired handle with unrestricted/client grants.
695
+
696
+ For current document-dependent authorization use a new normal read/list with suitable
697
+ selection and private `alwaysSelectFields` hook inputs. For presentation just use the
698
+ already-filtered DTO: no extra query, but no claim of current checks. See the executable
699
+ guide for exact **0/0 helper** versus **+1 read/+1 hook** refresh counts.
700
+
701
+ Mutations retain ordinary `args.select`, independent input admission, validation,
702
+ prepare/transform/save/afterPersist/change roles and separate pre-/post-write facts.
703
+ `new()` still ignores select. Presentation callbacks run after stage closure and may
704
+ construct data, with no automatic second filtering pass. Extract only
705
+ `{ outputFields: policy.outputFields }` for output helpers; full row/input/related
706
+ policies reject. There is no helper handle option or child lookup.
1147
707
 
1148
708
  ### Independent mutation input authority
1149
709
 
@@ -1360,7 +920,7 @@ for public adapters. Keep policies as server constants, not spreads of request
1360
920
  options. Positional helper overloads are removed; see the named-helper migration
1361
921
  and request-only data compatibility contract below.
1362
922
 
1363
- ### Runnable authorization and handle reuse
923
+ ### Runnable service authorization
1364
924
 
1365
925
  This complete example uses an installed package, Express and MongoDB. Save it as
1366
926
  `authorization-example.mts` and run `node authorization-example.mts` on Node 22.18+
@@ -1489,10 +1049,9 @@ async function runServiceAuthorizationExample() {
1489
1049
  const result = await service.findOne({ _id: rows[0]._id }, selected, { ...quiet, authorization });
1490
1050
  assert.ok(result.success);
1491
1051
  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);
1052
+ // Already-filtered DTO is usable DATA, not current-document authority.
1053
+ const subset = { status: result.data.status };
1054
+ assert.deepEqual(subset, { status: 'ready' });
1496
1055
  assert.equal(documentHookCalls, 1);
1497
1056
  const fresh = await service.pickAllowedFields(result.data, 'read', { authorization: output });
1498
1057
  assert.deepEqual(fresh, { internalNote: 'server note' }); // no original owner decision
@@ -1555,13 +1114,10 @@ async function runServiceAuthorizationExample() {
1555
1114
  assert.equal(related.data.contacts?.[0].ssn, undefined);
1556
1115
  const child: unknown = Reflect.get(related.data, 'customer');
1557
1116
  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);
1117
+ assert.equal(Reflect.get(child, 'billingEmail'), 'billing@example.test');
1118
+ assert.equal(Reflect.get(child, 'tenantId'), undefined);
1119
+ const targetRaw = await customerRouter.getService(req).pickAllowedFields(child, 'read');
1120
+ assert.equal(Reflect.get(targetRaw, 'billingEmail'), undefined); // no retained target authority
1565
1121
 
1566
1122
  // Input authority is independent: patch the existing first contact, preserve ssn,
1567
1123
  // persist the denied note, and grant neither field in the mutation response.
@@ -1776,7 +1332,7 @@ adapter or alternate legacy authority path.
1776
1332
  | `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
1333
  | `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
1334
  | `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. |
1335
+ | `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
1336
  | `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
1337
 
1782
1338
  The helper overloads in the last two rows are also **removed in this next breaking
@@ -1832,9 +1388,13 @@ hook, losing otherwise allowed persisted fields. Full internal document grants
1832
1388
  are now resolved once per projected document/access stage regardless of `skim`,
1833
1389
  `includePermissions`, `includeFieldPermissions`, stripping or exposed-key limits.
1834
1390
  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.
1391
+ hook inputs with `alwaysSelectFields`; the published DTO is data, not an authorization
1392
+ certificate after those inputs and `_permissions` are removed. A later raw helper pick
1393
+ uses captured global permissions, frozen empty document facts and explicit output-only
1394
+ server policy, not retained document decisions. For current document-dependent facts,
1395
+ issue a new normal read/list with suitable selection/private hook inputs. This adds
1396
+ read/hook work; raw picks perform no hidden refresh. Temporary backend grants do not
1397
+ forge request-user `_view`/`_edit` or document-hook metadata.
1838
1398
 
1839
1399
  Output grants cannot write protected fields. Explicit model mutation `inputFields`
1840
1400
  and dedicated parent/child/visibility policies are independent opt-in capabilities;
@@ -1848,12 +1408,13 @@ valid under ordinary rules.
1848
1408
  Model `Base`/`Service`/`PublicService` expose these finite signatures; Core prepends
1849
1409
  `modelName`. The option types are exported from both the root and `/advanced`:
1850
1410
 
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 |
1411
+ | Helper | Supported final argument / default |
1412
+ | ------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
1413
+ | `genSelect(access, select?, options?)`, `genQuerySelect(...)` | `OutputPlanningOptions<TModel, TVirtuals>`, defaults to `{}` |
1414
+ | `pickAllowedFields(doc, access, options?)`, `trimOutputFields(...)` | `OutputFieldOptions<TModel, TVirtuals>`, defaults to `{}` |
1415
+ | `pickAllowedFieldsMany(rows, access, options?)` | `OutputFieldOptions<TModel, TVirtuals>`, defaults to `{}`; one explicit collection capture, `readonly FilteredOutput<T>[]` result |
1416
+ | `genAllowedFields(doc, access, options?)` | `AllowedOutputFieldOptions<TModel, TVirtuals>`, defaults to `{ purpose: 'output' }`; supplied objects require the purpose |
1417
+ | `genPopulate(access?, populate?, options?)` | Request-only `PopulatePlanningOptions`, defaults to `{}`; only `scopePath` is supported |
1857
1418
 
1858
1419
  **Default model calls changed.** There is no hidden no-option legacy path:
1859
1420
 
@@ -1865,11 +1426,12 @@ Model `Base`/`Service`/`PublicService` expose these finite signatures; Core prep
1865
1426
  that setting, still subject to request rules or explicit policy. It is no grant.
1866
1427
  A fetch projection never proves response or population permission.
1867
1428
  - 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.
1429
+ documents, using captured globals, frozen empty document facts and explicit server
1430
+ output policy. They run **no document hooks or hidden reads**. Serialized
1431
+ `_permissions` and already-trimmed DTOs carry no authority or reusable handle.
1432
+ Nested/array output rules, private `_id` retention and configured metadata posture
1433
+ still apply. Unsupported scalar/array root documents reject; an array inside a row
1434
+ remains a value. `genAllowedFields` only reports existing paths.
1873
1435
  - Request/input and query-field checks remain separate. Migrate writes to service
1874
1436
  mutations with independent `authorization.inputFields`; output picks never admit
1875
1437
  writes. Distinct/sort and request-user `_view`/`_edit` do not inherit output grants.
@@ -1886,6 +1448,93 @@ backend target authority. The obsolete raw `buildVirtualPlan`/`buildSubVirtualPl
1886
1448
  service builders are removed; use named fetch helpers. Retained plans, private
1887
1449
  identity/metadata/join retention and document-result issuance belong to package execution.
1888
1450
 
1451
+ #### Optional raw collections: one deliberately shared capture
1452
+
1453
+ `service.pickAllowedFieldsMany<T>(rows, access, options?)` returns
1454
+ `Promise<readonly FilteredOutput<T>[]>`. Both `getService` and `getPublicService`
1455
+ inherit it; `req.macl.pickAllowedFieldsMany(modelName, rows, access, options?)`
1456
+ is the Core form. There is no DataService member, generated route, client control,
1457
+ batch alias, reusable preparer or output capability. Existing single-row helpers
1458
+ remain independently fresh, including their weaker `Promise<T>` declarations
1459
+ (which never proved that required fields survived).
1460
+
1461
+ Use this **optional** API for existing backend-held raw records only when the backend
1462
+ deliberately wants **one** initialized actor/model/catalog/configuration/scope/output
1463
+ policy capture before awaits or field predicates. It is **not semantically equivalent**
1464
+ to N fresh independent calls, nor a default handle/H3 migration recommendation.
1465
+ Later actor-view, schema or options changes apply to the next call, not later rows.
1466
+ Changing `req.user` alone does not rerun the initialized permission resolver. Trusted
1467
+ closures, live request properties, external state and native normalization effects
1468
+ are not frozen: this is not an atomic multi-object/database snapshot or sandbox.
1469
+
1470
+ <!-- doc-example: partial -->
1471
+
1472
+ ```ts
1473
+ import type { FilteredOutput, OutputFieldOptions } from '@web-ts-toolkit/access-router';
1474
+ import type { ModelRequest } from '@web-ts-toolkit/access-router/advanced';
1475
+ type Contact = { label: string; email: string; address: { city: string } };
1476
+ type Employee = { contacts: Contact[] };
1477
+ async function filterRawContacts(req: ModelRequest, rows: readonly Contact[]) {
1478
+ // Backend-owned policy, NEVER copied from request body/query/options.
1479
+ const options: OutputFieldOptions<Employee> = {
1480
+ scopePath: ['contacts'],
1481
+ authorization: { outputFields: { mode: 'grant', paths: ['contacts.label'] } },
1482
+ };
1483
+ const result: readonly FilteredOutput<Contact>[] = await req.macl
1484
+ .getService<Employee>('Employee')
1485
+ .pickAllowedFieldsMany(rows, 'list', options);
1486
+ return result.map((row) => row.label?.toUpperCase()); // nested fields can also be omitted
1487
+ }
1488
+ void filterRawContacts;
1489
+ ```
1490
+
1491
+ Scope paths use ordinary response segments; grants remain **model-relative**
1492
+ (`contacts.label`, not `label`). Only output policy is accepted, never row/input/
1493
+ related authority, selection, handles, tokens, `purpose` or mode controls. Every row
1494
+ occurrence gets an independent isolated source/stage/memo in **all modes**, including
1495
+ repeated references. All sources are owned before the **first** field predicate;
1496
+ field evaluations are not shared between rows. The helper uses globals + literal
1497
+ frozen EMPTY facts + explicit output policy: **0 DB operations / 0 document hooks**,
1498
+ no virtuals, row/operation/related checks, reference-provenance recovery or restoration.
1499
+ `!facts.suspended` on EMPTY is not current-document authority. Presentation subsets
1500
+ normally need **zero helpers**; current document facts require a **new normal READ/LIST**
1501
+ with normal row policy/private hook inputs. See the executable alternatives in
1502
+ [M3](MIGRATION.md#m3-remove-handles-choose-presentation-or-a-fresh-normal-query).
1503
+
1504
+ - Outer input: dense ordinary Array, **0–1,000** positions, frozen/readonly accepted,
1505
+ null/undefined positions preserved. Proxies (before traps), subclasses, holes,
1506
+ accessor/non-enumerable indices, extra own string/symbol keys and iterables reject;
1507
+ no iterator is used. Empty calls still validate receiver/controls/model/policy/catalog.
1508
+ - Separate per-row source/fact/view/selected **20,000-slot / depth-100** owners remain;
1509
+ embedded/native/metadata/copy/wire work shares the relevant remainder. One whole-call
1510
+ **200,000 work-unit / 16 MiB cumulative payload** ledger covers **router-controlled
1511
+ admission, staging, traversal and explicit copies**, including preparation and all
1512
+ rows/phases. It never resets per row or internal chunk. Caller chunking creates new
1513
+ fresh operations, not one atomic collection operation.
1514
+ - **Excluded:** opaque Mongoose/native normalization internals and dependency-owned
1515
+ allocations/traversals, arbitrary trusted callback/closure effects and engine
1516
+ enumeration costs. This is **not** a total-memory/RSS, whole-normalization, CPU-operation
1517
+ or sandbox cap. Canonical normalization may copy 17 MiB and discard it into a tiny
1518
+ admitted row; a returned 17 MiB normalized value must reject **before the next explicit
1519
+ router copy**. Explicit router native/wire preparation is still accounted for.
1520
+ - Row work uses the minimum row/scheduler/shared-hook-gate concurrency, preserving
1521
+ FIFO/reentry/depth, stable outer order and each row's field order/sync-until-async
1522
+ behavior; no unbounded Promise.all or persistence permit while waiting. Structural,
1523
+ native or router-budget poison rejects the **whole** operation with controlled 400,
1524
+ even if caught inside a callback. Admission closes, admitted library work drains,
1525
+ private state clears and late work cannot publish. Ordinary predicate-body errors
1526
+ omit their fields. No partial result, side-effect rollback, automatic retry or wait
1527
+ for untracked detached closure work is promised.
1528
+
1529
+ `FilteredOutput<T>` is a **type-only** root/advanced export: recursively optional
1530
+ readonly string properties (including `_id`), nullish array elements without tuple/
1531
+ cardinality inference, string Maps normalized to readonly records, and canonical
1532
+ Date/RegExp/Buffer base types. Other BSON, hydrated documents (including string-ID
1533
+ documents), unknown inputs and recursion at depth eight become `unknown`; narrow or
1534
+ validate them. Readonly does not freeze native methods. The type is not a supported-
1535
+ input validator, exact-selected-field inference or authority certificate. No speedup,
1536
+ old performance-gate substitution or performance acceptance is implied.
1537
+
1889
1538
  #### Request-only data helpers
1890
1539
 
1891
1540
  `DataCore` keeps `genSelect`, `genAllowedFields`, and `pickAllowedFields` with a
@@ -1898,8 +1547,11 @@ Selection, input document and resulting field paths are relative to that scope.
1898
1547
 
1899
1548
  These helpers retain the **request-only data evaluator**: no Mongoose registration
1900
1549
  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;
1550
+ Field permission functions receive the original request as `this` and
1551
+ `(permissions, grants)`: `grants` is the built-in frozen empty document-facts record. Request-only
1552
+ means no model document facts, not a one-argument field callback. Operation `GuardHook`
1553
+ remains separate: it receives only `permissions`, with the original request as `this`.
1554
+ Allowed-fields returns a schema allowlist even with a null/empty document;
1903
1555
  pick/trim select existing values from it. An allowed container remains a whole value;
1904
1556
  use a scoped helper to filter a child. `_id` and metadata require ordinary data-field
1905
1557
  rules, with no automatic retention.
@@ -2425,7 +2077,7 @@ Root entrypoint (`@web-ts-toolkit/access-router`):
2425
2077
  - fetch configuration types (also `/advanced`): `HydrationMode`, `ModelHydrationOptions` — server-owned model/default configuration, never per-call/wire options.
2426
2078
  - 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
2079
  - 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.
2080
+ - 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
2081
 
2430
2082
  Subpath entrypoints:
2431
2083
 
@@ -2737,9 +2389,11 @@ Include output is tracked separately from the original projected source. Documen
2737
2389
  permission hooks and virtual dependencies see the source values even when a successful
2738
2390
  attachment replaces the same business field (for example, `restricted`). Only results
2739
2391
  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
2392
+ filtering using the target's own captured policy, facts and output filtering during
2393
+ private in-flight construction. Attached results are ordinary DTO data, not reusable
2394
+ target authority. A legacy read miss or omitted result never turns an existing source
2395
+ value into an attachment: that field still requires source selection and permission.
2396
+ Correlated empty results remain explicit
2743
2397
  `null`/`[]`/`0` attachments. This separation also applies to nested targets and each list
2744
2398
  row; include output does not mutate fetched persistence documents.
2745
2399
 
@@ -3511,7 +3165,7 @@ view for every getter. Automatically fetched private-only refs are not added the
3511
3165
  an existing local `dependsOn` on that ref keeps its ordinary behavior. Each getter
3512
3166
  sees only its own resolved declarations and target selections in argument four.
3513
3167
  Private maps/raw targets are not implicitly attached to response DTOs, contexts,
3514
- lifecycle snapshots, public permission hooks/metadata, document handles, or ordinary
3168
+ lifecycle snapshots, public permission hooks/metadata, or ordinary
3515
3169
  decorate/decorateAll/task inputs. **Only an authorized getter's deliberate return
3516
3170
  becomes computed output**; this is not a prohibition on returning derived values.
3517
3171
 
@@ -3555,7 +3209,7 @@ missing target IDs, order, duplicates, nulls, empty arrays and own absence. Stri
3555
3209
  private operation denial, private row/query failure, getter omission/failure and deferred
3556
3210
  virtual authorization denial cannot hide permitted IDs. Public list/custom population
3557
3211
  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.
3212
+ authority. Cleanup runs before output publication and presentation hooks/tasks.
3559
3213
 
3560
3214
  #### Supported declarations and validation
3561
3215
 
@@ -3674,6 +3328,31 @@ deny the **source field** instead. Private inputs remain isolated fourth argumen
3674
3328
  and registration, row, static-ref and hydration limitations remain mandatory. Plan this
3675
3329
  as a breaking application upgrade; no release/version automation is changed here.
3676
3330
 
3331
+ ### Model-condition guards
3332
+
3333
+ `guard({ modelName, id, condition })` requires a visible row and fresh document facts
3334
+ from the current actor. It uses the normal public by-ID defaults, query/projection,
3335
+ hydration and hook-source preparation, but **publishes no DTO**. Conditions use global
3336
+ permissions OR literal-true facts with the existing string/array grammar, not metadata.
3337
+
3338
+ Guards do not run output-field callbacks, virtuals, embedded/populated-target DTO
3339
+ finalizers, output-only include attachments, metadata, decoration/tasks or `_read`
3340
+ overrides. Errors/effects solely in that work no longer veto a guard; ordinary DTO
3341
+ reads still perform it. Source/fact/necessary-dependency structural errors remain 400;
3342
+ ordinary missing/denied conditions remain 401. Descriptor preflight and any necessary
3343
+ target-input queries retain target-local admission and private-input masks.
3344
+
3345
+ A visible-row guard normally performs one root read/hook and zero output callbacks.
3346
+ An admitted miss may retry once under captured LIST admission and initiating READ
3347
+ mode; a true/false condition and 400/403 are terminal. Like direct request-only `_read`,
3348
+ this is not the generated HTTP READ-route operation gate. Compose that existing
3349
+ route/global check when needed; generated routes retain their operation admission.
3350
+
3351
+ Put security in operation/row/fact hooks, not output side effects. If a caller needs
3352
+ a DTO or business effects, perform a separate ordinary authorized read, check success
3353
+ and handle errors at its explicit additional read/hook/output cost. See the shipped
3354
+ [guard migration](MIGRATION.md#model-conditions-are-facts-only-not-an-implicit-dto-read).
3355
+
3677
3356
  ### Hook admission and reentrant service calls
3678
3357
 
3679
3358
  `requestComplexity.maxHookConcurrency` (default `10`) limits **independently
@@ -3681,7 +3360,7 @@ admitted hook chains per request/runtime**. Independent services, root-batch
3681
3360
  entries, legacy/correlated includes, populate and embedded/subdocument outputs
3682
3361
  share one private pool. It covers:
3683
3362
 
3684
- - Model `docPermissions`, including pre-write, output-helper and owning-parent stages;
3363
+ - Model `docPermissions`, including pre-write and owning-parent stages (raw output helpers never invoke it);
3685
3364
  - Virtual getters;
3686
3365
  - Model/data `decorate` and `decorateAll` chains and service output decorator callbacks;
3687
3366
  - Data request-field selection/trimming stages (their field rules run sequentially).