@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/advanced.mjs CHANGED
@@ -47,53 +47,999 @@ import JsonRouter3 from "@web-ts-toolkit/express-json-router";
47
47
  import mongoose from "mongoose";
48
48
 
49
49
  // src/validation/public-admission.ts
50
- import JsonRouter from "@web-ts-toolkit/express-json-router";
50
+ import JsonRouter2 from "@web-ts-toolkit/express-json-router";
51
+ import { types as types6 } from "util";
51
52
  import { isPlainObject } from "@web-ts-toolkit/utils";
52
53
 
53
- // src/acl/unsafe-snapshot-options.ts
54
- var unsafeSnapshotCheckOptions = [
54
+ // src/acl/output-work-ledger.ts
55
+ import { AsyncLocalStorage } from "async_hooks";
56
+
57
+ // src/acl/authorization-snapshot.ts
58
+ import { types as types4 } from "util";
59
+ import { mongo as mongo2 } from "mongoose";
60
+ import JsonRouter from "@web-ts-toolkit/express-json-router";
61
+
62
+ // src/acl/field-catalog.ts
63
+ import { types } from "util";
64
+ var ownedCatalogs = /* @__PURE__ */ new WeakMap();
65
+ function readOwnedAuthorizationCatalogWork(value) {
66
+ return ownedCatalogs.get(value);
67
+ }
68
+ var safeSegment = (part) => !!part && part !== "sub" && !["__proto__", "constructor", "prototype", "_doc", "__v"].includes(part) && !/^[+$-]|[\s*]/.test(part) && !part.includes("[") && !part.includes("]") && !/^\d+$/.test(part) && !hasControlCharacter(part);
69
+ function hasControlCharacter(part) {
70
+ for (let index = 0; index < part.length; index++) {
71
+ const code = part.charCodeAt(index);
72
+ if (code < 32 || code === 127) return true;
73
+ }
74
+ return false;
75
+ }
76
+ function prepareCatalogPathParts(path) {
77
+ const ledger = currentOutputWorkLedger();
78
+ if (ledger) {
79
+ let segments = 1;
80
+ for (let index = 0; index < path.length; index++) if (path.charCodeAt(index) === 46) segments++;
81
+ debitOutputWork(ledger, segments);
82
+ debitOutputPayload(ledger, path);
83
+ }
84
+ }
85
+ function catalogPathParts(path) {
86
+ prepareCatalogPathParts(path);
87
+ return path.split(".");
88
+ }
89
+ var isSafeOutputPath = (path) => catalogPathParts(path).every(safeSegment);
90
+ var inputControlSegments = /* @__PURE__ */ new Set([
91
+ "_permissions",
92
+ "_view",
93
+ "_edit",
94
+ "documentAuthorization",
95
+ "documentAuthorizationStage",
96
+ "resolvedAuthorization",
97
+ "execution",
98
+ "executionContext",
99
+ "serviceExecutionContext",
100
+ "preparedQuery",
101
+ "preparedFilter",
102
+ "preparedModelQuery",
103
+ "resolvedIdentifier",
104
+ "skipParsing",
105
+ "skipAuthorization",
106
+ "alreadyAuthorized"
107
+ ]);
108
+ function isSafeInputPath(path, requestIdentity = false) {
109
+ return isSafeOutputPath(path) && path.split(".").every((part) => !inputControlSegments.has(part) && (requestIdentity || part !== "_id"));
110
+ }
111
+ function matchesCatalogPattern(pattern, path, descendants = false) {
112
+ debitOutputWork();
113
+ if (typeof pattern === "string" && typeof path === "string" && !pattern.includes("$*")) {
114
+ return pattern === path || !!descendants && path.startsWith(pattern) && path[pattern.length] === ".";
115
+ }
116
+ prepareCatalogPathParts(pattern);
117
+ const expected = pattern.split(".");
118
+ prepareCatalogPathParts(path);
119
+ const actual = path.split(".");
120
+ return (descendants ? actual.length >= expected.length : actual.length === expected.length) && expected.every((part, index) => part === "$*" || part === actual[index]);
121
+ }
122
+ function captureAuthorizationFieldCatalog(schema, virtuals, documentPermissionField = "_permissions") {
123
+ debitOutputPayload(currentOutputWorkLedger(), documentPermissionField);
124
+ const paths = /* @__PURE__ */ new Set();
125
+ const containers = /* @__PURE__ */ new Set();
126
+ const opaque = /* @__PURE__ */ new Set();
127
+ const references = /* @__PURE__ */ new Set();
128
+ const virtualPaths = /* @__PURE__ */ new Set();
129
+ const virtualScopes = /* @__PURE__ */ new Set();
130
+ const schemaVirtualPaths = /* @__PURE__ */ new Set();
131
+ const arrays = /* @__PURE__ */ new Set();
132
+ const protectedPaths = /* @__PURE__ */ new Set([documentPermissionField, "_doc", "$__", "__v"]);
133
+ const add = (path) => {
134
+ debitOutputWork();
135
+ debitOutputPayload(currentOutputWorkLedger(), path);
136
+ if (catalogPathParts(path).every((part) => part === "$*" || safeSegment(part))) paths.add(path);
137
+ };
138
+ const ancestors = (path) => {
139
+ const parts = catalogPathParts(path);
140
+ for (let n = 1; n < parts.length; n++) {
141
+ debitOutputWork(void 0, n);
142
+ const parent = prepareOutputWorkString(parts.slice(0, n));
143
+ add(parent);
144
+ containers.add(parent);
145
+ }
146
+ };
147
+ const visitType = (type, path, active) => {
148
+ debitOutputWork();
149
+ add(path);
150
+ ancestors(path);
151
+ const element = type.$embeddedSchemaType ?? type.embeddedSchemaType ?? type.caster;
152
+ if (type.instance === "Array" || type.$isMongooseDocumentArray) arrays.add(path);
153
+ if (type.options?.ref || type.options?.refPath || element?.options?.ref || element?.options?.refPath) {
154
+ references.add(path);
155
+ return;
156
+ }
157
+ if (type.$isSchemaMap || type.instance === "Map") {
158
+ const value = type.$__schemaType;
159
+ if (value) visitType(value, prepareOutputWorkString([path, "$*"]), active);
160
+ else opaque.add(path);
161
+ containers.delete(path);
162
+ return;
163
+ }
164
+ const child = type.schema ?? element?.schema;
165
+ if (child) {
166
+ containers.add(path);
167
+ if (!active.has(child)) visitSchema(child, path, /* @__PURE__ */ new Set([...active, child]));
168
+ return;
169
+ }
170
+ if (type.instance === "Mixed" || element?.instance === "Mixed") opaque.add(path);
171
+ };
172
+ const visitSchema = (current, prefix, active) => {
173
+ debitOutputWork();
174
+ const version = current.options.versionKey;
175
+ if (typeof version === "string") protectedPaths.add(prefix ? `${prefix}.${version}` : version);
176
+ for (const name of Object.keys(current.virtuals)) {
177
+ debitOutputWork();
178
+ schemaVirtualPaths.add(prefix ? prepareOutputWorkString([prefix, name]) : name);
179
+ }
180
+ for (const [name, raw] of Object.entries(current.paths)) {
181
+ debitOutputWork();
182
+ if (name.includes("$*")) continue;
183
+ visitType(raw, prefix ? prepareOutputWorkString([prefix, name]) : name, active);
184
+ }
185
+ };
186
+ visitSchema(schema, "", /* @__PURE__ */ new Set([schema]));
187
+ const copyPaths = (values) => {
188
+ debitOutputWork(void 0, 1 + (Array.isArray(values) ? values.length : values.size));
189
+ return [...values];
190
+ };
191
+ const persistedPaths = copyPaths(paths);
192
+ const visitVirtuals = (record2, prefix) => {
193
+ for (const [name, value] of Object.entries(record2 ?? {})) {
194
+ debitOutputWork();
195
+ if (value === void 0) continue;
196
+ const path = prefix ? prepareOutputWorkString([prefix, name]) : name;
197
+ debitOutputPayload(currentOutputWorkLedger(), path);
198
+ if (!isSafeOutputPath(path)) continue;
199
+ if (value && typeof value === "object" && "sub" in value) {
200
+ if (references.has(path)) continue;
201
+ virtualScopes.add(path);
202
+ add(path);
203
+ containers.add(path);
204
+ visitVirtuals(value.sub, path);
205
+ } else {
206
+ add(path);
207
+ ancestors(path);
208
+ virtualPaths.add(path);
209
+ }
210
+ }
211
+ };
212
+ visitVirtuals(virtuals, "");
213
+ const protectedEntries = copyPaths(protectedPaths);
214
+ const filterPaths = (values, keep) => {
215
+ debitOutputWork(void 0, values.length + 1);
216
+ return values.filter(keep);
217
+ };
218
+ const eligible = filterPaths(
219
+ copyPaths(paths),
220
+ (p) => !protectedEntries.some((v) => matchesCatalogPattern(v, p, true))
221
+ );
222
+ debitOutputWork(void 0, 3);
223
+ const catalog = Object.freeze({
224
+ paths: Object.freeze(filterPaths(eligible, (p) => !p.includes("$*"))),
225
+ persistedPaths: Object.freeze(persistedPaths),
226
+ arrayPaths: Object.freeze(copyPaths(arrays)),
227
+ schemaVirtualPaths: Object.freeze(copyPaths(schemaVirtualPaths)),
228
+ metadataPaths: Object.freeze([documentPermissionField]),
229
+ dynamicPaths: Object.freeze(filterPaths(eligible, (p) => p.includes("$*"))),
230
+ containerPaths: Object.freeze(copyPaths(containers)),
231
+ opaquePaths: Object.freeze(copyPaths(opaque)),
232
+ referencePaths: Object.freeze(copyPaths(references)),
233
+ virtualPaths: Object.freeze(copyPaths(virtualPaths)),
234
+ virtualScopePaths: Object.freeze(copyPaths(virtualScopes)),
235
+ protectedPaths: Object.freeze(protectedEntries)
236
+ });
237
+ if (typeof documentPermissionField === "string") {
238
+ const arrays2 = Object.values(catalog);
239
+ ownedCatalogs.set(
240
+ catalog,
241
+ Object.freeze({ slots: 1 + arrays2.length + arrays2.reduce((sum, paths2) => sum + paths2.length, 0), depth: 2 })
242
+ );
243
+ }
244
+ return catalog;
245
+ }
246
+
247
+ // src/acl/trusted-output-materialization.ts
248
+ import { types as types3 } from "util";
249
+ import { mongo } from "mongoose";
250
+
251
+ // src/output/permissions-alias.ts
252
+ import { get } from "@web-ts-toolkit/utils";
253
+ import { types as types2 } from "util";
254
+ var aliases = /* @__PURE__ */ new WeakMap();
255
+ function isGeneratedPermissionsAliasSlot(output, key, slot) {
256
+ return key === "permissions" && aliases.has(output) && "value" in slot && !slot.enumerable;
257
+ }
258
+ function attachPermissionsAlias(output, field) {
259
+ if ("permissions" in output) return;
260
+ const metadata = get(output, field);
261
+ if (metadata === void 0) return;
262
+ Object.defineProperty(output, "permissions", {
263
+ value: metadata,
264
+ enumerable: false,
265
+ writable: true,
266
+ configurable: true
267
+ });
268
+ aliases.set(output, field);
269
+ }
270
+ function copyPermissionsAlias(source, target) {
271
+ if (source && typeof source === "object" && target && typeof target === "object") {
272
+ const field = aliases.get(source);
273
+ const readData = (value) => {
274
+ const parts = field?.split(".") ?? [];
275
+ if (parts.length > 100) return void 0;
276
+ for (const key of parts) {
277
+ if (!value || typeof value !== "object" || types2.isProxy(value)) return void 0;
278
+ const slot = Object.getOwnPropertyDescriptor(value, key);
279
+ if (!slot || !("value" in slot)) return void 0;
280
+ value = slot.value;
281
+ }
282
+ return value;
283
+ };
284
+ if (field && readData(target) !== void 0 && Object.getOwnPropertyDescriptor(source, "permissions")?.value === readData(source))
285
+ attachPermissionsAlias(target, field);
286
+ }
287
+ return target;
288
+ }
289
+
290
+ // src/acl/trusted-output-materialization.ts
291
+ var unsafeKeys = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype", "_doc", "$__"]);
292
+ var protectedValueKeys = /* @__PURE__ */ new Set([...unsafeKeys, "__v"]);
293
+ var budgets = /* @__PURE__ */ new WeakMap();
294
+ function createTrustedOutputBudget(onFailure, ownerCheck, ledger) {
295
+ const budget = Object.freeze(/* @__PURE__ */ Object.create(null));
296
+ const ownerLedger = arguments.length < 3 ? currentOutputWorkLedger() : ledger;
297
+ budgets.set(budget, {
298
+ slots: 0,
299
+ failure: void 0,
300
+ recipients: void 0,
301
+ onFailure,
302
+ ownerCheck,
303
+ ledger: ownerLedger
304
+ });
305
+ return budget;
306
+ }
307
+ function failTrustedOutputBudget(budget, error) {
308
+ const record2 = budgets.get(budget);
309
+ if (!record2) authorizationError("invalid selected output budget");
310
+ record2.failure ??= error instanceof ServiceAuthorizationError ? error : new ServiceAuthorizationError("unsupported selected value");
311
+ record2.onFailure?.(record2.failure);
312
+ for (const edge of record2.recipients ?? []) {
313
+ try {
314
+ failTrustedOutputBudget(edge.budget, record2.failure);
315
+ } catch {
316
+ }
317
+ }
318
+ throw record2.failure;
319
+ }
320
+ function assertTrustedOutputBudget(budget) {
321
+ const record2 = budgets.get(budget);
322
+ if (!record2) authorizationError("invalid selected output budget");
323
+ record2.ownerCheck?.();
324
+ record2.ledger?.check();
325
+ if (record2.failure) throw record2.failure;
326
+ for (const edge of record2.recipients ?? []) assertTrustedOutputBudget(edge.budget);
327
+ }
328
+ function visitTrustedOutput(budget, depth, slots = 1, charged) {
329
+ const record2 = budgets.get(budget);
330
+ if (!record2) authorizationError("invalid selected output budget");
331
+ assertTrustedOutputBudget(budget);
332
+ if (record2.recipients?.length) charged ??= /* @__PURE__ */ new Set();
333
+ if (record2.ledger && !charged?.has(record2.ledger)) {
334
+ debitOutputWork(record2.ledger, slots);
335
+ charged?.add(record2.ledger);
336
+ }
337
+ if (depth > 100 || (record2.slots += slots) > 2e4)
338
+ failTrustedOutputBudget(budget, new ServiceAuthorizationError("selected output exceeds structural limits"));
339
+ try {
340
+ for (const edge of record2.recipients ?? [])
341
+ visitTrustedOutput(edge.budget, depth + edge.depth, slots * edge.multiplicity, charged);
342
+ } catch (error) {
343
+ failTrustedOutputBudget(budget, error);
344
+ }
345
+ }
346
+ function preloadTrustedOutputBudget(budget, depth, slots) {
347
+ const record2 = budgets.get(budget);
348
+ if (!record2) authorizationError("invalid selected output budget");
349
+ visitTrustedOutput(budget, depth, slots, record2.ledger ? /* @__PURE__ */ new Set([record2.ledger]) : void 0);
350
+ }
351
+ function prepareTrustedOutputPayload(budget, value, charged) {
352
+ const record2 = budgets.get(budget);
353
+ if (!record2) authorizationError("invalid selected output budget");
354
+ if (!record2.ledger && !record2.recipients?.length) return;
355
+ assertTrustedOutputBudget(budget);
356
+ if (record2.recipients?.length) charged ??= /* @__PURE__ */ new Set();
357
+ if (record2.ledger && !charged?.has(record2.ledger)) {
358
+ debitOutputPayload(record2.ledger, value);
359
+ charged?.add(record2.ledger);
360
+ }
361
+ for (const edge of record2.recipients ?? []) prepareTrustedOutputPayload(edge.budget, value, charged);
362
+ }
363
+ function defineTrustedOutputValue(output, key, value) {
364
+ Object.defineProperty(output, key, { value, enumerable: true, configurable: true, writable: true });
365
+ }
366
+ function isBsonValue(input) {
367
+ let prototype = Object.getPrototypeOf(input);
368
+ for (let depth = 0; prototype && depth <= 100; depth++) {
369
+ debitOutputWork();
370
+ if (types3.isProxy(prototype)) return false;
371
+ if (prototype === mongo.BSON.BSONValue.prototype) return true;
372
+ prototype = Object.getPrototypeOf(prototype);
373
+ }
374
+ return false;
375
+ }
376
+ var bsonFamilies = new Map(
377
+ Object.entries({
378
+ ObjectId: mongo.BSON.ObjectId,
379
+ Code: mongo.BSON.Code,
380
+ DBRef: mongo.BSON.DBRef,
381
+ Timestamp: mongo.BSON.Timestamp,
382
+ Long: mongo.BSON.Long,
383
+ Decimal128: mongo.BSON.Decimal128,
384
+ Binary: mongo.BSON.Binary,
385
+ Double: mongo.BSON.Double,
386
+ Int32: mongo.BSON.Int32,
387
+ BSONRegExp: mongo.BSON.BSONRegExp,
388
+ BSONSymbol: mongo.BSON.BSONSymbol,
389
+ MinKey: mongo.BSON.MinKey,
390
+ MaxKey: mongo.BSON.MaxKey
391
+ }).map(([name, family]) => [family.prototype, name])
392
+ );
393
+ function selectedDataProperty(input, key, own = false) {
394
+ let object = input;
395
+ for (let depth = 0; object && depth <= 100; depth++) {
396
+ debitOutputWork();
397
+ if (types3.isProxy(object)) authorizationError("unsupported selected proxy");
398
+ const slot = Object.getOwnPropertyDescriptor(object, key);
399
+ if (slot) {
400
+ if (!("value" in slot)) authorizationError("accessor selected BSON state");
401
+ return slot.value;
402
+ }
403
+ object = own ? null : Object.getPrototypeOf(object);
404
+ }
405
+ if (object) authorizationError("unsupported selected prototype depth");
406
+ return void 0;
407
+ }
408
+ function selectedBsonBytes(input, budget) {
409
+ if (!input || typeof input !== "object" || types3.isProxy(input) || !types3.isUint8Array(input))
410
+ authorizationError("unsupported selected BSON bytes");
411
+ const prototype = Object.getPrototypeOf(Uint8Array.prototype);
412
+ const buffer = Object.getOwnPropertyDescriptor(prototype, "buffer").get.call(input);
413
+ const offset = Object.getOwnPropertyDescriptor(prototype, "byteOffset").get.call(input);
414
+ const length = Object.getOwnPropertyDescriptor(prototype, "byteLength").get.call(input);
415
+ prepareTrustedOutputPayload(budget, length);
416
+ return Buffer.from(new Uint8Array(buffer, offset, length));
417
+ }
418
+ var regexpFlagNames = [
419
+ "hasIndices",
420
+ "global",
421
+ "ignoreCase",
422
+ "multiline",
423
+ "dotAll",
424
+ "unicode",
425
+ "unicodeSets",
426
+ "sticky"
427
+ ];
428
+ function prepareRegExpFlags(input, budget) {
429
+ const ledger = budgets.get(budget).ledger;
430
+ if (ledger) debitOutputWork(ledger, regexpFlagNames.length);
431
+ const flags = [];
432
+ for (let index = 0; index < regexpFlagNames.length; index++)
433
+ if (Object.getOwnPropertyDescriptor(RegExp.prototype, regexpFlagNames[index])?.get?.call(input)) {
434
+ prepareTrustedOutputPayload(budget, 1);
435
+ defineTrustedOutputValue(flags, String(flags.length), "dgimsuvy"[index]);
436
+ }
437
+ prepareTrustedOutputPayload(budget, flags.length);
438
+ return flags.join("");
439
+ }
440
+ function copyTrustedBsonValue(value, path, budget, policy, depth, active) {
441
+ const wireKeys = /* @__PURE__ */ new Set([
442
+ "value",
443
+ "code",
444
+ "scope",
445
+ "collection",
446
+ "oid",
447
+ "db",
448
+ "fields",
449
+ "low",
450
+ "high",
451
+ "unsigned",
452
+ "buffer",
453
+ "sub_type",
454
+ "position",
455
+ "pattern",
456
+ "options",
457
+ "bytes",
458
+ "i0",
459
+ "i1",
460
+ "i2",
461
+ "i3"
462
+ ]);
463
+ const defineWireValue = (output, key, value2) => {
464
+ debitOutputWork();
465
+ prepareTrustedOutputPayload(budget, key);
466
+ wireKeys.add(key);
467
+ defineTrustedOutputValue(output, key, value2);
468
+ };
469
+ const prepareWire = (input, current, level, observeHook = true, entered = false, documentRoot = false, slots = 1) => {
470
+ if (!entered) visitTrustedOutput(budget, level, slots);
471
+ if (typeof input === "function" || typeof input === "symbol") authorizationError("unsupported selected BSON value");
472
+ if (input === null || typeof input !== "object") {
473
+ if (typeof input === "string") prepareTrustedOutputPayload(budget, input);
474
+ return input;
475
+ }
476
+ if (types3.isProxy(input)) authorizationError("unsupported selected proxy");
477
+ if (!entered && active.has(input)) authorizationError("cyclic selected output");
478
+ if (!entered) active.add(input);
479
+ try {
480
+ const hook = selectedDataProperty(input, "toBSON");
481
+ if (typeof hook === "function") {
482
+ if (!observeHook) authorizationError("chained selected BSON hooks");
483
+ const normalized = outsideOutputWorkLedger(() => Reflect.apply(hook, input, []));
484
+ if (normalized !== input) return prepareWire(normalized, current, level, false, false, documentRoot);
485
+ }
486
+ if (isBsonValue(input)) {
487
+ if (documentRoot) authorizationError("unsupported selected BSON document");
488
+ let prototype2 = input;
489
+ for (let hops = 0; prototype2 && !bsonFamilies.has(prototype2) && hops <= 100; hops++) {
490
+ if (types3.isProxy(prototype2)) authorizationError("unsupported selected proxy");
491
+ if (Object.hasOwn(prototype2, "_bsontype") || Object.hasOwn(prototype2, /* @__PURE__ */ Symbol.for("@@mdb.bson.type")))
492
+ authorizationError("overridden selected BSON brand");
493
+ prototype2 = Object.getPrototypeOf(prototype2);
494
+ }
495
+ if (!prototype2 || !bsonFamilies.has(prototype2)) authorizationError("unsupported selected BSON family");
496
+ const family = bsonFamilies.get(prototype2);
497
+ const output2 = Object.create(prototype2);
498
+ Object.defineProperty(output2, "toBSON", { value: void 0 });
499
+ const field = (key, type) => {
500
+ const value2 = selectedDataProperty(input, key, true);
501
+ if (typeof value2 !== type) authorizationError("unsupported selected BSON state");
502
+ if (typeof value2 === "string") prepareTrustedOutputPayload(budget, value2);
503
+ defineWireValue(output2, key, value2);
504
+ return value2;
505
+ };
506
+ const bytes = (key, length) => {
507
+ const value2 = selectedBsonBytes(selectedDataProperty(input, key, true), budget);
508
+ if (length !== void 0 && value2.length !== length) authorizationError("invalid selected BSON bytes");
509
+ defineWireValue(output2, key, value2);
510
+ };
511
+ const method = (key) => {
512
+ if (selectedDataProperty(input, key) !== selectedDataProperty(prototype2, key))
513
+ authorizationError("unsupported selected BSON serializer override");
514
+ };
515
+ const document = (key) => {
516
+ const raw = selectedDataProperty(input, key, true);
517
+ const value2 = prepareWire(raw, prepareOutputWorkString([current, key]), level + 1, true, false, true);
518
+ if (!value2 || typeof value2 !== "object" || !Array.isArray(value2) && Object.getPrototypeOf(value2) !== null)
519
+ authorizationError("unsupported selected BSON document");
520
+ defineWireValue(output2, key, value2);
521
+ };
522
+ switch (family) {
523
+ case "Code": {
524
+ field("code", "string");
525
+ const scope = selectedDataProperty(input, "scope", true);
526
+ if (scope != null) document("scope");
527
+ else defineWireValue(output2, "scope", scope);
528
+ break;
529
+ }
530
+ case "DBRef": {
531
+ field("collection", "string");
532
+ const db = selectedDataProperty(input, "db", true);
533
+ if (db != null) field("db", "string");
534
+ defineWireValue(
535
+ output2,
536
+ "oid",
537
+ prepareWire(
538
+ selectedDataProperty(input, "oid", true),
539
+ prepareOutputWorkString([current, "oid"]),
540
+ level + 1
541
+ )
542
+ );
543
+ document("fields");
544
+ const ordered = /* @__PURE__ */ Object.create(null);
545
+ defineWireValue(ordered, "$ref", output2.collection);
546
+ defineWireValue(ordered, "$id", output2.oid);
547
+ if (db != null) defineWireValue(ordered, "$db", output2.db);
548
+ for (const key of Object.keys(output2.fields))
549
+ defineWireValue(ordered, key, output2.fields[key]);
550
+ return ordered;
551
+ }
552
+ case "ObjectId":
553
+ method("serializeInto");
554
+ if (Object.hasOwn(input, "buffer"))
555
+ bytes("buffer", 12);
556
+ else for (const key of ["i0", "i1", "i2", "i3"]) field(key, "number");
557
+ break;
558
+ case "Timestamp":
559
+ case "Long":
560
+ method("getLowBits");
561
+ method("getHighBits");
562
+ field("low", "number");
563
+ field("high", "number");
564
+ field("unsigned", "boolean");
565
+ break;
566
+ case "Decimal128":
567
+ bytes("bytes", 16);
568
+ break;
569
+ case "Binary": {
570
+ bytes("buffer");
571
+ const position = field("position", "number");
572
+ const subtype = field("sub_type", "number");
573
+ if (!Number.isInteger(position) || position < 0 || position > output2.buffer.length || !Number.isInteger(subtype) || subtype < 0 || subtype > 255)
574
+ authorizationError("invalid selected BSON binary");
575
+ break;
576
+ }
577
+ case "Int32":
578
+ method("valueOf");
579
+ field("value", "number");
580
+ break;
581
+ case "Double":
582
+ field("value", "number");
583
+ break;
584
+ case "BSONSymbol":
585
+ field("value", "string");
586
+ break;
587
+ case "BSONRegExp":
588
+ field("pattern", "string");
589
+ field("options", "string");
590
+ break;
591
+ }
592
+ return output2;
593
+ }
594
+ if (selectedDataProperty(input, "_bsontype") != null) authorizationError("unsupported selected BSON tag");
595
+ const noHook = (value2) => {
596
+ Object.defineProperty(value2, "toBSON", { value: void 0 });
597
+ return value2;
598
+ };
599
+ if (types3.isDate(input)) {
600
+ const getTime = selectedDataProperty(input, "getTime");
601
+ if (typeof getTime !== "function") authorizationError("unsupported selected BSON date");
602
+ const time = outsideOutputWorkLedger(() => Reflect.apply(getTime, input, []));
603
+ if (typeof time !== "number") authorizationError("unsupported selected BSON date");
604
+ prepareTrustedOutputPayload(budget, 8);
605
+ return noHook(new Date(time));
606
+ }
607
+ if (types3.isUint8Array(input)) return noHook(selectedBsonBytes(input, budget));
608
+ if (types3.isRegExp(input)) {
609
+ const source = Object.getOwnPropertyDescriptor(RegExp.prototype, "source").get.call(input);
610
+ prepareTrustedOutputPayload(budget, source);
611
+ const flags = prepareRegExpFlags(input, budget);
612
+ prepareTrustedOutputPayload(budget, flags);
613
+ return noHook(new RegExp(source, flags));
614
+ }
615
+ const output = /* @__PURE__ */ Object.create(null);
616
+ if (types3.isMap(input)) {
617
+ for (const [key, entry] of Map.prototype.entries.call(input)) {
618
+ visitTrustedOutput(budget, level + 1);
619
+ if (typeof key !== "string") authorizationError("selected Map requires string keys");
620
+ if (protectedValueKeys.has(key)) {
621
+ if (policy.rejectProtectedKeys) authorizationError("protected native snapshot key");
622
+ continue;
623
+ }
624
+ const child = prepareOutputWorkString([current, key]);
625
+ if (!policy.keep(key, child)) continue;
626
+ prepareTrustedOutputPayload(budget, key);
627
+ defineWireValue(output, key, prepareWire(entry, child, level + 1));
628
+ }
629
+ return output;
630
+ }
631
+ const array = Array.isArray(input);
632
+ const prototype = Object.getPrototypeOf(input);
633
+ if (!array && prototype !== Object.prototype && prototype !== null)
634
+ authorizationError("unsupported selected object");
635
+ const container = array ? noHook([]) : output;
636
+ if (array) {
637
+ const length = Object.getOwnPropertyDescriptor(input, "length").value;
638
+ if (length) visitTrustedOutput(budget, level + 1, length);
639
+ container.length = length;
640
+ for (let index = 0; index < length; index++) defineWireValue(container, String(index), void 0);
641
+ }
642
+ for (const key of Reflect.ownKeys(input)) {
643
+ if (array && key === "length") continue;
644
+ visitTrustedOutput(budget, level + 1);
645
+ if (typeof key !== "string") authorizationError("symbol selected output key");
646
+ if (protectedValueKeys.has(key)) {
647
+ if (policy.rejectProtectedKeys) authorizationError("protected native snapshot key");
648
+ continue;
649
+ }
650
+ if (key === "toBSON" && (array || typeof hook === "function")) continue;
651
+ if (array && !/^(0|[1-9]\d*)$/.test(key)) authorizationError("invalid selected array property");
652
+ const child = array ? current : prepareOutputWorkString([current, key]);
653
+ if (!array && !policy.keep(key, child)) continue;
654
+ prepareTrustedOutputPayload(budget, key);
655
+ const slot = Object.getOwnPropertyDescriptor(input, key);
656
+ if (!("value" in slot) || !slot.enumerable) authorizationError("accessor/non-enumerable selected value");
657
+ defineWireValue(container, key, prepareWire(slot.value, child, level + 1, true, false, false, 0));
658
+ }
659
+ return container;
660
+ } finally {
661
+ if (!entered) active.delete(input);
662
+ }
663
+ };
664
+ const prepared = prepareWire(value, path, depth, true, true);
665
+ assertTrustedOutputBudget(budget);
666
+ for (const key of wireKeys) {
667
+ const slot = Object.getOwnPropertyDescriptor(Object.prototype, key);
668
+ if (slot && !("value" in slot)) authorizationError("inherited accessor selected BSON output");
669
+ }
670
+ const wrapper = /* @__PURE__ */ Object.create(null);
671
+ defineTrustedOutputValue(wrapper, "value", prepared);
672
+ const result = outsideOutputWorkLedger(
673
+ () => mongo.BSON.deserialize(mongo.BSON.serialize(wrapper), { promoteValues: false, bsonRegExp: true }).value
674
+ );
675
+ assertTrustedOutputBudget(budget);
676
+ return result;
677
+ }
678
+ function materializeTrustedOutputValue(value, path, budget, policy, depth = 0, prepaid = false) {
679
+ const ledger = budgets.get(budget)?.ledger;
680
+ if (ledger && currentOutputWorkLedger() !== ledger)
681
+ return withOutputWorkLedger(
682
+ ledger,
683
+ () => materializeTrustedOutputValue(value, path, budget, policy, depth, prepaid)
684
+ );
685
+ if (value === null || typeof value !== "object" && typeof value !== "function" && typeof value !== "symbol") {
686
+ try {
687
+ visitTrustedOutput(budget, depth, prepaid ? 0 : 1);
688
+ if (typeof value === "string") prepareTrustedOutputPayload(budget, value);
689
+ assertTrustedOutputBudget(budget);
690
+ return value;
691
+ } catch (error) {
692
+ failTrustedOutputBudget(budget, error);
693
+ }
694
+ }
695
+ const active = /* @__PURE__ */ new WeakSet();
696
+ const visit = (input, current, level, slots = 1) => {
697
+ visitTrustedOutput(budget, level, slots);
698
+ if (typeof input === "function" || typeof input === "symbol") authorizationError("unsupported selected value");
699
+ if (input === null || typeof input !== "object") {
700
+ if (typeof input === "string") prepareTrustedOutputPayload(budget, input);
701
+ return input;
702
+ }
703
+ if (types3.isProxy(input)) authorizationError("unsupported selected proxy");
704
+ if (active.has(input)) authorizationError("cyclic selected output");
705
+ active.add(input);
706
+ try {
707
+ if (types3.isDate(input)) {
708
+ const method = selectedDataProperty(input, "getTime");
709
+ if (typeof method !== "function") authorizationError("unsupported selected date");
710
+ const time = outsideOutputWorkLedger(() => Reflect.apply(method, input, []));
711
+ if (typeof time !== "number") authorizationError("unsupported selected date");
712
+ prepareTrustedOutputPayload(budget, 8);
713
+ return new Date(time);
714
+ }
715
+ if (Buffer.isBuffer(input)) return selectedBsonBytes(input, budget);
716
+ if (types3.isRegExp(input)) {
717
+ const source = Object.getOwnPropertyDescriptor(RegExp.prototype, "source").get.call(input);
718
+ prepareTrustedOutputPayload(budget, source);
719
+ const flags = prepareRegExpFlags(input, budget);
720
+ prepareTrustedOutputPayload(budget, flags);
721
+ const output2 = new RegExp(source, flags);
722
+ const lastIndex = selectedDataProperty(input, "lastIndex", true);
723
+ if (typeof lastIndex !== "number") authorizationError("unsupported selected regexp");
724
+ output2.lastIndex = lastIndex;
725
+ return output2;
726
+ }
727
+ if (isBsonValue(input)) {
728
+ try {
729
+ return copyTrustedBsonValue(input, current, budget, policy, level, active);
730
+ } catch (error) {
731
+ if (error instanceof ServiceAuthorizationError) throw error;
732
+ authorizationError("unsupported selected BSON value");
733
+ }
734
+ }
735
+ if (types3.isMap(input)) {
736
+ const output2 = {};
737
+ for (const [key, entry] of Map.prototype.entries.call(input)) {
738
+ visitTrustedOutput(budget, level + 1);
739
+ if (typeof key !== "string") authorizationError("selected Map requires string keys");
740
+ if (protectedValueKeys.has(key)) {
741
+ if (policy.rejectProtectedKeys) authorizationError("protected native snapshot key");
742
+ continue;
743
+ }
744
+ const child = prepareOutputWorkString([current, key]);
745
+ if (!policy.keep(key, child)) continue;
746
+ prepareTrustedOutputPayload(budget, key);
747
+ defineTrustedOutputValue(output2, key, visit(entry, child, level + 1));
748
+ }
749
+ return output2;
750
+ }
751
+ const array = Array.isArray(input);
752
+ const prototype = Object.getPrototypeOf(input);
753
+ if (!array && prototype !== Object.prototype && prototype !== null)
754
+ authorizationError("unsupported selected object");
755
+ const output = array ? [] : {};
756
+ if (array) {
757
+ const length = Object.getOwnPropertyDescriptor(input, "length").value;
758
+ if (length) visitTrustedOutput(budget, level + 1, length);
759
+ output.length = length;
760
+ }
761
+ for (const key of Reflect.ownKeys(input)) {
762
+ if (array && key === "length") continue;
763
+ visitTrustedOutput(budget, level + 1);
764
+ if (typeof key !== "string") authorizationError("symbol selected output key");
765
+ if (protectedValueKeys.has(key)) {
766
+ if (policy.rejectProtectedKeys) authorizationError("protected native snapshot key");
767
+ continue;
768
+ }
769
+ if (array && !/^(0|[1-9]\d*)$/.test(key)) authorizationError("invalid selected array property");
770
+ const child = array ? current : prepareOutputWorkString([current, key]);
771
+ if (!array && !policy.keep(key, child)) continue;
772
+ prepareTrustedOutputPayload(budget, key);
773
+ const slot = Object.getOwnPropertyDescriptor(input, key);
774
+ if (isGeneratedPermissionsAliasSlot(input, key, slot)) continue;
775
+ if (!("value" in slot) || !slot.enumerable) authorizationError("accessor/non-enumerable selected value");
776
+ defineTrustedOutputValue(output, key, visit(slot.value, child, level + 1, 0));
777
+ }
778
+ return copyPermissionsAlias(input, output);
779
+ } catch (error) {
780
+ failTrustedOutputBudget(budget, error);
781
+ } finally {
782
+ active.delete(input);
783
+ }
784
+ };
785
+ try {
786
+ const result = visit(value, path, depth, prepaid ? 0 : 1);
787
+ assertTrustedOutputBudget(budget);
788
+ return result;
789
+ } catch (error) {
790
+ failTrustedOutputBudget(budget, error);
791
+ }
792
+ }
793
+
794
+ // src/acl/authorization-snapshot.ts
795
+ var ServiceAuthorizationError = class extends JsonRouter.clientErrors.BadRequestError {
796
+ constructor(detail) {
797
+ const errors = [{ detail: `Service authorization: ${detail}` }];
798
+ super("Bad Request", { errors });
799
+ this.result = { success: false, kind: "error", code: "bad_request" /* BadRequest */, errors };
800
+ Object.freeze(errors[0]);
801
+ Object.freeze(errors);
802
+ Object.freeze(this.result);
803
+ Object.defineProperty(this, "result", {
804
+ value: this.result,
805
+ enumerable: true,
806
+ writable: false,
807
+ configurable: false
808
+ });
809
+ }
810
+ };
811
+ function authorizationError(detail) {
812
+ throw new ServiceAuthorizationError(detail);
813
+ }
814
+ var unsafeKeys2 = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
815
+ function authorizationRecord(value, label) {
816
+ if (!value || typeof value !== "object" || Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) {
817
+ authorizationError(`${label} must be a plain object`);
818
+ }
819
+ return value;
820
+ }
821
+ function copyAuthorizationValue(value, configuration = false) {
822
+ const active = /* @__PURE__ */ new WeakSet();
823
+ const budget = createTrustedOutputBudget();
824
+ function copy(input, depth) {
825
+ visitTrustedOutput(budget, depth);
826
+ if (typeof input === "function") {
827
+ if (configuration === true) return input;
828
+ authorizationError("functions are not policy values");
829
+ }
830
+ if (typeof input === "symbol") authorizationError("symbols are not policy values");
831
+ if (input === null || typeof input !== "object") {
832
+ if (typeof input === "string") prepareTrustedOutputPayload(budget, input);
833
+ return input;
834
+ }
835
+ if (types4.isProxy(input)) authorizationError("proxy snapshot input");
836
+ const ownedCatalog = configuration === true ? readOwnedAuthorizationCatalogWork(input) : void 0;
837
+ if (ownedCatalog) {
838
+ preloadTrustedOutputBudget(budget, depth + ownedCatalog.depth, ownedCatalog.slots - 1);
839
+ return input;
840
+ }
841
+ if (active.has(input)) authorizationError("cyclic input");
842
+ active.add(input);
843
+ try {
844
+ if (input instanceof Date) {
845
+ const time = outsideOutputWorkLedger(() => input.getTime());
846
+ prepareTrustedOutputPayload(budget, 8);
847
+ return outsideOutputWorkLedger(() => new Date(time));
848
+ }
849
+ if (Buffer.isBuffer(input)) {
850
+ if (!currentOutputWorkLedger()) return Buffer.from(input);
851
+ const normalized = outsideOutputWorkLedger(() => Buffer.from(input));
852
+ return materializeTrustedOutputValue(normalized, "", budget, { keep: () => true }, depth, true);
853
+ }
854
+ if (input instanceof RegExp) {
855
+ const result2 = outsideOutputWorkLedger(() => new RegExp(input.source, input.flags));
856
+ result2.lastIndex = input.lastIndex;
857
+ return currentOutputWorkLedger() ? materializeTrustedOutputValue(result2, "", budget, { keep: () => true }, depth, true) : result2;
858
+ }
859
+ if (input instanceof mongo2.BSON.BSONValue) {
860
+ try {
861
+ return materializeTrustedOutputValue(
862
+ input,
863
+ "",
864
+ budget,
865
+ { keep: () => true, rejectProtectedKeys: true },
866
+ depth,
867
+ true
868
+ );
869
+ } catch (error) {
870
+ if (error instanceof ServiceAuthorizationError) throw error;
871
+ authorizationError("unsupported BSON snapshot");
872
+ }
873
+ }
874
+ if (configuration && input instanceof Map) {
875
+ const result2 = /* @__PURE__ */ new Map();
876
+ for (const [key, entry] of Map.prototype.entries.call(input))
877
+ result2.set(copy(key, depth + 1), copy(entry, depth + 1));
878
+ return result2;
879
+ }
880
+ if (configuration && input instanceof Set) {
881
+ const result2 = /* @__PURE__ */ new Set();
882
+ for (const entry of Set.prototype.values.call(input)) result2.add(copy(entry, depth + 1));
883
+ return result2;
884
+ }
885
+ const array = Array.isArray(input);
886
+ if (array && input.length > 2e4) authorizationError("snapshot array exceeds structural limits");
887
+ if (!array) authorizationRecord(input, "snapshot");
888
+ const result = array ? [] : {};
889
+ let definedProperty = false;
890
+ for (const key of Reflect.ownKeys(input)) {
891
+ if (array && key === "length") continue;
892
+ if (typeof key !== "string" || unsafeKeys2.has(key)) authorizationError("unsafe snapshot key");
893
+ prepareTrustedOutputPayload(budget, key);
894
+ if (array && !/^(0|[1-9]\d*)$/.test(key)) authorizationError("invalid array property");
895
+ const descriptor = Object.getOwnPropertyDescriptor(input, key);
896
+ if (!("value" in descriptor) || !descriptor.enumerable && configuration !== "document")
897
+ authorizationError("accessor/non-enumerable input");
898
+ const value2 = copy(descriptor.value, depth + 1);
899
+ if (array || definedProperty && Object.getPrototypeOf(result) !== Object.prototype || key in result) {
900
+ definedProperty = true;
901
+ Object.defineProperty(result, key, {
902
+ value: value2,
903
+ enumerable: true,
904
+ writable: true,
905
+ configurable: true
906
+ });
907
+ } else result[key] = value2;
908
+ }
909
+ if (array) result.length = input.length;
910
+ return Object.freeze(result);
911
+ } finally {
912
+ active.delete(input);
913
+ }
914
+ }
915
+ return copy(value, 0);
916
+ }
917
+
918
+ // src/acl/output-work-ledger.ts
919
+ var preparation = new AsyncLocalStorage();
920
+ function currentOutputWorkLedger() {
921
+ return preparation.getStore();
922
+ }
923
+ function withOutputWorkLedger(ledger, run) {
924
+ if (preparation.getStore() === ledger) return run();
925
+ return preparation.run(ledger, run);
926
+ }
927
+ function outsideOutputWorkLedger(run) {
928
+ if (!preparation.getStore()) return run();
929
+ return preparation.run(void 0, run);
930
+ }
931
+ function debitOutputWork(ledger = currentOutputWorkLedger(), units = 1) {
932
+ if (!ledger) return;
933
+ ledger.check();
934
+ if (ledger.failure) throw ledger.failure;
935
+ if (!Number.isSafeInteger(units) || units < 0 || ledger.work + units > 2e5) {
936
+ ledger.failure ??= new ServiceAuthorizationError("collection output exceeds aggregate work limit");
937
+ ledger.fail(ledger.failure);
938
+ throw ledger.failure;
939
+ }
940
+ ledger.work += units;
941
+ }
942
+ function debitOutputPayload(ledger, value) {
943
+ if (!ledger) return;
944
+ ledger.check();
945
+ if (ledger.failure) throw ledger.failure;
946
+ const bytes = typeof value === "string" ? Buffer.byteLength(value, "utf8") : value;
947
+ if (!Number.isSafeInteger(bytes) || bytes < 0 || ledger.payload + bytes > 16 * 1024 * 1024) {
948
+ ledger.failure ??= new ServiceAuthorizationError("collection output exceeds payload limit");
949
+ ledger.fail(ledger.failure);
950
+ throw ledger.failure;
951
+ }
952
+ ledger.payload += bytes;
953
+ }
954
+ function prepareOutputWorkString(parts, separator = ".", ledger = currentOutputWorkLedger()) {
955
+ if (ledger) {
956
+ const bytes = parts.reduce((sum, part) => sum + Buffer.byteLength(part, "utf8"), 0) + Math.max(0, parts.length - 1) * Buffer.byteLength(separator, "utf8");
957
+ debitOutputPayload(ledger, bytes);
958
+ }
959
+ return parts.join(separator);
960
+ }
961
+
962
+ // src/acl/authorization-modes.ts
963
+ import { types as types5 } from "util";
964
+ var retiredAuthorizationOptions = [
55
965
  "unsafeSkipListDocumentSnapshotChecks",
56
966
  "unsafeSkipReadDocumentSnapshotChecks",
57
967
  "unsafeSkipListOutputSnapshotChecks",
58
968
  "unsafeSkipReadOutputSnapshotChecks",
59
969
  "unsafeSkipListNestedDocumentSnapshotChecks",
60
- "unsafeSkipReadNestedDocumentSnapshotChecks"
61
- ];
62
- var unsafeInitialOutputCopyOptions = [
970
+ "unsafeSkipReadNestedDocumentSnapshotChecks",
63
971
  "unsafeSkipListInitialOutputSnapshotCopy",
64
- "unsafeSkipReadInitialOutputSnapshotCopy"
65
- ];
66
- var unsafeSnapshotOptions = [...unsafeSnapshotCheckOptions, ...unsafeInitialOutputCopyOptions];
67
- var unsafeAuthorizationFastPathOptions = [
972
+ "unsafeSkipReadInitialOutputSnapshotCopy",
68
973
  "unsafeUseListAuthorizationFastPath",
69
974
  "unsafeUseReadAuthorizationFastPath"
70
975
  ];
71
- var unsafeServerOptions = [...unsafeSnapshotOptions, ...unsafeAuthorizationFastPathOptions];
72
- function authorizationFastPathPrerequisites(origin) {
73
- const operation = origin === "read" ? "Read" : "List";
74
- return [
75
- `unsafeSkip${operation}DocumentSnapshotChecks`,
76
- `unsafeSkip${operation}OutputSnapshotChecks`,
77
- `unsafeSkip${operation}NestedDocumentSnapshotChecks`,
78
- `unsafeSkip${operation}InitialOutputSnapshotCopy`
79
- ];
80
- }
81
- function captureAuthorizationFastPath(options, origin) {
82
- const literalTrue = (key2) => {
83
- const descriptor = Object.getOwnPropertyDescriptor(options, key2);
84
- return !!descriptor && "value" in descriptor && descriptor.value === true;
85
- };
86
- const key = origin === "read" ? unsafeAuthorizationFastPathOptions[1] : unsafeAuthorizationFastPathOptions[0];
87
- const requested = literalTrue(key);
88
- const prerequisites = authorizationFastPathPrerequisites(origin).reduce(
89
- (mask, key2, index) => mask | (literalTrue(key2) ? 1 << index : 0),
90
- 0
976
+ var authorizationModeKeys = [
977
+ "readAuthorizationMode",
978
+ "listAuthorizationMode",
979
+ "createAuthorizationMode",
980
+ "updateAuthorizationMode"
981
+ ];
982
+ var authorizationModeOperations = {
983
+ readAuthorizationMode: "read",
984
+ listAuthorizationMode: "list",
985
+ createAuthorizationMode: "create",
986
+ updateAuthorizationMode: "update"
987
+ };
988
+ var serverAuthorizationControls = [...retiredAuthorizationOptions, ...authorizationModeKeys];
989
+ function authorizationControlError(key) {
990
+ return retiredAuthorizationOptions.includes(key) ? `${key} was removed; migrate to readAuthorizationMode/listAuthorizationMode on server model/default-model options` : `${key} is server model/default-model configuration only`;
991
+ }
992
+ function normalizeAuthorizationMode(value) {
993
+ if (value === void 0) return void 0;
994
+ if (value === "isolated" || value === "trusted") return value;
995
+ throw new TypeError(
996
+ "Authorization mode must be the literal isolated or trusted, or undefined to restore inheritance"
91
997
  );
92
- return Object.freeze({
93
- origin,
94
- mode: !requested ? "off" : prerequisites === 15 ? "active" : "dormant",
95
- prerequisites
96
- });
998
+ }
999
+ function assertAuthorizationModeKey(key, model) {
1000
+ if (typeof key !== "string") throw new TypeError("Configuration option key must be a string");
1001
+ const root = key.split(".")[0];
1002
+ if (retiredAuthorizationOptions.includes(root))
1003
+ throw new TypeError(authorizationControlError(root));
1004
+ if (authorizationModeKeys.includes(root) && (!model || key !== root))
1005
+ throw new TypeError(
1006
+ !model ? authorizationControlError(root) : `${root} is a scalar mode; dotted setters are unsupported`
1007
+ );
1008
+ }
1009
+ function admitControlPrototypes(value, reject) {
1010
+ const owners = [];
1011
+ for (let owner = value; owner; owner = Object.getPrototypeOf(owner)) {
1012
+ if (types5.isProxy(owner)) reject("Proxy control/configuration prototype is unsupported");
1013
+ if (owners.length > 100) reject("Control/configuration prototype depth exceeded");
1014
+ owners.push(owner);
1015
+ }
1016
+ return owners;
1017
+ }
1018
+ function controlPropertyKeys(owners, reject) {
1019
+ const keys2 = /* @__PURE__ */ new Set();
1020
+ for (const owner of owners) {
1021
+ for (const key of Reflect.ownKeys(owner)) {
1022
+ if (typeof key === "string") keys2.add(key);
1023
+ if (keys2.size > 2e4) reject("Control/configuration keys exceed structural limits");
1024
+ }
1025
+ }
1026
+ return [...keys2];
1027
+ }
1028
+ function assertAuthorizationModeOptions(value, model) {
1029
+ const reject = (detail) => {
1030
+ throw new TypeError(detail);
1031
+ };
1032
+ if (!value || typeof value !== "object" || Array.isArray(value))
1033
+ throw new TypeError("Authorization configuration must be an options object");
1034
+ const owners = admitControlPrototypes(value, reject);
1035
+ for (const key of controlPropertyKeys(owners, reject)) {
1036
+ assertAuthorizationModeKey(key, model);
1037
+ if (!authorizationModeKeys.includes(key)) continue;
1038
+ const slot = Object.getOwnPropertyDescriptor(value, key);
1039
+ if (!slot || !("value" in slot) || !slot.enumerable)
1040
+ throw new TypeError(`${key} must be an own enumerable data option`);
1041
+ normalizeAuthorizationMode(slot.value);
1042
+ }
97
1043
  }
98
1044
 
99
1045
  // src/validation/public-admission.ts
@@ -114,10 +1060,10 @@ var privateControls = [
114
1060
  "skipParsing",
115
1061
  "skipAuthorization",
116
1062
  "alreadyAuthorized",
117
- ...unsafeServerOptions,
1063
+ ...serverAuthorizationControls,
118
1064
  "operation"
119
1065
  ];
120
- var PublicAdmissionError = class extends JsonRouter.clientErrors.BadRequestError {
1066
+ var PublicAdmissionError = class extends JsonRouter2.clientErrors.BadRequestError {
121
1067
  constructor(detail) {
122
1068
  const errors = [{ detail }];
123
1069
  super("Bad Request", { errors });
@@ -156,11 +1102,12 @@ function assertPublicControlAdmission(input, kind) {
156
1102
  walkControlAdmission(
157
1103
  input,
158
1104
  kind,
159
- (record2, path) => {
160
- for (const key of privateControls) {
161
- if (key in record2) {
1105
+ (_record, path, keys2) => {
1106
+ for (const property of keys2) {
1107
+ const key = property.split(".")[0];
1108
+ if (privateControls.includes(key)) {
162
1109
  throw new PublicAdmissionError(
163
- unsafeServerOptions.includes(key) ? `Unsupported public control ${path}.${key}; this unsafe flag is server model configuration only` : `Unsupported public control ${path}.${key}; use explicit per-call internal service options for backend authorization`
1110
+ serverAuthorizationControls.includes(key) ? `Unsupported public control ${path}.${authorizationControlError(key)}` : `Unsupported public control ${path}.${key}; use explicit per-call internal service options for backend authorization`
164
1111
  );
165
1112
  }
166
1113
  }
@@ -170,13 +1117,33 @@ function assertPublicControlAdmission(input, kind) {
170
1117
  }
171
1118
  );
172
1119
  }
1120
+ function assertNoServerModelControls(input, reject, kind = "envelope") {
1121
+ walkControlAdmission(
1122
+ input,
1123
+ kind,
1124
+ (_record, path, keys2) => {
1125
+ for (const property of keys2) {
1126
+ const key = property.split(".")[0];
1127
+ if (serverAuthorizationControls.includes(key))
1128
+ reject(`${path}.${authorizationControlError(key)}`);
1129
+ if (key === "documentAuthorization" || key === "documentAuthorizationStage")
1130
+ reject(`${path}.${key} was removed; output DTOs carry no authority`);
1131
+ }
1132
+ },
1133
+ reject
1134
+ );
1135
+ }
173
1136
  function walkControlAdmission(input, kind, check, reject) {
174
1137
  const pending = [{ value: input, kind, path: "request", depth: 0 }];
175
1138
  const seen = /* @__PURE__ */ new WeakMap();
176
1139
  let slots = 1;
177
1140
  while (pending.length) {
1141
+ debitOutputWork();
178
1142
  const { value, kind: slot, path, depth } = pending.pop();
179
1143
  if (!value || typeof value !== "object" && typeof value !== "function") continue;
1144
+ if (typeof value === "function" && (slot === "policy" || slot === "data")) continue;
1145
+ if (types6.isProxy(value)) reject(`unsupported proxy in control admission: ${path}`);
1146
+ const owners = admitControlPrototypes(value, reject);
180
1147
  const kinds = seen.get(value) ?? /* @__PURE__ */ new Set();
181
1148
  if (kinds.has(slot)) continue;
182
1149
  kinds.add(slot);
@@ -187,11 +1154,29 @@ function walkControlAdmission(input, kind, check, reject) {
187
1154
  pending.push({ value: child, kind: childKind, path: `${path}.${key}`, depth: depth + 1 });
188
1155
  };
189
1156
  const record2 = value;
190
- if (slot !== "data" && slot !== "policies") check(record2, path);
1157
+ const propertyKeys = slot === "data" || slot === "policies" ? [] : controlPropertyKeys(owners, reject);
1158
+ debitOutputWork(void 0, propertyKeys.length);
1159
+ if (slot !== "data" && slot !== "policies" && slot !== "model-options") check(record2, path, propertyKeys);
1160
+ for (const property of propertyKeys) {
1161
+ const parts = property.split(".");
1162
+ if (parts.length < 2 || !parts.some((part) => serverAuthorizationControls.includes(part)))
1163
+ continue;
1164
+ const roots = slot === "defaults" ? defaultControlBuckets : slot === "policy" ? ["rows", "outputFields", "inputFields", "operation", "related"] : ["args", "options", "sqOptions", "include", "populate", "authorization", "defaults"];
1165
+ if (!roots.includes(parts[0])) continue;
1166
+ if (parts.length > 100) reject("control admission dotted path exceeds structural limits");
1167
+ const wrapper = {};
1168
+ let target = wrapper;
1169
+ for (const part of parts.slice(0, -1)) {
1170
+ const child = {};
1171
+ Object.defineProperty(target, part, { value: child, enumerable: true });
1172
+ target = child;
1173
+ }
1174
+ const descriptor = owners.map((owner) => Object.getOwnPropertyDescriptor(owner, property)).find(Boolean);
1175
+ Object.defineProperty(target, parts.at(-1), descriptor);
1176
+ add(wrapper, slot, property);
1177
+ }
191
1178
  const read = (key) => {
192
- let owner = value;
193
- for (let depth2 = 0; owner; depth2++, owner = Object.getPrototypeOf(owner)) {
194
- if (depth2 > 100) reject("control admission prototype depth exceeded");
1179
+ for (const owner of owners) {
195
1180
  const descriptor = Object.getOwnPropertyDescriptor(owner, key);
196
1181
  if (!descriptor) continue;
197
1182
  if (!("value" in descriptor)) reject(`accessor control/data property: ${path}.${key}`);
@@ -218,12 +1203,14 @@ function walkControlAdmission(input, kind, check, reject) {
218
1203
  for (const key of keys2) if (key in record2) add(read(key), "envelope", key);
219
1204
  continue;
220
1205
  }
1206
+ add(read("defaults"), "defaults", "defaults");
221
1207
  if (slot === "policies") {
222
1208
  for (const key of Object.keys(value)) add(read(key), "policy", key);
223
1209
  continue;
224
1210
  }
225
1211
  if (slot === "policy") {
226
- for (const key of ["rows", "outputFields", "inputFields", "operation"]) add(read(key), "policy", key);
1212
+ for (const key of ["rows", "outputFields", "inputFields", "operation", "parent", "child", "visibility"])
1213
+ add(read(key), "policy", key);
227
1214
  add(read("related"), "policies", "related");
228
1215
  add(read("filter"), "data", "filter");
229
1216
  continue;
@@ -232,7 +1219,9 @@ function walkControlAdmission(input, kind, check, reject) {
232
1219
  add(read("include"), "include", "include");
233
1220
  add(read("populate"), "populate", "populate");
234
1221
  add(read("authorization"), "policy", "authorization");
235
- for (const key of ["filter", "match", "data"]) add(read(key), "data", key);
1222
+ add(read("operationAccess"), "policy", "operationAccess");
1223
+ for (const key of slot === "data-options" ? ["filter", "match"] : ["filter", "match", "data"])
1224
+ add(read(key), "data", key);
236
1225
  }
237
1226
  }
238
1227
  function assertHydrationDefaults(defaults2) {
@@ -327,7 +1316,7 @@ import mschema2Jsonschema from "mongoose-schema-jsonschema";
327
1316
  import {
328
1317
  addLeadingSlash,
329
1318
  forEach as forEach2,
330
- get as get3,
1319
+ get as get4,
331
1320
  isArray as isArray4,
332
1321
  isBoolean,
333
1322
  isFunction as isFunction2,
@@ -767,7 +1756,7 @@ var defaultLogger = createLogger({
767
1756
  });
768
1757
 
769
1758
  // src/options/manager.ts
770
- import { assign, get, isPlainObject as isPlainObject8, set } from "@web-ts-toolkit/utils";
1759
+ import { assign, get as get2, isPlainObject as isPlainObject8, set } from "@web-ts-toolkit/utils";
771
1760
  var toPath = (key) => {
772
1761
  if (Array.isArray(key)) return key;
773
1762
  return typeof key === "string" ? key.split(".") : [key];
@@ -875,7 +1864,7 @@ var OptionsManager = class {
875
1864
  return this;
876
1865
  }
877
1866
  get(key, defaultValue) {
878
- return get(this.currentOptions, key, defaultValue);
1867
+ return get2(this.currentOptions, key, defaultValue);
879
1868
  }
880
1869
  set(key, value) {
881
1870
  const path = toPath(key);
@@ -884,7 +1873,7 @@ var OptionsManager = class {
884
1873
  return;
885
1874
  }
886
1875
  const [rootKey, ...nestedPath] = path;
887
- const currentRoot = get(this.currentOptions, [rootKey], void 0);
1876
+ const currentRoot = get2(this.currentOptions, [rootKey], void 0);
888
1877
  const baseRoot = isPlainObject8(currentRoot) ? currentRoot : {};
889
1878
  const nextRoot = cloneConfigValue(baseRoot);
890
1879
  set(nextRoot, nestedPath, cloneForRead(value));
@@ -943,7 +1932,7 @@ var OptionsManager = class {
943
1932
  import { set as set2 } from "@web-ts-toolkit/utils";
944
1933
 
945
1934
  // src/options/data-values.ts
946
- import { types } from "util";
1935
+ import { types as types7 } from "util";
947
1936
  var typedArrays = [
948
1937
  Int8Array,
949
1938
  Uint8Array,
@@ -973,7 +1962,7 @@ var assertNativeProperties = (value, path, allowed = () => false) => {
973
1962
  }
974
1963
  };
975
1964
  var copyBytes = (buffer, path, start = 0, end) => {
976
- if (!types.isArrayBuffer(buffer) || Object.getPrototypeOf(buffer) !== ArrayBuffer.prototype) {
1965
+ if (!types7.isArrayBuffer(buffer) || Object.getPrototypeOf(buffer) !== ArrayBuffer.prototype) {
977
1966
  return unsupported(path, "binary storage must be a fixed, non-shared ArrayBuffer");
978
1967
  }
979
1968
  assertNativeProperties(buffer, path);
@@ -994,7 +1983,7 @@ function copyValue(input, freezePlain, rootPath) {
994
1983
  return unsupported(path, `${typeof value} values are not supported`);
995
1984
  }
996
1985
  if (value === null || typeof value !== "object") return value;
997
- if (types.isProxy(value)) return unsupported(path, "proxies are not supported");
1986
+ if (types7.isProxy(value)) return unsupported(path, "proxies are not supported");
998
1987
  if (active.has(value)) return unsupported(path, "cycles are not supported");
999
1988
  const previous = copies.get(value);
1000
1989
  if (previous) return previous;
@@ -1015,10 +2004,10 @@ function copyValue(input, freezePlain, rootPath) {
1015
2004
  return freezePlain ? Object.freeze(output2) : output2;
1016
2005
  }
1017
2006
  let output;
1018
- if (prototype === Date.prototype && types.isDate(value)) {
2007
+ if (prototype === Date.prototype && types7.isDate(value)) {
1019
2008
  assertNativeProperties(value, path);
1020
2009
  output = new Date(Date.prototype.getTime.call(value));
1021
- } else if (prototype === Map.prototype && types.isMap(value)) {
2010
+ } else if (prototype === Map.prototype && types7.isMap(value)) {
1022
2011
  assertNativeProperties(value, path);
1023
2012
  const map = /* @__PURE__ */ new Map();
1024
2013
  copies.set(value, map);
@@ -1028,7 +2017,7 @@ function copyValue(input, freezePlain, rootPath) {
1028
2017
  index += 1;
1029
2018
  }
1030
2019
  output = map;
1031
- } else if (prototype === Set.prototype && types.isSet(value)) {
2020
+ } else if (prototype === Set.prototype && types7.isSet(value)) {
1032
2021
  assertNativeProperties(value, path);
1033
2022
  const set4 = /* @__PURE__ */ new Set();
1034
2023
  copies.set(value, set4);
@@ -1038,7 +2027,7 @@ function copyValue(input, freezePlain, rootPath) {
1038
2027
  index += 1;
1039
2028
  }
1040
2029
  output = set4;
1041
- } else if (prototype === RegExp.prototype && types.isRegExp(value)) {
2030
+ } else if (prototype === RegExp.prototype && types7.isRegExp(value)) {
1042
2031
  assertNativeProperties(value, path, (key) => key === "lastIndex");
1043
2032
  const regexp = value;
1044
2033
  if (typeof regexp.lastIndex !== "number") return unsupported(path, "RegExp.lastIndex must be a number");
@@ -1115,7 +2104,7 @@ var emptyDataSnapshot = Object.freeze([]);
1115
2104
  var ownedSnapshots = new WeakMap([[emptyDataSnapshot, emptyDataSnapshot]]);
1116
2105
  function createDataSnapshot(data) {
1117
2106
  if (data === void 0) return void 0;
1118
- if (!Array.isArray(data) || types.isProxy(data) || Object.getPrototypeOf(data) !== Array.prototype) {
2107
+ if (!Array.isArray(data) || types7.isProxy(data) || Object.getPrototypeOf(data) !== Array.prototype) {
1119
2108
  return unsupported("data", "expected an ordinary array or undefined");
1120
2109
  }
1121
2110
  if (ownedSnapshots.has(data)) return data;
@@ -1155,7 +2144,147 @@ var DataOptionsManager = class extends OptionsManager {
1155
2144
  restore(snapshot) {
1156
2145
  super.restore(admitData(snapshot));
1157
2146
  }
1158
- };
2147
+ };
2148
+
2149
+ // src/operation-access.ts
2150
+ var operations = /* @__PURE__ */ new Set(["new", "list", "read", "create", "update", "upsert", "delete", "count", "distinct"]);
2151
+ var subOperations = /* @__PURE__ */ new Set(["list", "read", "create", "update", "delete"]);
2152
+ var members = /* @__PURE__ */ new Set(["default", "basic", "advanced", "root"]);
2153
+ var removedAccesses = new Set(
2154
+ ["List", "Read", "Create", "Update", "Upsert", "Count", "Distinct"].flatMap((operation) => [
2155
+ `basic${operation}`,
2156
+ `advanced${operation}`
2157
+ ])
2158
+ );
2159
+ var isRemovedOperationAccess = (access) => typeof access === "string" && removedAccesses.has(access);
2160
+ function isOperationAccessMemberPath(access) {
2161
+ const keys2 = access.split(".");
2162
+ if (operations.has(keys2[0]) && members.has(keys2[1])) return true;
2163
+ return keys2[0] === "subs" && keys2[1] !== "" && subOperations.has(keys2[2]) && members.has(keys2[3]);
2164
+ }
2165
+ var isRecord = (value) => value !== null && typeof value === "object" && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
2166
+ function readOwnOption(root, key) {
2167
+ let value = root;
2168
+ for (const part of key.split(".")) {
2169
+ if (value === null || typeof value !== "object") return void 0;
2170
+ const slot = Object.getOwnPropertyDescriptor(value, part);
2171
+ if (!slot || !("value" in slot)) return void 0;
2172
+ value = slot.value;
2173
+ }
2174
+ return value;
2175
+ }
2176
+ function createOperationAccessReaders(options, defaults2) {
2177
+ return {
2178
+ readOption: (key) => readOwnOption(options, key),
2179
+ readDefaultOption: defaults2 === void 0 ? void 0 : (key) => readOwnOption(defaults2, key)
2180
+ };
2181
+ }
2182
+ var scalarGuard = (value) => {
2183
+ if (value === void 0) return void 0;
2184
+ if (typeof value === "boolean" || typeof value === "string" || typeof value === "function")
2185
+ return value;
2186
+ if (Array.isArray(value) && value.every((entry) => typeof entry === "string")) return value;
2187
+ return false;
2188
+ };
2189
+ function operationDefault(value) {
2190
+ if (!isRecord(value)) return scalarGuard(value);
2191
+ if (Reflect.ownKeys(value).some((key) => typeof key !== "string" || !members.has(key))) return false;
2192
+ return scalarGuard(readOwnOption(value, "default"));
2193
+ }
2194
+ function selectOperationAccessGuard({
2195
+ baseAccess,
2196
+ context,
2197
+ readOption,
2198
+ readDefaultOption,
2199
+ subdocuments = false
2200
+ }) {
2201
+ const keys2 = baseAccess.split(".");
2202
+ if (isRemovedOperationAccess(baseAccess) || isOperationAccessMemberPath(baseAccess) || keys2[0] === "subs" && isRemovedOperationAccess(keys2[2]))
2203
+ return false;
2204
+ if (context !== void 0 && !["basic", "advanced", "root"].includes(context)) return false;
2205
+ const exact = (key) => {
2206
+ const value = readOption(key);
2207
+ return value === void 0 ? readDefaultOption?.(key) : value;
2208
+ };
2209
+ const contextGuard = (key, supported) => context === void 0 || !supported ? void 0 : scalarGuard(exact(`${key}.${context}`));
2210
+ let access = baseAccess;
2211
+ if (subdocuments && keys2[0] === "subs") {
2212
+ if (keys2.length < 3 || keys2[1] === "") return false;
2213
+ const fieldKey = `operationAccess.subs.${keys2[1]}`;
2214
+ const operationKey2 = `operationAccess.${baseAccess}`;
2215
+ const selected2 = contextGuard(operationKey2, keys2.length === 3 && subOperations.has(keys2[2]));
2216
+ if (selected2 !== void 0) return selected2;
2217
+ const operation2 = exact(operationKey2);
2218
+ if (operation2 !== void 0) {
2219
+ const guard = keys2.length === 3 && subOperations.has(keys2[2]) ? operationDefault(operation2) : scalarGuard(operation2);
2220
+ if (guard !== void 0) return guard;
2221
+ }
2222
+ const field = exact(fieldKey);
2223
+ if (field !== void 0) return scalarGuard(field);
2224
+ access = keys2[2];
2225
+ }
2226
+ const operationKey = `operationAccess.${access}`;
2227
+ const selected = contextGuard(operationKey, operations.has(access));
2228
+ if (selected !== void 0) return selected;
2229
+ const operation = readOption(operationKey);
2230
+ if (operation !== void 0) {
2231
+ const guard = operations.has(access) ? operationDefault(operation) : scalarGuard(operation);
2232
+ if (guard !== void 0) return guard;
2233
+ }
2234
+ const outerDefault = readOption("operationAccess.default");
2235
+ if (outerDefault !== void 0) return scalarGuard(outerDefault);
2236
+ const outer = readOption("operationAccess");
2237
+ if (outer !== void 0) return scalarGuard(outer);
2238
+ const inherited = readDefaultOption?.(operationKey);
2239
+ return operations.has(access) ? operationDefault(inherited) : scalarGuard(inherited);
2240
+ }
2241
+ function rejectRemovedKey(key, prefix) {
2242
+ const context = key.startsWith("basic") ? "basic" : "advanced";
2243
+ const operation = key.slice(context.length);
2244
+ const replacement = `${operation[0].toLowerCase()}${operation.slice(1)}.${context}`;
2245
+ throw new TypeError(
2246
+ `Removed operation-access key "${prefix}${key}"; use "${prefix}${replacement}" instead. Move the operation's former scalar guard to its "default" member when using an object.`
2247
+ );
2248
+ }
2249
+ function assertOperationNode(node, prefix) {
2250
+ if (!node || typeof node !== "object" || Array.isArray(node)) return;
2251
+ for (const key of removedAccesses) if (key in node) rejectRemovedKey(key, prefix);
2252
+ for (const key of Object.getOwnPropertyNames(node)) {
2253
+ const [operation] = key.split(".");
2254
+ if (isRemovedOperationAccess(operation)) rejectRemovedKey(operation, prefix);
2255
+ }
2256
+ }
2257
+ function assertOperationAccessOptions(options) {
2258
+ if (!options || typeof options !== "object") return;
2259
+ for (const key of Object.getOwnPropertyNames(options)) {
2260
+ if (key === "operationAccess" || key.startsWith("operationAccess.")) {
2261
+ assertOperationAccessUpdate(key, options[key]);
2262
+ }
2263
+ }
2264
+ }
2265
+ function assertOperationAccessUpdate(key, value) {
2266
+ const path = key.split(".");
2267
+ if (path[0] !== "operationAccess") return;
2268
+ if (isRemovedOperationAccess(path[1])) rejectRemovedKey(path[1], "operationAccess.");
2269
+ if (path[1] === "subs" && path.length >= 4 && isRemovedOperationAccess(path[3]))
2270
+ rejectRemovedKey(path[3], `operationAccess.subs.${path[2]}.`);
2271
+ if (path.length === 1) {
2272
+ assertOperationNode(value, "operationAccess.");
2273
+ if (value && typeof value === "object" && !Array.isArray(value)) {
2274
+ for (const property of Object.getOwnPropertyNames(value)) {
2275
+ if (property === "subs" || property.startsWith("subs."))
2276
+ assertOperationAccessUpdate(`operationAccess.${property}`, value[property]);
2277
+ }
2278
+ }
2279
+ } else if (path.length === 2 && path[1] === "subs") {
2280
+ if (value && typeof value === "object" && !Array.isArray(value)) {
2281
+ for (const field of Object.getOwnPropertyNames(value))
2282
+ assertOperationAccessUpdate(`operationAccess.subs.${field}`, value[field]);
2283
+ }
2284
+ } else if (path.length === 3 && path[1] === "subs") {
2285
+ assertOperationNode(value, `${key}.`);
2286
+ }
2287
+ }
1159
2288
 
1160
2289
  // src/request-complexity.ts
1161
2290
  import { isArray as isArray3, isPlainObject as isPlainObject9 } from "@web-ts-toolkit/utils";
@@ -1182,363 +2311,147 @@ var resolveRequestComplexity = (options) => ({
1182
2311
  maxInValues: normalizePositiveInteger(options?.maxInValues, defaultRequestComplexity.maxInValues),
1183
2312
  maxBulkItems: normalizePositiveInteger(options?.maxBulkItems, defaultRequestComplexity.maxBulkItems),
1184
2313
  maxIncludeCount: normalizePositiveInteger(options?.maxIncludeCount, defaultRequestComplexity.maxIncludeCount),
1185
- maxSubQueryCount: normalizePositiveInteger(options?.maxSubQueryCount, defaultRequestComplexity.maxSubQueryCount),
1186
- maxBulkConcurrency: normalizePositiveInteger(
1187
- options?.maxBulkConcurrency,
1188
- defaultRequestComplexity.maxBulkConcurrency
1189
- ),
1190
- maxHookConcurrency: normalizePositiveInteger(
1191
- options?.maxHookConcurrency,
1192
- defaultRequestComplexity.maxHookConcurrency
1193
- ),
1194
- maxCorrelatedQueries: normalizePositiveInteger(
1195
- options?.maxCorrelatedQueries,
1196
- defaultRequestComplexity.maxCorrelatedQueries
1197
- ),
1198
- maxCorrelatedDepth: normalizePositiveInteger(
1199
- options?.maxCorrelatedDepth,
1200
- defaultRequestComplexity.maxCorrelatedDepth
1201
- )
1202
- });
1203
- function validateRequestComplexity(value, options, scope = "request") {
1204
- const limits = resolveRequestComplexity(options);
1205
- const errors = [];
1206
- let nodes = 0;
1207
- let logicalClauses = 0;
1208
- let includeCount = 0;
1209
- let subQueryCount = 0;
1210
- const pointer = (path) => path.length === 0 ? "#" : `#/${path.join("/")}`;
1211
- const pushError = (detail, path) => {
1212
- if (errors.length === 0) {
1213
- errors.push({ detail, pointer: pointer(path) });
1214
- }
1215
- };
1216
- const visit = (current, path, depth, parentKey) => {
1217
- if (errors.length > 0) return;
1218
- nodes += 1;
1219
- if (nodes > limits.maxNodes) {
1220
- pushError(`Request exceeds maximum node budget of ${limits.maxNodes}`, path);
1221
- return;
1222
- }
1223
- if (depth > limits.maxDepth) {
1224
- pushError(`Request exceeds maximum depth of ${limits.maxDepth}`, path);
1225
- return;
1226
- }
1227
- if (isArray3(current)) {
1228
- if (parentKey === "$and" || parentKey === "$or" || parentKey === "$nor") {
1229
- logicalClauses += current.length;
1230
- if (logicalClauses > limits.maxLogicalClauses) {
1231
- pushError(`Filter exceeds maximum logical clause budget of ${limits.maxLogicalClauses}`, path);
1232
- return;
1233
- }
1234
- }
1235
- if (parentKey === "$in") {
1236
- if (current.length > limits.maxInValues) {
1237
- pushError(`Filter exceeds maximum $in values of ${limits.maxInValues}`, path);
1238
- return;
1239
- }
1240
- }
1241
- for (let index = 0; index < current.length; index++) {
1242
- visit(current[index], path.concat(index), depth + 1, parentKey);
1243
- if (errors.length > 0) return;
1244
- }
1245
- return;
1246
- }
1247
- if (!isPlainObject9(current)) return;
1248
- for (const [key, child] of Object.entries(current)) {
1249
- if (key === "__proto__" || key === "prototype" || key === "constructor") {
1250
- pushError(`Unsupported key: ${key}`, path.concat(key));
1251
- return;
1252
- }
1253
- if (scope === "request" && key === "include") {
1254
- includeCount += isArray3(child) ? child.length : 1;
1255
- if (includeCount > limits.maxIncludeCount) {
1256
- pushError(`Request exceeds maximum include count of ${limits.maxIncludeCount}`, path.concat(key));
1257
- return;
1258
- }
1259
- }
1260
- if (key === "$$sq") {
1261
- subQueryCount += 1;
1262
- if (subQueryCount > limits.maxSubQueryCount) {
1263
- pushError(`Request exceeds maximum subquery count of ${limits.maxSubQueryCount}`, path.concat(key));
1264
- return;
1265
- }
1266
- visit(child, path.concat(key), depth + 1, key);
1267
- if (errors.length > 0) return;
1268
- continue;
1269
- }
1270
- visit(child, path.concat(key), depth + 1, key);
1271
- if (errors.length > 0) return;
1272
- }
1273
- };
1274
- visit(value, [], 0);
1275
- return errors;
1276
- }
1277
-
1278
- // src/acl/virtual-descriptor.ts
1279
- import { isFunction, isPlainObject as isPlainObject10 } from "@web-ts-toolkit/utils";
1280
- var isVirtualContainerValue = (value) => isPlainObject10(value) && "sub" in value;
1281
- function getScopeVirtualsObject(root, scopePath = []) {
1282
- let current = root;
1283
- for (let i = 0; i < scopePath.length; i += 2) {
1284
- if (!current || scopePath[i + 1] !== "sub") return null;
1285
- const container = current[scopePath[i]];
1286
- if (!isVirtualContainerValue(container)) return null;
1287
- current = container.sub;
1288
- }
1289
- return isPlainObject10(current) ? current : null;
1290
- }
1291
- function toDescriptor(leaf, shared = {}) {
1292
- const record2 = isFunction(leaf) ? { get: leaf } : isPlainObject10(leaf) ? leaf : null;
1293
- if (!record2 || !isFunction(record2.get)) return void 0;
1294
- const dependsOn = record2.dependsOn ?? shared.dependsOn ?? [];
1295
- const populated = record2.dependsOnPopulate === void 0 ? shared.dependsOnPopulate : record2.dependsOnPopulate;
1296
- return {
1297
- get: record2.get,
1298
- dependsOn: [...dependsOn],
1299
- ...populated === void 0 ? {} : {
1300
- dependsOnPopulate: populated.map(({ path, select }) => ({
1301
- path,
1302
- ...select === void 0 ? {} : { select: Array.isArray(select) ? [...select] : typeof select === "object" ? { ...select } : select }
1303
- }))
1304
- }
1305
- };
1306
- }
1307
- function resolveSnapshotDescriptor(scopeVirtuals, virtualName, access) {
1308
- const entry = scopeVirtuals?.[virtualName];
1309
- if (entry === void 0 || isVirtualContainerValue(entry)) return void 0;
1310
- if (isFunction(entry)) return toDescriptor(entry);
1311
- if (!isPlainObject10(entry)) return void 0;
1312
- const record2 = entry;
1313
- if ("get" in record2) return toDescriptor(record2);
1314
- return toDescriptor(record2[access], record2) ?? toDescriptor(record2.default, record2);
1315
- }
1316
-
1317
- // src/acl/virtual-populate-dependencies.ts
1318
- import { get as get2, isPlainObject as isPlainObject12 } from "@web-ts-toolkit/utils";
1319
-
1320
- // src/acl/authorization-snapshot.ts
1321
- import { isDeepStrictEqual, types as types2 } from "util";
1322
- import { Buffer as NodeBuffer } from "buffer";
1323
- import { mongo } from "mongoose";
1324
- import JsonRouter2 from "@web-ts-toolkit/express-json-router";
1325
- var ServiceAuthorizationError = class extends JsonRouter2.clientErrors.BadRequestError {
1326
- constructor(detail) {
1327
- const errors = [{ detail: `Service authorization: ${detail}` }];
1328
- super("Bad Request", { errors });
1329
- this.result = { success: false, kind: "error", code: "bad_request" /* BadRequest */, errors };
1330
- }
1331
- };
1332
- function authorizationError(detail) {
1333
- throw new ServiceAuthorizationError(detail);
1334
- }
1335
- var unsafeKeys = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
1336
- function authorizationRecord(value, label) {
1337
- if (!value || typeof value !== "object" || Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) {
1338
- authorizationError(`${label} must be a plain object`);
1339
- }
1340
- return value;
1341
- }
1342
- function copyAuthorizationValue(value, configuration = false) {
1343
- const active = /* @__PURE__ */ new WeakSet();
1344
- let nodes = 0;
1345
- function copy(input, depth) {
1346
- if (++nodes > 2e4 || depth > 100) authorizationError("snapshot exceeds structural limits");
1347
- if (typeof input === "function") {
1348
- if (configuration === true) return input;
1349
- authorizationError("functions are not policy values");
1350
- }
1351
- if (typeof input === "symbol") authorizationError("symbols are not policy values");
1352
- if (input === null || typeof input !== "object") return input;
1353
- if (active.has(input)) authorizationError("cyclic input");
1354
- active.add(input);
1355
- try {
1356
- if (input instanceof Date) return new Date(input.getTime());
1357
- if (Buffer.isBuffer(input)) return Buffer.from(input);
1358
- if (input instanceof RegExp) {
1359
- const result2 = new RegExp(input.source, input.flags);
1360
- result2.lastIndex = input.lastIndex;
1361
- return result2;
1362
- }
1363
- if (input instanceof mongo.BSON.BSONValue) {
1364
- try {
1365
- return mongo.BSON.deserialize(mongo.BSON.serialize({ value: input }), {
1366
- promoteValues: false,
1367
- bsonRegExp: true
1368
- }).value;
1369
- } catch {
1370
- authorizationError("unsupported BSON snapshot");
1371
- }
1372
- }
1373
- if (configuration && input instanceof Map) {
1374
- return new Map([...input].map(([key, entry]) => [copy(key, depth + 1), copy(entry, depth + 1)]));
1375
- }
1376
- if (configuration && input instanceof Set) return new Set([...input].map((entry) => copy(entry, depth + 1)));
1377
- const array = Array.isArray(input);
1378
- if (array && input.length > 2e4) authorizationError("snapshot array exceeds structural limits");
1379
- if (!array) authorizationRecord(input, "snapshot");
1380
- const result = array ? [] : {};
1381
- let definedProperty = false;
1382
- for (const key of Reflect.ownKeys(input)) {
1383
- if (array && key === "length") continue;
1384
- if (typeof key !== "string" || unsafeKeys.has(key)) authorizationError("unsafe snapshot key");
1385
- if (array && !/^(0|[1-9]\d*)$/.test(key)) authorizationError("invalid array property");
1386
- const descriptor = Object.getOwnPropertyDescriptor(input, key);
1387
- if (!("value" in descriptor) || !descriptor.enumerable && configuration !== "document")
1388
- authorizationError("accessor/non-enumerable input");
1389
- const value2 = copy(descriptor.value, depth + 1);
1390
- if (array || definedProperty && Object.getPrototypeOf(result) !== Object.prototype || key in result) {
1391
- definedProperty = true;
1392
- Object.defineProperty(result, key, {
1393
- value: value2,
1394
- enumerable: true,
1395
- writable: true,
1396
- configurable: true
1397
- });
1398
- } else result[key] = value2;
1399
- }
1400
- if (array) result.length = input.length;
1401
- return Object.freeze(result);
1402
- } finally {
1403
- active.delete(input);
1404
- }
1405
- }
1406
- return copy(value, 0);
1407
- }
1408
-
1409
- // src/acl/field-catalog.ts
1410
- import { types as types3 } from "util";
1411
- var safeSegment = (part) => !!part && part !== "sub" && !["__proto__", "constructor", "prototype", "_doc", "__v"].includes(part) && !/^[+$-]|[\s*]/.test(part) && !part.includes("[") && !part.includes("]") && !/^\d+$/.test(part) && ![...part].some((character) => character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127);
1412
- var isSafeOutputPath = (path) => path.split(".").every(safeSegment);
1413
- var inputControlSegments = /* @__PURE__ */ new Set([
1414
- "_permissions",
1415
- "_view",
1416
- "_edit",
1417
- "documentAuthorization",
1418
- "documentAuthorizationStage",
1419
- "resolvedAuthorization",
1420
- "execution",
1421
- "executionContext",
1422
- "serviceExecutionContext",
1423
- "preparedQuery",
1424
- "preparedFilter",
1425
- "preparedModelQuery",
1426
- "resolvedIdentifier",
1427
- "skipParsing",
1428
- "skipAuthorization",
1429
- "alreadyAuthorized"
1430
- ]);
1431
- function isSafeInputPath(path, requestIdentity = false) {
1432
- return isSafeOutputPath(path) && path.split(".").every((part) => !inputControlSegments.has(part) && (requestIdentity || part !== "_id"));
1433
- }
1434
- function matchesCatalogPattern(pattern, path, descendants = false) {
1435
- if (typeof pattern === "string" && typeof path === "string" && !pattern.includes("$*")) {
1436
- return pattern === path || !!descendants && path.startsWith(pattern) && path[pattern.length] === ".";
1437
- }
1438
- const expected = pattern.split(".");
1439
- const actual = path.split(".");
1440
- return (descendants ? actual.length >= expected.length : actual.length === expected.length) && expected.every((part, index) => part === "$*" || part === actual[index]);
1441
- }
1442
- function captureAuthorizationFieldCatalog(schema, virtuals, documentPermissionField = "_permissions") {
1443
- const paths = /* @__PURE__ */ new Set();
1444
- const containers = /* @__PURE__ */ new Set();
1445
- const opaque = /* @__PURE__ */ new Set();
1446
- const references = /* @__PURE__ */ new Set();
1447
- const virtualPaths = /* @__PURE__ */ new Set();
1448
- const virtualScopes = /* @__PURE__ */ new Set();
1449
- const schemaVirtualPaths = /* @__PURE__ */ new Set();
1450
- const arrays = /* @__PURE__ */ new Set();
1451
- const protectedPaths = /* @__PURE__ */ new Set([documentPermissionField, "_doc", "$__", "__v"]);
1452
- const add = (path) => {
1453
- if (path.split(".").every((part) => part === "$*" || safeSegment(part))) paths.add(path);
1454
- };
1455
- const ancestors = (path) => {
1456
- const parts = path.split(".");
1457
- for (let n = 1; n < parts.length; n++) {
1458
- const parent = parts.slice(0, n).join(".");
1459
- add(parent);
1460
- containers.add(parent);
2314
+ maxSubQueryCount: normalizePositiveInteger(options?.maxSubQueryCount, defaultRequestComplexity.maxSubQueryCount),
2315
+ maxBulkConcurrency: normalizePositiveInteger(
2316
+ options?.maxBulkConcurrency,
2317
+ defaultRequestComplexity.maxBulkConcurrency
2318
+ ),
2319
+ maxHookConcurrency: normalizePositiveInteger(
2320
+ options?.maxHookConcurrency,
2321
+ defaultRequestComplexity.maxHookConcurrency
2322
+ ),
2323
+ maxCorrelatedQueries: normalizePositiveInteger(
2324
+ options?.maxCorrelatedQueries,
2325
+ defaultRequestComplexity.maxCorrelatedQueries
2326
+ ),
2327
+ maxCorrelatedDepth: normalizePositiveInteger(
2328
+ options?.maxCorrelatedDepth,
2329
+ defaultRequestComplexity.maxCorrelatedDepth
2330
+ )
2331
+ });
2332
+ function validateRequestComplexity(value, options, scope = "request") {
2333
+ const limits = resolveRequestComplexity(options);
2334
+ const errors = [];
2335
+ let nodes = 0;
2336
+ let logicalClauses = 0;
2337
+ let includeCount = 0;
2338
+ let subQueryCount = 0;
2339
+ const pointer = (path) => path.length === 0 ? "#" : `#/${path.join("/")}`;
2340
+ const pushError = (detail, path) => {
2341
+ if (errors.length === 0) {
2342
+ errors.push({ detail, pointer: pointer(path) });
1461
2343
  }
1462
2344
  };
1463
- const visitType = (type, path, active) => {
1464
- add(path);
1465
- ancestors(path);
1466
- const element = type.$embeddedSchemaType ?? type.embeddedSchemaType ?? type.caster;
1467
- if (type.instance === "Array" || type.$isMongooseDocumentArray) arrays.add(path);
1468
- if (type.options?.ref || type.options?.refPath || element?.options?.ref || element?.options?.refPath) {
1469
- references.add(path);
2345
+ const visit = (current, path, depth, parentKey) => {
2346
+ if (errors.length > 0) return;
2347
+ nodes += 1;
2348
+ if (nodes > limits.maxNodes) {
2349
+ pushError(`Request exceeds maximum node budget of ${limits.maxNodes}`, path);
1470
2350
  return;
1471
2351
  }
1472
- if (type.$isSchemaMap || type.instance === "Map") {
1473
- const value = type.$__schemaType;
1474
- if (value) visitType(value, `${path}.$*`, active);
1475
- else opaque.add(path);
1476
- containers.delete(path);
2352
+ if (depth > limits.maxDepth) {
2353
+ pushError(`Request exceeds maximum depth of ${limits.maxDepth}`, path);
1477
2354
  return;
1478
2355
  }
1479
- const child = type.schema ?? element?.schema;
1480
- if (child) {
1481
- containers.add(path);
1482
- if (!active.has(child)) visitSchema(child, path, /* @__PURE__ */ new Set([...active, child]));
2356
+ if (isArray3(current)) {
2357
+ if (parentKey === "$and" || parentKey === "$or" || parentKey === "$nor") {
2358
+ logicalClauses += current.length;
2359
+ if (logicalClauses > limits.maxLogicalClauses) {
2360
+ pushError(`Filter exceeds maximum logical clause budget of ${limits.maxLogicalClauses}`, path);
2361
+ return;
2362
+ }
2363
+ }
2364
+ if (parentKey === "$in") {
2365
+ if (current.length > limits.maxInValues) {
2366
+ pushError(`Filter exceeds maximum $in values of ${limits.maxInValues}`, path);
2367
+ return;
2368
+ }
2369
+ }
2370
+ for (let index = 0; index < current.length; index++) {
2371
+ visit(current[index], path.concat(index), depth + 1, parentKey);
2372
+ if (errors.length > 0) return;
2373
+ }
1483
2374
  return;
1484
2375
  }
1485
- if (type.instance === "Mixed" || element?.instance === "Mixed") opaque.add(path);
1486
- };
1487
- const visitSchema = (current, prefix, active) => {
1488
- const version = current.options.versionKey;
1489
- if (typeof version === "string") protectedPaths.add(prefix ? `${prefix}.${version}` : version);
1490
- for (const name of Object.keys(current.virtuals)) {
1491
- schemaVirtualPaths.add(prefix ? `${prefix}.${name}` : name);
1492
- }
1493
- for (const [name, raw] of Object.entries(current.paths)) {
1494
- if (name.includes("$*")) continue;
1495
- visitType(raw, prefix ? `${prefix}.${name}` : name, active);
2376
+ if (!isPlainObject9(current)) return;
2377
+ for (const [key, child] of Object.entries(current)) {
2378
+ if (key === "__proto__" || key === "prototype" || key === "constructor") {
2379
+ pushError(`Unsupported key: ${key}`, path.concat(key));
2380
+ return;
2381
+ }
2382
+ if (scope === "request" && key === "include") {
2383
+ includeCount += isArray3(child) ? child.length : 1;
2384
+ if (includeCount > limits.maxIncludeCount) {
2385
+ pushError(`Request exceeds maximum include count of ${limits.maxIncludeCount}`, path.concat(key));
2386
+ return;
2387
+ }
2388
+ }
2389
+ if (key === "$$sq") {
2390
+ subQueryCount += 1;
2391
+ if (subQueryCount > limits.maxSubQueryCount) {
2392
+ pushError(`Request exceeds maximum subquery count of ${limits.maxSubQueryCount}`, path.concat(key));
2393
+ return;
2394
+ }
2395
+ visit(child, path.concat(key), depth + 1, key);
2396
+ if (errors.length > 0) return;
2397
+ continue;
2398
+ }
2399
+ visit(child, path.concat(key), depth + 1, key);
2400
+ if (errors.length > 0) return;
1496
2401
  }
1497
2402
  };
1498
- visitSchema(schema, "", /* @__PURE__ */ new Set([schema]));
1499
- const persistedPaths = [...paths];
1500
- const visitVirtuals = (record2, prefix) => {
1501
- for (const [name, value] of Object.entries(record2 ?? {})) {
1502
- if (value === void 0) continue;
1503
- const path = prefix ? `${prefix}.${name}` : name;
1504
- if (!isSafeOutputPath(path)) continue;
1505
- if (value && typeof value === "object" && "sub" in value) {
1506
- if (references.has(path)) continue;
1507
- virtualScopes.add(path);
1508
- add(path);
1509
- containers.add(path);
1510
- visitVirtuals(value.sub, path);
1511
- } else {
1512
- add(path);
1513
- ancestors(path);
1514
- virtualPaths.add(path);
1515
- }
2403
+ visit(value, [], 0);
2404
+ return errors;
2405
+ }
2406
+
2407
+ // src/acl/virtual-descriptor.ts
2408
+ import { isFunction, isPlainObject as isPlainObject10 } from "@web-ts-toolkit/utils";
2409
+ var isVirtualContainerValue = (value) => isPlainObject10(value) && "sub" in value;
2410
+ function getScopeVirtualsObject(root, scopePath = []) {
2411
+ let current = root;
2412
+ for (let i = 0; i < scopePath.length; i += 2) {
2413
+ if (!current || scopePath[i + 1] !== "sub") return null;
2414
+ const container = current[scopePath[i]];
2415
+ if (!isVirtualContainerValue(container)) return null;
2416
+ current = container.sub;
2417
+ }
2418
+ return isPlainObject10(current) ? current : null;
2419
+ }
2420
+ function toDescriptor(leaf, shared = {}) {
2421
+ const record2 = isFunction(leaf) ? { get: leaf } : isPlainObject10(leaf) ? leaf : null;
2422
+ if (!record2 || !isFunction(record2.get)) return void 0;
2423
+ const dependsOn = record2.dependsOn ?? shared.dependsOn ?? [];
2424
+ const populated = record2.dependsOnPopulate === void 0 ? shared.dependsOnPopulate : record2.dependsOnPopulate;
2425
+ return {
2426
+ get: record2.get,
2427
+ dependsOn: [...dependsOn],
2428
+ ...populated === void 0 ? {} : {
2429
+ dependsOnPopulate: populated.map(({ path, select }) => ({
2430
+ path,
2431
+ ...select === void 0 ? {} : { select: Array.isArray(select) ? [...select] : typeof select === "object" ? { ...select } : select }
2432
+ }))
1516
2433
  }
1517
2434
  };
1518
- visitVirtuals(virtuals, "");
1519
- const eligible = [...paths].filter((p) => ![...protectedPaths].some((v) => matchesCatalogPattern(v, p, true)));
1520
- return Object.freeze({
1521
- paths: Object.freeze(eligible.filter((p) => !p.includes("$*"))),
1522
- persistedPaths: Object.freeze(persistedPaths),
1523
- arrayPaths: Object.freeze([...arrays]),
1524
- schemaVirtualPaths: Object.freeze([...schemaVirtualPaths]),
1525
- metadataPaths: Object.freeze([documentPermissionField]),
1526
- dynamicPaths: Object.freeze(eligible.filter((p) => p.includes("$*"))),
1527
- containerPaths: Object.freeze([...containers]),
1528
- opaquePaths: Object.freeze([...opaque]),
1529
- referencePaths: Object.freeze([...references]),
1530
- virtualPaths: Object.freeze([...virtualPaths]),
1531
- virtualScopePaths: Object.freeze([...virtualScopes]),
1532
- protectedPaths: Object.freeze([...protectedPaths])
1533
- });
1534
2435
  }
2436
+ function resolveSnapshotDescriptor(scopeVirtuals, virtualName, access) {
2437
+ const entry = scopeVirtuals?.[virtualName];
2438
+ if (entry === void 0 || isVirtualContainerValue(entry)) return void 0;
2439
+ if (isFunction(entry)) return toDescriptor(entry);
2440
+ if (!isPlainObject10(entry)) return void 0;
2441
+ const record2 = entry;
2442
+ if ("get" in record2) return toDescriptor(record2);
2443
+ return toDescriptor(record2[access], record2) ?? toDescriptor(record2.default, record2);
2444
+ }
2445
+
2446
+ // src/acl/virtual-populate-dependencies.ts
2447
+ import { get as get3, isPlainObject as isPlainObject12 } from "@web-ts-toolkit/utils";
1535
2448
 
1536
2449
  // src/acl/populate-target-configuration.ts
1537
2450
  import { isPlainObject as isPlainObject11 } from "@web-ts-toolkit/utils";
1538
2451
 
1539
2452
  // src/runtime-context.ts
1540
- import { AsyncLocalStorage } from "async_hooks";
1541
- var runtimeStorage = new AsyncLocalStorage();
2453
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
2454
+ var runtimeStorage = new AsyncLocalStorage2();
1542
2455
  function getActiveRuntime() {
1543
2456
  return runtimeStorage.getStore() ?? null;
1544
2457
  }
@@ -1733,7 +2646,7 @@ function captureVirtualPopulateDependencies(runtime, modelName, options, populat
1733
2646
  proposed?.defaults
1734
2647
  );
1735
2648
  const defaults2 = proposed?.defaults ?? runtime.getDefaultModelOptions();
1736
- const readOption = (key) => resolveNestedOption((path2, fallback) => get2(targetOptions, path2, fallback), key, get2(defaults2, key));
2649
+ const readOption = (key) => resolveNestedOption((path2, fallback) => get3(targetOptions, path2, fallback), key, get3(defaults2, key));
1737
2650
  const documentPermissionField = targetOptions.documentPermissionField ?? defaults2.documentPermissionField;
1738
2651
  const catalog = captureAuthorizationFieldCatalog(targetModel.schema, void 0, documentPermissionField);
1739
2652
  const configuration = copyAuthorizationValue(
@@ -1743,7 +2656,12 @@ function captureVirtualPopulateDependencies(runtime, modelName, options, populat
1743
2656
  populatePolicyDefaults,
1744
2657
  ...resolvePopulatePolicy(targetOptions, populatePolicyDefaults),
1745
2658
  permissionSchema: targetOptions.permissionSchema,
1746
- operationAccess: { read: readOption("operationAccess.read") },
2659
+ operationAccess: {
2660
+ read: selectOperationAccessGuard({
2661
+ ...createOperationAccessReaders(targetOptions, defaults2),
2662
+ baseAccess: "read"
2663
+ })
2664
+ },
1747
2665
  baseFilter: { read: readOption("baseFilter.read") },
1748
2666
  overrideFilter: { read: readOption("overrideFilter.read") },
1749
2667
  hydration: targetOptions.hydration
@@ -1823,6 +2741,86 @@ function captureVirtualPopulateDependencies(runtime, modelName, options, populat
1823
2741
  return Object.freeze({ scopes: Object.freeze(scopes) });
1824
2742
  }
1825
2743
 
2744
+ // src/acl/document-permissions-definition.ts
2745
+ import { types as types9 } from "util";
2746
+
2747
+ // src/acl/persisted-dependencies.ts
2748
+ import { types as types8 } from "util";
2749
+ function collectPersistedTopLevel(schema) {
2750
+ return /* @__PURE__ */ new Set([
2751
+ ...Object.keys(schema?.paths ?? {}).map((path) => path.split(".")[0]),
2752
+ ...Object.keys(schema?.obj ?? {})
2753
+ ]);
2754
+ }
2755
+ function capturePersistedDependencies(value, label, storedFields, virtualNames = /* @__PURE__ */ new Set()) {
2756
+ if (value === void 0) return Object.freeze([]);
2757
+ if (!Array.isArray(value) || types8.isProxy(value) || Object.getPrototypeOf(value) !== Array.prototype)
2758
+ throw new TypeError(`${label}: dependsOn must be an array of top-level persisted field names`);
2759
+ const length = Object.getOwnPropertyDescriptor(value, "length").value;
2760
+ if (length > 2e4 || Reflect.ownKeys(value).length !== length + 1)
2761
+ throw new TypeError(`${label}: dependsOn must be a dense array of persisted field names`);
2762
+ const result = [];
2763
+ for (let index = 0; index < length; index++) {
2764
+ const slot = Object.getOwnPropertyDescriptor(value, String(index));
2765
+ if (!slot || !("value" in slot) || typeof slot.value !== "string" || !slot.value)
2766
+ throw new TypeError(`${label}: dependsOn entries must be non-empty strings`);
2767
+ const dep = slot.value;
2768
+ if (dep.includes("."))
2769
+ throw new TypeError(`${label}: dependsOn "${dep}" must be a top-level persisted name (dotted paths rejected)`);
2770
+ if (!isSafeOutputPath(dep)) throw new TypeError(`${label}: unsafe dependsOn field "${dep}"`);
2771
+ if (virtualNames.has(dep)) throw new TypeError(`${label}: dependsOn "${dep}" must not reference another virtual`);
2772
+ if (storedFields && !storedFields.has(dep))
2773
+ throw new TypeError(`${label}: dependsOn "${dep}" is not a persisted field in its scope`);
2774
+ result.push(dep);
2775
+ }
2776
+ return Object.freeze([...new Set(result)]);
2777
+ }
2778
+
2779
+ // src/acl/document-permissions-definition.ts
2780
+ function dataRecord(value, label) {
2781
+ if (!value || typeof value !== "object" || types9.isProxy(value))
2782
+ throw new TypeError(`${label}: expected a function, { get, dependsOn? }, or per-access record`);
2783
+ const prototype = Object.getPrototypeOf(value);
2784
+ if (prototype !== Object.prototype && prototype !== null)
2785
+ throw new TypeError(`${label}: definition must be a plain object`);
2786
+ const result = /* @__PURE__ */ Object.create(null);
2787
+ const keys2 = Reflect.ownKeys(value);
2788
+ if (keys2.length > 2e4) throw new TypeError(`${label}: too many definition entries`);
2789
+ for (const key of keys2) {
2790
+ if (typeof key !== "string" || ["__proto__", "constructor", "prototype"].includes(key))
2791
+ throw new TypeError(`${label}: unsafe definition key`);
2792
+ const slot = Object.getOwnPropertyDescriptor(value, key);
2793
+ if (!slot.enumerable || !("value" in slot))
2794
+ throw new TypeError(`${label}: definition entries must be enumerable data properties`);
2795
+ Object.defineProperty(result, key, { value: slot.value, enumerable: true });
2796
+ }
2797
+ return result;
2798
+ }
2799
+ function captureLeaf(value, label, scope) {
2800
+ if (typeof value === "function") return value;
2801
+ const record2 = dataRecord(value, label);
2802
+ if (typeof record2.get !== "function") throw new TypeError(`${label}: descriptor.get must be callable`);
2803
+ if (Object.keys(record2).some((key) => key !== "get" && key !== "dependsOn"))
2804
+ throw new TypeError(`${label}: descriptor accepts only get/dependsOn; cannot mix per-access keys`);
2805
+ return Object.freeze({
2806
+ get: record2.get,
2807
+ dependsOn: capturePersistedDependencies(record2.dependsOn, label, scope.storedFields, scope.virtualNames)
2808
+ });
2809
+ }
2810
+ function captureDocumentPermissionsDefinition(value, scope = {}) {
2811
+ if (value === void 0) return void 0;
2812
+ if (typeof value === "function") return value;
2813
+ const record2 = dataRecord(value, "docPermissions");
2814
+ if (Object.hasOwn(record2, "get") || Object.hasOwn(record2, "dependsOn"))
2815
+ return captureLeaf(record2, "docPermissions", scope);
2816
+ const entries = Object.entries(record2).map(([access, leaf]) => {
2817
+ if (!/^[A-Za-z_][A-Za-z0-9_$]*$/.test(access))
2818
+ throw new TypeError(`docPermissions: unsafe or dotted access "${access}"`);
2819
+ return [access, leaf === void 0 ? void 0 : captureLeaf(leaf, `docPermissions.${access}`, scope)];
2820
+ });
2821
+ return Object.freeze(Object.fromEntries(entries));
2822
+ }
2823
+
1826
2824
  // src/runtime.ts
1827
2825
  var mongooseJsonSchemaInitialized = false;
1828
2826
  var ensureMongooseJsonSchemaInitialized = () => {
@@ -1833,8 +2831,7 @@ var ensureMongooseJsonSchemaInitialized = () => {
1833
2831
  var pluralize = mongoose.pluralize();
1834
2832
  var FIELD_ACCESS_KEYS = ["list", "create", "read", "update"];
1835
2833
  var defaultModelOptions = {
1836
- basePath: null,
1837
- alwaysSelectFields: []
2834
+ basePath: null
1838
2835
  };
1839
2836
  var modelOverrides = (options) => {
1840
2837
  const result = Object.fromEntries(
@@ -1842,7 +2839,6 @@ var modelOverrides = (options) => {
1842
2839
  ([key, value]) => value !== void 0 || key === "operationAccess" || isPopulatePolicyKey(key)
1843
2840
  )
1844
2841
  );
1845
- for (const key of unsafeServerOptions) if (key in result) result[key] = result[key] === true;
1846
2842
  return cloneOptionsSnapshot(result);
1847
2843
  };
1848
2844
  var defaultDataOptions = {
@@ -1926,29 +2922,14 @@ var virtualFullPath = (prefix, name) => prefix ? `${prefix}.${name}` : name;
1926
2922
  var virtualPathsOverlap = (virtualPath, permissionField) => {
1927
2923
  if (!virtualPath || !permissionField) return false;
1928
2924
  try {
1929
- if (get3(set3({}, virtualPath, true), permissionField) !== void 0) return true;
1930
- if (get3(set3({}, permissionField, true), virtualPath) !== void 0) return true;
2925
+ if (get4(set3({}, virtualPath, true), permissionField) !== void 0) return true;
2926
+ if (get4(set3({}, permissionField, true), virtualPath) !== void 0) return true;
1931
2927
  } catch {
1932
2928
  return false;
1933
2929
  }
1934
2930
  return false;
1935
2931
  };
1936
- var collectStoredTopLevel = (schema) => {
1937
- const fields = /* @__PURE__ */ new Set();
1938
- if (!schema) return fields;
1939
- const paths = schema.paths;
1940
- if (paths) {
1941
- for (const p of Object.keys(paths)) {
1942
- const top = p.split(".")[0];
1943
- if (top) fields.add(top);
1944
- }
1945
- }
1946
- const obj = schema.obj;
1947
- if (obj) {
1948
- for (const k of Object.keys(obj)) fields.add(k);
1949
- }
1950
- return fields;
1951
- };
2932
+ var collectStoredTopLevel = collectPersistedTopLevel;
1952
2933
  var getChildSchemaForField = (parentSchema, fieldName) => {
1953
2934
  if (!parentSchema) return null;
1954
2935
  try {
@@ -1987,32 +2968,7 @@ var cloneModelOptionForUpdate = (value) => {
1987
2968
  );
1988
2969
  };
1989
2970
  var validateVirtualDependsOn = (dependsOn, entryLabel, storedFields, siblingVirtualNames) => {
1990
- if (dependsOn === void 0) return [];
1991
- if (!isArray4(dependsOn)) {
1992
- throw new Error(`Virtual ${entryLabel}: dependsOn must be an array of top-level persisted field names`);
1993
- }
1994
- const list = dependsOn;
1995
- for (const dep of list) {
1996
- if (!isString3(dep) || dep.length === 0) {
1997
- throw new Error(`Virtual ${entryLabel}: dependsOn entries must be non-empty strings`);
1998
- }
1999
- if (dep.includes(".")) {
2000
- throw new Error(
2001
- `Virtual ${entryLabel}: dependsOn "${dep}" must be a top-level persisted name relative to its scope (dotted paths rejected)`
2002
- );
2003
- }
2004
- if (siblingVirtualNames.has(dep)) {
2005
- throw new Error(
2006
- `Virtual ${entryLabel}: dependsOn "${dep}" must not reference another virtual (virtual-to-virtual rejected)`
2007
- );
2008
- }
2009
- if (!storedFields.has(dep)) {
2010
- throw new Error(
2011
- `Virtual ${entryLabel}: dependsOn "${dep}" is not a persisted field in its scope (validated against the receiving Mongoose schema/child scope)`
2012
- );
2013
- }
2014
- }
2015
- return list;
2971
+ return [...capturePersistedDependencies(dependsOn, `Virtual ${entryLabel}`, storedFields, siblingVirtualNames)];
2016
2972
  };
2017
2973
  var validateVirtualLeafValue = (value, entryLabel, storedFields, siblingVirtualNames, sharedDependsOn) => {
2018
2974
  if (isFunction2(value)) return;
@@ -2187,6 +3143,7 @@ var AccessRuntime = class {
2187
3143
  this.defaultModelOptions = new OptionsManager({
2188
3144
  listHardLimit: DEFAULT_LIST_HARD_LIMIT,
2189
3145
  documentPermissionField: "_permissions",
3146
+ disableFieldPermissions: true,
2190
3147
  idParam: "id",
2191
3148
  idField: "_id",
2192
3149
  parentPath: "/",
@@ -2196,19 +3153,14 @@ var AccessRuntime = class {
2196
3153
  requireOperationAccessForPopulateQueries: true,
2197
3154
  requireOperationAccessForPopulateDependencies: true,
2198
3155
  modelPermissionPrefix: "",
2199
- unsafeSkipListDocumentSnapshotChecks: false,
2200
- unsafeSkipReadDocumentSnapshotChecks: false,
2201
- unsafeSkipListOutputSnapshotChecks: false,
2202
- unsafeSkipReadOutputSnapshotChecks: false,
2203
- unsafeSkipListNestedDocumentSnapshotChecks: false,
2204
- unsafeSkipReadNestedDocumentSnapshotChecks: false,
2205
- unsafeSkipListInitialOutputSnapshotCopy: false,
2206
- unsafeSkipReadInitialOutputSnapshotCopy: false,
2207
- unsafeUseListAuthorizationFastPath: false,
2208
- unsafeUseReadAuthorizationFastPath: false
3156
+ readAuthorizationMode: "isolated",
3157
+ listAuthorizationMode: "isolated",
3158
+ createAuthorizationMode: "isolated",
3159
+ updateAuthorizationMode: "isolated"
2209
3160
  }).build();
2210
3161
  this.modelOptions = {};
2211
3162
  this.modelOptionOverrides = {};
3163
+ this.publishingAuthorizationModes = false;
2212
3164
  this.modelJsonSchemas = {};
2213
3165
  this.dataOptions = {};
2214
3166
  this.modelRefs = {};
@@ -2217,6 +3169,10 @@ var AccessRuntime = class {
2217
3169
  this.modelInstances = {};
2218
3170
  this.openApiRegistry = new OpenApiRegistry();
2219
3171
  this.openApiPathPrefix = "";
3172
+ assertAuthorizationModeOptions(options, false);
3173
+ assertNoServerModelControls(options, (detail) => {
3174
+ throw new TypeError(detail);
3175
+ });
2220
3176
  this.allowGlobalModelLookup = options.allowGlobalModelLookup ?? false;
2221
3177
  ensureMongooseJsonSchemaInitialized();
2222
3178
  }
@@ -2309,6 +3265,52 @@ var AccessRuntime = class {
2309
3265
  };
2310
3266
  }
2311
3267
  restoreBootstrapSnapshot(snapshot) {
3268
+ assertAuthorizationModeOptions(snapshot, false);
3269
+ const reject = (detail) => {
3270
+ throw new TypeError(detail);
3271
+ };
3272
+ for (const key of [
3273
+ "globalOptions",
3274
+ "defaultModelOptions",
3275
+ "modelOptions",
3276
+ "modelOptionOverrides",
3277
+ "dataOptions",
3278
+ "modelInstances",
3279
+ "modelJsonSchemas",
3280
+ "modelRefs",
3281
+ "modelSubs",
3282
+ "modelAtts",
3283
+ "openApi"
3284
+ ]) {
3285
+ const slot = Object.getOwnPropertyDescriptor(snapshot, key);
3286
+ if (!slot || !("value" in slot) || !slot.enumerable) reject(`Invalid bootstrap snapshot slot: ${key}`);
3287
+ if (!slot.value || typeof slot.value !== "object" || Array.isArray(slot.value))
3288
+ reject(`Invalid bootstrap snapshot object: ${key}`);
3289
+ admitControlPrototypes(slot.value, reject);
3290
+ if (key === "globalOptions" || key === "defaultModelOptions" || key === "openApi") continue;
3291
+ for (const entry of Reflect.ownKeys(slot.value)) {
3292
+ const item = Object.getOwnPropertyDescriptor(slot.value, entry);
3293
+ if (typeof entry !== "string" || !("value" in item) || !item.enumerable)
3294
+ reject(`Invalid bootstrap snapshot entry: ${key}`);
3295
+ }
3296
+ }
3297
+ assertAuthorizationModeOptions(snapshot.globalOptions, false);
3298
+ assertNoServerModelControls(snapshot.globalOptions, reject);
3299
+ assertAuthorizationModeOptions(snapshot.defaultModelOptions, true);
3300
+ assertOperationAccessOptions(snapshot.defaultModelOptions);
3301
+ assertNoServerModelControls(snapshot.defaultModelOptions, reject, "model-options");
3302
+ assertPublicDefaults(snapshot.defaultModelOptions.defaults);
3303
+ for (const options of [...Object.values(snapshot.modelOptions), ...Object.values(snapshot.modelOptionOverrides)]) {
3304
+ assertAuthorizationModeOptions(options, true);
3305
+ assertOperationAccessOptions(options);
3306
+ assertNoServerModelControls(options, reject, "model-options");
3307
+ assertPublicDefaults(options.defaults);
3308
+ }
3309
+ for (const options of Object.values(snapshot.dataOptions)) {
3310
+ assertAuthorizationModeOptions(options, false);
3311
+ assertOperationAccessOptions(options);
3312
+ assertNoServerModelControls(options, reject, "data-options");
3313
+ }
2312
3314
  this.globalOptions.restore(snapshot.globalOptions);
2313
3315
  this.defaultModelOptions.restore(snapshot.defaultModelOptions);
2314
3316
  for (const name of Object.keys(this.modelOptionOverrides)) delete this.modelOptionOverrides[name];
@@ -2368,11 +3370,21 @@ var AccessRuntime = class {
2368
3370
  }
2369
3371
  /** Shallowly replace supplied global values; nested objects such as requestComplexity are not deep-merged. */
2370
3372
  setGlobalOptions(options) {
3373
+ assertAuthorizationModeOptions(options, false);
3374
+ assertNoServerModelControls(options, (detail) => {
3375
+ throw new TypeError(detail);
3376
+ });
2371
3377
  for (const key of populatePolicyKeys) if (key in options) assertNoGlobalPopulatePolicy(key);
2372
3378
  this.globalOptions.assign({ ...options });
2373
3379
  }
2374
3380
  setGlobalOption(key, value) {
3381
+ assertAuthorizationModeKey(key, false);
2375
3382
  assertNoGlobalPopulatePolicy(String(key));
3383
+ const proposed = {};
3384
+ set3(proposed, key, value);
3385
+ assertNoServerModelControls(proposed, (detail) => {
3386
+ throw new TypeError(detail);
3387
+ });
2376
3388
  this.globalOptions.set(key, value);
2377
3389
  }
2378
3390
  getGlobalOptions() {
@@ -2383,6 +3395,18 @@ var AccessRuntime = class {
2383
3395
  }
2384
3396
  /** Update inherited model defaults shallowly. Explicit model values and captured calls are unchanged. */
2385
3397
  setDefaultModelOptions(options) {
3398
+ assertAuthorizationModeOptions(options, true);
3399
+ assertOperationAccessOptions(options);
3400
+ assertNoServerModelControls(
3401
+ options,
3402
+ (detail) => {
3403
+ throw new TypeError(detail);
3404
+ },
3405
+ "model-options"
3406
+ );
3407
+ options = { ...options };
3408
+ for (const key of authorizationModeKeys)
3409
+ if (key in options && options[key] === void 0) options[key] = "isolated";
2386
3410
  assertPublicDefaults(options.defaults);
2387
3411
  if ("hydration" in options) options = { ...options, hydration: normalizeHydration(options.hydration) };
2388
3412
  const draft = new OptionsManager(
@@ -2392,11 +3416,32 @@ var AccessRuntime = class {
2392
3416
  this.publishDefaultModelOptions(draft.fetch());
2393
3417
  }
2394
3418
  setDefaultModelOption(key, value) {
2395
- const keyStr = String(key);
2396
- if (keyStr === "defaults") assertPublicDefaults(value);
2397
- else if (keyStr.startsWith("defaults.")) {
3419
+ assertAuthorizationModeKey(key, true);
3420
+ const keyStr = key;
3421
+ assertOperationAccessUpdate(keyStr, value);
3422
+ if (authorizationModeKeys.includes(keyStr)) {
3423
+ this.setDefaultModelOptions({ [keyStr]: value });
3424
+ return;
3425
+ }
3426
+ if (keyStr === "defaults") {
3427
+ assertNoServerModelControls(
3428
+ value,
3429
+ (detail) => {
3430
+ throw new TypeError(detail);
3431
+ },
3432
+ "defaults"
3433
+ );
3434
+ assertPublicDefaults(value);
3435
+ } else if (keyStr.startsWith("defaults.")) {
2398
3436
  const proposed = {};
2399
3437
  set3(proposed, keyStr.slice("defaults.".length), value);
3438
+ assertNoServerModelControls(
3439
+ proposed,
3440
+ (detail) => {
3441
+ throw new TypeError(detail);
3442
+ },
3443
+ "defaults"
3444
+ );
2400
3445
  assertPublicDefaults(proposed);
2401
3446
  }
2402
3447
  const draft = new OptionsManager(
@@ -2423,92 +3468,62 @@ var AccessRuntime = class {
2423
3468
  for (const key of populatePolicyKeys) delete inherited[key];
2424
3469
  const effective = { ...defaultModelOptions, ...inherited, ...overrides, modelName };
2425
3470
  effective.basePath = normalizeBasePath(modelName, effective.basePath);
2426
- for (const key of unsafeServerOptions) effective[key] = effective[key] === true;
2427
3471
  refreshPermissionMetadata(effective);
2428
3472
  return cloneOptionsSnapshot(effective);
2429
3473
  }
2430
3474
  validateModelOptions(modelName, options, proposed) {
2431
- validateVirtualsTree(
2432
- this.getModelInstance(modelName),
2433
- options.virtuals,
2434
- options.documentPermissionField ?? "_permissions",
2435
- modelName
2436
- );
3475
+ assertOperationAccessOptions(options);
3476
+ const model = this.getModelInstance(modelName);
3477
+ validateVirtualsTree(model, options.virtuals, options.documentPermissionField ?? "_permissions", modelName);
3478
+ captureDocumentPermissionsDefinition(options.docPermissions, {
3479
+ storedFields: collectPersistedTopLevel(model?.schema),
3480
+ virtualNames: /* @__PURE__ */ new Set([
3481
+ ...Object.keys(model?.schema.virtuals ?? {}),
3482
+ ...Object.entries(options.virtuals ?? {}).filter(([, value]) => value !== void 0 && !isVirtualContainerValue2(value)).map(([name]) => name)
3483
+ ])
3484
+ });
2437
3485
  captureVirtualPopulateDependencies(this, modelName, options, void 0, proposed);
2438
3486
  }
2439
3487
  publishDefaultModelOptions(options) {
3488
+ assertOperationAccessOptions(options);
2440
3489
  const next = { ...options };
2441
- for (const key of unsafeServerOptions) if (key in next) next[key] = next[key] === true;
2442
3490
  const defaults2 = cloneOptionsSnapshot(next);
2443
3491
  const models = new Map(
2444
3492
  Object.keys(this.modelOptions).map((name) => [name, this.resolveModelOptions(name, void 0, defaults2)])
2445
3493
  );
2446
3494
  for (const [name, options2] of models) this.validateModelOptions(name, options2, { defaults: defaults2, models });
2447
- this.deferSnapshotWarnings(() => {
3495
+ this.publishAuthorizationModes(() => {
2448
3496
  this.defaultModelOptions.restore(defaults2);
2449
3497
  for (const [name, options2] of models) this.modelOptions[name].restore(options2);
2450
3498
  });
2451
3499
  }
2452
- warnSnapshotFlag(modelName, key) {
2453
- if (this.pendingSnapshotWarnings) {
2454
- this.pendingSnapshotWarnings.push({ modelName, key });
2455
- return;
2456
- }
2457
- const operation = key.startsWith("unsafeSkipRead") ? "read" : "list";
2458
- const category = key.includes("NestedDocument") ? "nested-document" : key.includes("Output") ? "output" : "document";
2459
- const risk = category === "output" ? "output mutation" : "source mutation";
2460
- try {
2461
- this.getGlobalOption("logger")?.warn?.(
2462
- `UNSAFE: ${operation} ${category} snapshot checks disabled; ${risk} can leave stale authorization decisions. Restore ${key}=false after the temporary workaround.`,
2463
- { modelName }
2464
- );
2465
- } catch {
2466
- }
2467
- }
2468
- deferSnapshotWarnings(publish) {
2469
- if (this.pendingSnapshotWarnings) return publish();
2470
- const copyModes = this.initialOutputCopyModes();
2471
- const fastModes = this.authorizationFastPathModes();
2472
- const pending = [];
2473
- this.pendingSnapshotWarnings = pending;
3500
+ /** Warn only on effective transitions into trusted, after the entire update commits. */
3501
+ publishAuthorizationModes(publish) {
3502
+ if (this.publishingAuthorizationModes) return publish();
3503
+ const capture = () => new Map([
3504
+ ["default-model", this.getDefaultModelOptions()],
3505
+ ...Object.entries(this.modelOptions).map(([name, manager]) => [name, manager.fetch()])
3506
+ ]);
3507
+ const before = capture();
3508
+ this.publishingAuthorizationModes = true;
2474
3509
  let result;
2475
3510
  try {
2476
3511
  result = publish();
2477
3512
  } finally {
2478
- this.pendingSnapshotWarnings = void 0;
2479
- }
2480
- const nextCopyModes = this.initialOutputCopyModes();
2481
- const nextFastModes = this.authorizationFastPathModes();
2482
- for (const { modelName, key } of pending) this.warnSnapshotFlag(modelName, key);
2483
- for (const [modelName, modes] of nextCopyModes) {
2484
- for (const operation of ["List", "Read"]) {
2485
- const mode = modes[operation];
2486
- if (mode === "off" || mode === copyModes.get(modelName)?.[operation]) continue;
2487
- const key = `unsafeSkip${operation}InitialOutputSnapshotCopy`;
2488
- const prerequisite = `unsafeSkip${operation}OutputSnapshotChecks`;
2489
- try {
2490
- this.getGlobalOption("logger")?.warn?.(
2491
- mode === "active" ? `UNSAFE: ${operation.toLowerCase()} initial output snapshot copying disabled for eligible graphs; omitted native normalization/validation can change side effects and authorization outcomes. Restore ${key}=false after the temporary workaround.` : `UNSAFE: ${key} is dormant; requires ${prerequisite}=true. Initial copying and output comparisons remain enabled. Restore ${key}=false if not intended.`,
2492
- { modelName }
2493
- );
2494
- } catch {
2495
- }
2496
- }
3513
+ this.publishingAuthorizationModes = false;
2497
3514
  }
2498
- for (const [modelName, modes] of nextFastModes) {
2499
- for (const origin of ["list", "read"]) {
2500
- const captured = modes[origin];
2501
- const previous = fastModes.get(modelName)?.[origin];
2502
- if (captured.mode === "off" || captured.mode === previous?.mode && (captured.mode !== "dormant" || captured.prerequisites === previous.prerequisites))
2503
- continue;
2504
- const key = origin === "read" ? "unsafeUseReadAuthorizationFastPath" : "unsafeUseListAuthorizationFastPath";
2505
- const missing = authorizationFastPathPrerequisites(origin).filter(
2506
- (_, index) => !(captured.prerequisites & 1 << index)
2507
- );
3515
+ const after = capture();
3516
+ for (const [modelName, options] of after) {
3517
+ for (const key of authorizationModeKeys) {
3518
+ if (options[key] !== "trusted" || before.get(modelName)?.[key] === "trusted") continue;
2508
3519
  try {
2509
3520
  this.getGlobalOption("logger")?.warn?.(
2510
- captured.mode === "active" ? `UNSAFE: ${origin} authorization fast path active (${key}=true); eligible query rows borrow source/grant/context leaves and omit repeated snapshots, isolation and descendant graph checks. Borrowed source/grant mutation, stale decisions, descendant replacement, lost native normalization/validation observations and loss of full unvisited source shape/bounds can change authorization outcomes, including denial becoming allowance. Actual operation/row/field rules, document hooks/getters, request/work limits and cheap exact root authority remain; shallow-unproven rows retain compatible copies and graph checks. Restore ${key}=false after the temporary workaround.` : `UNSAFE: ${key} is dormant; requires ${missing.map((flag) => `${flag}=true`).join(", ")}. Original snapshot flag behavior remains unchanged. Restore ${key}=false if not intended.`,
2511
- { modelName }
3521
+ "Trusted authorization output source mode enabled; admitted source/document-hook input may be borrowed. Write input is unchanged. Actor, policy, facts, getter views and selected output bounds remain owned.",
3522
+ {
3523
+ modelName,
3524
+ access: authorizationModeOperations[key],
3525
+ category: "trustedAuthorizationSource"
3526
+ }
2512
3527
  );
2513
3528
  } catch {
2514
3529
  }
@@ -2516,25 +3531,6 @@ var AccessRuntime = class {
2516
3531
  }
2517
3532
  return result;
2518
3533
  }
2519
- authorizationFastPathModes() {
2520
- return new Map(
2521
- Object.entries(this.modelOptions).map(([modelName, manager]) => {
2522
- const options = manager.fetch();
2523
- return [
2524
- modelName,
2525
- { list: captureAuthorizationFastPath(options, "list"), read: captureAuthorizationFastPath(options, "read") }
2526
- ];
2527
- })
2528
- );
2529
- }
2530
- initialOutputCopyModes() {
2531
- return new Map(
2532
- Object.entries(this.modelOptions).map(([modelName, options]) => {
2533
- const mode = (operation) => options.get(`unsafeSkip${operation}InitialOutputSnapshotCopy`) !== true ? "off" : options.get(`unsafeSkip${operation}OutputSnapshotChecks`) === true ? "active" : "dormant";
2534
- return [modelName, { List: mode("List"), Read: mode("Read") }];
2535
- })
2536
- );
2537
- }
2538
3534
  createModelOptions(modelName, options = this.resolveModelOptions(modelName)) {
2539
3535
  const model = this.getModelInstance(modelName);
2540
3536
  if (!model) {
@@ -2543,16 +3539,11 @@ var AccessRuntime = class {
2543
3539
  );
2544
3540
  }
2545
3541
  const manager = new OptionsManager(options);
2546
- const snapshotFlagChanged = (newValue, key, target, oldValue) => {
2547
- target[key] = newValue === true;
2548
- if (newValue !== true || oldValue === true) return;
2549
- this.warnSnapshotFlag(modelName, key);
2550
- };
2551
3542
  manager.onchange("permissionSchema", function(_newval, _key, target) {
2552
3543
  refreshPermissionMetadata(target);
2553
3544
  }).onchange("modelPermissionPrefix", function(_newval, _key, target) {
2554
3545
  refreshPermissionMetadata(target);
2555
- }).onchange("unsafeSkipListDocumentSnapshotChecks", snapshotFlagChanged).onchange("unsafeSkipReadDocumentSnapshotChecks", snapshotFlagChanged).onchange("unsafeSkipListOutputSnapshotChecks", snapshotFlagChanged).onchange("unsafeSkipReadOutputSnapshotChecks", snapshotFlagChanged).onchange("unsafeSkipListNestedDocumentSnapshotChecks", snapshotFlagChanged).onchange("unsafeSkipReadNestedDocumentSnapshotChecks", snapshotFlagChanged).onchange("basePath", function(newval, key, target) {
3546
+ }).onchange("basePath", function(newval, key, target) {
2556
3547
  target[key] = normalizeBasePath(
2557
3548
  modelName,
2558
3549
  isString3(newval) || isNil2(newval) ? newval : void 0
@@ -2564,7 +3555,7 @@ var AccessRuntime = class {
2564
3555
  getOrCreateModelOptions(modelName) {
2565
3556
  let manager = this.modelOptions[modelName];
2566
3557
  if (!manager) {
2567
- manager = this.deferSnapshotWarnings(() => {
3558
+ manager = this.publishAuthorizationModes(() => {
2568
3559
  const created = this.createModelOptions(modelName);
2569
3560
  this.modelOptions[modelName] = created;
2570
3561
  return created;
@@ -2581,13 +3572,28 @@ var AccessRuntime = class {
2581
3572
  * calls capture the owner's current options/defaults; in-flight calls retain their snapshot.
2582
3573
  */
2583
3574
  setModelOptions(modelName, options) {
3575
+ assertAuthorizationModeOptions(options, true);
3576
+ assertOperationAccessOptions(options);
3577
+ assertNoServerModelControls(
3578
+ options,
3579
+ (detail) => {
3580
+ throw new TypeError(detail);
3581
+ },
3582
+ "model-options"
3583
+ );
2584
3584
  assertPublicDefaults(options.defaults);
3585
+ if ("docPermissions" in options) {
3586
+ const slot = Object.getOwnPropertyDescriptor(options, "docPermissions");
3587
+ if (!slot || !("value" in slot) || !slot.enumerable)
3588
+ throw new TypeError("docPermissions must be an enumerable data property");
3589
+ options = { ...options, docPermissions: captureDocumentPermissionsDefinition(slot.value) };
3590
+ }
2585
3591
  options = normalizePopulatePolicyOptions(options);
2586
3592
  if ("hydration" in options) options = { ...options, hydration: normalizeHydration(options.hydration) };
2587
3593
  const overrides = modelOverrides({ ...this.modelOptionOverrides[modelName], ...options });
2588
3594
  const effective = this.resolveModelOptions(modelName, overrides);
2589
3595
  this.validateModelOptions(modelName, effective);
2590
- this.deferSnapshotWarnings(() => {
3596
+ this.publishAuthorizationModes(() => {
2591
3597
  const manager = this.modelOptions[modelName];
2592
3598
  if (manager) manager.restore(effective);
2593
3599
  else this.modelOptions[modelName] = this.createModelOptions(modelName, effective);
@@ -2595,16 +3601,43 @@ var AccessRuntime = class {
2595
3601
  });
2596
3602
  }
2597
3603
  setModelOption(modelName, key, value) {
2598
- const keyStr = String(key);
3604
+ assertAuthorizationModeKey(key, true);
3605
+ const keyStr = key;
3606
+ assertOperationAccessUpdate(keyStr, value);
3607
+ if (keyStr === "docPermissions") {
3608
+ value = captureDocumentPermissionsDefinition(value);
3609
+ } else if (keyStr.startsWith("docPermissions.")) {
3610
+ const path2 = keyStr.slice("docPermissions.".length);
3611
+ if (path2.includes(".") || path2 === "get" || path2 === "dependsOn")
3612
+ throw new TypeError(
3613
+ "docPermissions dotted setters replace an access definition; set { get, dependsOn? } together"
3614
+ );
3615
+ captureDocumentPermissionsDefinition({ [path2]: value });
3616
+ }
2599
3617
  if (keyStr === "hydration" || keyStr.startsWith("hydration.")) {
2600
3618
  const hydration = normalizeHydrationUpdate(this.resolveModelOptions(modelName).hydration, keyStr, value);
2601
3619
  this.setModelOptions(modelName, { hydration });
2602
3620
  return;
2603
3621
  }
2604
- if (keyStr === "defaults") assertPublicDefaults(value);
2605
- else if (keyStr.startsWith("defaults.")) {
3622
+ if (keyStr === "defaults") {
3623
+ assertNoServerModelControls(
3624
+ value,
3625
+ (detail) => {
3626
+ throw new TypeError(detail);
3627
+ },
3628
+ "defaults"
3629
+ );
3630
+ assertPublicDefaults(value);
3631
+ } else if (keyStr.startsWith("defaults.")) {
2606
3632
  const proposed = {};
2607
3633
  set3(proposed, keyStr.slice("defaults.".length), value);
3634
+ assertNoServerModelControls(
3635
+ proposed,
3636
+ (detail) => {
3637
+ throw new TypeError(detail);
3638
+ },
3639
+ "defaults"
3640
+ );
2608
3641
  assertPublicDefaults(proposed);
2609
3642
  }
2610
3643
  const [root, ...path] = keyStr.split(".");
@@ -2613,9 +3646,12 @@ var AccessRuntime = class {
2613
3646
  return;
2614
3647
  }
2615
3648
  const current = this.resolveModelOptions(modelName);
2616
- const nested = cloneModelOptionForUpdate(isPlainObject13(current[root]) ? current[root] : {});
3649
+ const directDocumentPermissions = root === "docPermissions" && current[root] && typeof current[root] === "object" && Object.hasOwn(current[root], "get");
3650
+ const nested = cloneModelOptionForUpdate(
3651
+ isPlainObject13(current[root]) && !directDocumentPermissions ? current[root] : {}
3652
+ );
2617
3653
  if (root === "virtuals" && value === void 0) {
2618
- const parent = path.length === 1 ? nested : get3(nested, path.slice(0, -1));
3654
+ const parent = path.length === 1 ? nested : get4(nested, path.slice(0, -1));
2619
3655
  if (isPlainObject13(parent)) delete parent[path[path.length - 1]];
2620
3656
  } else set3(nested, path, value);
2621
3657
  this.setModelOptions(modelName, { [root]: nested });
@@ -2628,8 +3664,9 @@ var AccessRuntime = class {
2628
3664
  /**
2629
3665
  * Generic stored exact → parent.default → parent lookup; only undefined falls through.
2630
3666
  * The exact runtime-model-default path is the final fallback if the stored parent is
2631
- * absent. This is not the route-specific variant-to-base resolver; use
2632
- * getExactModelOption to inspect a variant including its exact model-default fallback.
3667
+ * absent. This raw generic lookup is not the final nested operation-entry resolver;
3668
+ * it may return an operation object. getExactModelOption inspects a member including
3669
+ * its same-owner exact model-default fallback, without resolving entry policy.
2633
3670
  */
2634
3671
  getModelOption(modelName, key, defaultValue) {
2635
3672
  const manager = this.getOrCreateModelOptions(modelName);
@@ -2639,7 +3676,7 @@ var AccessRuntime = class {
2639
3676
  );
2640
3677
  return getNestedOption(manager, key, defaultModelValue);
2641
3678
  }
2642
- /** Exact stored path, then the same runtime-model-default path; no parent/default or variant-to-base lookup. */
3679
+ /** Exact stored path, then the same runtime-model-default path; no parent/default or final entry resolution. */
2643
3680
  getExactModelOption(modelName, key) {
2644
3681
  const manager = this.getOrCreateModelOptions(modelName);
2645
3682
  const defaultModelValue = this.getDefaultModelOption(key);
@@ -2721,10 +3758,30 @@ var AccessRuntime = class {
2721
3758
  return manager;
2722
3759
  }
2723
3760
  setDataOptions(dataName, options) {
3761
+ assertAuthorizationModeOptions(options, false);
3762
+ assertOperationAccessOptions(options);
3763
+ assertNoServerModelControls(
3764
+ options,
3765
+ (detail) => {
3766
+ throw new TypeError(detail);
3767
+ },
3768
+ "data-options"
3769
+ );
2724
3770
  const manager = this.getOrCreateDataOptions(dataName);
2725
3771
  manager.assign(options);
2726
3772
  }
2727
3773
  setDataOption(dataName, key, value) {
3774
+ assertAuthorizationModeKey(key, false);
3775
+ assertOperationAccessUpdate(key, value);
3776
+ const proposed = {};
3777
+ set3(proposed, key, value);
3778
+ assertNoServerModelControls(
3779
+ proposed,
3780
+ (detail) => {
3781
+ throw new TypeError(detail);
3782
+ },
3783
+ "data-options"
3784
+ );
2728
3785
  const manager = this.getOrCreateDataOptions(dataName);
2729
3786
  manager.set(key, value);
2730
3787
  }
@@ -2771,16 +3828,16 @@ var AccessRuntime = class {
2771
3828
  }
2772
3829
  getModelRef(modelName, refPath) {
2773
3830
  this.ensureModelMeta(modelName);
2774
- const value = get3(this.modelRefs, `${modelName}.${refPath}`, null);
3831
+ const value = get4(this.modelRefs, `${modelName}.${refPath}`, null);
2775
3832
  return isString3(value) ? value : null;
2776
3833
  }
2777
3834
  getModelSub(modelName) {
2778
3835
  this.ensureModelMeta(modelName);
2779
- return get3(this.modelSubs, modelName, []);
3836
+ return get4(this.modelSubs, modelName, []);
2780
3837
  }
2781
3838
  getModelAtt(modelName) {
2782
3839
  this.ensureModelMeta(modelName);
2783
- return get3(this.modelAtts, modelName, []);
3840
+ return get4(this.modelAtts, modelName, []);
2784
3841
  }
2785
3842
  };
2786
3843
  var defaultRuntime = new AccessRuntime({ allowGlobalModelLookup: true });