@web-ts-toolkit/access-router 0.65.0 → 0.66.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/advanced.js CHANGED
@@ -126,56 +126,991 @@ var FilterOperator = /* @__PURE__ */ ((FilterOperator2) => {
126
126
  var import_express_json_router3 = __toESM(require("@web-ts-toolkit/express-json-router"));
127
127
 
128
128
  // src/runtime.ts
129
- var import_mongoose3 = __toESM(require("mongoose"));
129
+ var import_mongoose4 = __toESM(require("mongoose"));
130
130
 
131
131
  // src/validation/public-admission.ts
132
+ var import_express_json_router2 = __toESM(require("@web-ts-toolkit/express-json-router"));
133
+ var import_node_util6 = require("util");
134
+ var import_utils2 = require("@web-ts-toolkit/utils");
135
+
136
+ // src/acl/output-work-ledger.ts
137
+ var import_node_async_hooks = require("async_hooks");
138
+
139
+ // src/acl/authorization-snapshot.ts
140
+ var import_node_util4 = require("util");
141
+ var import_mongoose2 = require("mongoose");
132
142
  var import_express_json_router = __toESM(require("@web-ts-toolkit/express-json-router"));
143
+
144
+ // src/acl/field-catalog.ts
145
+ var import_node_util = require("util");
146
+ var ownedCatalogs = /* @__PURE__ */ new WeakMap();
147
+ function readOwnedAuthorizationCatalogWork(value) {
148
+ return ownedCatalogs.get(value);
149
+ }
150
+ 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);
151
+ function hasControlCharacter(part) {
152
+ for (let index = 0; index < part.length; index++) {
153
+ const code = part.charCodeAt(index);
154
+ if (code < 32 || code === 127) return true;
155
+ }
156
+ return false;
157
+ }
158
+ function prepareCatalogPathParts(path) {
159
+ const ledger = currentOutputWorkLedger();
160
+ if (ledger) {
161
+ let segments = 1;
162
+ for (let index = 0; index < path.length; index++) if (path.charCodeAt(index) === 46) segments++;
163
+ debitOutputWork(ledger, segments);
164
+ debitOutputPayload(ledger, path);
165
+ }
166
+ }
167
+ function catalogPathParts(path) {
168
+ prepareCatalogPathParts(path);
169
+ return path.split(".");
170
+ }
171
+ var isSafeOutputPath = (path) => catalogPathParts(path).every(safeSegment);
172
+ var inputControlSegments = /* @__PURE__ */ new Set([
173
+ "_permissions",
174
+ "_view",
175
+ "_edit",
176
+ "documentAuthorization",
177
+ "documentAuthorizationStage",
178
+ "resolvedAuthorization",
179
+ "execution",
180
+ "executionContext",
181
+ "serviceExecutionContext",
182
+ "preparedQuery",
183
+ "preparedFilter",
184
+ "preparedModelQuery",
185
+ "resolvedIdentifier",
186
+ "skipParsing",
187
+ "skipAuthorization",
188
+ "alreadyAuthorized"
189
+ ]);
190
+ function isSafeInputPath(path, requestIdentity = false) {
191
+ return isSafeOutputPath(path) && path.split(".").every((part) => !inputControlSegments.has(part) && (requestIdentity || part !== "_id"));
192
+ }
193
+ function matchesCatalogPattern(pattern, path, descendants = false) {
194
+ debitOutputWork();
195
+ if (typeof pattern === "string" && typeof path === "string" && !pattern.includes("$*")) {
196
+ return pattern === path || !!descendants && path.startsWith(pattern) && path[pattern.length] === ".";
197
+ }
198
+ prepareCatalogPathParts(pattern);
199
+ const expected = pattern.split(".");
200
+ prepareCatalogPathParts(path);
201
+ const actual = path.split(".");
202
+ return (descendants ? actual.length >= expected.length : actual.length === expected.length) && expected.every((part, index) => part === "$*" || part === actual[index]);
203
+ }
204
+ function captureAuthorizationFieldCatalog(schema, virtuals, documentPermissionField = "_permissions") {
205
+ debitOutputPayload(currentOutputWorkLedger(), documentPermissionField);
206
+ const paths = /* @__PURE__ */ new Set();
207
+ const containers = /* @__PURE__ */ new Set();
208
+ const opaque = /* @__PURE__ */ new Set();
209
+ const references = /* @__PURE__ */ new Set();
210
+ const virtualPaths = /* @__PURE__ */ new Set();
211
+ const virtualScopes = /* @__PURE__ */ new Set();
212
+ const schemaVirtualPaths = /* @__PURE__ */ new Set();
213
+ const arrays = /* @__PURE__ */ new Set();
214
+ const protectedPaths = /* @__PURE__ */ new Set([documentPermissionField, "_doc", "$__", "__v"]);
215
+ const add = (path) => {
216
+ debitOutputWork();
217
+ debitOutputPayload(currentOutputWorkLedger(), path);
218
+ if (catalogPathParts(path).every((part) => part === "$*" || safeSegment(part))) paths.add(path);
219
+ };
220
+ const ancestors = (path) => {
221
+ const parts = catalogPathParts(path);
222
+ for (let n = 1; n < parts.length; n++) {
223
+ debitOutputWork(void 0, n);
224
+ const parent = prepareOutputWorkString(parts.slice(0, n));
225
+ add(parent);
226
+ containers.add(parent);
227
+ }
228
+ };
229
+ const visitType = (type, path, active) => {
230
+ debitOutputWork();
231
+ add(path);
232
+ ancestors(path);
233
+ const element = type.$embeddedSchemaType ?? type.embeddedSchemaType ?? type.caster;
234
+ if (type.instance === "Array" || type.$isMongooseDocumentArray) arrays.add(path);
235
+ if (type.options?.ref || type.options?.refPath || element?.options?.ref || element?.options?.refPath) {
236
+ references.add(path);
237
+ return;
238
+ }
239
+ if (type.$isSchemaMap || type.instance === "Map") {
240
+ const value = type.$__schemaType;
241
+ if (value) visitType(value, prepareOutputWorkString([path, "$*"]), active);
242
+ else opaque.add(path);
243
+ containers.delete(path);
244
+ return;
245
+ }
246
+ const child = type.schema ?? element?.schema;
247
+ if (child) {
248
+ containers.add(path);
249
+ if (!active.has(child)) visitSchema(child, path, /* @__PURE__ */ new Set([...active, child]));
250
+ return;
251
+ }
252
+ if (type.instance === "Mixed" || element?.instance === "Mixed") opaque.add(path);
253
+ };
254
+ const visitSchema = (current, prefix, active) => {
255
+ debitOutputWork();
256
+ const version = current.options.versionKey;
257
+ if (typeof version === "string") protectedPaths.add(prefix ? `${prefix}.${version}` : version);
258
+ for (const name of Object.keys(current.virtuals)) {
259
+ debitOutputWork();
260
+ schemaVirtualPaths.add(prefix ? prepareOutputWorkString([prefix, name]) : name);
261
+ }
262
+ for (const [name, raw] of Object.entries(current.paths)) {
263
+ debitOutputWork();
264
+ if (name.includes("$*")) continue;
265
+ visitType(raw, prefix ? prepareOutputWorkString([prefix, name]) : name, active);
266
+ }
267
+ };
268
+ visitSchema(schema, "", /* @__PURE__ */ new Set([schema]));
269
+ const copyPaths = (values) => {
270
+ debitOutputWork(void 0, 1 + (Array.isArray(values) ? values.length : values.size));
271
+ return [...values];
272
+ };
273
+ const persistedPaths = copyPaths(paths);
274
+ const visitVirtuals = (record2, prefix) => {
275
+ for (const [name, value] of Object.entries(record2 ?? {})) {
276
+ debitOutputWork();
277
+ if (value === void 0) continue;
278
+ const path = prefix ? prepareOutputWorkString([prefix, name]) : name;
279
+ debitOutputPayload(currentOutputWorkLedger(), path);
280
+ if (!isSafeOutputPath(path)) continue;
281
+ if (value && typeof value === "object" && "sub" in value) {
282
+ if (references.has(path)) continue;
283
+ virtualScopes.add(path);
284
+ add(path);
285
+ containers.add(path);
286
+ visitVirtuals(value.sub, path);
287
+ } else {
288
+ add(path);
289
+ ancestors(path);
290
+ virtualPaths.add(path);
291
+ }
292
+ }
293
+ };
294
+ visitVirtuals(virtuals, "");
295
+ const protectedEntries = copyPaths(protectedPaths);
296
+ const filterPaths = (values, keep) => {
297
+ debitOutputWork(void 0, values.length + 1);
298
+ return values.filter(keep);
299
+ };
300
+ const eligible = filterPaths(
301
+ copyPaths(paths),
302
+ (p) => !protectedEntries.some((v) => matchesCatalogPattern(v, p, true))
303
+ );
304
+ debitOutputWork(void 0, 3);
305
+ const catalog = Object.freeze({
306
+ paths: Object.freeze(filterPaths(eligible, (p) => !p.includes("$*"))),
307
+ persistedPaths: Object.freeze(persistedPaths),
308
+ arrayPaths: Object.freeze(copyPaths(arrays)),
309
+ schemaVirtualPaths: Object.freeze(copyPaths(schemaVirtualPaths)),
310
+ metadataPaths: Object.freeze([documentPermissionField]),
311
+ dynamicPaths: Object.freeze(filterPaths(eligible, (p) => p.includes("$*"))),
312
+ containerPaths: Object.freeze(copyPaths(containers)),
313
+ opaquePaths: Object.freeze(copyPaths(opaque)),
314
+ referencePaths: Object.freeze(copyPaths(references)),
315
+ virtualPaths: Object.freeze(copyPaths(virtualPaths)),
316
+ virtualScopePaths: Object.freeze(copyPaths(virtualScopes)),
317
+ protectedPaths: Object.freeze(protectedEntries)
318
+ });
319
+ if (typeof documentPermissionField === "string") {
320
+ const arrays2 = Object.values(catalog);
321
+ ownedCatalogs.set(
322
+ catalog,
323
+ Object.freeze({ slots: 1 + arrays2.length + arrays2.reduce((sum, paths2) => sum + paths2.length, 0), depth: 2 })
324
+ );
325
+ }
326
+ return catalog;
327
+ }
328
+
329
+ // src/acl/trusted-output-materialization.ts
330
+ var import_node_util3 = require("util");
331
+ var import_mongoose = require("mongoose");
332
+
333
+ // src/output/permissions-alias.ts
133
334
  var import_utils = require("@web-ts-toolkit/utils");
335
+ var import_node_util2 = require("util");
336
+ var aliases = /* @__PURE__ */ new WeakMap();
337
+ function isGeneratedPermissionsAliasSlot(output, key, slot) {
338
+ return key === "permissions" && aliases.has(output) && "value" in slot && !slot.enumerable;
339
+ }
340
+ function attachPermissionsAlias(output, field) {
341
+ if ("permissions" in output) return;
342
+ const metadata = (0, import_utils.get)(output, field);
343
+ if (metadata === void 0) return;
344
+ Object.defineProperty(output, "permissions", {
345
+ value: metadata,
346
+ enumerable: false,
347
+ writable: true,
348
+ configurable: true
349
+ });
350
+ aliases.set(output, field);
351
+ }
352
+ function copyPermissionsAlias(source, target) {
353
+ if (source && typeof source === "object" && target && typeof target === "object") {
354
+ const field = aliases.get(source);
355
+ const readData = (value) => {
356
+ const parts = field?.split(".") ?? [];
357
+ if (parts.length > 100) return void 0;
358
+ for (const key of parts) {
359
+ if (!value || typeof value !== "object" || import_node_util2.types.isProxy(value)) return void 0;
360
+ const slot = Object.getOwnPropertyDescriptor(value, key);
361
+ if (!slot || !("value" in slot)) return void 0;
362
+ value = slot.value;
363
+ }
364
+ return value;
365
+ };
366
+ if (field && readData(target) !== void 0 && Object.getOwnPropertyDescriptor(source, "permissions")?.value === readData(source))
367
+ attachPermissionsAlias(target, field);
368
+ }
369
+ return target;
370
+ }
134
371
 
135
- // src/acl/unsafe-snapshot-options.ts
136
- var unsafeSnapshotCheckOptions = [
372
+ // src/acl/trusted-output-materialization.ts
373
+ var unsafeKeys = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype", "_doc", "$__"]);
374
+ var protectedValueKeys = /* @__PURE__ */ new Set([...unsafeKeys, "__v"]);
375
+ var budgets = /* @__PURE__ */ new WeakMap();
376
+ function createTrustedOutputBudget(onFailure, ownerCheck, ledger) {
377
+ const budget = Object.freeze(/* @__PURE__ */ Object.create(null));
378
+ const ownerLedger = arguments.length < 3 ? currentOutputWorkLedger() : ledger;
379
+ budgets.set(budget, {
380
+ slots: 0,
381
+ failure: void 0,
382
+ recipients: void 0,
383
+ onFailure,
384
+ ownerCheck,
385
+ ledger: ownerLedger
386
+ });
387
+ return budget;
388
+ }
389
+ function failTrustedOutputBudget(budget, error) {
390
+ const record2 = budgets.get(budget);
391
+ if (!record2) authorizationError("invalid selected output budget");
392
+ record2.failure ??= error instanceof ServiceAuthorizationError ? error : new ServiceAuthorizationError("unsupported selected value");
393
+ record2.onFailure?.(record2.failure);
394
+ for (const edge of record2.recipients ?? []) {
395
+ try {
396
+ failTrustedOutputBudget(edge.budget, record2.failure);
397
+ } catch {
398
+ }
399
+ }
400
+ throw record2.failure;
401
+ }
402
+ function assertTrustedOutputBudget(budget) {
403
+ const record2 = budgets.get(budget);
404
+ if (!record2) authorizationError("invalid selected output budget");
405
+ record2.ownerCheck?.();
406
+ record2.ledger?.check();
407
+ if (record2.failure) throw record2.failure;
408
+ for (const edge of record2.recipients ?? []) assertTrustedOutputBudget(edge.budget);
409
+ }
410
+ function visitTrustedOutput(budget, depth, slots = 1, charged) {
411
+ const record2 = budgets.get(budget);
412
+ if (!record2) authorizationError("invalid selected output budget");
413
+ assertTrustedOutputBudget(budget);
414
+ if (record2.recipients?.length) charged ??= /* @__PURE__ */ new Set();
415
+ if (record2.ledger && !charged?.has(record2.ledger)) {
416
+ debitOutputWork(record2.ledger, slots);
417
+ charged?.add(record2.ledger);
418
+ }
419
+ if (depth > 100 || (record2.slots += slots) > 2e4)
420
+ failTrustedOutputBudget(budget, new ServiceAuthorizationError("selected output exceeds structural limits"));
421
+ try {
422
+ for (const edge of record2.recipients ?? [])
423
+ visitTrustedOutput(edge.budget, depth + edge.depth, slots * edge.multiplicity, charged);
424
+ } catch (error) {
425
+ failTrustedOutputBudget(budget, error);
426
+ }
427
+ }
428
+ function preloadTrustedOutputBudget(budget, depth, slots) {
429
+ const record2 = budgets.get(budget);
430
+ if (!record2) authorizationError("invalid selected output budget");
431
+ visitTrustedOutput(budget, depth, slots, record2.ledger ? /* @__PURE__ */ new Set([record2.ledger]) : void 0);
432
+ }
433
+ function prepareTrustedOutputPayload(budget, value, charged) {
434
+ const record2 = budgets.get(budget);
435
+ if (!record2) authorizationError("invalid selected output budget");
436
+ if (!record2.ledger && !record2.recipients?.length) return;
437
+ assertTrustedOutputBudget(budget);
438
+ if (record2.recipients?.length) charged ??= /* @__PURE__ */ new Set();
439
+ if (record2.ledger && !charged?.has(record2.ledger)) {
440
+ debitOutputPayload(record2.ledger, value);
441
+ charged?.add(record2.ledger);
442
+ }
443
+ for (const edge of record2.recipients ?? []) prepareTrustedOutputPayload(edge.budget, value, charged);
444
+ }
445
+ function defineTrustedOutputValue(output, key, value) {
446
+ Object.defineProperty(output, key, { value, enumerable: true, configurable: true, writable: true });
447
+ }
448
+ function isBsonValue(input) {
449
+ let prototype = Object.getPrototypeOf(input);
450
+ for (let depth = 0; prototype && depth <= 100; depth++) {
451
+ debitOutputWork();
452
+ if (import_node_util3.types.isProxy(prototype)) return false;
453
+ if (prototype === import_mongoose.mongo.BSON.BSONValue.prototype) return true;
454
+ prototype = Object.getPrototypeOf(prototype);
455
+ }
456
+ return false;
457
+ }
458
+ var bsonFamilies = new Map(
459
+ Object.entries({
460
+ ObjectId: import_mongoose.mongo.BSON.ObjectId,
461
+ Code: import_mongoose.mongo.BSON.Code,
462
+ DBRef: import_mongoose.mongo.BSON.DBRef,
463
+ Timestamp: import_mongoose.mongo.BSON.Timestamp,
464
+ Long: import_mongoose.mongo.BSON.Long,
465
+ Decimal128: import_mongoose.mongo.BSON.Decimal128,
466
+ Binary: import_mongoose.mongo.BSON.Binary,
467
+ Double: import_mongoose.mongo.BSON.Double,
468
+ Int32: import_mongoose.mongo.BSON.Int32,
469
+ BSONRegExp: import_mongoose.mongo.BSON.BSONRegExp,
470
+ BSONSymbol: import_mongoose.mongo.BSON.BSONSymbol,
471
+ MinKey: import_mongoose.mongo.BSON.MinKey,
472
+ MaxKey: import_mongoose.mongo.BSON.MaxKey
473
+ }).map(([name, family]) => [family.prototype, name])
474
+ );
475
+ function selectedDataProperty(input, key, own = false) {
476
+ let object = input;
477
+ for (let depth = 0; object && depth <= 100; depth++) {
478
+ debitOutputWork();
479
+ if (import_node_util3.types.isProxy(object)) authorizationError("unsupported selected proxy");
480
+ const slot = Object.getOwnPropertyDescriptor(object, key);
481
+ if (slot) {
482
+ if (!("value" in slot)) authorizationError("accessor selected BSON state");
483
+ return slot.value;
484
+ }
485
+ object = own ? null : Object.getPrototypeOf(object);
486
+ }
487
+ if (object) authorizationError("unsupported selected prototype depth");
488
+ return void 0;
489
+ }
490
+ function selectedBsonBytes(input, budget) {
491
+ if (!input || typeof input !== "object" || import_node_util3.types.isProxy(input) || !import_node_util3.types.isUint8Array(input))
492
+ authorizationError("unsupported selected BSON bytes");
493
+ const prototype = Object.getPrototypeOf(Uint8Array.prototype);
494
+ const buffer = Object.getOwnPropertyDescriptor(prototype, "buffer").get.call(input);
495
+ const offset = Object.getOwnPropertyDescriptor(prototype, "byteOffset").get.call(input);
496
+ const length = Object.getOwnPropertyDescriptor(prototype, "byteLength").get.call(input);
497
+ prepareTrustedOutputPayload(budget, length);
498
+ return Buffer.from(new Uint8Array(buffer, offset, length));
499
+ }
500
+ var regexpFlagNames = [
501
+ "hasIndices",
502
+ "global",
503
+ "ignoreCase",
504
+ "multiline",
505
+ "dotAll",
506
+ "unicode",
507
+ "unicodeSets",
508
+ "sticky"
509
+ ];
510
+ function prepareRegExpFlags(input, budget) {
511
+ const ledger = budgets.get(budget).ledger;
512
+ if (ledger) debitOutputWork(ledger, regexpFlagNames.length);
513
+ const flags = [];
514
+ for (let index = 0; index < regexpFlagNames.length; index++)
515
+ if (Object.getOwnPropertyDescriptor(RegExp.prototype, regexpFlagNames[index])?.get?.call(input)) {
516
+ prepareTrustedOutputPayload(budget, 1);
517
+ defineTrustedOutputValue(flags, String(flags.length), "dgimsuvy"[index]);
518
+ }
519
+ prepareTrustedOutputPayload(budget, flags.length);
520
+ return flags.join("");
521
+ }
522
+ function copyTrustedBsonValue(value, path, budget, policy, depth, active) {
523
+ const wireKeys = /* @__PURE__ */ new Set([
524
+ "value",
525
+ "code",
526
+ "scope",
527
+ "collection",
528
+ "oid",
529
+ "db",
530
+ "fields",
531
+ "low",
532
+ "high",
533
+ "unsigned",
534
+ "buffer",
535
+ "sub_type",
536
+ "position",
537
+ "pattern",
538
+ "options",
539
+ "bytes",
540
+ "i0",
541
+ "i1",
542
+ "i2",
543
+ "i3"
544
+ ]);
545
+ const defineWireValue = (output, key, value2) => {
546
+ debitOutputWork();
547
+ prepareTrustedOutputPayload(budget, key);
548
+ wireKeys.add(key);
549
+ defineTrustedOutputValue(output, key, value2);
550
+ };
551
+ const prepareWire = (input, current, level, observeHook = true, entered = false, documentRoot = false, slots = 1) => {
552
+ if (!entered) visitTrustedOutput(budget, level, slots);
553
+ if (typeof input === "function" || typeof input === "symbol") authorizationError("unsupported selected BSON value");
554
+ if (input === null || typeof input !== "object") {
555
+ if (typeof input === "string") prepareTrustedOutputPayload(budget, input);
556
+ return input;
557
+ }
558
+ if (import_node_util3.types.isProxy(input)) authorizationError("unsupported selected proxy");
559
+ if (!entered && active.has(input)) authorizationError("cyclic selected output");
560
+ if (!entered) active.add(input);
561
+ try {
562
+ const hook = selectedDataProperty(input, "toBSON");
563
+ if (typeof hook === "function") {
564
+ if (!observeHook) authorizationError("chained selected BSON hooks");
565
+ const normalized = outsideOutputWorkLedger(() => Reflect.apply(hook, input, []));
566
+ if (normalized !== input) return prepareWire(normalized, current, level, false, false, documentRoot);
567
+ }
568
+ if (isBsonValue(input)) {
569
+ if (documentRoot) authorizationError("unsupported selected BSON document");
570
+ let prototype2 = input;
571
+ for (let hops = 0; prototype2 && !bsonFamilies.has(prototype2) && hops <= 100; hops++) {
572
+ if (import_node_util3.types.isProxy(prototype2)) authorizationError("unsupported selected proxy");
573
+ if (Object.hasOwn(prototype2, "_bsontype") || Object.hasOwn(prototype2, /* @__PURE__ */ Symbol.for("@@mdb.bson.type")))
574
+ authorizationError("overridden selected BSON brand");
575
+ prototype2 = Object.getPrototypeOf(prototype2);
576
+ }
577
+ if (!prototype2 || !bsonFamilies.has(prototype2)) authorizationError("unsupported selected BSON family");
578
+ const family = bsonFamilies.get(prototype2);
579
+ const output2 = Object.create(prototype2);
580
+ Object.defineProperty(output2, "toBSON", { value: void 0 });
581
+ const field = (key, type) => {
582
+ const value2 = selectedDataProperty(input, key, true);
583
+ if (typeof value2 !== type) authorizationError("unsupported selected BSON state");
584
+ if (typeof value2 === "string") prepareTrustedOutputPayload(budget, value2);
585
+ defineWireValue(output2, key, value2);
586
+ return value2;
587
+ };
588
+ const bytes = (key, length) => {
589
+ const value2 = selectedBsonBytes(selectedDataProperty(input, key, true), budget);
590
+ if (length !== void 0 && value2.length !== length) authorizationError("invalid selected BSON bytes");
591
+ defineWireValue(output2, key, value2);
592
+ };
593
+ const method = (key) => {
594
+ if (selectedDataProperty(input, key) !== selectedDataProperty(prototype2, key))
595
+ authorizationError("unsupported selected BSON serializer override");
596
+ };
597
+ const document = (key) => {
598
+ const raw = selectedDataProperty(input, key, true);
599
+ const value2 = prepareWire(raw, prepareOutputWorkString([current, key]), level + 1, true, false, true);
600
+ if (!value2 || typeof value2 !== "object" || !Array.isArray(value2) && Object.getPrototypeOf(value2) !== null)
601
+ authorizationError("unsupported selected BSON document");
602
+ defineWireValue(output2, key, value2);
603
+ };
604
+ switch (family) {
605
+ case "Code": {
606
+ field("code", "string");
607
+ const scope = selectedDataProperty(input, "scope", true);
608
+ if (scope != null) document("scope");
609
+ else defineWireValue(output2, "scope", scope);
610
+ break;
611
+ }
612
+ case "DBRef": {
613
+ field("collection", "string");
614
+ const db = selectedDataProperty(input, "db", true);
615
+ if (db != null) field("db", "string");
616
+ defineWireValue(
617
+ output2,
618
+ "oid",
619
+ prepareWire(
620
+ selectedDataProperty(input, "oid", true),
621
+ prepareOutputWorkString([current, "oid"]),
622
+ level + 1
623
+ )
624
+ );
625
+ document("fields");
626
+ const ordered = /* @__PURE__ */ Object.create(null);
627
+ defineWireValue(ordered, "$ref", output2.collection);
628
+ defineWireValue(ordered, "$id", output2.oid);
629
+ if (db != null) defineWireValue(ordered, "$db", output2.db);
630
+ for (const key of Object.keys(output2.fields))
631
+ defineWireValue(ordered, key, output2.fields[key]);
632
+ return ordered;
633
+ }
634
+ case "ObjectId":
635
+ method("serializeInto");
636
+ if (Object.hasOwn(input, "buffer"))
637
+ bytes("buffer", 12);
638
+ else for (const key of ["i0", "i1", "i2", "i3"]) field(key, "number");
639
+ break;
640
+ case "Timestamp":
641
+ case "Long":
642
+ method("getLowBits");
643
+ method("getHighBits");
644
+ field("low", "number");
645
+ field("high", "number");
646
+ field("unsigned", "boolean");
647
+ break;
648
+ case "Decimal128":
649
+ bytes("bytes", 16);
650
+ break;
651
+ case "Binary": {
652
+ bytes("buffer");
653
+ const position = field("position", "number");
654
+ const subtype = field("sub_type", "number");
655
+ if (!Number.isInteger(position) || position < 0 || position > output2.buffer.length || !Number.isInteger(subtype) || subtype < 0 || subtype > 255)
656
+ authorizationError("invalid selected BSON binary");
657
+ break;
658
+ }
659
+ case "Int32":
660
+ method("valueOf");
661
+ field("value", "number");
662
+ break;
663
+ case "Double":
664
+ field("value", "number");
665
+ break;
666
+ case "BSONSymbol":
667
+ field("value", "string");
668
+ break;
669
+ case "BSONRegExp":
670
+ field("pattern", "string");
671
+ field("options", "string");
672
+ break;
673
+ }
674
+ return output2;
675
+ }
676
+ if (selectedDataProperty(input, "_bsontype") != null) authorizationError("unsupported selected BSON tag");
677
+ const noHook = (value2) => {
678
+ Object.defineProperty(value2, "toBSON", { value: void 0 });
679
+ return value2;
680
+ };
681
+ if (import_node_util3.types.isDate(input)) {
682
+ const getTime = selectedDataProperty(input, "getTime");
683
+ if (typeof getTime !== "function") authorizationError("unsupported selected BSON date");
684
+ const time = outsideOutputWorkLedger(() => Reflect.apply(getTime, input, []));
685
+ if (typeof time !== "number") authorizationError("unsupported selected BSON date");
686
+ prepareTrustedOutputPayload(budget, 8);
687
+ return noHook(new Date(time));
688
+ }
689
+ if (import_node_util3.types.isUint8Array(input)) return noHook(selectedBsonBytes(input, budget));
690
+ if (import_node_util3.types.isRegExp(input)) {
691
+ const source = Object.getOwnPropertyDescriptor(RegExp.prototype, "source").get.call(input);
692
+ prepareTrustedOutputPayload(budget, source);
693
+ const flags = prepareRegExpFlags(input, budget);
694
+ prepareTrustedOutputPayload(budget, flags);
695
+ return noHook(new RegExp(source, flags));
696
+ }
697
+ const output = /* @__PURE__ */ Object.create(null);
698
+ if (import_node_util3.types.isMap(input)) {
699
+ for (const [key, entry] of Map.prototype.entries.call(input)) {
700
+ visitTrustedOutput(budget, level + 1);
701
+ if (typeof key !== "string") authorizationError("selected Map requires string keys");
702
+ if (protectedValueKeys.has(key)) {
703
+ if (policy.rejectProtectedKeys) authorizationError("protected native snapshot key");
704
+ continue;
705
+ }
706
+ const child = prepareOutputWorkString([current, key]);
707
+ if (!policy.keep(key, child)) continue;
708
+ prepareTrustedOutputPayload(budget, key);
709
+ defineWireValue(output, key, prepareWire(entry, child, level + 1));
710
+ }
711
+ return output;
712
+ }
713
+ const array = Array.isArray(input);
714
+ const prototype = Object.getPrototypeOf(input);
715
+ if (!array && prototype !== Object.prototype && prototype !== null)
716
+ authorizationError("unsupported selected object");
717
+ const container = array ? noHook([]) : output;
718
+ if (array) {
719
+ const length = Object.getOwnPropertyDescriptor(input, "length").value;
720
+ if (length) visitTrustedOutput(budget, level + 1, length);
721
+ container.length = length;
722
+ for (let index = 0; index < length; index++) defineWireValue(container, String(index), void 0);
723
+ }
724
+ for (const key of Reflect.ownKeys(input)) {
725
+ if (array && key === "length") continue;
726
+ visitTrustedOutput(budget, level + 1);
727
+ if (typeof key !== "string") authorizationError("symbol selected output key");
728
+ if (protectedValueKeys.has(key)) {
729
+ if (policy.rejectProtectedKeys) authorizationError("protected native snapshot key");
730
+ continue;
731
+ }
732
+ if (key === "toBSON" && (array || typeof hook === "function")) continue;
733
+ if (array && !/^(0|[1-9]\d*)$/.test(key)) authorizationError("invalid selected array property");
734
+ const child = array ? current : prepareOutputWorkString([current, key]);
735
+ if (!array && !policy.keep(key, child)) continue;
736
+ prepareTrustedOutputPayload(budget, key);
737
+ const slot = Object.getOwnPropertyDescriptor(input, key);
738
+ if (!("value" in slot) || !slot.enumerable) authorizationError("accessor/non-enumerable selected value");
739
+ defineWireValue(container, key, prepareWire(slot.value, child, level + 1, true, false, false, 0));
740
+ }
741
+ return container;
742
+ } finally {
743
+ if (!entered) active.delete(input);
744
+ }
745
+ };
746
+ const prepared = prepareWire(value, path, depth, true, true);
747
+ assertTrustedOutputBudget(budget);
748
+ for (const key of wireKeys) {
749
+ const slot = Object.getOwnPropertyDescriptor(Object.prototype, key);
750
+ if (slot && !("value" in slot)) authorizationError("inherited accessor selected BSON output");
751
+ }
752
+ const wrapper = /* @__PURE__ */ Object.create(null);
753
+ defineTrustedOutputValue(wrapper, "value", prepared);
754
+ const result = outsideOutputWorkLedger(
755
+ () => import_mongoose.mongo.BSON.deserialize(import_mongoose.mongo.BSON.serialize(wrapper), { promoteValues: false, bsonRegExp: true }).value
756
+ );
757
+ assertTrustedOutputBudget(budget);
758
+ return result;
759
+ }
760
+ function materializeTrustedOutputValue(value, path, budget, policy, depth = 0, prepaid = false) {
761
+ const ledger = budgets.get(budget)?.ledger;
762
+ if (ledger && currentOutputWorkLedger() !== ledger)
763
+ return withOutputWorkLedger(
764
+ ledger,
765
+ () => materializeTrustedOutputValue(value, path, budget, policy, depth, prepaid)
766
+ );
767
+ if (value === null || typeof value !== "object" && typeof value !== "function" && typeof value !== "symbol") {
768
+ try {
769
+ visitTrustedOutput(budget, depth, prepaid ? 0 : 1);
770
+ if (typeof value === "string") prepareTrustedOutputPayload(budget, value);
771
+ assertTrustedOutputBudget(budget);
772
+ return value;
773
+ } catch (error) {
774
+ failTrustedOutputBudget(budget, error);
775
+ }
776
+ }
777
+ const active = /* @__PURE__ */ new WeakSet();
778
+ const visit = (input, current, level, slots = 1) => {
779
+ visitTrustedOutput(budget, level, slots);
780
+ if (typeof input === "function" || typeof input === "symbol") authorizationError("unsupported selected value");
781
+ if (input === null || typeof input !== "object") {
782
+ if (typeof input === "string") prepareTrustedOutputPayload(budget, input);
783
+ return input;
784
+ }
785
+ if (import_node_util3.types.isProxy(input)) authorizationError("unsupported selected proxy");
786
+ if (active.has(input)) authorizationError("cyclic selected output");
787
+ active.add(input);
788
+ try {
789
+ if (import_node_util3.types.isDate(input)) {
790
+ const method = selectedDataProperty(input, "getTime");
791
+ if (typeof method !== "function") authorizationError("unsupported selected date");
792
+ const time = outsideOutputWorkLedger(() => Reflect.apply(method, input, []));
793
+ if (typeof time !== "number") authorizationError("unsupported selected date");
794
+ prepareTrustedOutputPayload(budget, 8);
795
+ return new Date(time);
796
+ }
797
+ if (Buffer.isBuffer(input)) return selectedBsonBytes(input, budget);
798
+ if (import_node_util3.types.isRegExp(input)) {
799
+ const source = Object.getOwnPropertyDescriptor(RegExp.prototype, "source").get.call(input);
800
+ prepareTrustedOutputPayload(budget, source);
801
+ const flags = prepareRegExpFlags(input, budget);
802
+ prepareTrustedOutputPayload(budget, flags);
803
+ const output2 = new RegExp(source, flags);
804
+ const lastIndex = selectedDataProperty(input, "lastIndex", true);
805
+ if (typeof lastIndex !== "number") authorizationError("unsupported selected regexp");
806
+ output2.lastIndex = lastIndex;
807
+ return output2;
808
+ }
809
+ if (isBsonValue(input)) {
810
+ try {
811
+ return copyTrustedBsonValue(input, current, budget, policy, level, active);
812
+ } catch (error) {
813
+ if (error instanceof ServiceAuthorizationError) throw error;
814
+ authorizationError("unsupported selected BSON value");
815
+ }
816
+ }
817
+ if (import_node_util3.types.isMap(input)) {
818
+ const output2 = {};
819
+ for (const [key, entry] of Map.prototype.entries.call(input)) {
820
+ visitTrustedOutput(budget, level + 1);
821
+ if (typeof key !== "string") authorizationError("selected Map requires string keys");
822
+ if (protectedValueKeys.has(key)) {
823
+ if (policy.rejectProtectedKeys) authorizationError("protected native snapshot key");
824
+ continue;
825
+ }
826
+ const child = prepareOutputWorkString([current, key]);
827
+ if (!policy.keep(key, child)) continue;
828
+ prepareTrustedOutputPayload(budget, key);
829
+ defineTrustedOutputValue(output2, key, visit(entry, child, level + 1));
830
+ }
831
+ return output2;
832
+ }
833
+ const array = Array.isArray(input);
834
+ const prototype = Object.getPrototypeOf(input);
835
+ if (!array && prototype !== Object.prototype && prototype !== null)
836
+ authorizationError("unsupported selected object");
837
+ const output = array ? [] : {};
838
+ if (array) {
839
+ const length = Object.getOwnPropertyDescriptor(input, "length").value;
840
+ if (length) visitTrustedOutput(budget, level + 1, length);
841
+ output.length = length;
842
+ }
843
+ for (const key of Reflect.ownKeys(input)) {
844
+ if (array && key === "length") continue;
845
+ visitTrustedOutput(budget, level + 1);
846
+ if (typeof key !== "string") authorizationError("symbol selected output key");
847
+ if (protectedValueKeys.has(key)) {
848
+ if (policy.rejectProtectedKeys) authorizationError("protected native snapshot key");
849
+ continue;
850
+ }
851
+ if (array && !/^(0|[1-9]\d*)$/.test(key)) authorizationError("invalid selected array property");
852
+ const child = array ? current : prepareOutputWorkString([current, key]);
853
+ if (!array && !policy.keep(key, child)) continue;
854
+ prepareTrustedOutputPayload(budget, key);
855
+ const slot = Object.getOwnPropertyDescriptor(input, key);
856
+ if (isGeneratedPermissionsAliasSlot(input, key, slot)) continue;
857
+ if (!("value" in slot) || !slot.enumerable) authorizationError("accessor/non-enumerable selected value");
858
+ defineTrustedOutputValue(output, key, visit(slot.value, child, level + 1, 0));
859
+ }
860
+ return copyPermissionsAlias(input, output);
861
+ } catch (error) {
862
+ failTrustedOutputBudget(budget, error);
863
+ } finally {
864
+ active.delete(input);
865
+ }
866
+ };
867
+ try {
868
+ const result = visit(value, path, depth, prepaid ? 0 : 1);
869
+ assertTrustedOutputBudget(budget);
870
+ return result;
871
+ } catch (error) {
872
+ failTrustedOutputBudget(budget, error);
873
+ }
874
+ }
875
+
876
+ // src/acl/authorization-snapshot.ts
877
+ var ServiceAuthorizationError = class extends import_express_json_router.default.clientErrors.BadRequestError {
878
+ constructor(detail) {
879
+ const errors = [{ detail: `Service authorization: ${detail}` }];
880
+ super("Bad Request", { errors });
881
+ this.result = { success: false, kind: "error", code: "bad_request" /* BadRequest */, errors };
882
+ Object.freeze(errors[0]);
883
+ Object.freeze(errors);
884
+ Object.freeze(this.result);
885
+ Object.defineProperty(this, "result", {
886
+ value: this.result,
887
+ enumerable: true,
888
+ writable: false,
889
+ configurable: false
890
+ });
891
+ }
892
+ };
893
+ function authorizationError(detail) {
894
+ throw new ServiceAuthorizationError(detail);
895
+ }
896
+ var unsafeKeys2 = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
897
+ function authorizationRecord(value, label) {
898
+ if (!value || typeof value !== "object" || Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) {
899
+ authorizationError(`${label} must be a plain object`);
900
+ }
901
+ return value;
902
+ }
903
+ function copyAuthorizationValue(value, configuration = false) {
904
+ const active = /* @__PURE__ */ new WeakSet();
905
+ const budget = createTrustedOutputBudget();
906
+ function copy(input, depth) {
907
+ visitTrustedOutput(budget, depth);
908
+ if (typeof input === "function") {
909
+ if (configuration === true) return input;
910
+ authorizationError("functions are not policy values");
911
+ }
912
+ if (typeof input === "symbol") authorizationError("symbols are not policy values");
913
+ if (input === null || typeof input !== "object") {
914
+ if (typeof input === "string") prepareTrustedOutputPayload(budget, input);
915
+ return input;
916
+ }
917
+ if (import_node_util4.types.isProxy(input)) authorizationError("proxy snapshot input");
918
+ const ownedCatalog = configuration === true ? readOwnedAuthorizationCatalogWork(input) : void 0;
919
+ if (ownedCatalog) {
920
+ preloadTrustedOutputBudget(budget, depth + ownedCatalog.depth, ownedCatalog.slots - 1);
921
+ return input;
922
+ }
923
+ if (active.has(input)) authorizationError("cyclic input");
924
+ active.add(input);
925
+ try {
926
+ if (input instanceof Date) {
927
+ const time = outsideOutputWorkLedger(() => input.getTime());
928
+ prepareTrustedOutputPayload(budget, 8);
929
+ return outsideOutputWorkLedger(() => new Date(time));
930
+ }
931
+ if (Buffer.isBuffer(input)) {
932
+ if (!currentOutputWorkLedger()) return Buffer.from(input);
933
+ const normalized = outsideOutputWorkLedger(() => Buffer.from(input));
934
+ return materializeTrustedOutputValue(normalized, "", budget, { keep: () => true }, depth, true);
935
+ }
936
+ if (input instanceof RegExp) {
937
+ const result2 = outsideOutputWorkLedger(() => new RegExp(input.source, input.flags));
938
+ result2.lastIndex = input.lastIndex;
939
+ return currentOutputWorkLedger() ? materializeTrustedOutputValue(result2, "", budget, { keep: () => true }, depth, true) : result2;
940
+ }
941
+ if (input instanceof import_mongoose2.mongo.BSON.BSONValue) {
942
+ try {
943
+ return materializeTrustedOutputValue(
944
+ input,
945
+ "",
946
+ budget,
947
+ { keep: () => true, rejectProtectedKeys: true },
948
+ depth,
949
+ true
950
+ );
951
+ } catch (error) {
952
+ if (error instanceof ServiceAuthorizationError) throw error;
953
+ authorizationError("unsupported BSON snapshot");
954
+ }
955
+ }
956
+ if (configuration && input instanceof Map) {
957
+ const result2 = /* @__PURE__ */ new Map();
958
+ for (const [key, entry] of Map.prototype.entries.call(input))
959
+ result2.set(copy(key, depth + 1), copy(entry, depth + 1));
960
+ return result2;
961
+ }
962
+ if (configuration && input instanceof Set) {
963
+ const result2 = /* @__PURE__ */ new Set();
964
+ for (const entry of Set.prototype.values.call(input)) result2.add(copy(entry, depth + 1));
965
+ return result2;
966
+ }
967
+ const array = Array.isArray(input);
968
+ if (array && input.length > 2e4) authorizationError("snapshot array exceeds structural limits");
969
+ if (!array) authorizationRecord(input, "snapshot");
970
+ const result = array ? [] : {};
971
+ let definedProperty = false;
972
+ for (const key of Reflect.ownKeys(input)) {
973
+ if (array && key === "length") continue;
974
+ if (typeof key !== "string" || unsafeKeys2.has(key)) authorizationError("unsafe snapshot key");
975
+ prepareTrustedOutputPayload(budget, key);
976
+ if (array && !/^(0|[1-9]\d*)$/.test(key)) authorizationError("invalid array property");
977
+ const descriptor = Object.getOwnPropertyDescriptor(input, key);
978
+ if (!("value" in descriptor) || !descriptor.enumerable && configuration !== "document")
979
+ authorizationError("accessor/non-enumerable input");
980
+ const value2 = copy(descriptor.value, depth + 1);
981
+ if (array || definedProperty && Object.getPrototypeOf(result) !== Object.prototype || key in result) {
982
+ definedProperty = true;
983
+ Object.defineProperty(result, key, {
984
+ value: value2,
985
+ enumerable: true,
986
+ writable: true,
987
+ configurable: true
988
+ });
989
+ } else result[key] = value2;
990
+ }
991
+ if (array) result.length = input.length;
992
+ return Object.freeze(result);
993
+ } finally {
994
+ active.delete(input);
995
+ }
996
+ }
997
+ return copy(value, 0);
998
+ }
999
+
1000
+ // src/acl/output-work-ledger.ts
1001
+ var preparation = new import_node_async_hooks.AsyncLocalStorage();
1002
+ function currentOutputWorkLedger() {
1003
+ return preparation.getStore();
1004
+ }
1005
+ function withOutputWorkLedger(ledger, run) {
1006
+ if (preparation.getStore() === ledger) return run();
1007
+ return preparation.run(ledger, run);
1008
+ }
1009
+ function outsideOutputWorkLedger(run) {
1010
+ if (!preparation.getStore()) return run();
1011
+ return preparation.run(void 0, run);
1012
+ }
1013
+ function debitOutputWork(ledger = currentOutputWorkLedger(), units = 1) {
1014
+ if (!ledger) return;
1015
+ ledger.check();
1016
+ if (ledger.failure) throw ledger.failure;
1017
+ if (!Number.isSafeInteger(units) || units < 0 || ledger.work + units > 2e5) {
1018
+ ledger.failure ??= new ServiceAuthorizationError("collection output exceeds aggregate work limit");
1019
+ ledger.fail(ledger.failure);
1020
+ throw ledger.failure;
1021
+ }
1022
+ ledger.work += units;
1023
+ }
1024
+ function debitOutputPayload(ledger, value) {
1025
+ if (!ledger) return;
1026
+ ledger.check();
1027
+ if (ledger.failure) throw ledger.failure;
1028
+ const bytes = typeof value === "string" ? Buffer.byteLength(value, "utf8") : value;
1029
+ if (!Number.isSafeInteger(bytes) || bytes < 0 || ledger.payload + bytes > 16 * 1024 * 1024) {
1030
+ ledger.failure ??= new ServiceAuthorizationError("collection output exceeds payload limit");
1031
+ ledger.fail(ledger.failure);
1032
+ throw ledger.failure;
1033
+ }
1034
+ ledger.payload += bytes;
1035
+ }
1036
+ function prepareOutputWorkString(parts, separator = ".", ledger = currentOutputWorkLedger()) {
1037
+ if (ledger) {
1038
+ const bytes = parts.reduce((sum, part) => sum + Buffer.byteLength(part, "utf8"), 0) + Math.max(0, parts.length - 1) * Buffer.byteLength(separator, "utf8");
1039
+ debitOutputPayload(ledger, bytes);
1040
+ }
1041
+ return parts.join(separator);
1042
+ }
1043
+
1044
+ // src/acl/authorization-modes.ts
1045
+ var import_node_util5 = require("util");
1046
+ var retiredAuthorizationOptions = [
137
1047
  "unsafeSkipListDocumentSnapshotChecks",
138
1048
  "unsafeSkipReadDocumentSnapshotChecks",
139
1049
  "unsafeSkipListOutputSnapshotChecks",
140
1050
  "unsafeSkipReadOutputSnapshotChecks",
141
1051
  "unsafeSkipListNestedDocumentSnapshotChecks",
142
- "unsafeSkipReadNestedDocumentSnapshotChecks"
143
- ];
144
- var unsafeInitialOutputCopyOptions = [
1052
+ "unsafeSkipReadNestedDocumentSnapshotChecks",
145
1053
  "unsafeSkipListInitialOutputSnapshotCopy",
146
- "unsafeSkipReadInitialOutputSnapshotCopy"
147
- ];
148
- var unsafeSnapshotOptions = [...unsafeSnapshotCheckOptions, ...unsafeInitialOutputCopyOptions];
149
- var unsafeAuthorizationFastPathOptions = [
1054
+ "unsafeSkipReadInitialOutputSnapshotCopy",
150
1055
  "unsafeUseListAuthorizationFastPath",
151
1056
  "unsafeUseReadAuthorizationFastPath"
152
1057
  ];
153
- var unsafeServerOptions = [...unsafeSnapshotOptions, ...unsafeAuthorizationFastPathOptions];
154
- function authorizationFastPathPrerequisites(origin) {
155
- const operation = origin === "read" ? "Read" : "List";
156
- return [
157
- `unsafeSkip${operation}DocumentSnapshotChecks`,
158
- `unsafeSkip${operation}OutputSnapshotChecks`,
159
- `unsafeSkip${operation}NestedDocumentSnapshotChecks`,
160
- `unsafeSkip${operation}InitialOutputSnapshotCopy`
161
- ];
162
- }
163
- function captureAuthorizationFastPath(options, origin) {
164
- const literalTrue = (key2) => {
165
- const descriptor = Object.getOwnPropertyDescriptor(options, key2);
166
- return !!descriptor && "value" in descriptor && descriptor.value === true;
167
- };
168
- const key = origin === "read" ? unsafeAuthorizationFastPathOptions[1] : unsafeAuthorizationFastPathOptions[0];
169
- const requested = literalTrue(key);
170
- const prerequisites = authorizationFastPathPrerequisites(origin).reduce(
171
- (mask, key2, index) => mask | (literalTrue(key2) ? 1 << index : 0),
172
- 0
1058
+ var authorizationModeKeys = ["readAuthorizationMode", "listAuthorizationMode"];
1059
+ var serverAuthorizationControls = [...retiredAuthorizationOptions, ...authorizationModeKeys];
1060
+ function authorizationControlError(key) {
1061
+ 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`;
1062
+ }
1063
+ function normalizeAuthorizationMode(value) {
1064
+ if (value === void 0) return void 0;
1065
+ if (value === "isolated" || value === "trusted") return value;
1066
+ throw new TypeError(
1067
+ "Authorization mode must be the literal isolated or trusted, or undefined to restore inheritance"
173
1068
  );
174
- return Object.freeze({
175
- origin,
176
- mode: !requested ? "off" : prerequisites === 15 ? "active" : "dormant",
177
- prerequisites
178
- });
1069
+ }
1070
+ function assertAuthorizationModeKey(key, model) {
1071
+ if (typeof key !== "string") throw new TypeError("Configuration option key must be a string");
1072
+ const root = key.split(".")[0];
1073
+ if (retiredAuthorizationOptions.includes(root))
1074
+ throw new TypeError(authorizationControlError(root));
1075
+ if (authorizationModeKeys.includes(root) && (!model || key !== root))
1076
+ throw new TypeError(
1077
+ !model ? authorizationControlError(root) : `${root} is a scalar mode; dotted setters are unsupported`
1078
+ );
1079
+ }
1080
+ function admitControlPrototypes(value, reject) {
1081
+ const owners = [];
1082
+ for (let owner = value; owner; owner = Object.getPrototypeOf(owner)) {
1083
+ if (import_node_util5.types.isProxy(owner)) reject("Proxy control/configuration prototype is unsupported");
1084
+ if (owners.length > 100) reject("Control/configuration prototype depth exceeded");
1085
+ owners.push(owner);
1086
+ }
1087
+ return owners;
1088
+ }
1089
+ function controlPropertyKeys(owners, reject) {
1090
+ const keys2 = /* @__PURE__ */ new Set();
1091
+ for (const owner of owners) {
1092
+ for (const key of Reflect.ownKeys(owner)) {
1093
+ if (typeof key === "string") keys2.add(key);
1094
+ if (keys2.size > 2e4) reject("Control/configuration keys exceed structural limits");
1095
+ }
1096
+ }
1097
+ return [...keys2];
1098
+ }
1099
+ function assertAuthorizationModeOptions(value, model) {
1100
+ const reject = (detail) => {
1101
+ throw new TypeError(detail);
1102
+ };
1103
+ if (!value || typeof value !== "object" || Array.isArray(value))
1104
+ throw new TypeError("Authorization configuration must be an options object");
1105
+ const owners = admitControlPrototypes(value, reject);
1106
+ for (const key of controlPropertyKeys(owners, reject)) {
1107
+ assertAuthorizationModeKey(key, model);
1108
+ if (!authorizationModeKeys.includes(key)) continue;
1109
+ const slot = Object.getOwnPropertyDescriptor(value, key);
1110
+ if (!slot || !("value" in slot) || !slot.enumerable)
1111
+ throw new TypeError(`${key} must be an own enumerable data option`);
1112
+ normalizeAuthorizationMode(slot.value);
1113
+ }
179
1114
  }
180
1115
 
181
1116
  // src/validation/public-admission.ts
@@ -196,10 +1131,10 @@ var privateControls = [
196
1131
  "skipParsing",
197
1132
  "skipAuthorization",
198
1133
  "alreadyAuthorized",
199
- ...unsafeServerOptions,
1134
+ ...serverAuthorizationControls,
200
1135
  "operation"
201
1136
  ];
202
- var PublicAdmissionError = class extends import_express_json_router.default.clientErrors.BadRequestError {
1137
+ var PublicAdmissionError = class extends import_express_json_router2.default.clientErrors.BadRequestError {
203
1138
  constructor(detail) {
204
1139
  const errors = [{ detail }];
205
1140
  super("Bad Request", { errors });
@@ -238,11 +1173,12 @@ function assertPublicControlAdmission(input, kind) {
238
1173
  walkControlAdmission(
239
1174
  input,
240
1175
  kind,
241
- (record2, path) => {
242
- for (const key of privateControls) {
243
- if (key in record2) {
1176
+ (_record, path, keys2) => {
1177
+ for (const property of keys2) {
1178
+ const key = property.split(".")[0];
1179
+ if (privateControls.includes(key)) {
244
1180
  throw new PublicAdmissionError(
245
- 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`
1181
+ serverAuthorizationControls.includes(key) ? `Unsupported public control ${path}.${authorizationControlError(key)}` : `Unsupported public control ${path}.${key}; use explicit per-call internal service options for backend authorization`
246
1182
  );
247
1183
  }
248
1184
  }
@@ -252,13 +1188,33 @@ function assertPublicControlAdmission(input, kind) {
252
1188
  }
253
1189
  );
254
1190
  }
