@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/MIGRATION.md ADDED
@@ -0,0 +1,777 @@
1
+ # Owned authorization: breaking migration
2
+
3
+ This guide describes the **next breaking contract**, not an already-published
4
+ version. 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
+ ## M1. Replace rich grants with immutable boolean facts
14
+
15
+ Before (historical, not a target example):
16
+
17
+ ```text
18
+ docPermissions.read = async doc => ({ membership: await loadMembership(doc), expiresAt: new Date() });
19
+ salary.read = (_permissions, grants) => grants.membership.canReadSalary;
20
+ ```
21
+
22
+ After: calculate decisions inside the document hook. `loadMembership` below is an
23
+ **application function**, supplied here, not a library export. Global permission
24
+ queries and document facts are different inputs. This typed function rule and the
25
+ prefixed string rule use the same evaluator; neither is an unconditional grant.
26
+
27
+ <!-- doc-example: partial -->
28
+
29
+ ```ts
30
+ import { createAccessRuntime, type DocumentGrants, type FieldPermissionHook } from '@web-ts-toolkit/access-router';
31
+ import type { ModelRequest } from '@web-ts-toolkit/access-router/advanced';
32
+
33
+ async function loadMembership(request: ModelRequest, doc: unknown) {
34
+ // Fixed server-owned example identity; replace with a verified principal / membership lookup.
35
+ if (!request.macl) throw new Error('Missing owning request middleware');
36
+ return {
37
+ canReadSalary: doc !== null && typeof doc === 'object' && 'ownerId' in doc && doc.ownerId === 'alice',
38
+ };
39
+ }
40
+ const salaryRule: FieldPermissionHook = function (permissions, facts) {
41
+ return permissions.has('isHR') || facts.canReadSalary === true;
42
+ };
43
+ const api = createAccessRuntime();
44
+ api.setModelOptions('Employee', {
45
+ modelPermissionPrefix: 'doc:',
46
+ alwaysSelectFields: ['ownerId'], // fetched privately, not selected/authorized output
47
+ docPermissions: {
48
+ async read(doc): Promise<DocumentGrants> {
49
+ const membership = await loadMembership(this, doc);
50
+ return { canReadSalary: membership.canReadSalary === true };
51
+ },
52
+ },
53
+ permissionSchema: {
54
+ salary: { read: salaryRule },
55
+ bonus: { read: 'isHR doc:canReadSalary' }, // space = AND
56
+ allowance: { read: ['isHR', 'doc:canReadSalary'] }, // array = OR
57
+ },
58
+ });
59
+ void salaryRule;
60
+ ```
61
+
62
+ Supply the model, middleware and original request as in the complete workflow
63
+ below. For a production actor, use authenticated middleware and verified membership,
64
+ not the fixed example identity or client-supplied claims. Strings first check the global permission with that exact name, then a
65
+ document fact with the optional `doc:` prefix stripped. Unprefixed strings still
66
+ have global-OR-document behavior; the prefix is not an exclusive namespace or a
67
+ way to revoke a global grant. Boolean/string/
68
+ string-array rules, short-circuit order and effective base-operation access remain.
69
+
70
+ `DocumentGrants = Readonly<Record<string, boolean>>`: only own enumerable string
71
+ keys on a plain record and **literal booleans**. One root + one slot per key means
72
+ at most **19,999 keys**. No generic escape hatch accepts rich grants. Nested values,
73
+ Date/Buffer/BSON/Map/Set, undefined, getters/accessors, proxies, symbols,
74
+ non-enumerables and protected keys reject without getter execution or truthiness
75
+ coercion. Protected keys: `__proto__`, `constructor`, `prototype`, `_doc`, `$__`,
76
+ `__v`, `_permissions`, `_view`, `_edit` and the configured metadata field name.
77
+ Other string keys, including dotted/prefixed names, remain valid.
78
+
79
+ The library copies once into its own frozen null-prototype facts, never freezes or
80
+ retains the application's returned map. Mutating that map later cannot change the
81
+ stage in **either mode**. Do not mutate supplied facts, compare grant-object
82
+ identities, or store rich mutable context state. A missing hook yields empty facts;
83
+ a thrown/rejected hook yields empty facts plus a fixed-category warning. A **fulfilled invalid map** is a
84
+ whole-operation controlled **400**, not empty success. Arbitrary thenables are not
85
+ supported; application Promise assimilation is not sandboxed.
86
+
87
+ Facts are computed once even if an expensive fact goes unused. Closures, an
88
+ external cache or database state can change after an await; a captured function
89
+ does not keep them current. Design expensive loading/freshness explicitly.
90
+
91
+ Existing-document update/upsert-update and existing-parent subdocument input
92
+ admission use normalized **pre-write** facts, including negative predicates such
93
+ as `!facts.suspended`. Post-write output has a **separate fresh stage**. Do not
94
+ empty pre-write facts or derive write authority from output. DataService, standalone
95
+ raw helpers and new/create-input request-only evaluation receive frozen **empty
96
+ facts**. Pre-fetch planning defers functions rather than inventing facts.
97
+
98
+ ## M2. Replace output-context mutation with explicit business work
99
+
100
+ Before (historical):
101
+
102
+ ```text
103
+ docPermissions.read = (doc, permissions, context) => {
104
+ context.originalDocumentSnapshot.lastReviewed = new Date();
105
+ context.currentDocument.save();
106
+ return { owner: true };
107
+ };
108
+ ```
109
+
110
+ After: use local application values to compute facts, and a separate normal write
111
+ for an intended persisted change. Do not move read side effects into a closure.
112
+
113
+ <!-- doc-example: partial -->
114
+
115
+ ```ts
116
+ import type { ModelRequest } from '@web-ts-toolkit/access-router/advanced';
117
+ async function recordReview(req: ModelRequest, id: string, reviewedAt: Date) {
118
+ const service = req.macl.getService<{ lastReviewed?: Date }>('Employee');
119
+ const written = await service.updateById(id, { lastReviewed: reviewedAt }, { select: ['lastReviewed'] });
120
+ if (!written.success) throw new Error(`Review write failed: ${written.code}`);
121
+ return written.data; // ordinary row/input/output rules and persistence hooks apply
122
+ }
123
+ void recordReview;
124
+ ```
125
+
126
+ `ModelOutputContext` is the frozen context for document hooks (including pre-write),
127
+ virtuals, `decorate`, `decorateAll` and result diagnostics. **Exact allowlist**:
128
+
129
+ | Member | Meaning |
130
+ | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------ |
131
+ | `modelName`, `receivingModelName` | Definition/receiving model names, not a raw Mongoose Model |
132
+ | `operation` | Initiating operation, not overwritten by fallback/effective output access |
133
+ | `scopePath` | Frozen definition segments, including `sub` markers |
134
+ | `virtualAccess`, `outputAccess`, `docPermissionsAccess` | Effective access strings |
135
+ | `docPermissions` | Frozen boolean facts; empty in the document hook and decorateAll |
136
+ | `resolvedQuery?` | Frozen `select`/`populate`/`sort` canonical string arrays, numeric `skip`/`limit`; **NO filter** |
137
+
138
+ Removed from **output** contexts, with no renamed backing aliases:
139
+
140
+ | Removed member | Replacement |
141
+ | ---------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- |
142
+ | `mongooseModel` | Use an application-owned registered model for explicit business work; diagnostic names for logging |
143
+ | `originalDocumentSnapshot`, `finalDocumentSnapshot`, `currentDocument` | Explicit hook argument for calculation; normal write for persistence |
144
+ | `originalData`, `allowedData`, `preparedData` | Explicit local application variables or mutation lifecycle hook |
145
+ | `allowedFields`, `modifiedPaths`, `changes` | Use genuine mutation lifecycle bookkeeping, not output authorization |
146
+ | `resolvedQuery.filter` | Keep your application's query input separately; do not recover private row policy |
147
+ | `documentAuthorization`, `getDocumentAuthorization` | No output-authority replacement; see M3 |
148
+
149
+ `ModelHookContext` remains mutable in real validate/prepare/transform/save
150
+ (`afterPersist`)/delete/change lifecycle work, including its legitimate document,
151
+ data, query and diff fields. Use `ModelOutputHook` / `ModelOutputListHook` for
152
+ presentation annotations instead of lifecycle `ModelHook` / `ModelListHook`.
153
+
154
+ In `isolated`, doc hooks get disposable detached projected views, including
155
+ supported mutable native leaves. In `trusted`, an admitted ordinary projected
156
+ source/doc-hook input may be borrowed: mutations can affect values and facts the
157
+ hook computes, and hidden unvisited source graphs are not whole-document bounded.
158
+ **Only source borrowing relaxes**; captured actor, private policy and normalized
159
+ facts remain immutable. Neither Object.freeze nor a readonly native type makes
160
+ arbitrary Date/Buffer/BSON/Map methods immutable.
161
+
162
+ Virtual getters keep separate disposable views, private populated argument-four
163
+ isolation and **return staging in both modes**. Mutating an argument is not an
164
+ implicit output write; return the intended value. Trusted post-filter presentation
165
+ callbacks may construct/replace data but run after stage closure, with **no automatic
166
+ second authorization pass**. No callback sandbox, transaction or rollback is implied.
167
+
168
+ **Model guards no longer construct an output document.** Business interception in
169
+ an overridden `_read`, field callbacks, virtual getters, decorators, tasks or include
170
+ attachment work no longer runs during `guard({ modelName, id, condition })`. Move
171
+ security decisions to operation/row policy or the document-fact hook; move business
172
+ validation/effects to an explicit application boundary. Ordinary DTO reads still run
173
+ all selected-field checks, virtuals and presentation, with their normal errors.
174
+
175
+ ## M3. Remove handles; choose presentation or a fresh normal query
176
+
177
+ Before (historical):
178
+
179
+ ```text
180
+ service.pickAllowedFields(row, 'list', { documentAuthorization: context.documentAuthorization });
181
+ context.getDocumentAuthorization(child);
182
+ ```
183
+
184
+ `DocumentAuthorization`, the helper option, result-context handle and child lookup
185
+ are removed entirely. There is no public issuer, callback replacement, hidden DTO
186
+ symbol or result-keyed authority. A serialized/copied/forged old token is not
187
+ accepted. `getDocPermissions` reads metadata **DATA**, not authority; changing
188
+ `_permissions` or the non-enumerable presentation alias cannot grant access.
189
+
190
+ - **Presentation only:** use the already-filtered DTO, or `{ name: result.data.name }`.
191
+ This adds **0 reads / 0 document hooks** and does **not check current permissions**.
192
+ - **Raw output-only evaluation:** `pickAllowedFields`, `trimOutputFields` and
193
+ `genAllowedFields` evaluate current supplied values, captured global permissions,
194
+ frozen empty facts and optional explicit scoped server `outputFields`. They do
195
+ **0 DB operations / 0 document hooks**, no row admission, hidden refresh, virtuals
196
+ or omitted-field recovery. `!facts.suspended` may be true on empty facts; that is
197
+ **not proof** the current document is unsuspended.
198
+ - **Optional raw collection:** `pickAllowedFieldsMany` uses one deliberate capture
199
+ with separate isolated sources/stages/decisions, not N independently fresh picks.
200
+ It is not a default migration or a replacement for current document facts.
201
+ - **Current document-dependent authorization:** issue a **new normal service READ
202
+ or LIST**, with suitable selection/private hook inputs and normal row scope.
203
+ One single-row refresh in the workflow adds **1 read / 1 document hook**. It is
204
+ not a hidden helper cost or a transaction/freshness promise after completion.
205
+
206
+ Never replace an old handle with `unrestricted` policy, automatically grant all
207
+ old fields, or accept client-supplied grants. Explicit backend grants are a
208
+ separate deliberate server decision. Example scoped helper, no hidden query:
209
+
210
+ <!-- doc-example: partial -->
211
+
212
+ ```ts
213
+ import type { ModelRequest } from '@web-ts-toolkit/access-router/advanced';
214
+ async function presentContact(req: ModelRequest, contact: { email?: string; label?: string }) {
215
+ return req.macl
216
+ .getService<{ contacts: { email?: string; label?: string }[] }>('Employee')
217
+ .pickAllowedFields(contact, 'read', {
218
+ scopePath: ['contacts'],
219
+ authorization: { outputFields: { mode: 'grant', paths: ['contacts.label'] } },
220
+ }); // grant paths remain model-relative; this is not current-document authority
221
+ }
222
+ void presentContact;
223
+ ```
224
+
225
+ ### Optional raw collection, not N fresh calls
226
+
227
+ Use this only for backend-held records whose output policy deliberately needs one
228
+ capture. All row sources are owned before the first field predicate; duplicate
229
+ references share no decisions. Actor/model/catalog/config/scope/output policy are
230
+ captured before awaits or predicates. Later actor-view/schema/options changes affect
231
+ the **next call**, not later rows; setting `req.user` alone does not refresh initialized
232
+ permissions. Closures, live request state and native effects are not frozen.
233
+
234
+ The following three exact target blocks are compiled and executed by installed
235
+ consumer tests. They are application functions, not new library exports.
236
+
237
+ <!-- doc-example: partial -->
238
+
239
+ ```ts
240
+ import type { FilteredOutput, OutputFieldOptions } from '@web-ts-toolkit/access-router';
241
+ import type { ModelRequest } from '@web-ts-toolkit/access-router/advanced';
242
+ export type Contact = { label: string; email: string; address: { city: string } };
243
+ type Employee = { contacts: Contact[] };
244
+ // Server-owned only: NEVER copy these controls from request input.
245
+ const contactPolicy: OutputFieldOptions<Employee> = {
246
+ scopePath: ['contacts'],
247
+ authorization: { outputFields: { mode: 'grant', paths: ['contacts.label'] } },
248
+ };
249
+ export async function rawBefore(req: ModelRequest, rows: readonly Contact[]) {
250
+ const service = req.macl.getService<Employee>('Employee');
251
+ const output = [];
252
+ for (const row of rows) output.push(await service.pickAllowedFields(row, 'list', contactPolicy));
253
+ return output; // N independently fresh captures; existing Promise<T> does not prove field presence
254
+ }
255
+ export async function rawMany(
256
+ req: ModelRequest,
257
+ rows: readonly Contact[],
258
+ ): Promise<readonly FilteredOutput<Contact>[]> {
259
+ return req.macl.getService<Employee>('Employee').pickAllowedFieldsMany(rows, 'list', contactPolicy);
260
+ // ONE capture, not semantically equivalent to rawBefore. Every nested field can be omitted.
261
+ }
262
+ ```
263
+
264
+ The scope uses ordinary response segments; grant paths stay **model-relative**
265
+ (`contacts.label`). One output-only policy applies to the whole call; row/input/
266
+ related controls, selection, `purpose`, handles/tokens and modes reject. No DB,
267
+ document hooks, virtuals, row/operation/target checks, reference provenance or omitted
268
+ value restoration is added. Negative EMPTY predicates do not prove current facts.
269
+
270
+ If existing DTOs only need a presentation subset, normally use **zero helpers**:
271
+
272
+ <!-- doc-example: partial -->
273
+
274
+ ```ts
275
+ export function presentationSubset(rows: readonly { readonly name?: string }[]) {
276
+ // Already-filtered DATA only. No current-permission assertion or omitted-field restoration.
277
+ return rows.map((row) => (Object.hasOwn(row, 'name') ? { name: row.name } : {}));
278
+ // Subset adds 0 reads / 0 document hooks / 0 helper captures.
279
+ }
280
+ ```
281
+
282
+ For current document-dependent facts, use a **new normal LIST**, not either raw
283
+ recipe or an output grant. Configure `alwaysSelectFields`/declared dependencies for
284
+ private hook inputs on the model; keep normal row policy. After an earlier LIST:
285
+
286
+ <!-- doc-example: partial -->
287
+
288
+ ```ts
289
+ import type { ModelRequest } from '@web-ts-toolkit/access-router/advanced';
290
+ type Employee = { tenantId: string; name: string; salary: number; ownerId: string };
291
+ export async function currentList(req: ModelRequest, tenantId: string) {
292
+ const current = await req.macl.getService<Employee>('Employee').find(
293
+ { tenantId }, // trusted application filter, still subject to normal row policy
294
+ { select: ['name', 'salary', '-_id'], limit: 100 },
295
+ { includePermissions: false, includeFieldPermissions: false },
296
+ );
297
+ if (!current.success) throw new Error(`Current LIST failed: ${current.code}`);
298
+ return current.data; // +1 explicit LIST; configured document hook runs per returned row
299
+ }
300
+ ```
301
+
302
+ The installed runtime test changes private owner facts between LISTs: presentation
303
+ adds no work, while the fresh two-row LIST adds one query/two hooks and removes the
304
+ now-denied salary. This is not a transaction or freshness guarantee after completion.
305
+
306
+ Collection admission requires an ordinary dense Array of **0–1,000** positions;
307
+ readonly/frozen is accepted, nullish positions preserved. Proxies reject before
308
+ traps; subclasses, holes, accessor/non-enumerable indices, extra own strings/symbols
309
+ and iterables reject without reading an iterator. Empty input still validates all
310
+ controls/model/policy/catalog. Every row remains isolated in both source modes.
311
+ Separate per-row source/fact/view/selected **20,000-slot / depth-100** owners remain,
312
+ with native/embedded/metadata/copy/wire work sharing the relevant remainder.
313
+
314
+ One **200,000 work-unit / 16 MiB cumulative payload** ledger covers the entire call's
315
+ **router-controlled admission, staging, traversal and explicit copies**, including
316
+ configuration/preparation and all rows/phases. No row/chunk transition resets it.
317
+ **Excluded:** opaque Mongoose/native normalization internals and dependency-owned
318
+ allocations/traversals, arbitrary trusted closure/callback effects and engine
319
+ enumeration costs. This is **not** a total-memory/RSS, whole-normalization, CPU-operation
320
+ or sandbox cap. Canonical normalization can copy 17 MiB and discard it into a tiny
321
+ admitted row. A returned oversized normalized value rejects **before the next explicit
322
+ router copy**; explicit router-owned native/wire preparation is not excluded.
323
+
324
+ Bounded row scheduling uses the minimum row/scheduler/shared-hook-gate limits,
325
+ retaining FIFO/reentry/depth, stable outer order and per-row field order/sync-until-async
326
+ evaluation. Structural/native/router-budget poison is one controlled **400**, even if
327
+ caught: close admission, drain admitted library work, clear state and prohibit late
328
+ publication. Ordinary predicate-body failures omit fields. There is no partial result,
329
+ callback-side-effect rollback, automatic retry, persistence permit while waiting or
330
+ untracked detached-closure wait. Caller chunking starts new fresh operations, not one
331
+ atomic batch. Existing singles retain their independent freshness and error contracts.
332
+
333
+ The new root/advanced **type-only** `FilteredOutput<T>` makes string properties
334
+ recursively optional/readonly, including `_id`. Arrays include null/undefined without
335
+ tuple/cardinality inference; string Maps become readonly records; Date/RegExp/Buffer
336
+ use canonical base types. Other BSON/hydrated values (including string-ID documents),
337
+ unknown inputs and branches at depth eight are `unknown`: narrow/validate them.
338
+ Readonly is not native freezing, an input validator, exact field inference or authority.
339
+ Do not assign filtered rows to required `T[]` or cast away omissions. Both service
340
+ getters and Core expose the method (Core prepends `modelName`); DataService, HTTP and
341
+ clients do not. No new default migration, H3 replacement, gate waiver or speedup claim.
342
+
343
+ ### Complete public workflow: facts, helper costs and checked refresh
344
+
345
+ Compile as `.mts` or `.cts` with TypeScript NodeNext/Node16, or bundle using public
346
+ imports. Requires Node >=22, Express >=5, Mongoose >=8 and MongoDB. The example
347
+ creates/drops only its unique database and closes its server/connection. The
348
+ server-owned example actor is not an authentication implementation.
349
+
350
+ <!-- doc-example: complete-runtime -->
351
+
352
+ ```ts
353
+ import assert from 'node:assert/strict';
354
+ import { randomUUID } from 'node:crypto';
355
+ import { once } from 'node:events';
356
+ import type { Server } from 'node:http';
357
+ import express from 'express';
358
+ import mongoose from 'mongoose';
359
+ import { createAccessRuntime, type DocumentGrants, type FieldPermissionHook } from '@web-ts-toolkit/access-router';
360
+ import type { ModelRequest } from '@web-ts-toolkit/access-router/advanced';
361
+
362
+ async function runOwnedAuthorizationExample() {
363
+ const connection = await mongoose
364
+ .createConnection(process.env.MONGODB_URL ?? 'mongodb://127.0.0.1:27017', {
365
+ dbName: `owned_authorization_${randomUUID().replaceAll('-', '')}`,
366
+ })
367
+ .asPromise();
368
+ let server: Server | undefined;
369
+ let reads = 0,
370
+ hooks = 0;
371
+ const observations: unknown[] = [];
372
+ try {
373
+ const api = createAccessRuntime();
374
+ api.setGlobalOptions({ globalPermissions: () => ['reader'], logger: { warn() {} } });
375
+ type Employee = {
376
+ name: string;
377
+ salary: number;
378
+ bonus: number;
379
+ allowance: number;
380
+ ownerId: string;
381
+ visible: boolean;
382
+ };
383
+ const schema = new mongoose.Schema<Employee>({
384
+ name: String,
385
+ salary: Number,
386
+ bonus: Number,
387
+ allowance: Number,
388
+ ownerId: String,
389
+ visible: Boolean,
390
+ });
391
+ schema.pre('findOne', function () {
392
+ reads++;
393
+ });
394
+ const EmployeeModel = connection.model('MigrationEmployee', schema);
395
+ const salaryRule: FieldPermissionHook = function (permissions, facts) {
396
+ assert.ok(Object.isFrozen(facts));
397
+ return permissions.has('isHR') || facts.canReadSalary === true;
398
+ };
399
+ async function loadMembership(request: ModelRequest, doc: unknown) {
400
+ assert.ok(request.macl); // the original initialized request, not an elevated actor
401
+ return { canReadSalary: doc !== null && typeof doc === 'object' && 'ownerId' in doc && doc.ownerId === 'alice' };
402
+ }
403
+ const router = api.createRouter(EmployeeModel, {
404
+ basePath: '/employees',
405
+ operationAccess: { read: true },
406
+ hydration: { findById: 'lean' },
407
+ modelPermissionPrefix: 'doc:',
408
+ alwaysSelectFields: ['ownerId'],
409
+ stripPermissionsField: true,
410
+ baseFilter: { read: () => ({ visible: true }) },
411
+ permissionSchema: {
412
+ name: 'reader',
413
+ salary: { read: salaryRule },
414
+ bonus: { read: 'reader doc:canReadSalary' }, // AND
415
+ allowance: { read: ['isHR', 'doc:canReadSalary'] }, // OR
416
+ },
417
+ docPermissions: {
418
+ async read(doc, _permissions, context): Promise<DocumentGrants> {
419
+ hooks++;
420
+ assert.ok(Object.isFrozen(context));
421
+ assert.equal('currentDocument' in context, false);
422
+ const membership = await loadMembership(this, doc);
423
+ return { canReadSalary: membership.canReadSalary === true };
424
+ },
425
+ },
426
+ });
427
+ const row = await EmployeeModel.create({
428
+ name: 'Ada',
429
+ salary: 100,
430
+ bonus: 10,
431
+ allowance: 5,
432
+ ownerId: 'alice',
433
+ visible: true,
434
+ });
435
+ function initializedRequest(req: express.Request): req is ModelRequest {
436
+ return 'macl' in req; // the owning router middleware must have run first
437
+ }
438
+ router.router.post('/verify', async (req, res) => {
439
+ assert.ok(initializedRequest(req), 'Missing owning router middleware');
440
+ const service = router.getService(req);
441
+ const before = { reads, hooks };
442
+ const query = { select: ['name', 'salary', 'bonus', 'allowance', '-_id'] };
443
+ const quiet = { includePermissions: false, includeFieldPermissions: false };
444
+ const first = await service.findById(String(row._id), query, quiet);
445
+ if (!first.success) throw new Error(`Initial read failed: ${first.code}`);
446
+ assert.deepEqual(first.data, { name: 'Ada', salary: 100, bonus: 10, allowance: 5 });
447
+ assert.deepEqual({ reads, hooks }, { reads: before.reads + 1, hooks: before.hooks + 1 });
448
+ assert.deepEqual({ name: first.data.name }, { name: 'Ada' }); // presentation DATA, not reauthorization
449
+ assert.deepEqual(await service.pickAllowedFields(first.data, 'read'), { name: 'Ada' });
450
+ assert.deepEqual(
451
+ await service.pickAllowedFields(first.data, 'read', {
452
+ authorization: { outputFields: { mode: 'grant', paths: ['salary', 'bonus', 'allowance'] } },
453
+ }),
454
+ first.data,
455
+ ); // explicit server-only output decision, NOT replacement handle authority
456
+ assert.deepEqual({ reads, hooks }, { reads: before.reads + 1, hooks: before.hooks + 1 });
457
+ // Simulate independent application change. No DTO/context can keep this fresh.
458
+ await EmployeeModel.collection.updateOne({ _id: row._id }, { $set: { ownerId: 'bob' } });
459
+ const current = await service.findById(String(row._id), query, quiet);
460
+ if (!current.success) throw new Error(`Refresh failed: ${current.code}`);
461
+ assert.deepEqual(current.data, { name: 'Ada' });
462
+ assert.equal(first.data.salary, 100); // the old DTO remains DATA, not a current certificate
463
+ assert.deepEqual({ reads, hooks }, { reads: before.reads + 2, hooks: before.hooks + 2 });
464
+ observations.push({
465
+ mode: api.getModelOption(EmployeeModel.modelName, 'readAuthorizationMode'),
466
+ initial: { reads: 1, hooks: 1 },
467
+ helperExtra: { reads: 0, hooks: 0 },
468
+ currentExtra: { reads: 1, hooks: 1 },
469
+ });
470
+ await EmployeeModel.collection.updateOne({ _id: row._id }, { $set: { ownerId: 'alice' } });
471
+ res.json({ ok: true });
472
+ });
473
+ const app = express();
474
+ app.use(express.json());
475
+ app.use(router.routes);
476
+ server = app.listen(0, '127.0.0.1');
477
+ await once(server, 'listening');
478
+ const address = server.address();
479
+ assert.ok(address && typeof address !== 'string');
480
+ const statuses: number[] = [];
481
+ for (const mode of ['isolated', 'trusted'] as const) {
482
+ api.setModelOption(EmployeeModel.modelName, 'readAuthorizationMode', mode);
483
+ const response: globalThis.Response = await fetch(`http://127.0.0.1:${address.port}/employees/verify`, {
484
+ method: 'POST',
485
+ });
486
+ statuses.push(response.status);
487
+ assert.equal(response.status, 200, await response.text());
488
+ }
489
+ // Untyped/JS wire control is controlled 400 BEFORE a DB read/hook, even false.
490
+ const beforeInvalid = { reads, hooks };
491
+ const invalid = await fetch(`http://127.0.0.1:${address.port}/employees/__query/${row._id}`, {
492
+ method: 'POST',
493
+ headers: { 'content-type': 'application/json' },
494
+ body: JSON.stringify({ select: ['name'], options: { readAuthorizationMode: false } }),
495
+ });
496
+ statuses.push(invalid.status);
497
+ assert.equal(invalid.status, 400, await invalid.text());
498
+ assert.deepEqual({ reads, hooks }, beforeInvalid);
499
+ api.setModelOption(EmployeeModel.modelName, 'readAuthorizationMode', 'isolated'); // NEW calls only
500
+ console.log(JSON.stringify({ guide: 'owned-authorization', statuses, observations, reads, hooks }));
501
+ } finally {
502
+ if (server)
503
+ await new Promise<void>((resolve, reject) => server!.close((error) => (error ? reject(error) : resolve())));
504
+ await connection.dropDatabase();
505
+ await connection.close();
506
+ }
507
+ }
508
+ void runOwnedAuthorizationExample().catch((error) => {
509
+ console.error(error);
510
+ process.exitCode = 1;
511
+ });
512
+ ```
513
+
514
+ ### Model conditions are facts-only, not an implicit DTO read
515
+
516
+ `guard({ modelName, id, condition })` consumes a **private fresh read stage**, not
517
+ metadata or post-decorate output. A visible row and a fresh owning document hook are
518
+ required even for a global-only condition. Strings/arrays keep the same grammar and
519
+ look up global permission OR a literal-true document fact, without field prefixes.
520
+ Stripping, exposing no keys or forging metadata cannot authorize the guard.
521
+
522
+ The normal public by-ID defaults, identifier/query/row/sort admission, root DB
523
+ projection, hydration and pre-output hook source remain the same. Ordinary/private
524
+ populate preparation needed for that source retains target-local operation/row/mode
525
+ admission and private-input masks. Include descriptors still undergo preflight, but
526
+ **output-only include attachment queries and target DTO hooks do not run**.
527
+
528
+ No DTO, field metadata, selected-output traversal, embedded/target DTO finalization,
529
+ virtual getter, decoration or task is built/run. Thus an invalid virtual/output-only
530
+ native return, throwing decorator or output-only include error no longer vetoes a
531
+ guard. Source/fact/necessary-dependency structural failures still fail with controlled
532
+ 400 and cannot be caught to authorize. Ordinary denied/missing guards remain 401.
533
+
534
+ A successful visible-row guard normally costs one root read/one root hook and **zero
535
+ output-field callbacks**. An admitted miss may retry once using the captured LIST
536
+ operation gate and initiating READ source mode; true and false conditions are both
537
+ terminal, as are 400/403. Required dependency queries may add reads. This request-only
538
+ service path, like direct `_read`, does **not** run the generated HTTP route's initial
539
+ READ operation gate. Compose the appropriate existing route/global guard when both
540
+ checks are required; generated routes retain their operation checks unchanged.
541
+
542
+ If the caller also needs data or output/business effects, perform a separate ordinary
543
+ authorized read, check `result.success`, and handle its errors. That adds its normal
544
+ read/hook/output cost; the library does not silently fetch a second DTO for a guard.
545
+
546
+ <!-- doc-example: partial -->
547
+
548
+ ```ts
549
+ import { guard } from '@web-ts-toolkit/access-router';
550
+ import type { ModelRequest } from '@web-ts-toolkit/access-router/advanced';
551
+ const ownerCondition = guard({ modelName: 'Employee', id: { type: 'param', key: 'id' }, condition: 'owner' });
552
+ async function readEmployeeForBusinessWork(req: ModelRequest, id: string) {
553
+ // Explicit additional ordinary read, not a reusable guard result/capability.
554
+ const result = await req.macl.getPublicService('Employee')._read(id, { select: ['name'] });
555
+ if (!result.success) throw new Error(`Employee read failed: ${result.code}`);
556
+ return result.data;
557
+ }
558
+ void ownerCondition;
559
+ void readEmployeeForBusinessWork;
560
+ ```
561
+
562
+ Related targets use **their own** captured policy/facts/mode; the unchanged
563
+ README runnable service/related example demonstrates separate scoped policies.
564
+
565
+ ## M4. Replace ten switches with two independent server modes
566
+
567
+ Before: combinations of comparison/copy/fast-path booleans. There is **no one-to-one
568
+ mapping** for old mixed configurations and no dormant prerequisite combination.
569
+
570
+ <!-- doc-example: partial -->
571
+
572
+ ```ts
573
+ import { createAccessRuntime } from '@web-ts-toolkit/access-router';
574
+ const api = createAccessRuntime();
575
+ api.setDefaultModelOptions({ readAuthorizationMode: 'isolated', listAuthorizationMode: 'isolated' });
576
+ api.setModelOptions('Employee', { readAuthorizationMode: 'isolated', listAuthorizationMode: 'trusted' });
577
+ api.setModelOptions('Payroll', { readAuthorizationMode: 'isolated', listAuthorizationMode: 'isolated' });
578
+ api.setModelOption('Employee', 'listAuthorizationMode', undefined); // restore live default inheritance
579
+ api.setDefaultModelOption('listAuthorizationMode', 'isolated');
580
+ ```
581
+
582
+ Model/router/default bulk and exact setters accept only literal `isolated` /
583
+ `trusted`, or `undefined` restoration. Omission preserves an override; explicit
584
+ undefined clears it. Defaults inherit live for future calls; bulk failure is
585
+ atomic. `getModelOption` and `getModelOptions` expose effective modes, while a
586
+ router's `options` is its construction-time snapshot. Logger failures cannot abort
587
+ committed configuration; warn once per effective owner/access transition into
588
+ trusted, not on every request or repeated assignment.
589
+
590
+ Every retired key below rejects **by presence**, including `false`, `undefined`,
591
+ inherited and non-enumerable slots. Delete the keys, not just their truthy values:
592
+
593
+ 1. `unsafeSkipListDocumentSnapshotChecks`
594
+ 2. `unsafeSkipReadDocumentSnapshotChecks`
595
+ 3. `unsafeSkipListOutputSnapshotChecks`
596
+ 4. `unsafeSkipReadOutputSnapshotChecks`
597
+ 5. `unsafeSkipListNestedDocumentSnapshotChecks`
598
+ 6. `unsafeSkipReadNestedDocumentSnapshotChecks`
599
+ 7. `unsafeSkipListInitialOutputSnapshotCopy`
600
+ 8. `unsafeSkipReadInitialOutputSnapshotCopy`
601
+ 9. `unsafeUseListAuthorizationFastPath`
602
+ 10. `unsafeUseReadAuthorizationFastPath`
603
+
604
+ Untyped JavaScript is checked too. This executable error example deliberately
605
+ tests rejected inputs; it is not an adapter that translates old flags:
606
+
607
+ <!-- doc-example: javascript-errors -->
608
+
609
+ ```js
610
+ import assert from 'node:assert/strict';
611
+ import mongoose from 'mongoose';
612
+ import { createAccessRuntime } from '@web-ts-toolkit/access-router';
613
+ const api = createAccessRuntime();
614
+ const Employee = mongoose.model('Employee', new mongoose.Schema({ name: String }));
615
+ api.registerModelInstance('Employee', Employee); // configuration needs a real registered model; no DB connection here
616
+ const retired = [
617
+ 'unsafeSkipListDocumentSnapshotChecks',
618
+ 'unsafeSkipReadDocumentSnapshotChecks',
619
+ 'unsafeSkipListOutputSnapshotChecks',
620
+ 'unsafeSkipReadOutputSnapshotChecks',
621
+ 'unsafeSkipListNestedDocumentSnapshotChecks',
622
+ 'unsafeSkipReadNestedDocumentSnapshotChecks',
623
+ 'unsafeSkipListInitialOutputSnapshotCopy',
624
+ 'unsafeSkipReadInitialOutputSnapshotCopy',
625
+ 'unsafeUseListAuthorizationFastPath',
626
+ 'unsafeUseReadAuthorizationFastPath',
627
+ ];
628
+ for (const key of retired) {
629
+ for (const options of [
630
+ { [key]: false },
631
+ { [key]: undefined },
632
+ Object.create({ [key]: false }),
633
+ Object.defineProperty({}, key, { value: undefined, enumerable: false }),
634
+ ])
635
+ assert.throws(() => api.setModelOptions('Employee', options), /was removed; migrate/);
636
+ }
637
+ for (const mode of [true, false, null, 1, 'false', {}]) {
638
+ assert.throws(() => api.setModelOption('Employee', 'readAuthorizationMode', mode), /literal isolated or trusted/);
639
+ }
640
+ api.setModelOptions('Employee', { readAuthorizationMode: 'isolated', listAuthorizationMode: 'isolated' });
641
+ assert.throws(
642
+ () =>
643
+ api.setModelOptions('Employee', {
644
+ readAuthorizationMode: 'trusted',
645
+ listAuthorizationMode: false,
646
+ }),
647
+ /literal isolated or trusted/,
648
+ );
649
+ assert.equal(api.getModelOption('Employee', 'readAuthorizationMode'), 'isolated'); // bulk was atomic
650
+ assert.throws(() => api.setGlobalOption('readAuthorizationMode', 'trusted'), /server model\/default-model/);
651
+ console.log(JSON.stringify({ retiredPresenceRejections: 40, invalidModes: 6, atomicBulk: true }));
652
+ ```
653
+
654
+ The new keys are also prohibited in HTTP/query/body/root-batch, per-call/helper,
655
+ method-default, include/populate and subquery **authority namespaces**. Persisted
656
+ business data/filter fields with the same names remain inert ordinary data.
657
+
658
+ Capture happens before hooks/awaits. Embedded scopes inherit a genuine owning
659
+ model; related targets select their own model/access mode plus private policy and
660
+ facts. A trusted parent cannot lower an isolated target. READ-to-LIST retry keeps
661
+ the initiating READ mode and creates a fresh stage. Independent callback service
662
+ calls are fresh calls. Writes/write-derived output, new templates and dedicated
663
+ subdocument origins are **always isolated**, not trusted because a response looks
664
+ like a read.
665
+
666
+ For decorators, configure modes on `@Router`/`@RouterOptions`, or factory
667
+ `defaultModelOptions`, never request input. Decorated hook `this` is the **class
668
+ instance**; obtain the original request with `@Request()`. See the matching
669
+ access-router-deco README's executable owned-authorization module.
670
+
671
+ Roll out a tested matching application/library revision, default isolated, inspect
672
+ workload behavior and then opt individual READ/LIST owners into trusted deliberately.
673
+ Switching back to isolated affects **new calls only**; in-flight captures do not
674
+ change. Deployment rollback requires a tested matching application **and library**
675
+ revision, not adding removed flags to this version or assuming mixed rolling safety.
676
+
677
+ ## M5. Mechanical checklist, preserved APIs and errors
678
+
679
+ Also audit model guards semantically: search for `_read` overrides and field/getter/
680
+ decorate/task/include effects used as business checks. Those output effects no longer
681
+ intercept a guard. Search alone cannot identify a security dependency on their side
682
+ effects. Keep such decisions in operation/row/fact hooks, or explicitly run and check
683
+ a normal DTO read at the application boundary (see M2/M3).
684
+
685
+ Search application configuration, computed/spread defaults, wrappers, decorators,
686
+ tests, generated clients and dependency adapters for:
687
+
688
+ - All ten M4 names; also remove unshipped `unsafeFuseListOutputPublication` /
689
+ `unsafeFuseReadOutputPublication` if copied from a prototype (never an API).
690
+ - `DocumentAuthorization`, `documentAuthorization`, `getDocumentAuthorization`;
691
+ old helper options and child-handle caches/lookups/serialization/replay.
692
+ - Every removed M2 output member, `resolvedQuery.filter`, `ModelHookContext` /
693
+ `ModelHook` / `ModelListHook` annotations used for output callbacks; use the
694
+ diagnostic/output types instead, **not** for legitimate lifecycle hooks.
695
+ - Rich or mutated docPermissions returns, identity comparisons, closures retaining
696
+ source/context/facts and document-dependent raw-helper predicates.
697
+ - Positional `baseFields`, `skipChecks`, `subPaths`, old `overrides`, private
698
+ prepared/execution options and deep `src`/`dist` imports. Named helpers accept
699
+ `OutputFieldOptions` / `AllowedOutputFieldOptions`, not legacy overloads.
700
+
701
+ Search cannot decide whether a use is presentation or current authority, whether
702
+ `!facts.suspended` incorrectly admits empty facts, whether dependencies are fetched,
703
+ whether expensive unused facts are worth loading, or whether side effects belonged
704
+ in a real write. Review those semantics explicitly. No casts, `any` escape hatches
705
+ or suppressed declaration errors are a migration strategy.
706
+
707
+ Unchanged: `authorization.rows`, `inputFields`, `outputFields`, `related` are
708
+ independent server dimensions; parent grants do not elevate target operations/rows/
709
+ fields. Input grants do not grant output. Field boolean/string/array grammar,
710
+ selection/exclusions **versus authority**, private hook/dependency fetches,
711
+ hydration/native support, raw-parent business APIs and mutable persistence hooks
712
+ remain. Supported native/hydrated values can normalize at their actual boundary;
713
+ that is not arbitrary native support or identical native side effects in both modes.
714
+ Permission metadata remains **request-user facts**, never backend grants. Strip/
715
+ exposure/include flags affect metadata, not internal fact resolution or enforcement.
716
+
717
+ `FieldPermissionHook` has `(permissions, facts)` and original-request `this`;
718
+ `GuardHook`/operationAccess still has **one permissions argument**. Root and
719
+ `/advanced` export the same new types (`AuthorizationMode`, `DocumentGrants`,
720
+ `FieldPermissionHook`, `FieldValidation`, `ModelOutputContext`, `ModelOutputHook`,
721
+ `ModelOutputListHook`); `/processors` remains data transformation, not an issuer.
722
+ `FilteredOutput<T>` is also available from root and `/advanced`, only as a type.
723
+ There are no new entrypoints or legacy aliases. ESM imports select `.d.mts` +
724
+ `.mjs`; CJS requires select `.d.ts` + `.js` (factory under `.default` / named
725
+ `createAccessRuntime`). Use strict Bundler, Node16 or NodeNext module resolution.
726
+ Actual minimum/current peer workflows are tested; minimum-peer declaration checking
727
+ retains its existing `skipLibCheck` distinction, current peers check declarations.
728
+
729
+ ### TypeScript before: intentionally rejected, compile separately
730
+
731
+ This exact old-style source is a **negative fixture**, not a target example. Do
732
+ not compile it alongside the positive examples or suppress these errors:
733
+
734
+ <!-- doc-example: expected-error -->
735
+
736
+ ```ts
737
+ import type {
738
+ DocumentAuthorization,
739
+ ModelRouterOptions,
740
+ ModelOutputContext,
741
+ OutputFieldOptions,
742
+ } from '@web-ts-toolkit/access-router';
743
+ const oldMode: ModelRouterOptions = { unsafeUseReadAuthorizationFastPath: false };
744
+ const invalidMode: ModelRouterOptions = { readAuthorizationMode: true };
745
+ const rich: ModelRouterOptions = { docPermissions: () => ({ membership: { owner: true } }) };
746
+ declare const context: ModelOutputContext;
747
+ context.currentDocument;
748
+ context.resolvedQuery?.filter;
749
+ context.getDocumentAuthorization({});
750
+ const oldHelper: OutputFieldOptions = { documentAuthorization: context };
751
+ void [oldMode, invalidMode, rich, oldHelper];
752
+ export type OldHandle = DocumentAuthorization;
753
+ ```
754
+
755
+ ### Error reference (also applies to untyped JavaScript)
756
+
757
+ | Input / failure | Result and action |
758
+ | ----------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
759
+ | 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. |
760
+ | Invalid mode (`true`, `false`, null, number, arbitrary string/object) | Reject, no coercion; failed bulk setter publishes none of the update. |
761
+ | Fulfilled invalid/rich/protected/accessor/proxy/over-budget facts | Whole operation 400, no partial result; fix the hook return. |
762
+ | 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. |
763
+ | Field predicate throw | Denies that field; operation guard remains request-only. |
764
+ | Getter body throw / `undefined` | Omits that field. |
765
+ | 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. |
766
+ | Ordinary row miss / guard denial | Normal checked error result (`not_found`, or guard 401); do not treat it as successful data. |
767
+ | Post-save output/fact/budget failure | Controlled 400 **may follow persistence**. No rollback and **no automatic retry**; reconcile persisted business state explicitly. |
768
+
769
+ Selected root-row work retains inclusive **20,000 slots / depth 100**, shared with
770
+ embedded/related/native/metadata output, including denied/protected encountered
771
+ keys before reading values. No child/helper/native transition replenishes it.
772
+ Document-source, facts and explicit callback views have separate bounded owners.
773
+ No source profile disables row/operation/field/target rules or the original actor.
774
+
775
+ Untyped JavaScript uses the same checked result/error handling as the workflow:
776
+ `{ options: { readAuthorizationMode: false } }` on an HTTP request returns 400
777
+ before reads/hooks. Do not depend on TypeScript alone to protect a wire boundary.