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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/MIGRATION.md ADDED
@@ -0,0 +1,1089 @@
1
+ # Access router: breaking migration
2
+
3
+ This guide describes the **breaking contract implemented by this package**.
4
+ Deploy a tested matching application/library revision. There are no legacy
5
+ aliases or mixed-version rolling-compatibility flags. Start with `isolated`.
6
+
7
+ One engine captures actor/policy at operation entry, normalizes facts once per
8
+ document stage, and publishes an ordinary filtered DTO. A DTO, its metadata and
9
+ its diagnostic context have **no reusable authorization authority**. Neither mode
10
+ is a callback sandbox, database transaction, rollback mechanism, external-cache
11
+ freshness guarantee, blanket security-equivalence claim or performance promise.
12
+
13
+ ## Breaking change: nested operation access
14
+
15
+ **Hard removal, no compatibility period.** Flat operation-access variants and their
16
+ public flat-name type are removed. There are no aliases, automatic translation, or
17
+ warning-only deprecations. Model, model-default and data bulk/dotted/fluent updates
18
+ reject removed keys before publishing partial policy, including keys set to undefined.
19
+
20
+ ### Replace flat variants with per-operation rules
21
+
22
+ Each operation accepts either a scalar `Validation` or an object with four optional
23
+ `Validation` members: `default`, `basic`, `advanced`, and `root`. `Validation` still
24
+ means boolean, permission string, permission-string array, or a synchronous/async
25
+ request-bound guard; the new structure is not limited to booleans.
26
+
27
+ Before (historical):
28
+
29
+ ```text
30
+ operationAccess: {
31
+ read: 'canRead',
32
+ basicRead: true,
33
+ advancedRead: 'admin',
34
+ subs: {
35
+ comments: { read: 'canReadComments', advancedRead: 'moderator' },
36
+ },
37
+ }
38
+ ```
39
+
40
+ After (public target types, compiled through root and `./advanced` declarations):
41
+
42
+ <!-- doc-example: partial -->
43
+
44
+ ```ts
45
+ import type { OperationAccess, OperationAccessContext, OperationAccessRule } from '@web-ts-toolkit/access-router';
46
+ import type { OperationAccessVariants } from '@web-ts-toolkit/access-router/advanced';
47
+
48
+ const context: OperationAccessContext = 'root';
49
+ const read: OperationAccessVariants = {
50
+ default: 'canRead',
51
+ basic: true,
52
+ advanced: 'admin',
53
+ [context]: 'canRead', // optional: omitted root already falls back to default
54
+ };
55
+ const rule: OperationAccessRule = read;
56
+ const operationAccess: OperationAccess = {
57
+ read: rule,
58
+ subs: {
59
+ comments: {
60
+ read: { default: 'canReadComments', advanced: 'moderator' },
61
+ },
62
+ },
63
+ };
64
+ void operationAccess;
65
+ ```
66
+
67
+ Move the old base operation guard to its nested `default` when adding variant
68
+ members. An omitted `root` inherits that default, preserving the old root entry
69
+ guard; the explicit `root: 'canRead'` above is optional. Set `root: false` to deny
70
+ that target's read entries through the root/batch router independently of direct
71
+ read endpoints. Scalar operation rules, e.g. `read: 'canRead'`, remain supported.
72
+
73
+ | Removed operation-access keys | Replacement members |
74
+ | ----------------------------------- | ------------------------------------- |
75
+ | `basicList`, `advancedList` | `list.basic`, `list.advanced` |
76
+ | `basicRead`, `advancedRead` | `read.basic`, `read.advanced` |
77
+ | `basicCreate`, `advancedCreate` | `create.basic`, `create.advanced` |
78
+ | `basicUpdate`, `advancedUpdate` | `update.basic`, `update.advanced` |
79
+ | `basicUpsert`, `advancedUpsert` | `upsert.basic`, `upsert.advanced` |
80
+ | `basicCount`, `advancedCount` | `count.basic`, `count.advanced` |
81
+ | `basicDistinct`, `advancedDistinct` | `distinct.basic`, `distinct.advanced` |
82
+
83
+ Inside `subs.<field>`, replace the former four flat list/read variants in the same
84
+ way: `subs.comments.basicRead` becomes `subs.comments.read.basic`. Subdocument
85
+ create/update/delete also accept scalar-or-object rules. Defined field scalars such
86
+ as `subs.attachments: true` continue to supply that field's operation fallback.
87
+ Remove imports of the flat-name `RouteVariantAccess` type. Use
88
+ `OperationAccessContext`, `OperationAccessVariants` and `OperationAccessRule` from
89
+ the package root or `./advanced`, rather than concatenated key names.
90
+ Removed flat configuration keys reject with migration diagnostics rather than
91
+ being interpreted as custom accesses or automatically translated.
92
+
93
+ ### Entry points and fallback
94
+
95
+ All seven pairs select independent members (paths relative to the target base):
96
+
97
+ | Operation | Basic direct endpoint | Advanced direct endpoint | Root entry member |
98
+ | ---------- | ---------------------- | --------------------------------------------- | ----------------- |
99
+ | `list` | `GET /` | `POST /__query` | `list.root` |
100
+ | `read` | `GET /:id` | `POST /__query/:id`, `POST /__query/__filter` | `read.root` |
101
+ | `create` | `POST /` | `POST /__mutation` | `create.root` |
102
+ | `update` | `PATCH /:id` | `PATCH /__mutation/:id` | `update.root` |
103
+ | `upsert` | `PUT /` | `PUT /__mutation` | `upsert.root` |
104
+ | `count` | `GET /count` | `POST /count` | `count.root` |
105
+ | `distinct` | `GET /distinct/:field` | `POST /distinct/:field` | `distinct.root` |
106
+
107
+ Paths are relative to the target's base path and use default route segments.
108
+ Data-router list/read and subdocument list/read follow the same context mapping.
109
+ HEAD follows its GET's basic member. Unpaired direct new/delete and subdocument mutation
110
+ routes choose `basic`; their root counterparts choose `root`. Both root
111
+ `subUpdate` and `subBulkUpdate` use the field's `update.root`. No new advanced
112
+ endpoint or root wire `op` name is introduced. Setting `advanced` on an unpaired
113
+ operation does not create an endpoint. Context is explicit server-owned dispatch
114
+ metadata, not inferred from POST or a caller-selected access string.
115
+
116
+ Top-level fallback is:
117
+
118
+ ```text
119
+ operation.<basic | advanced | root>
120
+ -> operation.default (or the operation's scalar rule)
121
+ -> operationAccess.default (or scalar operationAccess shorthand)
122
+ -> deny
123
+ ```
124
+
125
+ Only `undefined` inherits. A selected false/empty-array/false-returning guard
126
+ denies immediately; it is not combined with another guard. An empty top-level
127
+ operation object can inherit `operationAccess.default`. Model runtime exact-path
128
+ defaults still participate before general fallback: a runtime-default
129
+ `read.advanced` can outrank a model's scalar `read` or `read.default`. Set the model's
130
+ own context member to override it. Configuration still replaces objects shallowly;
131
+ this is not recursive merging of model and runtime-default objects. The selected
132
+ operation object supplies its own `default`; a defined model `read: {}` does not
133
+ independently inherit a runtime `read.default`. A whole operation inherited by the
134
+ existing base lookup can supply its own default. These defaults always belong to
135
+ the same runtime as the model; they are not process-global catch-alls.
136
+
137
+ For a defined subdocument field, use its operation's context member, then its scalar
138
+ or nested `default`, then deny. Missing operations in a defined field object do
139
+ **not** inherit top-level operations or `operationAccess.default`. An absent field
140
+ rule uses the corresponding top-level operation/context. A field-level
141
+ `subs.comments.default` is not a new wildcard fallback, and scalar `subs` is not
142
+ made an umbrella guard. Existing runtime exact-path specificity still applies.
143
+
144
+ Omitting model `operationAccess` inherits configured model defaults; without any
145
+ applicable grant, model operations deny. `operationAccess: true` explicitly supplies
146
+ the scalar allow fallback. Explicit model `operationAccess: undefined` retains its
147
+ existing exact-key-only runtime fallback, not inheritance of runtime bare/outer
148
+ `.default` catch-alls. Data routers do not inherit model defaults. Invalid defined
149
+ JavaScript values deny instead of falling through to an allowed default.
150
+
151
+ The root router's **own** scalar `operationAccess` still guards the outer batch
152
+ endpoint. A target's `read.root` is an additional per-entry decision, not a
153
+ replacement for that outer guard. Root being POST does not select `advanced`.
154
+ Direct denials remain 401; root target denials keep per-entry unauthorized results.
155
+ Denied routes remain registered and visible in endpoint listings/OpenAPI.
156
+
157
+ <!-- doc-example: partial -->
158
+
159
+ ```ts
160
+ import { createAccessRuntime } from '@web-ts-toolkit/access-router';
161
+
162
+ const api = createAccessRuntime();
163
+ const data = api.createDataRouter('Catalog', {
164
+ basePath: '/catalog',
165
+ idParam: 'id',
166
+ idField: 'id',
167
+ data: [{ id: 'one', name: 'One' }],
168
+ operationAccess: { list: true, read: { default: false, basic: false, advanced: false, root: true } },
169
+ permissionSchema: { id: true, name: true },
170
+ });
171
+ const batch = api.createRouter({ basePath: '/batch', operationAccess: 'canBatch' });
172
+ // Mount data.routes and batch.routes in an Express app with express.json().
173
+ // A root read still requires the independent outer canBatch guard; both direct reads deny.
174
+ void [data, batch];
175
+ ```
176
+
177
+ ### Keep transport entry separate from base policy
178
+
179
+ Existing context-free operation checks select the operation's scalar or nested
180
+ `default`, followed by the applicable outer fallback. They never choose `basic`,
181
+ `advanced`, or `root` merely because the initiating request used that entry point.
182
+ This includes existing populate/include target checks, private populated dependency
183
+ checks when required by target policy, READ-to-LIST retry, and subdocument mutation
184
+ response visibility. Existing populate-policy flags and trusted service admission
185
+ remain unchanged. Transport grants do not grant fields or related targets;
186
+ `permissionSchema`, row policy, and hook access names continue to use base operations.
187
+
188
+ For example, `read: { default: false, root: true }` permits root read entry, but does
189
+ not grant context-free target read admission. Use `default` deliberately when
190
+ migrating old base guards; putting them only under `basic` would change secondary
191
+ and root behavior.
192
+
193
+ ### Update setters, not unrelated schema names
194
+
195
+ Replace `router.operationAccess('basicRead', false)` with
196
+ `router.operationAccess('read.basic', false)`. Replace
197
+ `router.setOption('operationAccess.advancedRead', rule)` with
198
+ `router.setOption('operationAccess.read.advanced', rule)`, and use the same nested
199
+ paths for runtime model/default/data setters. Nested `undefined` restores the
200
+ documented fallback; whole-object assignment remains shallow replacement.
201
+
202
+ <!-- doc-example: partial -->
203
+
204
+ ```ts
205
+ import mongoose from 'mongoose';
206
+ import { createAccessRuntime } from '@web-ts-toolkit/access-router';
207
+
208
+ const api = createAccessRuntime();
209
+ const Post = mongoose.model('MigrationPost', new mongoose.Schema({ title: String, comments: [{ text: String }] }));
210
+ const router = api.createRouter(Post, {
211
+ operationAccess: {
212
+ default: false,
213
+ read: { default: 'canRead', basic: true, advanced: 'admin' },
214
+ subs: {
215
+ comments: { read: { default: 'canReadComments', root: false }, create: { basic: 'canComment', root: false } },
216
+ closed: {}, // missing operations deny; outer default never opens this field
217
+ attachments: true, // scalar field fallback; absent fields instead use top-level rules
218
+ },
219
+ },
220
+ });
221
+ router.operationAccess('read.basic', false);
222
+ router.operationAccess('subs.comments.read.advanced', 'moderator');
223
+ router.setOption('operationAccess.read.root', false);
224
+ router.operationAccess('read.basic', undefined); // clear a member, not a whole permission string assignment
225
+ api.setModelOption(Post.modelName, 'operationAccess.read', { default: 'canRead', root: false });
226
+ api.setDefaultModelOption('operationAccess.read.advanced', 'admin');
227
+ const data = api.createDataRouter('MigrationData', { data: [], operationAccess: true }); // scalar shorthand
228
+ data.setOption('operationAccess.read', { default: true, root: false }); // keep scalar meaning explicitly
229
+ data.runtime.setDataOption('MigrationData', 'operationAccess.read.basic', true);
230
+ ```
231
+
232
+ Updating beneath a scalar replaces it with an object; explicitly keep its old guard
233
+ under `default` if needed. Generic `getModelOption`/`getDataOption` remain raw generic
234
+ fallback lookups, not the final entry resolver (they can return an operation object).
235
+ Exact getters inspect a path; they do not evaluate a route. Setters remain live for
236
+ fresh work, construction snapshots remain frozen, and in-flight captured policy
237
+ retains its owning actor/runtime/defaults across updates.
238
+
239
+ Search operation-access configurations and their dotted/fluent paths for removed
240
+ flat names. Do **not** rename `requestSchemas.advancedRead`, request-schema exports,
241
+ client read/list method names, business fields, or permission names. Nested context
242
+ paths are configuration, not new request-selectable operations or populate access
243
+ values. Wire populate access remains `read`/`list`; retired and nested route-only
244
+ selectors must not become alternate target-authorization capabilities.
245
+
246
+ ## Field permission maps are disabled by default
247
+
248
+ `disableFieldPermissions` now defaults to `true`. `_view`/`_edit` maps and their
249
+ placeholders are no longer computed or emitted, even when a request or method
250
+ default sets `includeFieldPermissions: true`. Permission enforcement and
251
+ `docPermissions`-hook keys (controlled by `includePermissions`) are unchanged.
252
+
253
+ To retain field maps, explicitly set `disableFieldPermissions: false` on the model
254
+ or use `api.setDefaultModelOptions({ disableFieldPermissions: false })` for runtime
255
+ model defaults. Use `stripPermissionsField: true` to remove the metadata field entirely.
256
+
257
+ ## Replace global private-fetch inputs with document-permission descriptors
258
+
259
+ `alwaysSelectFields` is removed entirely: no option, dotted option, fluent setter,
260
+ default or compatibility alias. For each hook that needs extra projected data,
261
+ replace its function with `{ dependsOn: ['ownerId'], get: existingFunction }`.
262
+ Functions remain valid and add no private fetch inputs. Direct descriptors and
263
+ per-access/default/custom entries share the same contract; use `get`, not `getter`.
264
+
265
+ Only the active `docPermissionsAccess` supplies inputs (exact entry, then `default`
266
+ if undefined); it is not unioned with output/read or virtual access. Declare each
267
+ definition's actual inputs, not a global union. Hook/dependencies are captured as a
268
+ pair before awaits. Absent/empty dependencies add nothing. Missing/undefined values
269
+ never skip `get`. Inputs grant no output: selection and authorization still apply,
270
+ including exclusions and denied fields. Virtuals retain their own dependencies.
271
+
272
+ Use top-level persisted schema keys only, like virtuals. Dotted, unsafe, unknown and
273
+ virtual inputs reject. Move old nested paths such as `profile.ownerId` to the whole
274
+ `profile` container. Dotted access setters such as
275
+ `router.set('docPermissions.read', { dependsOn: ['ownerId'], get: hook })` replace
276
+ whole definitions; partial `.get`/`.dependsOn` edits reject. Those member names are
277
+ reserved, not custom accesses. Malformed definitions, including null/false or mixed
278
+ descriptor/access keys, reject rather than silently disabling calculation. To override
279
+ default with no facts, provide an exact callback returning `{}`. Move inputs used only by virtuals onto their virtual
280
+ descriptors; remove forced fields with no consumer rather than inventing a hook.
281
+
282
+ Embedded scopes inherit owning-document facts; dedicated subdocument routes prepare
283
+ their owning parent. Populate/include targets resolve their own hook and inputs.
284
+ Pre-/post-write stages stay independent; raw output helpers do no hidden query or
285
+ document-hook computation. See the [typed shapes](README.md#document-permission-dependencies-breaking-change).
286
+
287
+ ## M1. Replace rich grants with immutable boolean facts
288
+
289
+ Before (historical, not a target example):
290
+
291
+ ```text
292
+ docPermissions.read = async doc => ({ membership: await loadMembership(doc), expiresAt: new Date() });
293
+ salary.read = (_permissions, grants) => grants.membership.canReadSalary;
294
+ ```
295
+
296
+ After: calculate decisions inside the document hook. `loadMembership` below is an
297
+ **application function**, supplied here, not a library export. Global permission
298
+ queries and document facts are different inputs. This typed function rule and the
299
+ prefixed string rule use the same evaluator; neither is an unconditional grant.
300
+
301
+ <!-- doc-example: partial -->
302
+
303
+ ```ts
304
+ import { createAccessRuntime, type DocumentGrants, type FieldPermissionHook } from '@web-ts-toolkit/access-router';
305
+ import type { ModelRequest } from '@web-ts-toolkit/access-router/advanced';
306
+
307
+ async function loadMembership(request: ModelRequest, doc: unknown) {
308
+ // Fixed server-owned example identity; replace with a verified principal / membership lookup.
309
+ if (!request.macl) throw new Error('Missing owning request middleware');
310
+ return {
311
+ canReadSalary: doc !== null && typeof doc === 'object' && 'ownerId' in doc && doc.ownerId === 'alice',
312
+ };
313
+ }
314
+ const salaryRule: FieldPermissionHook = function (permissions, facts) {
315
+ return permissions.has('isHR') || facts.canReadSalary === true;
316
+ };
317
+ const api = createAccessRuntime();
318
+ api.setModelOptions('Employee', {
319
+ modelPermissionPrefix: 'doc:',
320
+ docPermissions: {
321
+ read: {
322
+ dependsOn: ['ownerId'], // fetched privately, not selected/authorized output
323
+ async get(doc): Promise<DocumentGrants> {
324
+ const membership = await loadMembership(this, doc);
325
+ return { canReadSalary: membership.canReadSalary === true };
326
+ },
327
+ },
328
+ },
329
+ permissionSchema: {
330
+ salary: { read: salaryRule },
331
+ bonus: { read: 'isHR doc:canReadSalary' }, // space = AND
332
+ allowance: { read: ['isHR', 'doc:canReadSalary'] }, // array = OR
333
+ },
334
+ });
335
+ void salaryRule;
336
+ ```
337
+
338
+ Supply the model, middleware and original request as in the complete workflow
339
+ below. For a production actor, use authenticated middleware and verified membership,
340
+ not the fixed example identity or client-supplied claims. Strings first check the global permission with that exact name, then a
341
+ document fact with the optional `doc:` prefix stripped. Unprefixed strings still
342
+ have global-OR-document behavior; the prefix is not an exclusive namespace or a
343
+ way to revoke a global grant. Boolean/string/
344
+ string-array rules, short-circuit order and effective base-operation access remain.
345
+
346
+ `DocumentGrants = Readonly<Record<string, boolean>>`: only own enumerable string
347
+ keys on a plain record and **literal booleans**. One root + one slot per key means
348
+ at most **19,999 keys**. No generic escape hatch accepts rich grants. Nested values,
349
+ Date/Buffer/BSON/Map/Set, undefined, getters/accessors, proxies, symbols,
350
+ non-enumerables and protected keys reject without getter execution or truthiness
351
+ coercion. Protected keys: `__proto__`, `constructor`, `prototype`, `_doc`, `$__`,
352
+ `__v`, `_permissions`, `_view`, `_edit` and the configured metadata field name.
353
+ Other string keys, including dotted/prefixed names, remain valid.
354
+
355
+ The library copies once into its own frozen null-prototype facts, never freezes or
356
+ retains the application's returned map. Mutating that map later cannot change the
357
+ stage in **either mode**. Do not mutate supplied facts, compare grant-object
358
+ identities, or store rich mutable context state. A missing hook yields empty facts;
359
+ a thrown/rejected hook yields empty facts plus a fixed-category warning. A **fulfilled invalid map** is a
360
+ whole-operation controlled **400**, not empty success. Arbitrary thenables are not
361
+ supported; application Promise assimilation is not sandboxed.
362
+
363
+ Facts are computed once even if an expensive fact goes unused. Closures, an
364
+ external cache or database state can change after an await; a captured function
365
+ does not keep them current. Design expensive loading/freshness explicitly.
366
+
367
+ Existing-document update/upsert-update and existing-parent subdocument input
368
+ admission use normalized **pre-write** facts, including negative predicates such
369
+ as `!facts.suspended`. Post-write output has a **separate fresh stage**. Do not
370
+ empty pre-write facts or derive write authority from output. DataService, standalone
371
+ raw helpers and new/create-input request-only evaluation receive frozen **empty
372
+ facts**. Pre-fetch planning defers functions rather than inventing facts.
373
+
374
+ ## M2. Replace output-context mutation with explicit business work
375
+
376
+ Before (historical):
377
+
378
+ ```text
379
+ docPermissions.read = (doc, permissions, context) => {
380
+ context.originalDocumentSnapshot.lastReviewed = new Date();
381
+ context.currentDocument.save();
382
+ return { owner: true };
383
+ };
384
+ ```
385
+
386
+ After: use local application values to compute facts, and a separate normal write
387
+ for an intended persisted change. Do not move read side effects into a closure.
388
+
389
+ <!-- doc-example: partial -->
390
+
391
+ ```ts
392
+ import type { ModelRequest } from '@web-ts-toolkit/access-router/advanced';
393
+ async function recordReview(req: ModelRequest, id: string, reviewedAt: Date) {
394
+ const service = req.macl.getService<{ lastReviewed?: Date }>('Employee');
395
+ const written = await service.updateById(id, { lastReviewed: reviewedAt }, { select: ['lastReviewed'] });
396
+ if (!written.success) throw new Error(`Review write failed: ${written.code}`);
397
+ return written.data; // ordinary row/input/output rules and persistence hooks apply
398
+ }
399
+ void recordReview;
400
+ ```
401
+
402
+ `ModelOutputContext` is the frozen context for document hooks (including pre-write),
403
+ virtuals, `decorate`, `decorateAll` and result diagnostics. **Exact allowlist**:
404
+
405
+ | Member | Meaning |
406
+ | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------ |
407
+ | `modelName`, `receivingModelName` | Definition/receiving model names, not a raw Mongoose Model |
408
+ | `operation` | Initiating operation, not overwritten by fallback/effective output access |
409
+ | `scopePath` | Frozen definition segments, including `sub` markers |
410
+ | `virtualAccess`, `outputAccess`, `docPermissionsAccess` | Effective access strings |
411
+ | `docPermissions` | Frozen boolean facts; empty in the document hook and decorateAll |
412
+ | `resolvedQuery?` | Frozen `select`/`populate`/`sort` canonical string arrays, numeric `skip`/`limit`; **NO filter** |
413
+
414
+ Removed from **output** contexts, with no renamed backing aliases:
415
+
416
+ | Removed member | Replacement |
417
+ | ---------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- |
418
+ | `mongooseModel` | Use an application-owned registered model for explicit business work; diagnostic names for logging |
419
+ | `originalDocumentSnapshot`, `finalDocumentSnapshot`, `currentDocument` | Explicit hook argument for calculation; normal write for persistence |
420
+ | `originalData`, `allowedData`, `preparedData` | Explicit local application variables or mutation lifecycle hook |
421
+ | `allowedFields`, `modifiedPaths`, `changes` | Use genuine mutation lifecycle bookkeeping, not output authorization |
422
+ | `resolvedQuery.filter` | Keep your application's query input separately; do not recover private row policy |
423
+ | `documentAuthorization`, `getDocumentAuthorization` | No output-authority replacement; see M3 |
424
+
425
+ `ModelHookContext` remains mutable in real validate/prepare/transform/save
426
+ (`afterPersist`)/delete/change lifecycle work, including its legitimate document,
427
+ data, query and diff fields. Use `ModelOutputHook` / `ModelOutputListHook` for
428
+ presentation annotations instead of lifecycle `ModelHook` / `ModelListHook`.
429
+
430
+ For output, `isolated` doc hooks get disposable detached views, including supported
431
+ mutable native leaves. In `trusted`, an admitted ordinary source/doc-hook input may
432
+ be borrowed: mutations can affect values and facts the hook computes. Only query-origin
433
+ trusted output leaves hidden unvisited source graphs unbounded. Write output and its
434
+ related targets always acquire a full bounded detached source first; trusted omits
435
+ only the subsequent disposable hook-view copy (see M4). The existing hydrated pre-write
436
+ UPDATE hook is unchanged; these output guarantees are not an input-hook sandbox.
437
+ **Only source borrowing relaxes**; captured actor, private policy and normalized
438
+ facts remain immutable. Neither Object.freeze nor a readonly native type makes
439
+ arbitrary Date/Buffer/BSON/Map methods immutable.
440
+
441
+ Virtual getters keep separate disposable views, private populated argument-four
442
+ isolation and **return staging in both modes**. Mutating an argument is not an
443
+ implicit output write; return the intended value. Trusted post-filter presentation
444
+ callbacks may construct/replace data but run after stage closure, with **no automatic
445
+ second authorization pass**. No callback sandbox, transaction or rollback is implied.
446
+
447
+ **Model guards no longer construct an output document.** Business interception in
448
+ an overridden `_read`, field callbacks, virtual getters, decorators, tasks or include
449
+ attachment work no longer runs during `guard({ modelName, id, condition })`. Move
450
+ security decisions to operation/row policy or the document-fact hook; move business
451
+ validation/effects to an explicit application boundary. Ordinary DTO reads still run
452
+ all selected-field checks, virtuals and presentation, with their normal errors.
453
+
454
+ ## M3. Remove handles; choose presentation or a fresh normal query
455
+
456
+ Before (historical):
457
+
458
+ ```text
459
+ service.pickAllowedFields(row, 'list', { documentAuthorization: context.documentAuthorization });
460
+ context.getDocumentAuthorization(child);
461
+ ```
462
+
463
+ `DocumentAuthorization`, the helper option, result-context handle and child lookup
464
+ are removed entirely. There is no public issuer, callback replacement, hidden DTO
465
+ symbol or result-keyed authority. A serialized/copied/forged old token is not
466
+ accepted. `getDocPermissions` reads metadata **DATA**, not authority; changing
467
+ `_permissions` or the non-enumerable presentation alias cannot grant access.
468
+
469
+ - **Presentation only:** use the already-filtered DTO, or `{ name: result.data.name }`.
470
+ This adds **0 reads / 0 document hooks** and does **not check current permissions**.
471
+ - **Raw output-only evaluation:** `pickAllowedFields`, `trimOutputFields` and
472
+ `genAllowedFields` evaluate current supplied values, captured global permissions,
473
+ frozen empty facts and optional explicit scoped server `outputFields`. They do
474
+ **0 DB operations / 0 document hooks**, no row admission, hidden refresh, virtuals
475
+ or omitted-field recovery. `!facts.suspended` may be true on empty facts; that is
476
+ **not proof** the current document is unsuspended.
477
+ - **Optional raw collection:** `pickAllowedFieldsMany` uses one deliberate capture
478
+ with separate isolated sources/stages/decisions, not N independently fresh picks.
479
+ It is not a default migration or a replacement for current document facts.
480
+ - **Current document-dependent authorization:** issue a **new normal service READ
481
+ or LIST**, with suitable selection/private hook inputs and normal row scope.
482
+ One single-row refresh in the workflow adds **1 read / 1 document hook**. It is
483
+ not a hidden helper cost or a transaction/freshness promise after completion.
484
+
485
+ Never replace an old handle with `unrestricted` policy, automatically grant all
486
+ old fields, or accept client-supplied grants. Explicit backend grants are a
487
+ separate deliberate server decision. Example scoped helper, no hidden query:
488
+
489
+ <!-- doc-example: partial -->
490
+
491
+ ```ts
492
+ import type { ModelRequest } from '@web-ts-toolkit/access-router/advanced';
493
+ async function presentContact(req: ModelRequest, contact: { email?: string; label?: string }) {
494
+ return req.macl
495
+ .getService<{ contacts: { email?: string; label?: string }[] }>('Employee')
496
+ .pickAllowedFields(contact, 'read', {
497
+ scopePath: ['contacts'],
498
+ authorization: { outputFields: { mode: 'grant', paths: ['contacts.label'] } },
499
+ }); // grant paths remain model-relative; this is not current-document authority
500
+ }
501
+ void presentContact;
502
+ ```
503
+
504
+ ### Optional raw collection, not N fresh calls
505
+
506
+ Use this only for backend-held records whose output policy deliberately needs one
507
+ capture. All row sources are owned before the first field predicate; duplicate
508
+ references share no decisions. Actor/model/catalog/config/scope/output policy are
509
+ captured before awaits or predicates. Later actor-view/schema/options changes affect
510
+ the **next call**, not later rows; setting `req.user` alone does not refresh initialized
511
+ permissions. Closures, live request state and native effects are not frozen.
512
+
513
+ The following three exact target blocks are compiled and executed by installed
514
+ consumer tests. They are application functions, not new library exports.
515
+
516
+ <!-- doc-example: partial -->
517
+
518
+ ```ts
519
+ import type { FilteredOutput, OutputFieldOptions } from '@web-ts-toolkit/access-router';
520
+ import type { ModelRequest } from '@web-ts-toolkit/access-router/advanced';
521
+ export type Contact = { label: string; email: string; address: { city: string } };
522
+ type Employee = { contacts: Contact[] };
523
+ // Server-owned only: NEVER copy these controls from request input.
524
+ const contactPolicy: OutputFieldOptions<Employee> = {
525
+ scopePath: ['contacts'],
526
+ authorization: { outputFields: { mode: 'grant', paths: ['contacts.label'] } },
527
+ };
528
+ export async function rawBefore(req: ModelRequest, rows: readonly Contact[]) {
529
+ const service = req.macl.getService<Employee>('Employee');
530
+ const output = [];
531
+ for (const row of rows) output.push(await service.pickAllowedFields(row, 'list', contactPolicy));
532
+ return output; // N independently fresh captures; existing Promise<T> does not prove field presence
533
+ }
534
+ export async function rawMany(
535
+ req: ModelRequest,
536
+ rows: readonly Contact[],
537
+ ): Promise<readonly FilteredOutput<Contact>[]> {
538
+ return req.macl.getService<Employee>('Employee').pickAllowedFieldsMany(rows, 'list', contactPolicy);
539
+ // ONE capture, not semantically equivalent to rawBefore. Every nested field can be omitted.
540
+ }
541
+ ```
542
+
543
+ The scope uses ordinary response segments; grant paths stay **model-relative**
544
+ (`contacts.label`). One output-only policy applies to the whole call; row/input/
545
+ related controls, selection, `purpose`, handles/tokens and modes reject. No DB,
546
+ document hooks, virtuals, row/operation/target checks, reference provenance or omitted
547
+ value restoration is added. Negative EMPTY predicates do not prove current facts.
548
+
549
+ If existing DTOs only need a presentation subset, normally use **zero helpers**:
550
+
551
+ <!-- doc-example: partial -->
552
+
553
+ ```ts
554
+ export function presentationSubset(rows: readonly { readonly name?: string }[]) {
555
+ // Already-filtered DATA only. No current-permission assertion or omitted-field restoration.
556
+ return rows.map((row) => (Object.hasOwn(row, 'name') ? { name: row.name } : {}));
557
+ // Subset adds 0 reads / 0 document hooks / 0 helper captures.
558
+ }
559
+ ```
560
+
561
+ For current document-dependent facts, use a **new normal LIST**, not either raw
562
+ recipe or an output grant. Configure the applicable `docPermissions.dependsOn` for
563
+ private hook inputs on the model; keep normal row policy. After an earlier LIST:
564
+
565
+ <!-- doc-example: partial -->
566
+
567
+ ```ts
568
+ import type { ModelRequest } from '@web-ts-toolkit/access-router/advanced';
569
+ type Employee = { tenantId: string; name: string; salary: number; ownerId: string };
570
+ export async function currentList(req: ModelRequest, tenantId: string) {
571
+ const current = await req.macl.getService<Employee>('Employee').find(
572
+ { tenantId }, // trusted application filter, still subject to normal row policy
573
+ { select: ['name', 'salary', '-_id'], limit: 100 },
574
+ { includePermissions: false, includeFieldPermissions: false },
575
+ );
576
+ if (!current.success) throw new Error(`Current LIST failed: ${current.code}`);
577
+ return current.data; // +1 explicit LIST; configured document hook runs per returned row
578
+ }
579
+ ```
580
+
581
+ The installed runtime test changes private owner facts between LISTs: presentation
582
+ adds no work, while the fresh two-row LIST adds one query/two hooks and removes the
583
+ now-denied salary. This is not a transaction or freshness guarantee after completion.
584
+
585
+ Collection admission requires an ordinary dense Array of **0–1,000** positions;
586
+ readonly/frozen is accepted, nullish positions preserved. Proxies reject before
587
+ traps; subclasses, holes, accessor/non-enumerable indices, extra own strings/symbols
588
+ and iterables reject without reading an iterator. Empty input still validates all
589
+ controls/model/policy/catalog. Every row remains isolated in both source modes.
590
+ Separate per-row source/fact/view/selected **20,000-slot / depth-100** owners remain,
591
+ with native/embedded/metadata/copy/wire work sharing the relevant remainder.
592
+
593
+ One **200,000 work-unit / 16 MiB cumulative payload** ledger covers the entire call's
594
+ **router-controlled admission, staging, traversal and explicit copies**, including
595
+ configuration/preparation and all rows/phases. No row/chunk transition resets it.
596
+ **Excluded:** opaque Mongoose/native normalization internals and dependency-owned
597
+ allocations/traversals, arbitrary trusted closure/callback effects and engine
598
+ enumeration costs. This is **not** a total-memory/RSS, whole-normalization, CPU-operation
599
+ or sandbox cap. Canonical normalization can copy 17 MiB and discard it into a tiny
600
+ admitted row. A returned oversized normalized value rejects **before the next explicit
601
+ router copy**; explicit router-owned native/wire preparation is not excluded.
602
+
603
+ Bounded row scheduling uses the minimum row/scheduler/shared-hook-gate limits,
604
+ retaining FIFO/reentry/depth, stable outer order and per-row field order/sync-until-async
605
+ evaluation. Structural/native/router-budget poison is one controlled **400**, even if
606
+ caught: close admission, drain admitted library work, clear state and prohibit late
607
+ publication. Ordinary predicate-body failures omit fields. There is no partial result,
608
+ callback-side-effect rollback, automatic retry, persistence permit while waiting or
609
+ untracked detached-closure wait. Caller chunking starts new fresh operations, not one
610
+ atomic batch. Existing singles retain their independent freshness and error contracts.
611
+
612
+ The new root/advanced **type-only** `FilteredOutput<T>` makes string properties
613
+ recursively optional/readonly, including `_id`. Arrays include null/undefined without
614
+ tuple/cardinality inference; string Maps become readonly records; Date/RegExp/Buffer
615
+ use canonical base types. Other BSON/hydrated values (including string-ID documents),
616
+ unknown inputs and branches at depth eight are `unknown`: narrow/validate them.
617
+ Readonly is not native freezing, an input validator, exact field inference or authority.
618
+ Do not assign filtered rows to required `T[]` or cast away omissions. Both service
619
+ getters and Core expose the method (Core prepends `modelName`); DataService, HTTP and
620
+ clients do not. No new default migration, H3 replacement, gate waiver or speedup claim.
621
+
622
+ ### Complete public workflow: facts, helper costs and checked refresh
623
+
624
+ Compile as `.mts` or `.cts` with TypeScript NodeNext/Node16, or bundle using public
625
+ imports. Requires Node >=22, Express >=5, Mongoose >=8 and MongoDB. The example
626
+ creates/drops only its unique database and closes its server/connection. The
627
+ server-owned example actor is not an authentication implementation.
628
+
629
+ <!-- doc-example: complete-runtime -->
630
+
631
+ ```ts
632
+ import assert from 'node:assert/strict';
633
+ import { randomUUID } from 'node:crypto';
634
+ import { once } from 'node:events';
635
+ import type { Server } from 'node:http';
636
+ import express from 'express';
637
+ import mongoose from 'mongoose';
638
+ import { createAccessRuntime, type DocumentGrants, type FieldPermissionHook } from '@web-ts-toolkit/access-router';
639
+ import type { ModelRequest } from '@web-ts-toolkit/access-router/advanced';
640
+
641
+ async function runOwnedAuthorizationExample() {
642
+ const connection = await mongoose
643
+ .createConnection(process.env.MONGODB_URL ?? 'mongodb://127.0.0.1:27017', {
644
+ dbName: `owned_authorization_${randomUUID().replaceAll('-', '')}`,
645
+ })
646
+ .asPromise();
647
+ let server: Server | undefined;
648
+ let reads = 0,
649
+ hooks = 0;
650
+ const observations: unknown[] = [];
651
+ try {
652
+ const api = createAccessRuntime();
653
+ api.setGlobalOptions({ globalPermissions: () => ['reader'], logger: { warn() {} } });
654
+ type Employee = {
655
+ name: string;
656
+ salary: number;
657
+ bonus: number;
658
+ allowance: number;
659
+ ownerId: string;
660
+ visible: boolean;
661
+ };
662
+ const schema = new mongoose.Schema<Employee>({
663
+ name: String,
664
+ salary: Number,
665
+ bonus: Number,
666
+ allowance: Number,
667
+ ownerId: String,
668
+ visible: Boolean,
669
+ });
670
+ schema.pre('findOne', function () {
671
+ reads++;
672
+ });
673
+ const EmployeeModel = connection.model('MigrationEmployee', schema);
674
+ const salaryRule: FieldPermissionHook = function (permissions, facts) {
675
+ assert.ok(Object.isFrozen(facts));
676
+ return permissions.has('isHR') || facts.canReadSalary === true;
677
+ };
678
+ async function loadMembership(request: ModelRequest, doc: unknown) {
679
+ assert.ok(request.macl); // the original initialized request, not an elevated actor
680
+ return { canReadSalary: doc !== null && typeof doc === 'object' && 'ownerId' in doc && doc.ownerId === 'alice' };
681
+ }
682
+ const router = api.createRouter(EmployeeModel, {
683
+ basePath: '/employees',
684
+ operationAccess: { read: true },
685
+ hydration: { findById: 'lean' },
686
+ modelPermissionPrefix: 'doc:',
687
+ stripPermissionsField: true,
688
+ baseFilter: { read: () => ({ visible: true }) },
689
+ permissionSchema: {
690
+ name: 'reader',
691
+ salary: { read: salaryRule },
692
+ bonus: { read: 'reader doc:canReadSalary' }, // AND
693
+ allowance: { read: ['isHR', 'doc:canReadSalary'] }, // OR
694
+ },
695
+ docPermissions: {
696
+ read: {
697
+ dependsOn: ['ownerId'],
698
+ async get(doc, _permissions, context): Promise<DocumentGrants> {
699
+ hooks++;
700
+ assert.ok(Object.isFrozen(context));
701
+ assert.equal('currentDocument' in context, false);
702
+ const membership = await loadMembership(this, doc);
703
+ return { canReadSalary: membership.canReadSalary === true };
704
+ },
705
+ },
706
+ },
707
+ });
708
+ const row = await EmployeeModel.create({
709
+ name: 'Ada',
710
+ salary: 100,
711
+ bonus: 10,
712
+ allowance: 5,
713
+ ownerId: 'alice',
714
+ visible: true,
715
+ });
716
+ function initializedRequest(req: express.Request): req is ModelRequest {
717
+ return 'macl' in req; // the owning router middleware must have run first
718
+ }
719
+ router.router.post('/verify', async (req, res) => {
720
+ assert.ok(initializedRequest(req), 'Missing owning router middleware');
721
+ const service = router.getService(req);
722
+ const before = { reads, hooks };
723
+ const query = { select: ['name', 'salary', 'bonus', 'allowance', '-_id'] };
724
+ const quiet = { includePermissions: false, includeFieldPermissions: false };
725
+ const first = await service.findById(String(row._id), query, quiet);
726
+ if (!first.success) throw new Error(`Initial read failed: ${first.code}`);
727
+ assert.deepEqual(first.data, { name: 'Ada', salary: 100, bonus: 10, allowance: 5 });
728
+ assert.deepEqual({ reads, hooks }, { reads: before.reads + 1, hooks: before.hooks + 1 });
729
+ assert.deepEqual({ name: first.data.name }, { name: 'Ada' }); // presentation DATA, not reauthorization
730
+ assert.deepEqual(await service.pickAllowedFields(first.data, 'read'), { name: 'Ada' });
731
+ assert.deepEqual(
732
+ await service.pickAllowedFields(first.data, 'read', {
733
+ authorization: { outputFields: { mode: 'grant', paths: ['salary', 'bonus', 'allowance'] } },
734
+ }),
735
+ first.data,
736
+ ); // explicit server-only output decision, NOT replacement handle authority
737
+ assert.deepEqual({ reads, hooks }, { reads: before.reads + 1, hooks: before.hooks + 1 });
738
+ // Simulate independent application change. No DTO/context can keep this fresh.
739
+ await EmployeeModel.collection.updateOne({ _id: row._id }, { $set: { ownerId: 'bob' } });
740
+ const current = await service.findById(String(row._id), query, quiet);
741
+ if (!current.success) throw new Error(`Refresh failed: ${current.code}`);
742
+ assert.deepEqual(current.data, { name: 'Ada' });
743
+ assert.equal(first.data.salary, 100); // the old DTO remains DATA, not a current certificate
744
+ assert.deepEqual({ reads, hooks }, { reads: before.reads + 2, hooks: before.hooks + 2 });
745
+ observations.push({
746
+ mode: api.getModelOption(EmployeeModel.modelName, 'readAuthorizationMode'),
747
+ initial: { reads: 1, hooks: 1 },
748
+ helperExtra: { reads: 0, hooks: 0 },
749
+ currentExtra: { reads: 1, hooks: 1 },
750
+ });
751
+ await EmployeeModel.collection.updateOne({ _id: row._id }, { $set: { ownerId: 'alice' } });
752
+ res.json({ ok: true });
753
+ });
754
+ const app = express();
755
+ app.use(express.json());
756
+ app.use(router.routes);
757
+ server = app.listen(0, '127.0.0.1');
758
+ await once(server, 'listening');
759
+ const address = server.address();
760
+ assert.ok(address && typeof address !== 'string');
761
+ const statuses: number[] = [];
762
+ for (const mode of ['isolated', 'trusted'] as const) {
763
+ api.setModelOption(EmployeeModel.modelName, 'readAuthorizationMode', mode);
764
+ const response: globalThis.Response = await fetch(`http://127.0.0.1:${address.port}/employees/verify`, {
765
+ method: 'POST',
766
+ });
767
+ statuses.push(response.status);
768
+ assert.equal(response.status, 200, await response.text());
769
+ }
770
+ // Untyped/JS wire control is controlled 400 BEFORE a DB read/hook, even false.
771
+ const beforeInvalid = { reads, hooks };
772
+ const invalid = await fetch(`http://127.0.0.1:${address.port}/employees/__query/${row._id}`, {
773
+ method: 'POST',
774
+ headers: { 'content-type': 'application/json' },
775
+ body: JSON.stringify({ select: ['name'], options: { readAuthorizationMode: false } }),
776
+ });
777
+ statuses.push(invalid.status);
778
+ assert.equal(invalid.status, 400, await invalid.text());
779
+ assert.deepEqual({ reads, hooks }, beforeInvalid);
780
+ api.setModelOption(EmployeeModel.modelName, 'readAuthorizationMode', 'isolated'); // NEW calls only
781
+ console.log(JSON.stringify({ guide: 'owned-authorization', statuses, observations, reads, hooks }));
782
+ } finally {
783
+ if (server)
784
+ await new Promise<void>((resolve, reject) => server!.close((error) => (error ? reject(error) : resolve())));
785
+ await connection.dropDatabase();
786
+ await connection.close();
787
+ }
788
+ }
789
+ void runOwnedAuthorizationExample().catch((error) => {
790
+ console.error(error);
791
+ process.exitCode = 1;
792
+ });
793
+ ```
794
+
795
+ ### Model conditions are facts-only, not an implicit DTO read
796
+
797
+ `guard({ modelName, id, condition })` consumes a **private fresh read stage**, not
798
+ metadata or post-decorate output. A visible row and a fresh owning document hook are
799
+ required even for a global-only condition. Strings/arrays keep the same grammar and
800
+ look up global permission OR a literal-true document fact, without field prefixes.
801
+ Stripping, exposing no keys or forging metadata cannot authorize the guard.
802
+
803
+ The normal public by-ID defaults, identifier/query/row/sort admission, root DB
804
+ projection, hydration and pre-output hook source remain the same. Ordinary/private
805
+ populate preparation needed for that source retains target-local operation/row/mode
806
+ admission and private-input masks. Include descriptors still undergo preflight, but
807
+ **output-only include attachment queries and target DTO hooks do not run**.
808
+
809
+ No DTO, field metadata, selected-output traversal, embedded/target DTO finalization,
810
+ virtual getter, decoration or task is built/run. Thus an invalid virtual/output-only
811
+ native return, throwing decorator or output-only include error no longer vetoes a
812
+ guard. Source/fact/necessary-dependency structural failures still fail with controlled
813
+ 400 and cannot be caught to authorize. Ordinary denied/missing guards remain 401.
814
+
815
+ A successful visible-row guard normally costs one root read/one root hook and **zero
816
+ output-field callbacks**. An admitted miss may retry once using the captured LIST
817
+ operation gate and initiating READ source mode; true and false conditions are both
818
+ terminal, as are 400/403. Required dependency queries may add reads. This request-only
819
+ service path, like direct `_read`, does **not** run the generated HTTP route's initial
820
+ READ operation gate. Compose the appropriate existing route/global guard when both
821
+ checks are required; generated routes retain their operation checks unchanged.
822
+
823
+ If the caller also needs data or output/business effects, perform a separate ordinary
824
+ authorized read, check `result.success`, and handle its errors. That adds its normal
825
+ read/hook/output cost; the library does not silently fetch a second DTO for a guard.
826
+
827
+ <!-- doc-example: partial -->
828
+
829
+ ```ts
830
+ import { guard } from '@web-ts-toolkit/access-router';
831
+ import type { ModelRequest } from '@web-ts-toolkit/access-router/advanced';
832
+ const ownerCondition = guard({ modelName: 'Employee', id: { type: 'param', key: 'id' }, condition: 'owner' });
833
+ async function readEmployeeForBusinessWork(req: ModelRequest, id: string) {
834
+ // Explicit additional ordinary read, not a reusable guard result/capability.
835
+ const result = await req.macl.getPublicService('Employee')._read(id, { select: ['name'] });
836
+ if (!result.success) throw new Error(`Employee read failed: ${result.code}`);
837
+ return result.data;
838
+ }
839
+ void ownerCondition;
840
+ void readEmployeeForBusinessWork;
841
+ ```
842
+
843
+ Related targets use **their own** captured policy/facts/mode; the unchanged
844
+ README runnable service/related example demonstrates separate scoped policies.
845
+
846
+ ## M4. Four independent server authorization modes
847
+
848
+ Keep `readAuthorizationMode` / `listAuthorizationMode`; configure
849
+ `createAuthorizationMode` / `updateAuthorizationMode` for CREATE/UPDATE **post-write
850
+ output only**. All four use `AuthorizationMode = 'isolated' | 'trusted'` and default
851
+ to isolated. There is no renamed-key migration, alias or separate UPSERT option.
852
+
853
+ Before: combinations of comparison/copy/fast-path booleans. There is **no one-to-one
854
+ mapping** for old mixed configurations and no dormant prerequisite combination.
855
+
856
+ <!-- doc-example: partial -->
857
+
858
+ ```ts
859
+ import { createAccessRuntime } from '@web-ts-toolkit/access-router';
860
+ const api = createAccessRuntime();
861
+ api.setDefaultModelOptions({
862
+ readAuthorizationMode: 'isolated',
863
+ listAuthorizationMode: 'isolated',
864
+ createAuthorizationMode: 'isolated',
865
+ updateAuthorizationMode: 'isolated',
866
+ });
867
+ api.setModelOptions('Employee', {
868
+ readAuthorizationMode: 'isolated',
869
+ listAuthorizationMode: 'trusted',
870
+ createAuthorizationMode: 'trusted',
871
+ updateAuthorizationMode: 'isolated',
872
+ });
873
+ api.setModelOptions('Payroll', { readAuthorizationMode: 'isolated', listAuthorizationMode: 'isolated' });
874
+ api.setModelOption('Employee', 'listAuthorizationMode', undefined); // restore live default inheritance
875
+ api.setDefaultModelOption('listAuthorizationMode', 'isolated');
876
+ ```
877
+
878
+ Model/router/default bulk and exact setters accept only literal `isolated` /
879
+ `trusted`, or `undefined` restoration. Omission preserves an override; explicit
880
+ undefined clears it. Defaults inherit live for future calls; bulk failure is
881
+ atomic. `getModelOption` and `getModelOptions` expose effective modes, while a
882
+ router's `options` is its construction-time snapshot. Logger failures cannot abort
883
+ committed configuration; warn once per effective owner/access transition into
884
+ trusted, not on every request or repeated assignment.
885
+
886
+ Every retired key below rejects **by presence**, including `false`, `undefined`,
887
+ inherited and non-enumerable slots. Delete the keys, not just their truthy values:
888
+
889
+ 1. `unsafeSkipListDocumentSnapshotChecks`
890
+ 2. `unsafeSkipReadDocumentSnapshotChecks`
891
+ 3. `unsafeSkipListOutputSnapshotChecks`
892
+ 4. `unsafeSkipReadOutputSnapshotChecks`
893
+ 5. `unsafeSkipListNestedDocumentSnapshotChecks`
894
+ 6. `unsafeSkipReadNestedDocumentSnapshotChecks`
895
+ 7. `unsafeSkipListInitialOutputSnapshotCopy`
896
+ 8. `unsafeSkipReadInitialOutputSnapshotCopy`
897
+ 9. `unsafeUseListAuthorizationFastPath`
898
+ 10. `unsafeUseReadAuthorizationFastPath`
899
+
900
+ Untyped JavaScript is checked too. This executable error example deliberately
901
+ tests rejected inputs; it is not an adapter that translates old flags:
902
+
903
+ <!-- doc-example: javascript-errors -->
904
+
905
+ ```js
906
+ import assert from 'node:assert/strict';
907
+ import mongoose from 'mongoose';
908
+ import { createAccessRuntime } from '@web-ts-toolkit/access-router';
909
+ const api = createAccessRuntime();
910
+ const Employee = mongoose.model('Employee', new mongoose.Schema({ name: String }));
911
+ api.registerModelInstance('Employee', Employee); // configuration needs a real registered model; no DB connection here
912
+ const retired = [
913
+ 'unsafeSkipListDocumentSnapshotChecks',
914
+ 'unsafeSkipReadDocumentSnapshotChecks',
915
+ 'unsafeSkipListOutputSnapshotChecks',
916
+ 'unsafeSkipReadOutputSnapshotChecks',
917
+ 'unsafeSkipListNestedDocumentSnapshotChecks',
918
+ 'unsafeSkipReadNestedDocumentSnapshotChecks',
919
+ 'unsafeSkipListInitialOutputSnapshotCopy',
920
+ 'unsafeSkipReadInitialOutputSnapshotCopy',
921
+ 'unsafeUseListAuthorizationFastPath',
922
+ 'unsafeUseReadAuthorizationFastPath',
923
+ ];
924
+ for (const key of retired) {
925
+ for (const options of [
926
+ { [key]: false },
927
+ { [key]: undefined },
928
+ Object.create({ [key]: false }),
929
+ Object.defineProperty({}, key, { value: undefined, enumerable: false }),
930
+ ])
931
+ assert.throws(() => api.setModelOptions('Employee', options), /was removed; migrate/);
932
+ }
933
+ for (const mode of [true, false, null, 1, 'false', {}]) {
934
+ assert.throws(() => api.setModelOption('Employee', 'readAuthorizationMode', mode), /literal isolated or trusted/);
935
+ }
936
+ api.setModelOptions('Employee', { readAuthorizationMode: 'isolated', listAuthorizationMode: 'isolated' });
937
+ assert.throws(
938
+ () =>
939
+ api.setModelOptions('Employee', {
940
+ readAuthorizationMode: 'trusted',
941
+ listAuthorizationMode: false,
942
+ }),
943
+ /literal isolated or trusted/,
944
+ );
945
+ assert.equal(api.getModelOption('Employee', 'readAuthorizationMode'), 'isolated'); // bulk was atomic
946
+ assert.throws(() => api.setGlobalOption('readAuthorizationMode', 'trusted'), /server model\/default-model/);
947
+ console.log(JSON.stringify({ retiredPresenceRejections: 40, invalidModes: 6, atomicBulk: true }));
948
+ ```
949
+
950
+ The new keys are also prohibited in HTTP/query/body/root-batch, per-call/helper,
951
+ method-default, include/populate and subquery **authority namespaces**. Persisted
952
+ business data/filter fields with the same names remain inert ordinary data.
953
+
954
+ Capture happens before hooks/awaits. Root READ/LIST select their matching setting;
955
+ READ-to-LIST retry retains READ with a fresh stage. CREATE (including bulk) and
956
+ UPDATE select their settings only after persistence/lifecycle processing. Both
957
+ UPSERT branches select the executed branch's captured mode, retaining initiating
958
+ `operation: 'upsert'` and its branch accesses, not re-reading live configuration.
959
+
960
+ **Both write modes always acquire a full bounded detached source**, including mutable
961
+ native leaves. Trusted omits only the subsequent disposable document-hook view copy;
962
+ it cannot borrow live write documents, `_doc`, payloads or lifecycle snapshots.
963
+ Conversion failure at this boundary fails output rather than falling back to `_doc`.
964
+ Write-input authority, pre-write grants, the hydrated pre-write UPDATE hook,
965
+ validation/preparation/transform/save and lifecycle contracts are unchanged, not
966
+ newly detached or sandboxed. No implicit save/query/rollback is added; an output
967
+ error may occur **after persistence**, so do not automatically retry the write.
968
+
969
+ Embedded output inherits its genuine owner's mode/facts. Related targets select
970
+ their **own model's READ/LIST mode** at effective target access, including genuine
971
+ write-origin populate, with independent policy/facts. Parent mode cannot lower an
972
+ isolated target; a trusted target cannot mutate an isolated parent's source or live
973
+ write graph. Write-origin targets still require mandatory full bounded detachment:
974
+ the trusted-query exception for hidden unvisited graphs does not apply. Independent
975
+ callback service calls capture anew. NEW, helpers, dedicated subdocument origins,
976
+ COUNT/DELETE/DISTINCT and unsupported custom origins gain no trusted stage.
977
+
978
+ For decorators, configure modes on `@Router`/`@RouterOptions`, or factory
979
+ `defaultModelOptions`, never request input. Decorated hook `this` is the **class
980
+ instance**; obtain the original request with `@Request()`. See the matching
981
+ access-router-deco README's executable owned-authorization module.
982
+
983
+ Roll out a tested matching application/library revision, default isolated, inspect
984
+ workload behavior and then opt individual operation owners into trusted deliberately.
985
+ Switching back to isolated affects **new calls only**; in-flight captures do not
986
+ change. Deployment rollback requires a tested matching application **and library**
987
+ revision, not adding removed flags to this version or assuming mixed rolling safety.
988
+
989
+ ## M5. Mechanical checklist, preserved APIs and errors
990
+
991
+ Also audit model guards semantically: search for `_read` overrides and field/getter/
992
+ decorate/task/include effects used as business checks. Those output effects no longer
993
+ intercept a guard. Search alone cannot identify a security dependency on their side
994
+ effects. Keep such decisions in operation/row/fact hooks, or explicitly run and check
995
+ a normal DTO read at the application boundary (see M2/M3).
996
+
997
+ Search application configuration, computed/spread defaults, wrappers, decorators,
998
+ tests, generated clients and dependency adapters for:
999
+
1000
+ - All ten M4 names; also remove unshipped `unsafeFuseListOutputPublication` /
1001
+ `unsafeFuseReadOutputPublication` if copied from a prototype (never an API).
1002
+ - `DocumentAuthorization`, `documentAuthorization`, `getDocumentAuthorization`;
1003
+ old helper options and child-handle caches/lookups/serialization/replay.
1004
+ - Every removed M2 output member, `resolvedQuery.filter`, `ModelHookContext` /
1005
+ `ModelHook` / `ModelListHook` annotations used for output callbacks; use the
1006
+ diagnostic/output types instead, **not** for legitimate lifecycle hooks.
1007
+ - Rich or mutated docPermissions returns, identity comparisons, closures retaining
1008
+ source/context/facts and document-dependent raw-helper predicates.
1009
+ - Positional `baseFields`, `skipChecks`, `subPaths`, old `overrides`, private
1010
+ prepared/execution options and deep `src`/`dist` imports. Named helpers accept
1011
+ `OutputFieldOptions` / `AllowedOutputFieldOptions`, not legacy overloads.
1012
+
1013
+ Search cannot decide whether a use is presentation or current authority, whether
1014
+ `!facts.suspended` incorrectly admits empty facts, whether dependencies are fetched,
1015
+ whether expensive unused facts are worth loading, or whether side effects belonged
1016
+ in a real write. Review those semantics explicitly. No casts, `any` escape hatches
1017
+ or suppressed declaration errors are a migration strategy.
1018
+
1019
+ Unchanged: `authorization.rows`, `inputFields`, `outputFields`, `related` are
1020
+ independent server dimensions; parent grants do not elevate target operations/rows/
1021
+ fields. Input grants do not grant output. Field boolean/string/array grammar,
1022
+ selection/exclusions **versus authority**, private hook/dependency fetches,
1023
+ hydration/native support, raw-parent business APIs and mutable persistence hooks
1024
+ remain. Supported native/hydrated values can normalize at their actual boundary;
1025
+ that is not arbitrary native support or identical native side effects in both modes.
1026
+ Permission metadata remains **request-user facts**, never backend grants. Strip/
1027
+ exposure/include flags affect metadata, not internal fact resolution or enforcement.
1028
+
1029
+ `FieldPermissionHook` has `(permissions, facts)` and original-request `this`;
1030
+ `GuardHook`/operationAccess still has **one permissions argument**. Root and
1031
+ `/advanced` export the same new types (`AuthorizationMode`, `DocumentGrants`,
1032
+ `FieldPermissionHook`, `FieldValidation`, `ModelOutputContext`, `ModelOutputHook`,
1033
+ `ModelOutputListHook`); `/processors` remains data transformation, not an issuer.
1034
+ `FilteredOutput<T>` is also available from root and `/advanced`, only as a type.
1035
+ There are no new entrypoints or legacy aliases. ESM imports select `.d.mts` +
1036
+ `.mjs`; CJS requires select `.d.ts` + `.js` (factory under `.default` / named
1037
+ `createAccessRuntime`). Use strict Bundler, Node16 or NodeNext module resolution.
1038
+ Actual minimum/current peer workflows are tested; minimum-peer declaration checking
1039
+ retains its existing `skipLibCheck` distinction, current peers check declarations.
1040
+
1041
+ ### TypeScript before: intentionally rejected, compile separately
1042
+
1043
+ This exact old-style source is a **negative fixture**, not a target example. Do
1044
+ not compile it alongside the positive examples or suppress these errors:
1045
+
1046
+ <!-- doc-example: expected-error -->
1047
+
1048
+ ```ts
1049
+ import type {
1050
+ DocumentAuthorization,
1051
+ ModelRouterOptions,
1052
+ ModelOutputContext,
1053
+ OutputFieldOptions,
1054
+ } from '@web-ts-toolkit/access-router';
1055
+ const oldMode: ModelRouterOptions = { unsafeUseReadAuthorizationFastPath: false };
1056
+ const invalidMode: ModelRouterOptions = { readAuthorizationMode: true };
1057
+ const rich: ModelRouterOptions = { docPermissions: () => ({ membership: { owner: true } }) };
1058
+ declare const context: ModelOutputContext;
1059
+ context.currentDocument;
1060
+ context.resolvedQuery?.filter;
1061
+ context.getDocumentAuthorization({});
1062
+ const oldHelper: OutputFieldOptions = { documentAuthorization: context };
1063
+ void [oldMode, invalidMode, rich, oldHelper];
1064
+ export type OldHandle = DocumentAuthorization;
1065
+ ```
1066
+
1067
+ ### Error reference (also applies to untyped JavaScript)
1068
+
1069
+ | Input / failure | Result and action |
1070
+ | ----------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
1071
+ | Retired control presence, illegal new-mode placement, legacy handle/helper option | Controlled BadRequest 400 before work; configuration setters throw an actionable error synchronously. Delete/move it; do not coerce false/undefined. |
1072
+ | Invalid mode (`true`, `false`, null, number, arbitrary string/object) | Reject, no coercion; failed bulk setter publishes none of the update. |
1073
+ | Fulfilled invalid/rich/protected/accessor/proxy/over-budget facts | Whole operation 400, no partial result; fix the hook return. |
1074
+ | Missing document hook / throwing or rejected hook | Empty facts; only throwing/rejected hooks emit the fixed-category warning. Normal global rules still apply, not an unconditional deny-all override. |
1075
+ | Field predicate throw | Denies that field; operation guard remains request-only. |
1076
+ | Getter body throw / `undefined` | Omits that field. |
1077
+ | Invalid selected getter return or selected/native structural overflow/cycle/depth failure | Sticky whole-operation 400, even if inner application code catches it; no partial publication. |
1078
+ | Ordinary row miss / guard denial | Normal checked error result (`not_found`, or guard 401); do not treat it as successful data. |
1079
+ | Post-save output/fact/budget failure | Controlled 400 **may follow persistence**. No rollback and **no automatic retry**; reconcile persisted business state explicitly. |
1080
+
1081
+ Selected root-row work retains inclusive **20,000 slots / depth 100**, shared with
1082
+ embedded/related/native/metadata output, including denied/protected encountered
1083
+ keys before reading values. No child/helper/native transition replenishes it.
1084
+ Document-source, facts and explicit callback views have separate bounded owners.
1085
+ No source profile disables row/operation/field/target rules or the original actor.
1086
+
1087
+ Untyped JavaScript uses the same checked result/error handling as the workflow:
1088
+ `{ options: { readAuthorizationMode: false } }` on an HTTP request returns 400
1089
+ before reads/hooks. Do not depend on TypeScript alone to protect a wire boundary.