1191
+ function assertNoServerModelControls(input, reject, kind = "envelope") {
1192
+ walkControlAdmission(
1193
+ input,
1194
+ kind,
1195
+ (_record, path, keys2) => {
1196
+ for (const property of keys2) {
1197
+ const key = property.split(".")[0];
1198
+ if (serverAuthorizationControls.includes(key))
1199
+ reject(`${path}.${authorizationControlError(key)}`);
1200
+ if (key === "documentAuthorization" || key === "documentAuthorizationStage")
1201
+ reject(`${path}.${key} was removed; output DTOs carry no authority`);
1202
+ }
1203
+ },
1204
+ reject
1205
+ );
1206
+ }
255
1207
  function walkControlAdmission(input, kind, check, reject) {
256
1208
  const pending = [{ value: input, kind, path: "request", depth: 0 }];
257
1209
  const seen = /* @__PURE__ */ new WeakMap();
258
1210
  let slots = 1;
259
1211
  while (pending.length) {
1212
+ debitOutputWork();
260
1213
  const { value, kind: slot, path, depth } = pending.pop();
261
1214
  if (!value || typeof value !== "object" && typeof value !== "function") continue;
1215
+ if (typeof value === "function" && (slot === "policy" || slot === "data")) continue;
1216
+ if (import_node_util6.types.isProxy(value)) reject(`unsupported proxy in control admission: ${path}`);
1217
+ const owners = admitControlPrototypes(value, reject);
262
1218
  const kinds = seen.get(value) ?? /* @__PURE__ */ new Set();
263
1219
  if (kinds.has(slot)) continue;
264
1220
  kinds.add(slot);
@@ -269,11 +1225,29 @@ function walkControlAdmission(input, kind, check, reject) {
269
1225
  pending.push({ value: child, kind: childKind, path: `${path}.${key}`, depth: depth + 1 });
270
1226
  };
271
1227
  const record2 = value;
272
- if (slot !== "data" && slot !== "policies") check(record2, path);
1228
+ const propertyKeys = slot === "data" || slot === "policies" ? [] : controlPropertyKeys(owners, reject);
1229
+ debitOutputWork(void 0, propertyKeys.length);
1230
+ if (slot !== "data" && slot !== "policies" && slot !== "model-options") check(record2, path, propertyKeys);
1231
+ for (const property of propertyKeys) {
1232
+ const parts = property.split(".");
1233
+ if (parts.length < 2 || !parts.some((part) => serverAuthorizationControls.includes(part)))
1234
+ continue;
1235
+ const roots = slot === "defaults" ? defaultControlBuckets : slot === "policy" ? ["rows", "outputFields", "inputFields", "operation", "related"] : ["args", "options", "sqOptions", "include", "populate", "authorization", "defaults"];
1236
+ if (!roots.includes(parts[0])) continue;
1237
+ if (parts.length > 100) reject("control admission dotted path exceeds structural limits");
1238
+ const wrapper = {};
1239
+ let target = wrapper;
1240
+ for (const part of parts.slice(0, -1)) {
1241
+ const child = {};
1242
+ Object.defineProperty(target, part, { value: child, enumerable: true });
1243
+ target = child;
1244
+ }
1245
+ const descriptor = owners.map((owner) => Object.getOwnPropertyDescriptor(owner, property)).find(Boolean);
1246
+ Object.defineProperty(target, parts.at(-1), descriptor);
1247
+ add(wrapper, slot, property);
1248
+ }
273
1249
  const read = (key) => {
274
- let owner = value;
275
- for (let depth2 = 0; owner; depth2++, owner = Object.getPrototypeOf(owner)) {
276
- if (depth2 > 100) reject("control admission prototype depth exceeded");
1250
+ for (const owner of owners) {
277
1251
  const descriptor = Object.getOwnPropertyDescriptor(owner, key);
278
1252
  if (!descriptor) continue;
279
1253
  if (!("value" in descriptor)) reject(`accessor control/data property: ${path}.${key}`);
@@ -289,7 +1263,7 @@ function walkControlAdmission(input, kind, check, reject) {
289
1263
  continue;
290
1264
  }
291
1265
  if (slot === "data") {
292
- if (!(0, import_utils.isPlainObject)(value)) continue;
1266
+ if (!(0, import_utils2.isPlainObject)(value)) continue;
293
1267
  add(read("$$sq"), "envelope", "$$sq");
294
1268
  for (const key of Object.keys(value)) if (key !== "$$sq") add(read(key), "data", key);
295
1269
  continue;
@@ -300,12 +1274,14 @@ function walkControlAdmission(input, kind, check, reject) {
300
1274
  for (const key of keys2) if (key in record2) add(read(key), "envelope", key);
301
1275
  continue;
302
1276
  }
1277
+ add(read("defaults"), "defaults", "defaults");
303
1278
  if (slot === "policies") {
304
1279
  for (const key of Object.keys(value)) add(read(key), "policy", key);
305
1280
  continue;
306
1281
  }
307
1282
  if (slot === "policy") {
308
- for (const key of ["rows", "outputFields", "inputFields", "operation"]) add(read(key), "policy", key);
1283
+ for (const key of ["rows", "outputFields", "inputFields", "operation", "parent", "child", "visibility"])
1284
+ add(read(key), "policy", key);
309
1285
  add(read("related"), "policies", "related");
310
1286
  add(read("filter"), "data", "filter");
311
1287
  continue;
@@ -314,7 +1290,9 @@ function walkControlAdmission(input, kind, check, reject) {
314
1290
  add(read("include"), "include", "include");
315
1291
  add(read("populate"), "populate", "populate");
316
1292
  add(read("authorization"), "policy", "authorization");
317
- for (const key of ["filter", "match", "data"]) add(read(key), "data", key);
1293
+ add(read("operationAccess"), "policy", "operationAccess");
1294
+ for (const key of slot === "data-options" ? ["filter", "match"] : ["filter", "match", "data"])
1295
+ add(read(key), "data", key);
318
1296
  }
319
1297
  }
320
1298
  function assertHydrationDefaults(defaults2) {
@@ -406,15 +1384,15 @@ function assertNoGlobalPopulatePolicy(key) {
406
1384
 
407
1385
  // src/runtime.ts
408
1386
  var import_mongoose_schema_jsonschema = __toESM(require("mongoose-schema-jsonschema"));
409
- var import_utils13 = require("@web-ts-toolkit/utils");
1387
+ var import_utils14 = require("@web-ts-toolkit/utils");
410
1388
 
411
1389
  // src/helpers/query.ts
412
- var import_utils2 = require("@web-ts-toolkit/utils");
1390
+ var import_utils3 = require("@web-ts-toolkit/utils");
413
1391
  var DEFAULT_LIST_HARD_LIMIT = 1e3;
414
1392
  function normalizeSelect(select) {
415
- if (Array.isArray(select)) return (0, import_utils2.flattenDeep)(select.map(normalizeSelect));
416
- if ((0, import_utils2.isPlainObject)(select)) {
417
- return (0, import_utils2.reduce)(
1393
+ if (Array.isArray(select)) return (0, import_utils3.flattenDeep)(select.map(normalizeSelect));
1394
+ if ((0, import_utils3.isPlainObject)(select)) {
1395
+ return (0, import_utils3.reduce)(
418
1396
  select,
419
1397
  (ret, val, key) => {
420
1398
  if (val === 1) ret.push(key);
@@ -424,7 +1402,7 @@ function normalizeSelect(select) {
424
1402
  []
425
1403
  );
426
1404
  }
427
- if ((0, import_utils2.isString)(select))
1405
+ if ((0, import_utils3.isString)(select))
428
1406
  return String(select).split(/[\s,]+/).map((v) => v.trim()).filter(Boolean);
429
1407
  return [];
430
1408
  }
@@ -436,44 +1414,44 @@ function isValidFieldPath(field) {
436
1414
  }
437
1415
 
438
1416
  // src/helpers/index.ts
439
- var import_utils4 = require("@web-ts-toolkit/utils");
1417
+ var import_utils5 = require("@web-ts-toolkit/utils");
440
1418
 
441
1419
  // src/lib.ts
442
- var import_mongoose = require("mongoose");
443
- var import_utils3 = require("@web-ts-toolkit/utils");
444
- var isSchema = (val) => val instanceof import_mongoose.Schema;
445
- var isObjectIdType = (val) => val === "ObjectId" || val === import_mongoose.Schema.Types.ObjectId;
446
- var isReference = (val) => (0, import_utils3.isPlainObject)(val) && !!val.ref && isObjectIdType(val.type);
1420
+ var import_mongoose3 = require("mongoose");
1421
+ var import_utils4 = require("@web-ts-toolkit/utils");
1422
+ var isSchema = (val) => val instanceof import_mongoose3.Schema;
1423
+ var isObjectIdType = (val) => val === "ObjectId" || val === import_mongoose3.Schema.Types.ObjectId;
1424
+ var isReference = (val) => (0, import_utils4.isPlainObject)(val) && !!val.ref && isObjectIdType(val.type);
447
1425
 
448
1426
  // src/helpers/index.ts
449
1427
  function recurseObject(obj) {
450
1428
  if (isSchema(obj)) {
451
1429
  return buildRefs(obj.tree);
452
1430
  }
453
- if (!(0, import_utils4.isObject)(obj)) return null;
1431
+ if (!(0, import_utils5.isObject)(obj)) return null;
454
1432
  if (isReference(obj)) {
455
1433
  return obj.ref;
456
1434
  }
457
1435
  let ret = null;
458
- (0, import_utils4.forEach)(obj, (val) => {
1436
+ (0, import_utils5.forEach)(obj, (val) => {
459
1437
  ret = recurseObject(val);
460
- if (!(0, import_utils4.isEmpty)(ret)) {
1438
+ if (!(0, import_utils5.isEmpty)(ret)) {
461
1439
  return false;
462
1440
  }
463
1441
  });
464
1442
  return ret;
465
1443
  }
466
1444
  function buildRefs(schema) {
467
- if (!(0, import_utils4.isObject)(schema)) return {};
1445
+ if (!(0, import_utils5.isObject)(schema)) return {};
468
1446
  const references = {};
469
- (0, import_utils4.forEach)(schema, (val, key) => {
1447
+ (0, import_utils5.forEach)(schema, (val, key) => {
470
1448
  const paths = recurseObject(val);
471
- if (!(0, import_utils4.isEmpty)(paths)) {
1449
+ if (!(0, import_utils5.isEmpty)(paths)) {
472
1450
  references[key] = paths;
473
1451
  }
474
- const target = (0, import_utils4.isObject)(val) && "type" in val ? val.type ?? val : val;
475
- if ((0, import_utils4.isArray)(target) && target.length > 0) {
476
- if (isSchema(target[0]) || (0, import_utils4.isPlainObject)(target[0])) {
1452
+ const target = (0, import_utils5.isObject)(val) && "type" in val ? val.type ?? val : val;
1453
+ if ((0, import_utils5.isArray)(target) && target.length > 0) {
1454
+ if (isSchema(target[0]) || (0, import_utils5.isPlainObject)(target[0])) {
477
1455
  return;
478
1456
  }
479
1457
  }
@@ -481,12 +1459,12 @@ function buildRefs(schema) {
481
1459
  return references;
482
1460
  }
483
1461
  function buildSubPaths(schema) {
484
- if (!(0, import_utils4.isObject)(schema)) return [];
1462
+ if (!(0, import_utils5.isObject)(schema)) return [];
485
1463
  const subPaths = [];
486
- (0, import_utils4.forEach)(schema, (val, key) => {
487
- const target = (0, import_utils4.isObject)(val) && "type" in val ? val.type ?? val : val;
488
- if ((0, import_utils4.isArray)(target) && target.length > 0) {
489
- if (isSchema(target[0]) || (0, import_utils4.isPlainObject)(target[0]) && !isReference(target[0])) {
1464
+ (0, import_utils5.forEach)(schema, (val, key) => {
1465
+ const target = (0, import_utils5.isObject)(val) && "type" in val ? val.type ?? val : val;
1466
+ if ((0, import_utils5.isArray)(target) && target.length > 0) {
1467
+ if (isSchema(target[0]) || (0, import_utils5.isPlainObject)(target[0]) && !isReference(target[0])) {
490
1468
  subPaths.push(key);
491
1469
  }
492
1470
  }
@@ -495,7 +1473,7 @@ function buildSubPaths(schema) {
495
1473
  }
496
1474
 
497
1475
  // src/openapi/build-spec.ts
498
- var import_utils6 = require("@web-ts-toolkit/utils");
1476
+ var import_utils7 = require("@web-ts-toolkit/utils");
499
1477
 
500
1478
  // src/openapi/responses.ts
501
1479
  var json = (schema) => ({
@@ -566,19 +1544,19 @@ var openApiResponses = {
566
1544
 
567
1545
  // src/openapi/schemas.ts
568
1546
  var import_zod = require("zod");
569
- var import_utils5 = require("@web-ts-toolkit/utils");
1547
+ var import_utils6 = require("@web-ts-toolkit/utils");
570
1548
  var fallbackObjectSchema = { type: "object", additionalProperties: true };
571
1549
  function isOpenApiSchemaPatch(source) {
572
- return (0, import_utils5.isPlainObject)(source) && source.kind === "objectProperties";
1550
+ return (0, import_utils6.isPlainObject)(source) && source.kind === "objectProperties";
573
1551
  }
574
1552
  function isOpenApiSchemaResolver(source) {
575
- return (0, import_utils5.isPlainObject)(source) && source.kind === "schemaResolver" && typeof source.resolve === "function";
1553
+ return (0, import_utils6.isPlainObject)(source) && source.kind === "schemaResolver" && typeof source.resolve === "function";
576
1554
  }
577
1555
  function isJsonSchemaLike(source) {
578
- return (0, import_utils5.isPlainObject)(source) && ("type" in source || "properties" in source || "$ref" in source || "anyOf" in source);
1556
+ return (0, import_utils6.isPlainObject)(source) && ("type" in source || "properties" in source || "$ref" in source || "anyOf" in source);
579
1557
  }
580
1558
  function hasOpenApiSchema(source) {
581
- return (0, import_utils5.isPlainObject)(source) && isJsonSchemaLike(source.openapi);
1559
+ return (0, import_utils6.isPlainObject)(source) && isJsonSchemaLike(source.openapi);
582
1560
  }
583
1561
  function toOpenApiSchema(source) {
584
1562
  if (!source) return void 0;
@@ -586,7 +1564,7 @@ function toOpenApiSchema(source) {
586
1564
  if (!resolvedSource) return void 0;
587
1565
  if (isOpenApiSchemaPatch(resolvedSource)) {
588
1566
  const schema = toOpenApiSchema(resolvedSource.source) ?? { ...fallbackObjectSchema };
589
- const properties = (0, import_utils5.isPlainObject)(schema.properties) ? { ...schema.properties } : {};
1567
+ const properties = (0, import_utils6.isPlainObject)(schema.properties) ? { ...schema.properties } : {};
590
1568
  for (const [key, value] of Object.entries(resolvedSource.properties)) {
591
1569
  properties[key] = toOpenApiSchema(value) ?? fallbackObjectSchema;
592
1570
  }
@@ -619,9 +1597,9 @@ var toOpenApiPath = (path) => normalizePath(path).replace(/:([A-Za-z0-9_]+)/g, "
619
1597
  var schemaToQueryParameters = (schema) => {
620
1598
  const jsonSchema = toOpenApiSchema(schema);
621
1599
  if (!jsonSchema || jsonSchema.type !== "object") return [];
622
- const properties = (0, import_utils6.isPlainObject)(jsonSchema.properties) ? jsonSchema.properties : {};
1600
+ const properties = (0, import_utils7.isPlainObject)(jsonSchema.properties) ? jsonSchema.properties : {};
623
1601
  const required = new Set(
624
- (0, import_utils6.isArray)(jsonSchema.required) ? jsonSchema.required.filter((item) => typeof item === "string") : []
1602
+ (0, import_utils7.isArray)(jsonSchema.required) ? jsonSchema.required.filter((item) => typeof item === "string") : []
625
1603
  );
626
1604
  return Object.entries(properties).map(([name, value]) => ({
627
1605
  name,
@@ -810,12 +1788,12 @@ var OpenApiRegistry = class {
810
1788
  };
811
1789
 
812
1790
  // src/logger-default.ts
813
- var import_node_util = __toESM(require("util"));
1791
+ var import_node_util7 = __toESM(require("util"));
814
1792
  var import_winston = require("winston");
815
1793
  var colorizer = import_winston.format.colorize();
816
1794
  var defaultLogLevel = process.env.WTT_LOG_LEVEL || "silent";
817
1795
  var inspectValue = (value) => {
818
- return typeof value === "string" ? value : import_node_util.default.inspect(value, { depth: 5, colors: false });
1796
+ return typeof value === "string" ? value : import_node_util7.default.inspect(value, { depth: 5, colors: false });
819
1797
  };
820
1798
  var defaultLogger = (0, import_winston.createLogger)({
821
1799
  level: defaultLogLevel,
@@ -836,7 +1814,7 @@ var defaultLogger = (0, import_winston.createLogger)({
836
1814
  });
837
1815
 
838
1816
  // src/options/manager.ts
839
- var import_utils7 = require("@web-ts-toolkit/utils");
1817
+ var import_utils8 = require("@web-ts-toolkit/utils");
840
1818
  var toPath = (key) => {
841
1819
  if (Array.isArray(key)) return key;
842
1820
  return typeof key === "string" ? key.split(".") : [key];
@@ -944,20 +1922,20 @@ var OptionsManager = class {
944
1922
  return this;
945
1923
  }
946
1924
  get(key, defaultValue) {
947
- return (0, import_utils7.get)(this.currentOptions, key, defaultValue);
1925
+ return (0, import_utils8.get)(this.currentOptions, key, defaultValue);
948
1926
  }
949
1927
  set(key, value) {
950
1928
  const path = toPath(key);
951
1929
  if (path.length <= 1) {
952
- (0, import_utils7.set)(this.currentOptions, path, this.preserveKeys.has(String(path[0])) ? value : cloneAndFreezeForStore(value));
1930
+ (0, import_utils8.set)(this.currentOptions, path, this.preserveKeys.has(String(path[0])) ? value : cloneAndFreezeForStore(value));
953
1931
  return;
954
1932
  }
955
1933
  const [rootKey, ...nestedPath] = path;
956
- const currentRoot = (0, import_utils7.get)(this.currentOptions, [rootKey], void 0);
957
- const baseRoot = (0, import_utils7.isPlainObject)(currentRoot) ? currentRoot : {};
1934
+ const currentRoot = (0, import_utils8.get)(this.currentOptions, [rootKey], void 0);
1935
+ const baseRoot = (0, import_utils8.isPlainObject)(currentRoot) ? currentRoot : {};
958
1936
  const nextRoot = cloneConfigValue(baseRoot);
959
- (0, import_utils7.set)(nextRoot, nestedPath, cloneForRead(value));
960
- (0, import_utils7.set)(this.currentOptions, [rootKey], freezeConfigValue(nextRoot));
1937
+ (0, import_utils8.set)(nextRoot, nestedPath, cloneForRead(value));
1938
+ (0, import_utils8.set)(this.currentOptions, [rootKey], freezeConfigValue(nextRoot));
961
1939
  }
962
1940
  fetch() {
963
1941
  const cloned = cloneForRead(this.currentOptions);
@@ -975,10 +1953,10 @@ var OptionsManager = class {
975
1953
  cloned[key] = options[key];
976
1954
  }
977
1955
  }
978
- (0, import_utils7.assign)(this.currentOptions, freezeConfigValue(cloned));
1956
+ (0, import_utils8.assign)(this.currentOptions, freezeConfigValue(cloned));
979
1957
  }
980
1958
  onchange(key, func) {
981
- (0, import_utils7.set)(this.listeners, key, func);
1959
+ (0, import_utils8.set)(this.listeners, key, func);
982
1960
  return this;
983
1961
  }
984
1962
  snapshot() {
@@ -1004,15 +1982,15 @@ var OptionsManager = class {
1004
1982
  cloned[key] = snap[key];
1005
1983
  }
1006
1984
  }
1007
- (0, import_utils7.assign)(current, freezeConfigValue(cloned));
1985
+ (0, import_utils8.assign)(current, freezeConfigValue(cloned));
1008
1986
  }
1009
1987
  };
1010
1988
 
1011
1989
  // src/options/data-manager.ts
1012
- var import_utils8 = require("@web-ts-toolkit/utils");
1990
+ var import_utils9 = require("@web-ts-toolkit/utils");
1013
1991
 
1014
1992
  // src/options/data-values.ts
1015
- var import_node_util2 = require("util");
1993
+ var import_node_util8 = require("util");
1016
1994
  var typedArrays = [
1017
1995
  Int8Array,
1018
1996
  Uint8Array,
@@ -1042,7 +2020,7 @@ var assertNativeProperties = (value, path, allowed = () => false) => {
1042
2020
  }
1043
2021
  };
1044
2022
  var copyBytes = (buffer, path, start = 0, end) => {
1045
- if (!import_node_util2.types.isArrayBuffer(buffer) || Object.getPrototypeOf(buffer) !== ArrayBuffer.prototype) {
2023
+ if (!import_node_util8.types.isArrayBuffer(buffer) || Object.getPrototypeOf(buffer) !== ArrayBuffer.prototype) {
1046
2024
  return unsupported(path, "binary storage must be a fixed, non-shared ArrayBuffer");
1047
2025
  }
1048
2026
  assertNativeProperties(buffer, path);
@@ -1063,7 +2041,7 @@ function copyValue(input, freezePlain, rootPath) {
1063
2041
  return unsupported(path, `${typeof value} values are not supported`);
1064
2042
  }
1065
2043
  if (value === null || typeof value !== "object") return value;
1066
- if (import_node_util2.types.isProxy(value)) return unsupported(path, "proxies are not supported");
2044
+ if (import_node_util8.types.isProxy(value)) return unsupported(path, "proxies are not supported");
1067
2045
  if (active.has(value)) return unsupported(path, "cycles are not supported");
1068
2046
  const previous = copies.get(value);
1069
2047
  if (previous) return previous;
@@ -1084,10 +2062,10 @@ function copyValue(input, freezePlain, rootPath) {
1084
2062
  return freezePlain ? Object.freeze(output2) : output2;
1085
2063
  }
1086
2064
  let output;
1087
- if (prototype === Date.prototype && import_node_util2.types.isDate(value)) {
2065
+ if (prototype === Date.prototype && import_node_util8.types.isDate(value)) {
1088
2066
  assertNativeProperties(value, path);
1089
2067
  output = new Date(Date.prototype.getTime.call(value));
1090
- } else if (prototype === Map.prototype && import_node_util2.types.isMap(value)) {
2068
+ } else if (prototype === Map.prototype && import_node_util8.types.isMap(value)) {
1091
2069
  assertNativeProperties(value, path);
1092
2070
  const map = /* @__PURE__ */ new Map();
1093
2071
  copies.set(value, map);
@@ -1097,7 +2075,7 @@ function copyValue(input, freezePlain, rootPath) {
1097
2075
  index += 1;
1098
2076
  }
1099
2077
  output = map;
1100
- } else if (prototype === Set.prototype && import_node_util2.types.isSet(value)) {
2078
+ } else if (prototype === Set.prototype && import_node_util8.types.isSet(value)) {
1101
2079
  assertNativeProperties(value, path);
1102
2080
  const set4 = /* @__PURE__ */ new Set();
1103
2081
  copies.set(value, set4);
@@ -1107,7 +2085,7 @@ function copyValue(input, freezePlain, rootPath) {
1107
2085
  index += 1;
1108
2086
  }
1109
2087
  output = set4;
1110
- } else if (prototype === RegExp.prototype && import_node_util2.types.isRegExp(value)) {
2088
+ } else if (prototype === RegExp.prototype && import_node_util8.types.isRegExp(value)) {
1111
2089
  assertNativeProperties(value, path, (key) => key === "lastIndex");
1112
2090
  const regexp = value;
1113
2091
  if (typeof regexp.lastIndex !== "number") return unsupported(path, "RegExp.lastIndex must be a number");
@@ -1184,7 +2162,7 @@ var emptyDataSnapshot = Object.freeze([]);
1184
2162
  var ownedSnapshots = new WeakMap([[emptyDataSnapshot, emptyDataSnapshot]]);
1185
2163
  function createDataSnapshot(data) {
1186
2164
  if (data === void 0) return void 0;
1187
- if (!Array.isArray(data) || import_node_util2.types.isProxy(data) || Object.getPrototypeOf(data) !== Array.prototype) {
2165
+ if (!Array.isArray(data) || import_node_util8.types.isProxy(data) || Object.getPrototypeOf(data) !== Array.prototype) {
1188
2166
  return unsupported("data", "expected an ordinary array or undefined");
1189
2167
  }
1190
2168
  if (ownedSnapshots.has(data)) return data;
@@ -1215,7 +2193,7 @@ var DataOptionsManager = class extends OptionsManager {
1215
2193
  super.set("data", createDataSnapshot(value));
1216
2194
  } else if (path.startsWith("data.")) {
1217
2195
  const next = copyDataValue(getOwnedDataSnapshot(super.get("data")));
1218
- (0, import_utils8.set)(next, path.slice("data.".length), value);
2196
+ (0, import_utils9.set)(next, path.slice("data.".length), value);
1219
2197
  super.set("data", createDataSnapshot(next));
1220
2198
  } else {
1221
2199
  super.set(key, value);
@@ -1227,7 +2205,7 @@ var DataOptionsManager = class extends OptionsManager {
1227
2205
  };
1228
2206
 
1229
2207
  // src/request-complexity.ts
1230
- var import_utils9 = require("@web-ts-toolkit/utils");
2208
+ var import_utils10 = require("@web-ts-toolkit/utils");
1231
2209
  var defaultRequestComplexity = {
1232
2210
  maxDepth: 8,
1233
2211
  maxNodes: 500,
@@ -1293,7 +2271,7 @@ function validateRequestComplexity(value, options, scope = "request") {
1293
2271
  pushError(`Request exceeds maximum depth of ${limits.maxDepth}`, path);
1294
2272
  return;
1295
2273
  }
1296
- if ((0, import_utils9.isArray)(current)) {
2274
+ if ((0, import_utils10.isArray)(current)) {
1297
2275
  if (parentKey === "$and" || parentKey === "$or" || parentKey === "$nor") {
1298
2276
  logicalClauses += current.length;
1299
2277
  if (logicalClauses > limits.maxLogicalClauses) {
@@ -1313,14 +2291,14 @@ function validateRequestComplexity(value, options, scope = "request") {
1313
2291
  }
1314
2292
  return;
1315
2293
  }
1316
- if (!(0, import_utils9.isPlainObject)(current)) return;
2294
+ if (!(0, import_utils10.isPlainObject)(current)) return;
1317
2295
  for (const [key, child] of Object.entries(current)) {
1318
2296
  if (key === "__proto__" || key === "prototype" || key === "constructor") {
1319
2297
  pushError(`Unsupported key: ${key}`, path.concat(key));
1320
2298
  return;
1321
2299
  }
1322
2300
  if (scope === "request" && key === "include") {
1323
- includeCount += (0, import_utils9.isArray)(child) ? child.length : 1;
2301
+ includeCount += (0, import_utils10.isArray)(child) ? child.length : 1;
1324
2302
  if (includeCount > limits.maxIncludeCount) {
1325
2303
  pushError(`Request exceeds maximum include count of ${limits.maxIncludeCount}`, path.concat(key));
1326
2304
  return;
@@ -1345,8 +2323,8 @@ function validateRequestComplexity(value, options, scope = "request") {
1345
2323
  }
1346
2324
 
1347
2325
  // src/acl/virtual-descriptor.ts
1348
- var import_utils10 = require("@web-ts-toolkit/utils");
1349
- var isVirtualContainerValue = (value) => (0, import_utils10.isPlainObject)(value) && "sub" in value;
2326
+ var import_utils11 = require("@web-ts-toolkit/utils");
2327
+ var isVirtualContainerValue = (value) => (0, import_utils11.isPlainObject)(value) && "sub" in value;
1350
2328
  function getScopeVirtualsObject(root, scopePath = []) {
1351
2329
  let current = root;
1352
2330
  for (let i = 0; i < scopePath.length; i += 2) {
@@ -1355,11 +2333,11 @@ function getScopeVirtualsObject(root, scopePath = []) {
1355
2333
  if (!isVirtualContainerValue(container)) return null;
1356
2334
  current = container.sub;
1357
2335
  }
1358
- return (0, import_utils10.isPlainObject)(current) ? current : null;
2336
+ return (0, import_utils11.isPlainObject)(current) ? current : null;
1359
2337
  }
1360
2338
  function toDescriptor(leaf, shared = {}) {
1361
- const record2 = (0, import_utils10.isFunction)(leaf) ? { get: leaf } : (0, import_utils10.isPlainObject)(leaf) ? leaf : null;
1362
- if (!record2 || !(0, import_utils10.isFunction)(record2.get)) return void 0;
2339
+ const record2 = (0, import_utils11.isFunction)(leaf) ? { get: leaf } : (0, import_utils11.isPlainObject)(leaf) ? leaf : null;
2340
+ if (!record2 || !(0, import_utils11.isFunction)(record2.get)) return void 0;
1363
2341
  const dependsOn = record2.dependsOn ?? shared.dependsOn ?? [];
1364
2342
  const populated = record2.dependsOnPopulate === void 0 ? shared.dependsOnPopulate : record2.dependsOnPopulate;
1365
2343
  return {
@@ -1376,238 +2354,22 @@ function toDescriptor(leaf, shared = {}) {
1376
2354
  function resolveSnapshotDescriptor(scopeVirtuals, virtualName, access) {
1377
2355
  const entry = scopeVirtuals?.[virtualName];
1378
2356
  if (entry === void 0 || isVirtualContainerValue(entry)) return void 0;
1379
- if ((0, import_utils10.isFunction)(entry)) return toDescriptor(entry);
1380
- if (!(0, import_utils10.isPlainObject)(entry)) return void 0;
2357
+ if ((0, import_utils11.isFunction)(entry)) return toDescriptor(entry);
2358
+ if (!(0, import_utils11.isPlainObject)(entry)) return void 0;
1381
2359
  const record2 = entry;
1382
2360
  if ("get" in record2) return toDescriptor(record2);
1383
2361
  return toDescriptor(record2[access], record2) ?? toDescriptor(record2.default, record2);
1384
2362
  }
1385
2363
 
1386
2364
  // src/acl/virtual-populate-dependencies.ts
1387
- var import_utils12 = require("@web-ts-toolkit/utils");
1388
-
1389
- // src/acl/authorization-snapshot.ts
1390
- var import_node_util3 = require("util");
1391
- var import_node_buffer = require("buffer");
1392
- var import_mongoose2 = require("mongoose");
1393
- var import_express_json_router2 = __toESM(require("@web-ts-toolkit/express-json-router"));
1394
- var ServiceAuthorizationError = class extends import_express_json_router2.default.clientErrors.BadRequestError {
1395
- constructor(detail) {
1396
- const errors = [{ detail: `Service authorization: ${detail}` }];
1397
- super("Bad Request", { errors });
1398
- this.result = { success: false, kind: "error", code: "bad_request" /* BadRequest */, errors };
1399
- }
1400
- };
1401
- function authorizationError(detail) {
1402
- throw new ServiceAuthorizationError(detail);
1403
- }
1404
- var unsafeKeys = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
1405
- function authorizationRecord(value, label) {
1406
- if (!value || typeof value !== "object" || Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) {
1407
- authorizationError(`${label} must be a plain object`);
1408
- }
1409
- return value;
1410
- }
1411
- function copyAuthorizationValue(value, configuration = false) {
1412
- const active = /* @__PURE__ */ new WeakSet();
1413
- let nodes = 0;
1414
- function copy(input, depth) {
1415
- if (++nodes > 2e4 || depth > 100) authorizationError("snapshot exceeds structural limits");
1416
- if (typeof input === "function") {
1417
- if (configuration === true) return input;
1418
- authorizationError("functions are not policy values");
1419
- }
1420
- if (typeof input === "symbol") authorizationError("symbols are not policy values");
1421
- if (input === null || typeof input !== "object") return input;
1422
- if (active.has(input)) authorizationError("cyclic input");
1423
- active.add(input);
1424
- try {
1425
- if (input instanceof Date) return new Date(input.getTime());
1426
- if (Buffer.isBuffer(input)) return Buffer.from(input);
1427
- if (input instanceof RegExp) {
1428
- const result2 = new RegExp(input.source, input.flags);
1429
- result2.lastIndex = input.lastIndex;
1430
- return result2;
1431
- }
1432
- if (input instanceof import_mongoose2.mongo.BSON.BSONValue) {
1433
- try {
1434
- return import_mongoose2.mongo.BSON.deserialize(import_mongoose2.mongo.BSON.serialize({ value: input }), {
1435
- promoteValues: false,
1436
- bsonRegExp: true
1437
- }).value;
1438
- } catch {
1439
- authorizationError("unsupported BSON snapshot");
1440
- }
1441
- }
1442
- if (configuration && input instanceof Map) {
1443
- return new Map([...input].map(([key, entry]) => [copy(key, depth + 1), copy(entry, depth + 1)]));
1444
- }
1445
- if (configuration && input instanceof Set) return new Set([...input].map((entry) => copy(entry, depth + 1)));
1446
- const array = Array.isArray(input);
1447
- if (array && input.length > 2e4) authorizationError("snapshot array exceeds structural limits");
1448
- if (!array) authorizationRecord(input, "snapshot");
1449
- const result = array ? [] : {};
1450
- let definedProperty = false;
1451
- for (const key of Reflect.ownKeys(input)) {
1452
- if (array && key === "length") continue;
1453
- if (typeof key !== "string" || unsafeKeys.has(key)) authorizationError("unsafe snapshot key");
1454
- if (array && !/^(0|[1-9]\d*)$/.test(key)) authorizationError("invalid array property");
1455
- const descriptor = Object.getOwnPropertyDescriptor(input, key);
1456
- if (!("value" in descriptor) || !descriptor.enumerable && configuration !== "document")
1457
- authorizationError("accessor/non-enumerable input");
1458
- const value2 = copy(descriptor.value, depth + 1);
1459
- if (array || definedProperty && Object.getPrototypeOf(result) !== Object.prototype || key in result) {
1460
- definedProperty = true;
1461
- Object.defineProperty(result, key, {
1462
- value: value2,
1463
- enumerable: true,
1464
- writable: true,
1465
- configurable: true
1466
- });
1467
- } else result[key] = value2;
1468
- }
1469
- if (array) result.length = input.length;
1470
- return Object.freeze(result);
1471
- } finally {
1472
- active.delete(input);
1473
- }
1474
- }
1475
- return copy(value, 0);
1476
- }
1477
-
1478
- // src/acl/field-catalog.ts
1479
- var import_node_util4 = require("util");
1480
- 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);
1481
- var isSafeOutputPath = (path) => path.split(".").every(safeSegment);
1482
- var inputControlSegments = /* @__PURE__ */ new Set([
1483
- "_permissions",
1484
- "_view",
1485
- "_edit",
1486
- "documentAuthorization",
1487
- "documentAuthorizationStage",
1488
- "resolvedAuthorization",
1489
- "execution",
1490
- "executionContext",
1491
- "serviceExecutionContext",
1492
- "preparedQuery",
1493
- "preparedFilter",
1494
- "preparedModelQuery",
1495
- "resolvedIdentifier",
1496
- "skipParsing",
1497
- "skipAuthorization",
1498
- "alreadyAuthorized"
1499
- ]);
1500
- function isSafeInputPath(path, requestIdentity = false) {
1501
- return isSafeOutputPath(path) && path.split(".").every((part) => !inputControlSegments.has(part) && (requestIdentity || part !== "_id"));
1502
- }
1503
- function matchesCatalogPattern(pattern, path, descendants = false) {
1504
- if (typeof pattern === "string" && typeof path === "string" && !pattern.includes("$*")) {
1505
- return pattern === path || !!descendants && path.startsWith(pattern) && path[pattern.length] === ".";
1506
- }
1507
- const expected = pattern.split(".");
1508
- const actual = path.split(".");
1509
- return (descendants ? actual.length >= expected.length : actual.length === expected.length) && expected.every((part, index) => part === "$*" || part === actual[index]);
1510
- }
1511
- function captureAuthorizationFieldCatalog(schema, virtuals, documentPermissionField = "_permissions") {
1512
- const paths = /* @__PURE__ */ new Set();
1513
- const containers = /* @__PURE__ */ new Set();
1514
- const opaque = /* @__PURE__ */ new Set();
1515
- const references = /* @__PURE__ */ new Set();
1516
- const virtualPaths = /* @__PURE__ */ new Set();
1517
- const virtualScopes = /* @__PURE__ */ new Set();
1518
- const schemaVirtualPaths = /* @__PURE__ */ new Set();
1519
- const arrays = /* @__PURE__ */ new Set();
1520
- const protectedPaths = /* @__PURE__ */ new Set([documentPermissionField, "_doc", "$__", "__v"]);
1521
- const add = (path) => {
1522
- if (path.split(".").every((part) => part === "$*" || safeSegment(part))) paths.add(path);
1523
- };
1524
- const ancestors = (path) => {
1525
- const parts = path.split(".");
1526
- for (let n = 1; n < parts.length; n++) {
1527
- const parent = parts.slice(0, n).join(".");
1528
- add(parent);
1529
- containers.add(parent);
1530
- }
1531
- };
1532
- const visitType = (type, path, active) => {
1533
- add(path);
1534
- ancestors(path);
1535
- const element = type.$embeddedSchemaType ?? type.embeddedSchemaType ?? type.caster;
1536
- if (type.instance === "Array" || type.$isMongooseDocumentArray) arrays.add(path);
1537
- if (type.options?.ref || type.options?.refPath || element?.options?.ref || element?.options?.refPath) {
1538
- references.add(path);
1539
- return;
1540
- }
1541
- if (type.$isSchemaMap || type.instance === "Map") {
1542
- const value = type.$__schemaType;
1543
- if (value) visitType(value, `${path}.$*`, active);
1544
- else opaque.add(path);
1545
- containers.delete(path);
1546
- return;
1547
- }
1548
- const child = type.schema ?? element?.schema;
1549
- if (child) {
1550
- containers.add(path);
1551
- if (!active.has(child)) visitSchema(child, path, /* @__PURE__ */ new Set([...active, child]));
1552
- return;
1553
- }
1554
- if (type.instance === "Mixed" || element?.instance === "Mixed") opaque.add(path);
1555
- };
1556
- const visitSchema = (current, prefix, active) => {
1557
- const version = current.options.versionKey;
1558
- if (typeof version === "string") protectedPaths.add(prefix ? `${prefix}.${version}` : version);
1559
- for (const name of Object.keys(current.virtuals)) {
1560
- schemaVirtualPaths.add(prefix ? `${prefix}.${name}` : name);
1561
- }
1562
- for (const [name, raw] of Object.entries(current.paths)) {
1563
- if (name.includes("$*")) continue;
1564
- visitType(raw, prefix ? `${prefix}.${name}` : name, active);
1565
- }
1566
- };
1567
- visitSchema(schema, "", /* @__PURE__ */ new Set([schema]));
1568
- const persistedPaths = [...paths];
1569
- const visitVirtuals = (record2, prefix) => {
1570
- for (const [name, value] of Object.entries(record2 ?? {})) {
1571
- if (value === void 0) continue;
1572
- const path = prefix ? `${prefix}.${name}` : name;
1573
- if (!isSafeOutputPath(path)) continue;
1574
- if (value && typeof value === "object" && "sub" in value) {
1575
- if (references.has(path)) continue;
1576
- virtualScopes.add(path);
1577
- add(path);
1578
- containers.add(path);
1579
- visitVirtuals(value.sub, path);
1580
- } else {
1581
- add(path);
1582
- ancestors(path);
1583
- virtualPaths.add(path);
1584
- }
1585
- }
1586
- };
1587
- visitVirtuals(virtuals, "");
1588
- const eligible = [...paths].filter((p) => ![...protectedPaths].some((v) => matchesCatalogPattern(v, p, true)));
1589
- return Object.freeze({
1590
- paths: Object.freeze(eligible.filter((p) => !p.includes("$*"))),
1591
- persistedPaths: Object.freeze(persistedPaths),
1592
- arrayPaths: Object.freeze([...arrays]),
1593
- schemaVirtualPaths: Object.freeze([...schemaVirtualPaths]),
1594
- metadataPaths: Object.freeze([documentPermissionField]),
1595
- dynamicPaths: Object.freeze(eligible.filter((p) => p.includes("$*"))),
1596
- containerPaths: Object.freeze([...containers]),
1597
- opaquePaths: Object.freeze([...opaque]),
1598
- referencePaths: Object.freeze([...references]),
1599
- virtualPaths: Object.freeze([...virtualPaths]),
1600
- virtualScopePaths: Object.freeze([...virtualScopes]),
1601
- protectedPaths: Object.freeze([...protectedPaths])
1602
- });
1603
- }
2365
+ var import_utils13 = require("@web-ts-toolkit/utils");
1604
2366
 
1605
2367
  // src/acl/populate-target-configuration.ts
1606
- var import_utils11 = require("@web-ts-toolkit/utils");
2368
+ var import_utils12 = require("@web-ts-toolkit/utils");
1607
2369
 
1608
2370
  // src/runtime-context.ts
1609
- var import_node_async_hooks = require("async_hooks");
1610
- var runtimeStorage = new import_node_async_hooks.AsyncLocalStorage();
2371
+ var import_node_async_hooks2 = require("async_hooks");
2372
+ var runtimeStorage = new import_node_async_hooks2.AsyncLocalStorage();
1611
2373
  function getActiveRuntime() {
1612
2374
  return runtimeStorage.getStore() ?? null;
1613
2375
  }
@@ -1623,7 +2385,7 @@ function capturePopulateTargetConfiguration(runtime, modelName, source, proposed
1623
2385
  if (!model) authorizationError(`${label} requires an actual registered Mongoose model in this runtime`);
1624
2386
  const options = proposedOptions ?? runtime.getModelOptions(modelName);
1625
2387
  const permissionSchema = options.permissionSchema === void 0 ? defaults2.permissionSchema : options.permissionSchema;
1626
- if (!(0, import_utils11.isPlainObject)(permissionSchema))
2388
+ if (!(0, import_utils12.isPlainObject)(permissionSchema))
1627
2389
  authorizationError(
1628
2390
  `${label} requires an effective object permissionSchema; configure the model or runtime model defaults ({} explicitly closes business fields)`
1629
2391
  );
@@ -1666,7 +2428,7 @@ var fail = (label, message) => {
1666
2428
  var varyingSchema = (schema) => Object.keys(schema.discriminators ?? {}).length > 0 || schema.discriminatorMapping?.isRoot === false;
1667
2429
  var varyingModel = (model) => !!model.baseModelName || Object.keys(model.discriminators ?? {}).length > 0 || varyingSchema(model.schema);
1668
2430
  function record(value, label) {
1669
- if (!(0, import_utils12.isPlainObject)(value)) return fail(label, "entries must be plain { path, select? } objects");
2431
+ if (!(0, import_utils13.isPlainObject)(value)) return fail(label, "entries must be plain { path, select? } objects");
1670
2432
  for (const key of Reflect.ownKeys(value)) {
1671
2433
  const property = Object.getOwnPropertyDescriptor(value, key);
1672
2434
  if (typeof key !== "string" || !property.enumerable || !("value" in property))
@@ -1802,7 +2564,7 @@ function captureVirtualPopulateDependencies(runtime, modelName, options, populat
1802
2564
  proposed?.defaults
1803
2565
  );
1804
2566
  const defaults2 = proposed?.defaults ?? runtime.getDefaultModelOptions();
1805
- const readOption = (key) => resolveNestedOption((path2, fallback) => (0, import_utils12.get)(targetOptions, path2, fallback), key, (0, import_utils12.get)(defaults2, key));
2567
+ const readOption = (key) => resolveNestedOption((path2, fallback) => (0, import_utils13.get)(targetOptions, path2, fallback), key, (0, import_utils13.get)(defaults2, key));
1806
2568
  const documentPermissionField = targetOptions.documentPermissionField ?? defaults2.documentPermissionField;
1807
2569
  const catalog = captureAuthorizationFieldCatalog(targetModel.schema, void 0, documentPermissionField);
1808
2570
  const configuration = copyAuthorizationValue(
@@ -1860,13 +2622,13 @@ function captureVirtualPopulateDependencies(runtime, modelName, options, populat
1860
2622
  );
1861
2623
  continue;
1862
2624
  }
1863
- if (!(0, import_utils12.isPlainObject)(raw)) continue;
2625
+ if (!(0, import_utils13.isPlainObject)(raw)) continue;
1864
2626
  const entry = raw;
1865
2627
  const label = join(sourcePrefix, name);
1866
2628
  captureList(entry.dependsOnPopulate, label);
1867
2629
  if (!("get" in entry))
1868
2630
  for (const access of accesses) {
1869
- if ((0, import_utils12.isPlainObject)(entry[access]))
2631
+ if ((0, import_utils13.isPlainObject)(entry[access]))
1870
2632
  captureList(entry[access].dependsOnPopulate, `${label}.${access}`);
1871
2633
  }
1872
2634
  const byAccess = {};
@@ -1896,10 +2658,10 @@ function captureVirtualPopulateDependencies(runtime, modelName, options, populat
1896
2658
  var mongooseJsonSchemaInitialized = false;
1897
2659
  var ensureMongooseJsonSchemaInitialized = () => {
1898
2660
  if (mongooseJsonSchemaInitialized) return;
1899
- (0, import_mongoose_schema_jsonschema.default)(import_mongoose3.default);
2661
+ (0, import_mongoose_schema_jsonschema.default)(import_mongoose4.default);
1900
2662
  mongooseJsonSchemaInitialized = true;
1901
2663
  };
1902
- var pluralize = import_mongoose3.default.pluralize();
2664
+ var pluralize = import_mongoose4.default.pluralize();
1903
2665
  var FIELD_ACCESS_KEYS = ["list", "create", "read", "update"];
1904
2666
  var defaultModelOptions = {
1905
2667
  basePath: null,
@@ -1911,7 +2673,6 @@ var modelOverrides = (options) => {
1911
2673
  ([key, value]) => value !== void 0 || key === "operationAccess" || isPopulatePolicyKey(key)
1912
2674
  )
1913
2675
  );
1914
- for (const key of unsafeServerOptions) if (key in result) result[key] = result[key] === true;
1915
2676
  return cloneOptionsSnapshot(result);
1916
2677
  };
1917
2678
  var defaultDataOptions = {
@@ -1921,44 +2682,44 @@ var defaultDataOptions = {
1921
2682
  listHardLimit: DEFAULT_LIST_HARD_LIMIT
1922
2683
  };
1923
2684
  var normalizeBasePath = (name, value) => {
1924
- if ((0, import_utils13.isNil)(value)) {
2685
+ if ((0, import_utils14.isNil)(value)) {
1925
2686
  return `/${pluralize(name)}`;
1926
2687
  }
1927
- return (0, import_utils13.isString)(value) ? (0, import_utils13.addLeadingSlash)(value) : "";
2688
+ return (0, import_utils14.isString)(value) ? (0, import_utils14.addLeadingSlash)(value) : "";
1928
2689
  };
1929
2690
  var hasModelPermission = (value, modelPermissionPrefix) => {
1930
2691
  if (!modelPermissionPrefix) {
1931
2692
  return true;
1932
2693
  }
1933
- if ((0, import_utils13.isString)(value)) {
2694
+ if ((0, import_utils14.isString)(value)) {
1934
2695
  return value.trim().split(" ").some((item) => item.startsWith(modelPermissionPrefix));
1935
2696
  }
1936
- if ((0, import_utils13.isArray)(value)) {
2697
+ if ((0, import_utils14.isArray)(value)) {
1937
2698
  return value.some((item) => {
1938
- if ((0, import_utils13.isString)(item) || (0, import_utils13.isArray)(item)) {
2699
+ if ((0, import_utils14.isString)(item) || (0, import_utils14.isArray)(item)) {
1939
2700
  return hasModelPermission(item, modelPermissionPrefix);
1940
2701
  }
1941
2702
  return true;
1942
2703
  });
1943
2704
  }
1944
- return (0, import_utils13.isFunction)(value);
2705
+ return (0, import_utils14.isFunction)(value);
1945
2706
  };
1946
2707
  var classifyPermissionSchema = (permissionSchema, modelPermissionPrefix) => {
1947
2708
  const schemaKeys = Object.keys(permissionSchema);
1948
2709
  const globalPermissionKeys = {};
1949
2710
  const modelPermissionKeys = {};
1950
- (0, import_utils13.forEach)(schemaKeys, (schemaKey) => {
2711
+ (0, import_utils14.forEach)(schemaKeys, (schemaKey) => {
1951
2712
  const schemaRule = permissionSchema[schemaKey];
1952
- const ruleEntries = (0, import_utils13.isPlainObject)(schemaRule) ? Object.entries(schemaRule) : FIELD_ACCESS_KEYS.map((accessKey) => [accessKey, schemaRule]);
2713
+ const ruleEntries = (0, import_utils14.isPlainObject)(schemaRule) ? Object.entries(schemaRule) : FIELD_ACCESS_KEYS.map((accessKey) => [accessKey, schemaRule]);
1953
2714
  for (let x = 0; x < ruleEntries.length; x++) {
1954
2715
  const [accessKey, value] = ruleEntries[x];
1955
- if (!(0, import_utils13.isArray)(globalPermissionKeys[accessKey])) {
2716
+ if (!(0, import_utils14.isArray)(globalPermissionKeys[accessKey])) {
1956
2717
  globalPermissionKeys[accessKey] = [];
1957
2718
  }
1958
- if (!(0, import_utils13.isArray)(modelPermissionKeys[accessKey])) {
2719
+ if (!(0, import_utils14.isArray)(modelPermissionKeys[accessKey])) {
1959
2720
  modelPermissionKeys[accessKey] = [];
1960
2721
  }
1961
- if ((0, import_utils13.isBoolean)(value)) {
2722
+ if ((0, import_utils14.isBoolean)(value)) {
1962
2723
  globalPermissionKeys[accessKey].push(schemaKey);
1963
2724
  continue;
1964
2725
  }
@@ -1990,13 +2751,13 @@ var VIRTUAL_UNSUPPORTED_ACCESSES = ["delete", "distinct", "count"];
1990
2751
  var VIRTUAL_RESERVED_NAMES = /* @__PURE__ */ new Set(["_id", "__v", "id"]);
1991
2752
  var VIRTUAL_DANGEROUS_SEGMENTS = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
1992
2753
  var VIRTUAL_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_$]*$/;
1993
- var isVirtualContainerValue2 = (value) => (0, import_utils13.isPlainObject)(value) && "sub" in value;
2754
+ var isVirtualContainerValue2 = (value) => (0, import_utils14.isPlainObject)(value) && "sub" in value;
1994
2755
  var virtualFullPath = (prefix, name) => prefix ? `${prefix}.${name}` : name;
1995
2756
  var virtualPathsOverlap = (virtualPath, permissionField) => {
1996
2757
  if (!virtualPath || !permissionField) return false;
1997
2758
  try {
1998
- if ((0, import_utils13.get)((0, import_utils13.set)({}, virtualPath, true), permissionField) !== void 0) return true;
1999
- if ((0, import_utils13.get)((0, import_utils13.set)({}, permissionField, true), virtualPath) !== void 0) return true;
2759
+ if ((0, import_utils14.get)((0, import_utils14.set)({}, virtualPath, true), permissionField) !== void 0) return true;
2760
+ if ((0, import_utils14.get)((0, import_utils14.set)({}, permissionField, true), virtualPath) !== void 0) return true;
2000
2761
  } catch {
2001
2762
  return false;
2002
2763
  }
@@ -2057,12 +2818,12 @@ var cloneModelOptionForUpdate = (value) => {
2057
2818
  };
2058
2819
  var validateVirtualDependsOn = (dependsOn, entryLabel, storedFields, siblingVirtualNames) => {
2059
2820
  if (dependsOn === void 0) return [];
2060
- if (!(0, import_utils13.isArray)(dependsOn)) {
2821
+ if (!(0, import_utils14.isArray)(dependsOn)) {
2061
2822
  throw new Error(`Virtual ${entryLabel}: dependsOn must be an array of top-level persisted field names`);
2062
2823
  }
2063
2824
  const list = dependsOn;
2064
2825
  for (const dep of list) {
2065
- if (!(0, import_utils13.isString)(dep) || dep.length === 0) {
2826
+ if (!(0, import_utils14.isString)(dep) || dep.length === 0) {
2066
2827
  throw new Error(`Virtual ${entryLabel}: dependsOn entries must be non-empty strings`);
2067
2828
  }
2068
2829
  if (dep.includes(".")) {
@@ -2084,12 +2845,12 @@ var validateVirtualDependsOn = (dependsOn, entryLabel, storedFields, siblingVirt
2084
2845
  return list;
2085
2846
  };
2086
2847
  var validateVirtualLeafValue = (value, entryLabel, storedFields, siblingVirtualNames, sharedDependsOn) => {
2087
- if ((0, import_utils13.isFunction)(value)) return;
2088
- if (!(0, import_utils13.isPlainObject)(value)) {
2848
+ if ((0, import_utils14.isFunction)(value)) return;
2849
+ if (!(0, import_utils14.isPlainObject)(value)) {
2089
2850
  throw new Error(`Virtual ${entryLabel}: descriptor must be a getter function or { get, dependsOn }`);
2090
2851
  }
2091
2852
  const record2 = value;
2092
- if (!(0, import_utils13.isFunction)(record2.get)) {
2853
+ if (!(0, import_utils14.isFunction)(record2.get)) {
2093
2854
  throw new Error(`Virtual ${entryLabel}: descriptor.get must be a callable getter function`);
2094
2855
  }
2095
2856
  validateVirtualDependsOn(record2.dependsOn ?? sharedDependsOn, entryLabel, storedFields, siblingVirtualNames);
@@ -2131,7 +2892,7 @@ var validateVirtualsScope = (scope, documentPermissionField) => {
2131
2892
  `Virtual ${scopeLabel}${name}: scope-container must only hold "sub" (embedded container "${name}" is not a virtual-leaf collision)`
2132
2893
  );
2133
2894
  }
2134
- if (!(0, import_utils13.isPlainObject)(record3.sub)) {
2895
+ if (!(0, import_utils14.isPlainObject)(record3.sub)) {
2135
2896
  throw new Error(`Virtual ${scopeLabel}${name}: scope-container "sub" must be a plain object`);
2136
2897
  }
2137
2898
  continue;
@@ -2141,8 +2902,8 @@ var validateVirtualsScope = (scope, documentPermissionField) => {
2141
2902
  `Virtual ${scopeLabel}${name}: collides with a stored path (inspected actual Mongoose schema/child scope; getModelAtt alone is insufficient)`
2142
2903
  );
2143
2904
  }
2144
- if ((0, import_utils13.isFunction)(raw)) continue;
2145
- if (!(0, import_utils13.isPlainObject)(raw)) {
2905
+ if ((0, import_utils14.isFunction)(raw)) continue;
2906
+ if (!(0, import_utils14.isPlainObject)(raw)) {
2146
2907
  throw new Error(
2147
2908
  `Virtual ${scopeLabel}${name}: malformed descriptor (expected getter, { get, dependsOn }, or per-access record)`
2148
2909
  );
@@ -2196,7 +2957,7 @@ var validateVirtualsScope = (scope, documentPermissionField) => {
2196
2957
  };
2197
2958
  var validateVirtualsTree = (model, virtuals, documentPermissionField, modelName) => {
2198
2959
  if (virtuals === void 0 || virtuals === null) return;
2199
- if (!(0, import_utils13.isPlainObject)(virtuals)) {
2960
+ if (!(0, import_utils14.isPlainObject)(virtuals)) {
2200
2961
  throw new Error(`Virtuals for model "${modelName}": virtuals must be a plain object mapping names to descriptors`);
2201
2962
  }
2202
2963
  const rootSchema = model?.schema ?? null;
@@ -2265,19 +3026,12 @@ var AccessRuntime = class {
2265
3026
  requireOperationAccessForPopulateQueries: true,
2266
3027
  requireOperationAccessForPopulateDependencies: true,
2267
3028
  modelPermissionPrefix: "",
2268
- unsafeSkipListDocumentSnapshotChecks: false,
2269
- unsafeSkipReadDocumentSnapshotChecks: false,
2270
- unsafeSkipListOutputSnapshotChecks: false,
2271
- unsafeSkipReadOutputSnapshotChecks: false,
2272
- unsafeSkipListNestedDocumentSnapshotChecks: false,
2273
- unsafeSkipReadNestedDocumentSnapshotChecks: false,
2274
- unsafeSkipListInitialOutputSnapshotCopy: false,
2275
- unsafeSkipReadInitialOutputSnapshotCopy: false,
2276
- unsafeUseListAuthorizationFastPath: false,
2277
- unsafeUseReadAuthorizationFastPath: false
3029
+ readAuthorizationMode: "isolated",
3030
+ listAuthorizationMode: "isolated"
2278
3031
  }).build();
2279
3032
  this.modelOptions = {};
2280
3033
  this.modelOptionOverrides = {};
3034
+ this.publishingAuthorizationModes = false;
2281
3035
  this.modelJsonSchemas = {};
2282
3036
  this.dataOptions = {};
2283
3037
  this.modelRefs = {};
@@ -2286,6 +3040,10 @@ var AccessRuntime = class {
2286
3040
  this.modelInstances = {};
2287
3041
  this.openApiRegistry = new OpenApiRegistry();
2288
3042
  this.openApiPathPrefix = "";
3043
+ assertAuthorizationModeOptions(options, false);
3044
+ assertNoServerModelControls(options, (detail) => {
3045
+ throw new TypeError(detail);
3046
+ });
2289
3047
  this.allowGlobalModelLookup = options.allowGlobalModelLookup ?? false;
2290
3048
  ensureMongooseJsonSchemaInitialized();
2291
3049
  }
@@ -2302,20 +3060,20 @@ var AccessRuntime = class {
2302
3060
  this.modelInstances[modelName] = model;
2303
3061
  }
2304
3062
  hasModelInstance(modelName) {
2305
- return modelName in this.modelInstances || this.allowGlobalModelLookup && modelName in import_mongoose3.default.models;
3063
+ return modelName in this.modelInstances || this.allowGlobalModelLookup && modelName in import_mongoose4.default.models;
2306
3064
  }
2307
3065
  getModelInstance(modelName) {
2308
3066
  const registered = this.modelInstances[modelName];
2309
3067
  if (registered) return registered;
2310
3068
  if (!this.allowGlobalModelLookup) return null;
2311
- const global = import_mongoose3.default.models[modelName];
3069
+ const global = import_mongoose4.default.models[modelName];
2312
3070
  if (!global) return null;
2313
3071
  this.registerModelInstance(modelName, global);
2314
3072
  return global;
2315
3073
  }
2316
3074
  registerOpenApiRoute(route) {
2317
3075
  this.openApiRegistry.register(
2318
- this.openApiPathPrefix ? { ...route, path: (0, import_utils13.normalizeUrlPath)(`${this.openApiPathPrefix}/${route.path}`) } : route
3076
+ this.openApiPathPrefix ? { ...route, path: (0, import_utils14.normalizeUrlPath)(`${this.openApiPathPrefix}/${route.path}`) } : route
2319
3077
  );
2320
3078
  }
2321
3079
  /**
@@ -2326,7 +3084,7 @@ var AccessRuntime = class {
2326
3084
  */
2327
3085
  withOpenApiPathPrefix(prefix, build) {
2328
3086
  const previous = this.openApiPathPrefix;
2329
- this.openApiPathPrefix = (0, import_utils13.normalizeUrlPath)(`${previous}/${prefix}`);
3087
+ this.openApiPathPrefix = (0, import_utils14.normalizeUrlPath)(`${previous}/${prefix}`);
2330
3088
  try {
2331
3089
  return build();
2332
3090
  } finally {
@@ -2378,6 +3136,49 @@ var AccessRuntime = class {
2378
3136
  };
2379
3137
  }
2380
3138
  restoreBootstrapSnapshot(snapshot) {
3139
+ assertAuthorizationModeOptions(snapshot, false);
3140
+ const reject = (detail) => {
3141
+ throw new TypeError(detail);
3142
+ };
3143
+ for (const key of [
3144
+ "globalOptions",
3145
+ "defaultModelOptions",
3146
+ "modelOptions",
3147
+ "modelOptionOverrides",
3148
+ "dataOptions",
3149
+ "modelInstances",
3150
+ "modelJsonSchemas",
3151
+ "modelRefs",
3152
+ "modelSubs",
3153
+ "modelAtts",
3154
+ "openApi"
3155
+ ]) {
3156
+ const slot = Object.getOwnPropertyDescriptor(snapshot, key);
3157
+ if (!slot || !("value" in slot) || !slot.enumerable) reject(`Invalid bootstrap snapshot slot: ${key}`);
3158
+ if (!slot.value || typeof slot.value !== "object" || Array.isArray(slot.value))
3159
+ reject(`Invalid bootstrap snapshot object: ${key}`);
3160
+ admitControlPrototypes(slot.value, reject);
3161
+ if (key === "globalOptions" || key === "defaultModelOptions" || key === "openApi") continue;
3162
+ for (const entry of Reflect.ownKeys(slot.value)) {
3163
+ const item = Object.getOwnPropertyDescriptor(slot.value, entry);
3164
+ if (typeof entry !== "string" || !("value" in item) || !item.enumerable)
3165
+ reject(`Invalid bootstrap snapshot entry: ${key}`);
3166
+ }
3167
+ }
3168
+ assertAuthorizationModeOptions(snapshot.globalOptions, false);
3169
+ assertNoServerModelControls(snapshot.globalOptions, reject);
3170
+ assertAuthorizationModeOptions(snapshot.defaultModelOptions, true);
3171
+ assertNoServerModelControls(snapshot.defaultModelOptions, reject, "model-options");
3172
+ assertPublicDefaults(snapshot.defaultModelOptions.defaults);
3173
+ for (const options of [...Object.values(snapshot.modelOptions), ...Object.values(snapshot.modelOptionOverrides)]) {
3174
+ assertAuthorizationModeOptions(options, true);
3175
+ assertNoServerModelControls(options, reject, "model-options");
3176
+ assertPublicDefaults(options.defaults);
3177
+ }
3178
+ for (const options of Object.values(snapshot.dataOptions)) {
3179
+ assertAuthorizationModeOptions(options, false);
3180
+ assertNoServerModelControls(options, reject, "data-options");
3181
+ }
2381
3182
  this.globalOptions.restore(snapshot.globalOptions);
2382
3183
  this.defaultModelOptions.restore(snapshot.defaultModelOptions);
2383
3184
  for (const name of Object.keys(this.modelOptionOverrides)) delete this.modelOptionOverrides[name];
@@ -2437,11 +3238,21 @@ var AccessRuntime = class {
2437
3238
  }
2438
3239
  /** Shallowly replace supplied global values; nested objects such as requestComplexity are not deep-merged. */
2439
3240
  setGlobalOptions(options) {
3241
+ assertAuthorizationModeOptions(options, false);
3242
+ assertNoServerModelControls(options, (detail) => {
3243
+ throw new TypeError(detail);
3244
+ });
2440
3245
  for (const key of populatePolicyKeys) if (key in options) assertNoGlobalPopulatePolicy(key);
2441
3246
  this.globalOptions.assign({ ...options });
2442
3247
  }
2443
3248
  setGlobalOption(key, value) {
3249
+ assertAuthorizationModeKey(key, false);
2444
3250
  assertNoGlobalPopulatePolicy(String(key));
3251
+ const proposed = {};
3252
+ (0, import_utils14.set)(proposed, key, value);
3253
+ assertNoServerModelControls(proposed, (detail) => {
3254
+ throw new TypeError(detail);
3255
+ });
2445
3256
  this.globalOptions.set(key, value);
2446
3257
  }
2447
3258
  getGlobalOptions() {
@@ -2452,6 +3263,17 @@ var AccessRuntime = class {
2452
3263
  }
2453
3264
  /** Update inherited model defaults shallowly. Explicit model values and captured calls are unchanged. */
2454
3265
  setDefaultModelOptions(options) {
3266
+ assertAuthorizationModeOptions(options, true);
3267
+ assertNoServerModelControls(
3268
+ options,
3269
+ (detail) => {
3270
+ throw new TypeError(detail);
3271
+ },
3272
+ "model-options"
3273
+ );
3274
+ options = { ...options };
3275
+ for (const key of authorizationModeKeys)
3276
+ if (key in options && options[key] === void 0) options[key] = "isolated";
2455
3277
  assertPublicDefaults(options.defaults);
2456
3278
  if ("hydration" in options) options = { ...options, hydration: normalizeHydration(options.hydration) };
2457
3279
  const draft = new OptionsManager(
@@ -2461,11 +3283,31 @@ var AccessRuntime = class {
2461
3283
  this.publishDefaultModelOptions(draft.fetch());
2462
3284
  }
2463
3285
  setDefaultModelOption(key, value) {
2464
- const keyStr = String(key);
2465
- if (keyStr === "defaults") assertPublicDefaults(value);
2466
- else if (keyStr.startsWith("defaults.")) {
3286
+ assertAuthorizationModeKey(key, true);
3287
+ const keyStr = key;
3288
+ if (authorizationModeKeys.includes(keyStr)) {
3289
+ this.setDefaultModelOptions({ [keyStr]: value });
3290
+ return;
3291
+ }
3292
+ if (keyStr === "defaults") {
3293
+ assertNoServerModelControls(
3294
+ value,
3295
+ (detail) => {
3296
+ throw new TypeError(detail);
3297
+ },
3298
+ "defaults"
3299
+ );
3300
+ assertPublicDefaults(value);
3301
+ } else if (keyStr.startsWith("defaults.")) {
2467
3302
  const proposed = {};
2468
- (0, import_utils13.set)(proposed, keyStr.slice("defaults.".length), value);
3303
+ (0, import_utils14.set)(proposed, keyStr.slice("defaults.".length), value);
3304
+ assertNoServerModelControls(
3305
+ proposed,
3306
+ (detail) => {
3307
+ throw new TypeError(detail);
3308
+ },
3309
+ "defaults"
3310
+ );
2469
3311
  assertPublicDefaults(proposed);
2470
3312
  }
2471
3313
  const draft = new OptionsManager(
@@ -2492,7 +3334,6 @@ var AccessRuntime = class {
2492
3334
  for (const key of populatePolicyKeys) delete inherited[key];
2493
3335
  const effective = { ...defaultModelOptions, ...inherited, ...overrides, modelName };
2494
3336
  effective.basePath = normalizeBasePath(modelName, effective.basePath);
2495
- for (const key of unsafeServerOptions) effective[key] = effective[key] === true;
2496
3337
  refreshPermissionMetadata(effective);
2497
3338
  return cloneOptionsSnapshot(effective);
2498
3339
  }
@@ -2507,77 +3348,43 @@ var AccessRuntime = class {
2507
3348
  }
2508
3349
  publishDefaultModelOptions(options) {
2509
3350
  const next = { ...options };
2510
- for (const key of unsafeServerOptions) if (key in next) next[key] = next[key] === true;
2511
3351
  const defaults2 = cloneOptionsSnapshot(next);
2512
3352
  const models = new Map(
2513
3353
  Object.keys(this.modelOptions).map((name) => [name, this.resolveModelOptions(name, void 0, defaults2)])
2514
3354
  );
2515
3355
  for (const [name, options2] of models) this.validateModelOptions(name, options2, { defaults: defaults2, models });
2516
- this.deferSnapshotWarnings(() => {
3356
+ this.publishAuthorizationModes(() => {
2517
3357
  this.defaultModelOptions.restore(defaults2);
2518
3358
  for (const [name, options2] of models) this.modelOptions[name].restore(options2);
2519
3359
  });
2520
3360
  }
2521
- warnSnapshotFlag(modelName, key) {
2522
- if (this.pendingSnapshotWarnings) {
2523
- this.pendingSnapshotWarnings.push({ modelName, key });
2524
- return;
2525
- }
2526
- const operation = key.startsWith("unsafeSkipRead") ? "read" : "list";
2527
- const category = key.includes("NestedDocument") ? "nested-document" : key.includes("Output") ? "output" : "document";
2528
- const risk = category === "output" ? "output mutation" : "source mutation";
2529
- try {
2530
- this.getGlobalOption("logger")?.warn?.(
2531
- `UNSAFE: ${operation} ${category} snapshot checks disabled; ${risk} can leave stale authorization decisions. Restore ${key}=false after the temporary workaround.`,
2532
- { modelName }
2533
- );
2534
- } catch {
2535
- }
2536
- }
2537
- deferSnapshotWarnings(publish) {
2538
- if (this.pendingSnapshotWarnings) return publish();
2539
- const copyModes = this.initialOutputCopyModes();
2540
- const fastModes = this.authorizationFastPathModes();
2541
- const pending = [];
2542
- this.pendingSnapshotWarnings = pending;
3361
+ /** Warn only on effective transitions into trusted, after the entire update commits. */
3362
+ publishAuthorizationModes(publish) {
3363
+ if (this.publishingAuthorizationModes) return publish();
3364
+ const capture = () => new Map([
3365
+ ["default-model", this.getDefaultModelOptions()],
3366
+ ...Object.entries(this.modelOptions).map(([name, manager]) => [name, manager.fetch()])
3367
+ ]);
3368
+ const before = capture();
3369
+ this.publishingAuthorizationModes = true;
2543
3370
  let result;
2544
3371
  try {
2545
3372
  result = publish();
2546
3373
  } finally {
2547
- this.pendingSnapshotWarnings = void 0;
2548
- }
2549
- const nextCopyModes = this.initialOutputCopyModes();
2550
- const nextFastModes = this.authorizationFastPathModes();
2551
- for (const { modelName, key } of pending) this.warnSnapshotFlag(modelName, key);
2552
- for (const [modelName, modes] of nextCopyModes) {
2553
- for (const operation of ["List", "Read"]) {
2554
- const mode = modes[operation];
2555
- if (mode === "off" || mode === copyModes.get(modelName)?.[operation]) continue;
2556
- const key = `unsafeSkip${operation}InitialOutputSnapshotCopy`;
2557
- const prerequisite = `unsafeSkip${operation}OutputSnapshotChecks`;
2558
- try {
2559
- this.getGlobalOption("logger")?.warn?.(
2560
- 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.`,
2561
- { modelName }
2562
- );
2563
- } catch {
2564
- }
2565
- }
3374
+ this.publishingAuthorizationModes = false;
2566
3375
  }
2567
- for (const [modelName, modes] of nextFastModes) {
2568
- for (const origin of ["list", "read"]) {
2569
- const captured = modes[origin];
2570
- const previous = fastModes.get(modelName)?.[origin];
2571
- if (captured.mode === "off" || captured.mode === previous?.mode && (captured.mode !== "dormant" || captured.prerequisites === previous.prerequisites))
2572
- continue;
2573
- const key = origin === "read" ? "unsafeUseReadAuthorizationFastPath" : "unsafeUseListAuthorizationFastPath";
2574
- const missing = authorizationFastPathPrerequisites(origin).filter(
2575
- (_, index) => !(captured.prerequisites & 1 << index)
2576
- );
3376
+ const after = capture();
3377
+ for (const [modelName, options] of after) {
3378
+ for (const key of authorizationModeKeys) {
3379
+ if (options[key] !== "trusted" || before.get(modelName)?.[key] === "trusted") continue;
2577
3380
  try {
2578
3381
  this.getGlobalOption("logger")?.warn?.(
2579
- 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.`,
2580
- { modelName }
3382
+ "Trusted authorization source mode enabled; projected source/document-hook input may be borrowed. Actor, policy, facts, getter views and selected output bounds remain owned.",
3383
+ {
3384
+ modelName,
3385
+ access: key === "readAuthorizationMode" ? "read" : "list",
3386
+ category: "trustedAuthorizationSource"
3387
+ }
2581
3388
  );
2582
3389
  } catch {
2583
3390
  }
@@ -2585,25 +3392,6 @@ var AccessRuntime = class {
2585
3392
  }
2586
3393
  return result;
2587
3394
  }
2588
- authorizationFastPathModes() {
2589
- return new Map(
2590
- Object.entries(this.modelOptions).map(([modelName, manager]) => {
2591
- const options = manager.fetch();
2592
- return [
2593
- modelName,
2594
- { list: captureAuthorizationFastPath(options, "list"), read: captureAuthorizationFastPath(options, "read") }
2595
- ];
2596
- })
2597
- );
2598
- }
2599
- initialOutputCopyModes() {
2600
- return new Map(
2601
- Object.entries(this.modelOptions).map(([modelName, options]) => {
2602
- const mode = (operation) => options.get(`unsafeSkip${operation}InitialOutputSnapshotCopy`) !== true ? "off" : options.get(`unsafeSkip${operation}OutputSnapshotChecks`) === true ? "active" : "dormant";
2603
- return [modelName, { List: mode("List"), Read: mode("Read") }];
2604
- })
2605
- );
2606
- }
2607
3395
  createModelOptions(modelName, options = this.resolveModelOptions(modelName)) {
2608
3396
  const model = this.getModelInstance(modelName);
2609
3397
  if (!model) {
@@ -2612,19 +3400,14 @@ var AccessRuntime = class {
2612
3400
  );
2613
3401
  }
2614
3402
  const manager = new OptionsManager(options);
2615
- const snapshotFlagChanged = (newValue, key, target, oldValue) => {
2616
- target[key] = newValue === true;
2617
- if (newValue !== true || oldValue === true) return;
2618
- this.warnSnapshotFlag(modelName, key);
2619
- };
2620
3403
  manager.onchange("permissionSchema", function(_newval, _key, target) {
2621
3404
  refreshPermissionMetadata(target);
2622
3405
  }).onchange("modelPermissionPrefix", function(_newval, _key, target) {
2623
3406
  refreshPermissionMetadata(target);
2624
- }).onchange("unsafeSkipListDocumentSnapshotChecks", snapshotFlagChanged).onchange("unsafeSkipReadDocumentSnapshotChecks", snapshotFlagChanged).onchange("unsafeSkipListOutputSnapshotChecks", snapshotFlagChanged).onchange("unsafeSkipReadOutputSnapshotChecks", snapshotFlagChanged).onchange("unsafeSkipListNestedDocumentSnapshotChecks", snapshotFlagChanged).onchange("unsafeSkipReadNestedDocumentSnapshotChecks", snapshotFlagChanged).onchange("basePath", function(newval, key, target) {
3407
+ }).onchange("basePath", function(newval, key, target) {
2625
3408
  target[key] = normalizeBasePath(
2626
3409
  modelName,
2627
- (0, import_utils13.isString)(newval) || (0, import_utils13.isNil)(newval) ? newval : void 0
3410
+ (0, import_utils14.isString)(newval) || (0, import_utils14.isNil)(newval) ? newval : void 0
2628
3411
  );
2629
3412
  }).build();
2630
3413
  this.modelJsonSchemas[modelName] = model.jsonSchema();
@@ -2633,7 +3416,7 @@ var AccessRuntime = class {
2633
3416
  getOrCreateModelOptions(modelName) {
2634
3417
  let manager = this.modelOptions[modelName];
2635
3418
  if (!manager) {
2636
- manager = this.deferSnapshotWarnings(() => {
3419
+ manager = this.publishAuthorizationModes(() => {
2637
3420
  const created = this.createModelOptions(modelName);
2638
3421
  this.modelOptions[modelName] = created;
2639
3422
  return created;
@@ -2650,13 +3433,21 @@ var AccessRuntime = class {
2650
3433
  * calls capture the owner's current options/defaults; in-flight calls retain their snapshot.
2651
3434
  */
2652
3435
  setModelOptions(modelName, options) {
3436
+ assertAuthorizationModeOptions(options, true);
3437
+ assertNoServerModelControls(
3438
+ options,
3439
+ (detail) => {
3440
+ throw new TypeError(detail);
3441
+ },
3442
+ "model-options"
3443
+ );
2653
3444
  assertPublicDefaults(options.defaults);
2654
3445
  options = normalizePopulatePolicyOptions(options);
2655
3446
  if ("hydration" in options) options = { ...options, hydration: normalizeHydration(options.hydration) };
2656
3447
  const overrides = modelOverrides({ ...this.modelOptionOverrides[modelName], ...options });
2657
3448
  const effective = this.resolveModelOptions(modelName, overrides);
2658
3449
  this.validateModelOptions(modelName, effective);
2659
- this.deferSnapshotWarnings(() => {
3450
+ this.publishAuthorizationModes(() => {
2660
3451
  const manager = this.modelOptions[modelName];
2661
3452
  if (manager) manager.restore(effective);
2662
3453
  else this.modelOptions[modelName] = this.createModelOptions(modelName, effective);
@@ -2664,16 +3455,32 @@ var AccessRuntime = class {
2664
3455
  });
2665
3456
  }
2666
3457
  setModelOption(modelName, key, value) {
2667
- const keyStr = String(key);
3458
+ assertAuthorizationModeKey(key, true);
3459
+ const keyStr = key;
2668
3460
  if (keyStr === "hydration" || keyStr.startsWith("hydration.")) {
2669
3461
  const hydration = normalizeHydrationUpdate(this.resolveModelOptions(modelName).hydration, keyStr, value);
2670
3462
  this.setModelOptions(modelName, { hydration });
2671
3463
  return;
2672
3464
  }
2673
- if (keyStr === "defaults") assertPublicDefaults(value);
2674
- else if (keyStr.startsWith("defaults.")) {
3465
+ if (keyStr === "defaults") {
3466
+ assertNoServerModelControls(
3467
+ value,
3468
+ (detail) => {
3469
+ throw new TypeError(detail);
3470
+ },
3471
+ "defaults"
3472
+ );
3473
+ assertPublicDefaults(value);
3474
+ } else if (keyStr.startsWith("defaults.")) {
2675
3475
  const proposed = {};
2676
- (0, import_utils13.set)(proposed, keyStr.slice("defaults.".length), value);
3476
+ (0, import_utils14.set)(proposed, keyStr.slice("defaults.".length), value);
3477
+ assertNoServerModelControls(
3478
+ proposed,
3479
+ (detail) => {
3480
+ throw new TypeError(detail);
3481
+ },
3482
+ "defaults"
3483
+ );
2677
3484
  assertPublicDefaults(proposed);
2678
3485
  }
2679
3486
  const [root, ...path] = keyStr.split(".");
@@ -2682,11 +3489,11 @@ var AccessRuntime = class {
2682
3489
  return;
2683
3490
  }
2684
3491
  const current = this.resolveModelOptions(modelName);
2685
- const nested = cloneModelOptionForUpdate((0, import_utils13.isPlainObject)(current[root]) ? current[root] : {});
3492
+ const nested = cloneModelOptionForUpdate((0, import_utils14.isPlainObject)(current[root]) ? current[root] : {});
2686
3493
  if (root === "virtuals" && value === void 0) {
2687
- const parent = path.length === 1 ? nested : (0, import_utils13.get)(nested, path.slice(0, -1));
2688
- if ((0, import_utils13.isPlainObject)(parent)) delete parent[path[path.length - 1]];
2689
- } else (0, import_utils13.set)(nested, path, value);
3494
+ const parent = path.length === 1 ? nested : (0, import_utils14.get)(nested, path.slice(0, -1));
3495
+ if ((0, import_utils14.isPlainObject)(parent)) delete parent[path[path.length - 1]];
3496
+ } else (0, import_utils14.set)(nested, path, value);
2690
3497
  this.setModelOptions(modelName, { [root]: nested });
2691
3498
  }
2692
3499
  /** Frozen model/default snapshot; populate flags remain raw overrides. Read again for current values. */
@@ -2776,7 +3583,7 @@ var AccessRuntime = class {
2776
3583
  manager.onchange("basePath", function(newval, key, target) {
2777
3584
  target[key] = normalizeBasePath(
2778
3585
  dataName,
2779
- (0, import_utils13.isString)(newval) || (0, import_utils13.isNil)(newval) ? newval : void 0
3586
+ (0, import_utils14.isString)(newval) || (0, import_utils14.isNil)(newval) ? newval : void 0
2780
3587
  );
2781
3588
  }).build();
2782
3589
  return manager;
@@ -2790,10 +3597,28 @@ var AccessRuntime = class {
2790
3597
  return manager;
2791
3598
  }
2792
3599
  setDataOptions(dataName, options) {
3600
+ assertAuthorizationModeOptions(options, false);
3601
+ assertNoServerModelControls(
3602
+ options,
3603
+ (detail) => {
3604
+ throw new TypeError(detail);
3605
+ },
3606
+ "data-options"
3607
+ );
2793
3608
  const manager = this.getOrCreateDataOptions(dataName);
2794
3609
  manager.assign(options);
2795
3610
  }
2796
3611
  setDataOption(dataName, key, value) {
3612
+ assertAuthorizationModeKey(key, false);
3613
+ const proposed = {};
3614
+ (0, import_utils14.set)(proposed, key, value);
3615
+ assertNoServerModelControls(
3616
+ proposed,
3617
+ (detail) => {
3618
+ throw new TypeError(detail);
3619
+ },
3620
+ "data-options"
3621
+ );
2797
3622
  const manager = this.getOrCreateDataOptions(dataName);
2798
3623
  manager.set(key, value);
2799
3624
  }
@@ -2836,20 +3661,20 @@ var AccessRuntime = class {
2836
3661
  const schema = model.schema;
2837
3662
  this.modelRefs[modelName] = buildRefs(schema.tree);
2838
3663
  this.modelSubs[modelName] = buildSubPaths(schema.tree);
2839
- this.modelAtts[modelName] = (0, import_utils13.keys)(schema.obj);
3664
+ this.modelAtts[modelName] = (0, import_utils14.keys)(schema.obj);
2840
3665
  }
2841
3666
  getModelRef(modelName, refPath) {
2842
3667
  this.ensureModelMeta(modelName);
2843
- const value = (0, import_utils13.get)(this.modelRefs, `${modelName}.${refPath}`, null);
2844
- return (0, import_utils13.isString)(value) ? value : null;
3668
+ const value = (0, import_utils14.get)(this.modelRefs, `${modelName}.${refPath}`, null);
3669
+ return (0, import_utils14.isString)(value) ? value : null;
2845
3670
  }
2846
3671
  getModelSub(modelName) {
2847
3672
  this.ensureModelMeta(modelName);
2848
- return (0, import_utils13.get)(this.modelSubs, modelName, []);
3673
+ return (0, import_utils14.get)(this.modelSubs, modelName, []);
2849
3674
  }
2850
3675
  getModelAtt(modelName) {
2851
3676
  this.ensureModelMeta(modelName);
2852
- return (0, import_utils13.get)(this.modelAtts, modelName, []);
3677
+ return (0, import_utils14.get)(this.modelAtts, modelName, []);
2853
3678
  }
2854
3679
  };
2855
3680
  var defaultRuntime = new AccessRuntime({ allowGlobalModelLookup: true });
@@ -2862,7 +3687,7 @@ var getGlobalOption = (key, defaultValue) => {
2862
3687
 
2863
3688
  // src/validation/common.ts
2864
3689
  var import_zod2 = require("zod");
2865
- var import_utils15 = require("@web-ts-toolkit/utils");
3690
+ var import_utils16 = require("@web-ts-toolkit/utils");
2866
3691
 
2867
3692
  // src/validation/public-admission-schema.ts
2868
3693
  var admissions = /* @__PURE__ */ new WeakMap();
@@ -2884,7 +3709,7 @@ function assertTransformedPublicAdmission(schema, value) {
2884
3709
  }
2885
3710
 
2886
3711
  // src/correlated-includes.ts
2887
- var import_utils14 = require("@web-ts-toolkit/utils");
3712
+ var import_utils15 = require("@web-ts-toolkit/utils");
2888
3713
  var PARENT_MARKER_KEY = "$parent";
2889
3714
  var ESCAPE_WRAPPER_KEY = "$escape";
2890
3715
  var SUBQUERY_PAYLOAD_KEYS = /* @__PURE__ */ new Set(["$$sq", "$$date"]);
@@ -2895,10 +3720,10 @@ var FIELD_SEGMENT_PATTERN = /^[A-Za-z_][A-Za-z0-9_$]*$/;
2895
3720
  var ARRAY_INDEX_SEGMENT_PATTERN = /^(0|[1-9]\d*)$/;
2896
3721
  var ownKeys = (value) => Object.keys(value);
2897
3722
  function isParentRefMarker(value) {
2898
- return (0, import_utils14.isPlainObject)(value) && ownKeys(value).length === 1 && ownKeys(value)[0] === PARENT_MARKER_KEY;
3723
+ return (0, import_utils15.isPlainObject)(value) && ownKeys(value).length === 1 && ownKeys(value)[0] === PARENT_MARKER_KEY;
2899
3724
  }
2900
3725
  function isEscapedParentRef(value) {
2901
- return (0, import_utils14.isPlainObject)(value) && ownKeys(value).length === 1 && ownKeys(value)[0] === ESCAPE_WRAPPER_KEY;
3726
+ return (0, import_utils15.isPlainObject)(value) && ownKeys(value).length === 1 && ownKeys(value)[0] === ESCAPE_WRAPPER_KEY;
2902
3727
  }
2903
3728
  function hasMarkerKey(value) {
2904
3729
  return ownKeys(value).includes(PARENT_MARKER_KEY) || ownKeys(value).includes(ESCAPE_WRAPPER_KEY);
@@ -2917,12 +3742,12 @@ function containsParentMarkerShape(value) {
2917
3742
  const seen = /* @__PURE__ */ new Set();
2918
3743
  const visit = (current) => {
2919
3744
  if (isParentRefMarker(current) || isEscapedParentRef(current)) return true;
2920
- if ((0, import_utils14.isArray)(current)) {
3745
+ if ((0, import_utils15.isArray)(current)) {
2921
3746
  if (seen.has(current)) return false;
2922
3747
  seen.add(current);
2923
3748
  return current.some(visit);
2924
3749
  }
2925
- if ((0, import_utils14.isPlainObject)(current)) {
3750
+ if ((0, import_utils15.isPlainObject)(current)) {
2926
3751
  if (seen.has(current)) return false;
2927
3752
  seen.add(current);
2928
3753
  if (hasMarkerKey(current)) return true;
@@ -2952,7 +3777,7 @@ function scanTemplateValueNode(value, path, issues) {
2952
3777
  }
2953
3778
  return;
2954
3779
  }
2955
- if ((0, import_utils14.isPlainObject)(value)) {
3780
+ if ((0, import_utils15.isPlainObject)(value)) {
2956
3781
  if (hasMarkerKey(value)) {
2957
3782
  issues.push({
2958
3783
  message: 'Malformed $parent reference: objects carrying $parent must be exactly { "$parent": "<field>" }',
@@ -2963,7 +3788,7 @@ function scanTemplateValueNode(value, path, issues) {
2963
3788
  scanTemplateObjectEntries(value, path, issues);
2964
3789
  return;
2965
3790
  }
2966
- if ((0, import_utils14.isArray)(value)) {
3791
+ if ((0, import_utils15.isArray)(value)) {
2967
3792
  value.forEach((item, index) => scanTemplateValueNode(item, [...path, index], issues));
2968
3793
  }
2969
3794
  }
@@ -3004,7 +3829,7 @@ function scanTemplateObjectEntries(obj, basePath, issues) {
3004
3829
  continue;
3005
3830
  }
3006
3831
  if (LOGICAL_CLAUSE_KEYS.has(key)) {
3007
- if (!(0, import_utils14.isArray)(child)) {
3832
+ if (!(0, import_utils15.isArray)(child)) {
3008
3833
  scanTemplateValueNode(child, childPath, issues);
3009
3834
  continue;
3010
3835
  }
@@ -3017,7 +3842,7 @@ function scanTemplateObjectEntries(obj, basePath, issues) {
3017
3842
  });
3018
3843
  return;
3019
3844
  }
3020
- if ((0, import_utils14.isPlainObject)(clause)) {
3845
+ if ((0, import_utils15.isPlainObject)(clause)) {
3021
3846
  scanTemplateObjectEntries(clause, clausePath, issues);
3022
3847
  }
3023
3848
  });
@@ -3028,7 +3853,7 @@ function scanTemplateObjectEntries(obj, basePath, issues) {
3028
3853
  }
3029
3854
  function validateCorrelatedFilterTemplate(filter) {
3030
3855
  const issues = [];
3031
- if (!(0, import_utils14.isPlainObject)(filter)) {
3856
+ if (!(0, import_utils15.isPlainObject)(filter)) {
3032
3857
  issues.push({ message: "Correlated include filter must be an object", path: [] });
3033
3858
  return issues;
3034
3859
  }
@@ -3156,7 +3981,7 @@ var correlatedFilterSchema = import_zod2.z.record(import_zod2.z.string(), import
3156
3981
  }
3157
3982
  });
3158
3983
  var correlatedEmptyOptionsSchema = import_zod2.z.unknown().refine(
3159
- (value) => value === void 0 || (0, import_utils15.isPlainObject)(value) && Object.keys(value).length === 0,
3984
+ (value) => value === void 0 || (0, import_utils16.isPlainObject)(value) && Object.keys(value).length === 0,
3160
3985
  "Correlated include options must be absent or empty"
3161
3986
  ).optional();
3162
3987
  var correlatedPathSchema = import_zod2.z.string().min(1).superRefine((path, ctx) => {
@@ -3193,7 +4018,7 @@ var correlatedListArgsSchema = import_zod2.z.object({
3193
4018
  include: import_zod2.z.lazy(() => correlatedNestedIncludeSchema).optional()
3194
4019
  }).strict().superRefine((args, ctx) => checkArgsMarkers(args.select, args.sort, ctx));
3195
4020
  var correlatedCountArgsSchema = import_zod2.z.unknown().refine(
3196
- (value) => value === void 0 || (0, import_utils15.isPlainObject)(value) && Object.keys(value).length === 0,
4021
+ (value) => value === void 0 || (0, import_utils16.isPlainObject)(value) && Object.keys(value).length === 0,
3197
4022
  "Count includes accept no args"
3198
4023
  ).optional();
3199
4024
  var correlatedReadByIdSchema = import_zod2.z.object({
@@ -3246,7 +4071,7 @@ var correlatedNestedIncludeSchema = import_zod2.z.union([includeItemSchema, impo
3246
4071
  var rejectDuplicateCorrelatedPaths = (items, ctx) => {
3247
4072
  const seen = /* @__PURE__ */ new Set();
3248
4073
  items.forEach((item, index) => {
3249
- if ((0, import_utils15.isPlainObject)(item) && item.mode === "correlated" && typeof item.path === "string") {
4074
+ if ((0, import_utils16.isPlainObject)(item) && item.mode === "correlated" && typeof item.path === "string") {
3250
4075
  if (seen.has(item.path)) {
3251
4076
  ctx.addIssue({
3252
4077
  code: import_zod2.z.ZodIssueCode.custom,