@web-ts-toolkit/access-router 0.64.0 → 0.65.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/index.js CHANGED
@@ -30,7 +30,33 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
30
30
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
31
31
 
32
32
  // src/acl/unsafe-snapshot-options.ts
33
- var unsafeSnapshotCheckOptions, unsafeInitialOutputCopyOptions, unsafeSnapshotOptions;
33
+ function authorizationFastPathPrerequisites(origin) {
34
+ const operation = origin === "read" ? "Read" : "List";
35
+ return [
36
+ `unsafeSkip${operation}DocumentSnapshotChecks`,
37
+ `unsafeSkip${operation}OutputSnapshotChecks`,
38
+ `unsafeSkip${operation}NestedDocumentSnapshotChecks`,
39
+ `unsafeSkip${operation}InitialOutputSnapshotCopy`
40
+ ];
41
+ }
42
+ function captureAuthorizationFastPath(options, origin) {
43
+ const literalTrue = (key2) => {
44
+ const descriptor = Object.getOwnPropertyDescriptor(options, key2);
45
+ return !!descriptor && "value" in descriptor && descriptor.value === true;
46
+ };
47
+ const key = origin === "read" ? unsafeAuthorizationFastPathOptions[1] : unsafeAuthorizationFastPathOptions[0];
48
+ const requested = literalTrue(key);
49
+ const prerequisites = authorizationFastPathPrerequisites(origin).reduce(
50
+ (mask, key2, index) => mask | (literalTrue(key2) ? 1 << index : 0),
51
+ 0
52
+ );
53
+ return Object.freeze({
54
+ origin,
55
+ mode: !requested ? "off" : prerequisites === 15 ? "active" : "dormant",
56
+ prerequisites
57
+ });
58
+ }
59
+ var unsafeSnapshotCheckOptions, unsafeInitialOutputCopyOptions, unsafeSnapshotOptions, unsafeAuthorizationFastPathOptions, unsafeServerOptions;
34
60
  var init_unsafe_snapshot_options = __esm({
35
61
  "src/acl/unsafe-snapshot-options.ts"() {
36
62
  unsafeSnapshotCheckOptions = [
@@ -46,46 +72,110 @@ var init_unsafe_snapshot_options = __esm({
46
72
  "unsafeSkipReadInitialOutputSnapshotCopy"
47
73
  ];
48
74
  unsafeSnapshotOptions = [...unsafeSnapshotCheckOptions, ...unsafeInitialOutputCopyOptions];
75
+ unsafeAuthorizationFastPathOptions = [
76
+ "unsafeUseListAuthorizationFastPath",
77
+ "unsafeUseReadAuthorizationFastPath"
78
+ ];
79
+ unsafeServerOptions = [...unsafeSnapshotOptions, ...unsafeAuthorizationFastPathOptions];
49
80
  }
50
81
  });
51
82
 
52
83
  // src/validation/public-admission.ts
53
84
  function assertPublicAdmission(input, kind = "envelope") {
54
- const pending = [{ value: input, kind, path: "request" }];
85
+ assertPublicControlAdmission(input, kind);
86
+ }
87
+ function assertPublicControlAdmission(input, kind) {
88
+ walkControlAdmission(
89
+ input,
90
+ kind,
91
+ (record3, path) => {
92
+ for (const key of privateControls) {
93
+ if (key in record3) {
94
+ throw new PublicAdmissionError(
95
+ 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`
96
+ );
97
+ }
98
+ }
99
+ },
100
+ (detail) => {
101
+ throw new PublicAdmissionError(detail);
102
+ }
103
+ );
104
+ }
105
+ function assertNoServerModelControls(input, reject, kind = "envelope") {
106
+ walkControlAdmission(
107
+ input,
108
+ kind,
109
+ (record3, path) => {
110
+ for (const key of unsafeServerOptions)
111
+ if (key in record3) reject(`${path}.${key} is server model configuration only`);
112
+ },
113
+ reject
114
+ );
115
+ }
116
+ function walkControlAdmission(input, kind, check, reject) {
117
+ const pending = [{ value: input, kind, path: "request", depth: 0 }];
55
118
  const seen = /* @__PURE__ */ new WeakMap();
119
+ let slots = 1;
56
120
  while (pending.length) {
57
- const { value, kind: slot, path } = pending.pop();
121
+ const { value, kind: slot, path, depth } = pending.pop();
58
122
  if (!value || typeof value !== "object" && typeof value !== "function") continue;
59
123
  const kinds = seen.get(value) ?? /* @__PURE__ */ new Set();
60
124
  if (kinds.has(slot)) continue;
61
125
  kinds.add(slot);
62
126
  seen.set(value, kinds);
63
127
  const add = (child, childKind, key) => {
64
- pending.push({ value: child, kind: childKind, path: `${path}.${key}` });
128
+ if (child === void 0 || child === null) return;
129
+ if (++slots > 2e4 || depth >= 100) reject("control admission exceeds structural limits");
130
+ pending.push({ value: child, kind: childKind, path: `${path}.${key}`, depth: depth + 1 });
65
131
  };
66
132
  const record3 = value;
67
- if (slot !== "data") {
68
- for (const key of privateControls) {
69
- if (key in record3) {
70
- throw new PublicAdmissionError(
71
- key.startsWith("unsafeSkip") ? `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`
72
- );
73
- }
133
+ if (slot !== "data" && slot !== "policies") check(record3, path);
134
+ const read = (key) => {
135
+ let owner = value;
136
+ for (let depth2 = 0; owner; depth2++, owner = Object.getPrototypeOf(owner)) {
137
+ if (depth2 > 100) reject("control admission prototype depth exceeded");
138
+ const descriptor = Object.getOwnPropertyDescriptor(owner, key);
139
+ if (!descriptor) continue;
140
+ if (!("value" in descriptor)) reject(`accessor control/data property: ${path}.${key}`);
141
+ return descriptor.value;
74
142
  }
75
- }
143
+ return void 0;
144
+ };
76
145
  if (Array.isArray(value)) {
77
- value.forEach((child, index) => add(child, slot, String(index)));
146
+ if (value.length > 2e4) reject("control admission array exceeds structural limits");
147
+ for (let index = 0; index < value.length; index++) {
148
+ if (index in value) add(read(String(index)), slot, String(index));
149
+ }
78
150
  continue;
79
151
  }
80
152
  if (slot === "data") {
81
153
  if (!(0, import_utils.isPlainObject)(value)) continue;
82
- for (const [key, child] of Object.entries(value)) add(child, key === "$$sq" ? "envelope" : "data", key);
154
+ add(read("$$sq"), "envelope", "$$sq");
155
+ for (const key of Object.keys(value)) if (key !== "$$sq") add(read(key), "data", key);
156
+ continue;
157
+ }
158
+ if (slot === "defaults") {
159
+ const keys2 = /* @__PURE__ */ new Set([...Object.keys(value), ...defaultControlBuckets]);
160
+ if (keys2.size > 2e4) reject("control admission defaults exceeds structural limits");
161
+ for (const key of keys2) if (key in record3) add(read(key), "envelope", key);
162
+ continue;
163
+ }
164
+ if (slot === "policies") {
165
+ for (const key of Object.keys(value)) add(read(key), "policy", key);
166
+ continue;
167
+ }
168
+ if (slot === "policy") {
169
+ for (const key of ["rows", "outputFields", "inputFields", "operation"]) add(read(key), "policy", key);
170
+ add(read("related"), "policies", "related");
171
+ add(read("filter"), "data", "filter");
83
172
  continue;
84
173
  }
85
- for (const key of ["args", "options", "sqOptions"]) add(record3[key], "envelope", key);
86
- add(record3.include, "include", "include");
87
- add(record3.populate, "populate", "populate");
88
- for (const key of ["filter", "match", "data"]) add(record3[key], "data", key);
174
+ for (const key of ["args", "options", "sqOptions"]) add(read(key), "envelope", key);
175
+ add(read("include"), "include", "include");
176
+ add(read("populate"), "populate", "populate");
177
+ add(read("authorization"), "policy", "authorization");
178
+ for (const key of ["filter", "match", "data"]) add(read(key), "data", key);
89
179
  }
90
180
  }
91
181
  function assertHydrationDefaults(defaults2) {
@@ -119,11 +209,8 @@ function assertHydrationDefaults(defaults2) {
119
209
  }
120
210
  }
121
211
  function assertPublicDefaults(defaults2) {
212
+ assertPublicControlAdmission(defaults2, "defaults");
122
213
  assertHydrationDefaults(defaults2);
123
- assertPublicAdmission(defaults2);
124
- if (defaults2 && typeof defaults2 === "object") {
125
- for (const value of Object.values(defaults2)) assertPublicAdmission(value);
126
- }
127
214
  }
128
215
  function pickPublicKeys(input, keys2) {
129
216
  const result2 = {};
@@ -148,7 +235,7 @@ function requestOnlyServiceOptions(options) {
148
235
  authorization: requestAuthorization
149
236
  };
150
237
  }
151
- var import_express_json_router, import_utils, privateControls, PublicAdmissionError, listArgs, readArgs, listOptions, readOptions, requestAuthorization;
238
+ var import_express_json_router, import_utils, privateControls, PublicAdmissionError, defaultControlBuckets, listArgs, readArgs, listOptions, readOptions, requestAuthorization;
152
239
  var init_public_admission = __esm({
153
240
  "src/validation/public-admission.ts"() {
154
241
  import_express_json_router = __toESM(require("@web-ts-toolkit/express-json-router"));
@@ -171,7 +258,7 @@ var init_public_admission = __esm({
171
258
  "skipParsing",
172
259
  "skipAuthorization",
173
260
  "alreadyAuthorized",
174
- ...unsafeSnapshotOptions,
261
+ ...unsafeServerOptions,
175
262
  "operation"
176
263
  ];
177
264
  PublicAdmissionError = class extends import_express_json_router.default.clientErrors.BadRequestError {
@@ -181,6 +268,31 @@ var init_public_admission = __esm({
181
268
  this.result = { success: false, kind: "error", code: "bad_request" /* BadRequest */, errors };
182
269
  }
183
270
  };
271
+ defaultControlBuckets = [
272
+ "findOneArgs",
273
+ "findOneOptions",
274
+ "findByIdArgs",
275
+ "findByIdOptions",
276
+ "findArgs",
277
+ "findOptions",
278
+ "createArgs",
279
+ "createOptions",
280
+ "updateOneArgs",
281
+ "updateOneOptions",
282
+ "upsertOptions",
283
+ "updateByIdArgs",
284
+ "upsertArgs",
285
+ "updateByIdOptions",
286
+ "existsOptions",
287
+ "publicListArgs",
288
+ "publicListOptions",
289
+ "publicCreateArgs",
290
+ "publicCreateOptions",
291
+ "publicReadArgs",
292
+ "publicReadOptions",
293
+ "publicUpdateArgs",
294
+ "publicUpdateOptions"
295
+ ];
184
296
  listArgs = ["select", "populate", "include", "sort", "skip", "limit", "page", "pageSize", "tasks"];
185
297
  readArgs = ["select", "populate", "include", "sort", "tasks"];
186
298
  listOptions = [
@@ -386,6 +498,9 @@ var init_concurrency = __esm({
386
498
  });
387
499
 
388
500
  // src/output/permissions-alias.ts
501
+ function isGeneratedPermissionsAliasSlot(output, key, slot) {
502
+ return key === "permissions" && aliases.has(output) && "value" in slot && !slot.enumerable;
503
+ }
389
504
  function attachPermissionsAlias(output, field) {
390
505
  if ("permissions" in output) return;
391
506
  const metadata = (0, import_utils3.get)(output, field);
@@ -2761,7 +2876,7 @@ var init_runtime = __esm({
2761
2876
  ([key, value]) => value !== void 0 || key === "operationAccess" || isPopulatePolicyKey(key)
2762
2877
  )
2763
2878
  );
2764
- for (const key of unsafeSnapshotOptions) if (key in result2) result2[key] = result2[key] === true;
2879
+ for (const key of unsafeServerOptions) if (key in result2) result2[key] = result2[key] === true;
2765
2880
  return cloneOptionsSnapshot(result2);
2766
2881
  };
2767
2882
  defaultDataOptions = {
@@ -3122,7 +3237,9 @@ var init_runtime = __esm({
3122
3237
  unsafeSkipListNestedDocumentSnapshotChecks: false,
3123
3238
  unsafeSkipReadNestedDocumentSnapshotChecks: false,
3124
3239
  unsafeSkipListInitialOutputSnapshotCopy: false,
3125
- unsafeSkipReadInitialOutputSnapshotCopy: false
3240
+ unsafeSkipReadInitialOutputSnapshotCopy: false,
3241
+ unsafeUseListAuthorizationFastPath: false,
3242
+ unsafeUseReadAuthorizationFastPath: false
3126
3243
  }).build();
3127
3244
  this.modelOptions = {};
3128
3245
  this.modelOptionOverrides = {};
@@ -3310,6 +3427,12 @@ var init_runtime = __esm({
3310
3427
  }
3311
3428
  setDefaultModelOption(key, value) {
3312
3429
  const keyStr = String(key);
3430
+ if (keyStr === "defaults") assertPublicDefaults(value);
3431
+ else if (keyStr.startsWith("defaults.")) {
3432
+ const proposed = {};
3433
+ (0, import_utils17.set)(proposed, keyStr.slice("defaults.".length), value);
3434
+ assertPublicDefaults(proposed);
3435
+ }
3313
3436
  const draft = new OptionsManager(
3314
3437
  this.getDefaultModelOptions()
3315
3438
  ).build();
@@ -3334,7 +3457,7 @@ var init_runtime = __esm({
3334
3457
  for (const key of populatePolicyKeys) delete inherited[key];
3335
3458
  const effective = { ...defaultModelOptions, ...inherited, ...overrides, modelName };
3336
3459
  effective.basePath = normalizeBasePath(modelName, effective.basePath);
3337
- for (const key of unsafeSnapshotOptions) effective[key] = effective[key] === true;
3460
+ for (const key of unsafeServerOptions) effective[key] = effective[key] === true;
3338
3461
  refreshPermissionMetadata(effective);
3339
3462
  return cloneOptionsSnapshot(effective);
3340
3463
  }
@@ -3349,7 +3472,7 @@ var init_runtime = __esm({
3349
3472
  }
3350
3473
  publishDefaultModelOptions(options) {
3351
3474
  const next = { ...options };
3352
- for (const key of unsafeSnapshotOptions) if (key in next) next[key] = next[key] === true;
3475
+ for (const key of unsafeServerOptions) if (key in next) next[key] = next[key] === true;
3353
3476
  const defaults2 = cloneOptionsSnapshot(next);
3354
3477
  const models = new Map(
3355
3478
  Object.keys(this.modelOptions).map((name) => [name, this.resolveModelOptions(name, void 0, defaults2)])
@@ -3379,6 +3502,7 @@ var init_runtime = __esm({
3379
3502
  deferSnapshotWarnings(publish) {
3380
3503
  if (this.pendingSnapshotWarnings) return publish();
3381
3504
  const copyModes = this.initialOutputCopyModes();
3505
+ const fastModes = this.authorizationFastPathModes();
3382
3506
  const pending = [];
3383
3507
  this.pendingSnapshotWarnings = pending;
3384
3508
  let result2;
@@ -3388,6 +3512,7 @@ var init_runtime = __esm({
3388
3512
  this.pendingSnapshotWarnings = void 0;
3389
3513
  }
3390
3514
  const nextCopyModes = this.initialOutputCopyModes();
3515
+ const nextFastModes = this.authorizationFastPathModes();
3391
3516
  for (const { modelName, key } of pending) this.warnSnapshotFlag(modelName, key);
3392
3517
  for (const [modelName, modes] of nextCopyModes) {
3393
3518
  for (const operation of ["List", "Read"]) {
@@ -3404,8 +3529,38 @@ var init_runtime = __esm({
3404
3529
  }
3405
3530
  }
3406
3531
  }
3532
+ for (const [modelName, modes] of nextFastModes) {
3533
+ for (const origin of ["list", "read"]) {
3534
+ const captured = modes[origin];
3535
+ const previous = fastModes.get(modelName)?.[origin];
3536
+ if (captured.mode === "off" || captured.mode === previous?.mode && (captured.mode !== "dormant" || captured.prerequisites === previous.prerequisites))
3537
+ continue;
3538
+ const key = origin === "read" ? "unsafeUseReadAuthorizationFastPath" : "unsafeUseListAuthorizationFastPath";
3539
+ const missing = authorizationFastPathPrerequisites(origin).filter(
3540
+ (_, index) => !(captured.prerequisites & 1 << index)
3541
+ );
3542
+ try {
3543
+ this.getGlobalOption("logger")?.warn?.(
3544
+ 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.`,
3545
+ { modelName }
3546
+ );
3547
+ } catch {
3548
+ }
3549
+ }
3550
+ }
3407
3551
  return result2;
3408
3552
  }
3553
+ authorizationFastPathModes() {
3554
+ return new Map(
3555
+ Object.entries(this.modelOptions).map(([modelName, manager]) => {
3556
+ const options = manager.fetch();
3557
+ return [
3558
+ modelName,
3559
+ { list: captureAuthorizationFastPath(options, "list"), read: captureAuthorizationFastPath(options, "read") }
3560
+ ];
3561
+ })
3562
+ );
3563
+ }
3409
3564
  initialOutputCopyModes() {
3410
3565
  return new Map(
3411
3566
  Object.entries(this.modelOptions).map(([modelName, options]) => {
@@ -3859,6 +4014,23 @@ var init_permission = __esm({
3859
4014
  }
3860
4015
  });
3861
4016
 
4017
+ // src/acl/captured-authorization-configuration.ts
4018
+ function captureAuthorizationConfiguration(value) {
4019
+ const capture = copyAuthorizationValue(value, true);
4020
+ captures.add(capture);
4021
+ return capture;
4022
+ }
4023
+ function ownedAuthorizationConfiguration(value) {
4024
+ return captures.has(value) ? value : captureAuthorizationConfiguration(value);
4025
+ }
4026
+ var captures;
4027
+ var init_captured_authorization_configuration = __esm({
4028
+ "src/acl/captured-authorization-configuration.ts"() {
4029
+ init_authorization_snapshot();
4030
+ captures = /* @__PURE__ */ new WeakSet();
4031
+ }
4032
+ });
4033
+
3862
4034
  // src/acl/service-authorization.ts
3863
4035
  function serviceAuthorizationInput(policy, targets) {
3864
4036
  const related = {};
@@ -3873,6 +4045,24 @@ function serviceAuthorizationInput(policy, targets) {
3873
4045
  }
3874
4046
  return { rows: policy.rows, outputFields: policy.outputFields, related };
3875
4047
  }
4048
+ function captureTrustedRelatedTargets(targets) {
4049
+ let slots = 0;
4050
+ const capture = (entries, depth) => {
4051
+ if (depth > 100 || (slots += entries.length) > 2e4)
4052
+ authorizationError("related capture exceeds structural limits");
4053
+ return Object.freeze(
4054
+ entries.map((entry) => {
4055
+ const { configuration, relatedTargets, ...rest } = entry;
4056
+ return Object.freeze({
4057
+ ...copyAuthorizationValue(rest, true),
4058
+ configuration: ownedAuthorizationConfiguration(configuration),
4059
+ relatedTargets: relatedTargets ? capture(relatedTargets, depth + 1) : void 0
4060
+ });
4061
+ })
4062
+ );
4063
+ };
4064
+ return capture(targets, 0);
4065
+ }
3876
4066
  function hasStableConfigurationCopies(value) {
3877
4067
  if (value === null || typeof value !== "object") return true;
3878
4068
  if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype) return false;
@@ -3941,6 +4131,8 @@ function assertCatalogPath(path, configuration) {
3941
4131
  }
3942
4132
  }
3943
4133
  function assertAuthorizationKeys(value, keys2, label) {
4134
+ for (const key of unsafeServerOptions)
4135
+ if (key in value) authorizationError(`${label}.${key} is server model configuration only`);
3944
4136
  for (const key of Object.keys(value)) if (!keys2.includes(key)) authorizationError(`unsupported ${label} key: ${key}`);
3945
4137
  }
3946
4138
  function normalizeRows(value) {
@@ -4059,7 +4251,7 @@ function nestedQueryResponse(input, access) {
4059
4251
  }
4060
4252
  if (edge.kind === "related") {
4061
4253
  const target = parent.relatedTargets.find((target2) => target2.path === edge.path);
4062
- return !!target && target.kind !== "count" && target.modelName === input.binding.modelName && scope(input.binding).length === 0;
4254
+ return !!target && target.kind !== "count" && target.modelName === input.binding.modelName && (target.model === void 0 || target.model === input.binding.model) && scope(input.binding).length === 0;
4063
4255
  }
4064
4256
  if (edge.kind !== "embedded") return false;
4065
4257
  assertAuthorizationBinding(input.parent, { ...input.binding, scopePath: parent.binding.scopePath });
@@ -4068,10 +4260,74 @@ function nestedQueryResponse(input, access) {
4068
4260
  (key) => access[key] === parent.output.access[key]
4069
4261
  );
4070
4262
  }
4263
+ function deriveTrustedQueryAuthorization(input) {
4264
+ if (!input.parent || !input.snapshotDerivation) return;
4265
+ const access = captureAuthorizationAccess(input.access);
4266
+ const parent = callRecord(input.parent);
4267
+ const retry = input.snapshotDerivation.kind === "retry" && parent.readResponse && access.operation === "read" && (input.applicability ?? "service") === "service" && queryOutputAccess(access);
4268
+ if (retry) {
4269
+ assertAuthorizationBinding(input.parent, input.snapshotDerivation.parentBinding);
4270
+ assertAuthorizationBinding(input.parent, input.binding);
4271
+ } else if (!nestedQueryResponse(input, access)) return;
4272
+ if (parent.authorizationFastPath?.mode !== "active") return;
4273
+ if (parent.binding.request !== input.binding.request || parent.binding.runtime !== input.binding.runtime) {
4274
+ authorizationError("derived call request/runtime mismatch");
4275
+ }
4276
+ const edge = input.snapshotDerivation;
4277
+ const target = edge.kind === "related" ? parent.relatedTargets.find((entry) => entry.path === edge.path) : void 0;
4278
+ const scopePath = Array.from(scope(input.binding));
4279
+ for (const part of scopePath) {
4280
+ assertAuthorizationPath(part);
4281
+ if (part.includes(".")) authorizationError("scopePath requires response segments");
4282
+ }
4283
+ if (edge.kind === "embedded" && !isCatalogOutputPath(parent.output.catalog, scopePath.join(".")))
4284
+ authorizationError("unknown output scope");
4285
+ const configuration = target?.configuration ?? parent.configuration;
4286
+ const relatedTargets = target?.relatedTargets ?? (target ? [] : parent.relatedTargets);
4287
+ const policy = target ? parent.policy.related[target.path] ?? Object.freeze({
4288
+ rows: Object.freeze({ mode: "request" }),
4289
+ outputFields: Object.freeze({ mode: "request" }),
4290
+ inputFields: Object.freeze({ mode: "request" }),
4291
+ related: Object.freeze({})
4292
+ }) : parent.policy;
4293
+ const catalog = target ? captureAuthorizationCatalog(configuration.catalog) : parent.output.catalog;
4294
+ const call = Object.freeze(/* @__PURE__ */ Object.create(null));
4295
+ calls.set(call, {
4296
+ binding: Object.freeze({ ...input.binding, scopePath: Object.freeze(scopePath) }),
4297
+ access,
4298
+ configuration,
4299
+ policy,
4300
+ relatedTargets,
4301
+ output: Object.freeze({ access, catalog, outputFields: policy.outputFields }),
4302
+ permissions: parent.permissions,
4303
+ provenance: parent.provenance,
4304
+ readResponse: edge.kind === "retry" && parent.readResponse,
4305
+ nestedResponse: true,
4306
+ responseSnapshots: parent.responseSnapshots,
4307
+ authorizationFastPath: parent.authorizationFastPath,
4308
+ fieldPolicyOwner: target ? call : parent.fieldPolicyOwner ?? input.parent,
4309
+ trustedView: void 0,
4310
+ reusableFieldConfiguration: void 0,
4311
+ validateDocumentSnapshots: false,
4312
+ validateOutputSnapshots: false,
4313
+ skipInitialOutputSnapshotCopy: true
4314
+ });
4315
+ return call;
4316
+ }
4071
4317
  function resolveServiceAuthorization(input) {
4318
+ assertNoServerModelControls(input.authorization, authorizationError, "policy");
4319
+ const derived = deriveTrustedQueryAuthorization(input);
4320
+ if (derived) return derived;
4321
+ const fastPaths = {
4322
+ list: captureAuthorizationFastPath(input.configuration, "list"),
4323
+ read: captureAuthorizationFastPath(input.configuration, "read")
4324
+ };
4325
+ const candidateAccess = captureAuthorizationAccess(input.access);
4326
+ const rootQuery = !input.parent && (input.applicability ?? "service") === "service" && !scope(input.binding).length;
4327
+ const trustedCapture = rootQuery && (input.listResponse === true && candidateAccess.operation === "list" && queryOutputAccess(candidateAccess) && fastPaths.list.mode === "active" || input.readResponse === true && candidateAccess.operation === "read" && queryOutputAccess(candidateAccess) && fastPaths.read.mode === "active");
4072
4328
  const raw = copyAuthorizationValue(input.authorization);
4073
- const configuration = copyAuthorizationValue(input.configuration, true);
4074
- const targets = copyAuthorizationValue(input.relatedTargets ?? [], true);
4329
+ const configuration = trustedCapture ? ownedAuthorizationConfiguration(input.configuration) : copyAuthorizationValue(input.configuration, true);
4330
+ const targets = trustedCapture ? captureTrustedRelatedTargets(input.relatedTargets ?? []) : copyAuthorizationValue(input.relatedTargets ?? [], true);
4075
4331
  const access = copyAuthorizationValue(input.access);
4076
4332
  const outputAccess = captureAuthorizationAccess(access);
4077
4333
  const catalog = captureAuthorizationCatalog(configuration.catalog);
@@ -4106,6 +4362,7 @@ function resolveServiceAuthorization(input) {
4106
4362
  skipNested: configuration.unsafeSkipReadNestedDocumentSnapshotChecks === true,
4107
4363
  skipInitialOutputCopy: configuration.unsafeSkipReadOutputSnapshotChecks === true && configuration.unsafeSkipReadInitialOutputSnapshotCopy === true
4108
4364
  }) : void 0;
4365
+ const authorizationFastPath = input.parent ? nestedResponse || readResponse && input.snapshotDerivation?.kind === "retry" ? callRecord(input.parent).authorizationFastPath : void 0 : listResponse ? fastPaths.list : readResponse ? fastPaths.read : void 0;
4109
4366
  const call = Object.freeze(/* @__PURE__ */ Object.create(null));
4110
4367
  calls.set(call, {
4111
4368
  binding: Object.freeze({ ...input.binding, scopePath: Object.freeze(scopePath) }),
@@ -4120,6 +4377,10 @@ function resolveServiceAuthorization(input) {
4120
4377
  readResponse,
4121
4378
  nestedResponse,
4122
4379
  responseSnapshots,
4380
+ authorizationFastPath,
4381
+ fieldPolicyOwner: void 0,
4382
+ trustedView: void 0,
4383
+ reusableFieldConfiguration: void 0,
4123
4384
  validateOutputSnapshots: responseSnapshots?.skipOutput !== true,
4124
4385
  skipInitialOutputSnapshotCopy: responseSnapshots?.skipInitialOutputCopy === true,
4125
4386
  validateDocumentSnapshots: !(input.listResponse === true && input.parent === void 0 && (input.applicability ?? "service") === "service" && outputAccess.operation === "list" && outputAccess.rowAccess === "list" && outputAccess.outputAccess === "list" && scopePath.length === 0 && configuration.unsafeSkipListDocumentSnapshotChecks === true || readResponse && configuration.unsafeSkipReadDocumentSnapshotChecks === true || nestedResponse && responseSnapshots?.skipNested === true)
@@ -4129,6 +4390,7 @@ function resolveServiceAuthorization(input) {
4129
4390
  function readServiceAuthorization(call, binding) {
4130
4391
  assertAuthorizationBinding(call, binding);
4131
4392
  const record3 = callRecord(call);
4393
+ if (record3.authorizationFastPath?.mode === "active") return readTrustedServiceAuthorization(call, binding);
4132
4394
  return copyAuthorizationValue(
4133
4395
  {
4134
4396
  authorization: record3.policy,
@@ -4139,6 +4401,27 @@ function readServiceAuthorization(call, binding) {
4139
4401
  true
4140
4402
  );
4141
4403
  }
4404
+ function readTrustedServiceAuthorization(call, binding) {
4405
+ assertAuthorizationBinding(call, binding);
4406
+ const record3 = callRecord(call);
4407
+ if (record3.authorizationFastPath?.mode !== "active") return;
4408
+ if (!record3.trustedView) {
4409
+ record3.trustedView = Object.freeze({
4410
+ authorization: record3.policy,
4411
+ configuration: record3.configuration,
4412
+ access: record3.access,
4413
+ relatedTargets: record3.relatedTargets
4414
+ });
4415
+ trustedViews.add(record3.trustedView);
4416
+ }
4417
+ if (!trustedViews.has(record3.trustedView)) authorizationError("invalid trusted configuration view");
4418
+ return record3.trustedView;
4419
+ }
4420
+ function serviceOutputFieldPolicyOwner(call, binding) {
4421
+ const record3 = callRecord(call);
4422
+ if (record3.authorizationFastPath?.mode === "active") assertAuthorizationBinding(call, binding);
4423
+ return record3.fieldPolicyOwner ?? call;
4424
+ }
4142
4425
  function readServiceAuthorizationAccess(call, binding) {
4143
4426
  assertAuthorizationBinding(call, binding);
4144
4427
  return callRecord(call).output.access;
@@ -4147,6 +4430,10 @@ function requiresDocumentSnapshotChecks(call, binding) {
4147
4430
  assertAuthorizationBinding(call, binding);
4148
4431
  return callRecord(call).validateDocumentSnapshots;
4149
4432
  }
4433
+ function readAuthorizationFastPath(call, binding) {
4434
+ assertAuthorizationBinding(call, binding);
4435
+ return callRecord(call).authorizationFastPath;
4436
+ }
4150
4437
  function requiresOutputSnapshotChecks(call, binding) {
4151
4438
  assertAuthorizationBinding(call, binding);
4152
4439
  return callRecord(call).validateOutputSnapshots;
@@ -4157,7 +4444,10 @@ function skipsInitialOutputSnapshotCopy(call) {
4157
4444
  }
4158
4445
  function readServiceAuthorizationHydration(call, binding) {
4159
4446
  assertAuthorizationBinding(call, binding);
4160
- return copyAuthorizationValue({ hydration: callRecord(call).configuration.hydration }, true);
4447
+ const record3 = callRecord(call);
4448
+ if (record3.authorizationFastPath?.mode === "active")
4449
+ return Object.freeze({ hydration: record3.configuration.hydration });
4450
+ return copyAuthorizationValue({ hydration: record3.configuration.hydration }, true);
4161
4451
  }
4162
4452
  function outputMetadata(configuration) {
4163
4453
  return {
@@ -4169,11 +4459,18 @@ function outputMetadata(configuration) {
4169
4459
  }
4170
4460
  function readServiceOutputMetadata(call, binding) {
4171
4461
  assertAuthorizationBinding(call, binding);
4172
- return copyAuthorizationValue(outputMetadata(callRecord(call).configuration), true);
4462
+ const record3 = callRecord(call);
4463
+ if (record3.authorizationFastPath?.mode === "active") return Object.freeze(outputMetadata(record3.configuration));
4464
+ return copyAuthorizationValue(outputMetadata(record3.configuration), true);
4173
4465
  }
4174
4466
  function readServiceDocumentPermissions(call, binding) {
4175
4467
  assertAuthorizationBinding(call, binding);
4176
4468
  const record3 = callRecord(call);
4469
+ if (record3.authorizationFastPath?.mode === "active")
4470
+ return Object.freeze({
4471
+ catalog: record3.output.catalog,
4472
+ docPermissions: record3.configuration.docPermissions
4473
+ });
4177
4474
  return Object.freeze({
4178
4475
  catalog: record3.output.catalog,
4179
4476
  ...copyAuthorizationValue({ docPermissions: record3.configuration.docPermissions }, true)
@@ -4182,6 +4479,13 @@ function readServiceDocumentPermissions(call, binding) {
4182
4479
  function readServiceFinalizerConfiguration(call, binding) {
4183
4480
  assertAuthorizationBinding(call, binding);
4184
4481
  const record3 = callRecord(call);
4482
+ if (record3.authorizationFastPath?.mode === "active")
4483
+ return Object.freeze({
4484
+ catalog: record3.output.catalog,
4485
+ ...outputMetadata(record3.configuration),
4486
+ virtuals: record3.configuration.virtuals,
4487
+ docPermissions: record3.configuration.docPermissions
4488
+ });
4185
4489
  return Object.freeze({
4186
4490
  catalog: record3.output.catalog,
4187
4491
  ...copyAuthorizationValue(
@@ -4201,6 +4505,15 @@ function readServiceOutputPolicy(call, binding) {
4201
4505
  function readServiceOutputFieldAuthorization(call, binding) {
4202
4506
  assertAuthorizationBinding(call, binding);
4203
4507
  const record3 = callRecord(call);
4508
+ if (record3.authorizationFastPath?.mode === "active")
4509
+ return Object.freeze({
4510
+ access: record3.output.access,
4511
+ catalog: record3.output.catalog,
4512
+ outputFields: record3.output.outputFields,
4513
+ reusable: true,
4514
+ permissionSchema: record3.configuration.permissionSchema,
4515
+ modelPermissionPrefix: record3.configuration.modelPermissionPrefix
4516
+ });
4204
4517
  const reusable = reusableOutputFieldConfiguration(record3);
4205
4518
  return Object.freeze({
4206
4519
  access: record3.output.access,
@@ -4224,7 +4537,7 @@ function reusableOutputFieldConfiguration(record3) {
4224
4537
  function canPrepareStaticOutputPolicy(call, binding) {
4225
4538
  assertAuthorizationBinding(call, binding);
4226
4539
  const record3 = callRecord(call);
4227
- return reusableOutputFieldConfiguration(record3) && typeof (record3.configuration.modelPermissionPrefix ?? "") === "string";
4540
+ return (record3.authorizationFastPath?.mode === "active" || reusableOutputFieldConfiguration(record3)) && typeof (record3.configuration.modelPermissionPrefix ?? "") === "string";
4228
4541
  }
4229
4542
  function getAuthorizationPermissions(call, binding) {
4230
4543
  assertAuthorizationBinding(call, binding);
@@ -4233,14 +4546,18 @@ function getAuthorizationPermissions(call, binding) {
4233
4546
  function getAuthorizationProvenance(call) {
4234
4547
  return callRecord(call).provenance;
4235
4548
  }
4236
- var calls;
4549
+ var calls, trustedViews;
4237
4550
  var init_service_authorization = __esm({
4238
4551
  "src/acl/service-authorization.ts"() {
4239
4552
  init_permission();
4240
4553
  init_field_catalog();
4241
4554
  init_authorization_snapshot();
4555
+ init_public_admission();
4556
+ init_captured_authorization_configuration();
4557
+ init_unsafe_snapshot_options();
4242
4558
  init_authorization_snapshot();
4243
4559
  calls = /* @__PURE__ */ new WeakMap();
4560
+ trustedViews = /* @__PURE__ */ new WeakSet();
4244
4561
  }
4245
4562
  });
4246
4563
 
@@ -4294,7 +4611,32 @@ function classifyEffectiveFieldAuthorization(args) {
4294
4611
  return combineFieldAuthorizationStates(states2);
4295
4612
  }
4296
4613
  async function evaluateScopedAccessRule(args) {
4297
- const { req, rule, globalPermissions, docPermissions, modelPermissionPrefix } = args;
4614
+ if (typeof args.rule !== "function") return evaluateNonFunctionAccessRule(args);
4615
+ try {
4616
+ return Boolean(await args.rule.call(args.req, args.globalPermissions, args.docPermissions));
4617
+ } catch {
4618
+ return false;
4619
+ }
4620
+ }
4621
+ function evaluateScopedAccessRuleValue(args) {
4622
+ if (typeof args.rule !== "function") return evaluateNonFunctionAccessRule(args);
4623
+ try {
4624
+ const value = args.rule.call(args.req, args.globalPermissions, args.docPermissions);
4625
+ if (value && typeof value.then === "function")
4626
+ return (async () => {
4627
+ try {
4628
+ return Boolean(await value);
4629
+ } catch {
4630
+ return false;
4631
+ }
4632
+ })();
4633
+ return Boolean(value);
4634
+ } catch {
4635
+ return false;
4636
+ }
4637
+ }
4638
+ function evaluateNonFunctionAccessRule(args) {
4639
+ const { rule, globalPermissions, docPermissions, modelPermissionPrefix } = args;
4298
4640
  if (typeof rule === "boolean") return rule;
4299
4641
  const validator = createValidator((key) => {
4300
4642
  try {
@@ -4309,13 +4651,6 @@ async function evaluateScopedAccessRule(args) {
4309
4651
  });
4310
4652
  if (typeof rule === "string") return validator.stringHandler(rule);
4311
4653
  if (Array.isArray(rule)) return validator.arrayHandler(rule);
4312
- if (typeof rule === "function") {
4313
- try {
4314
- return Boolean(await rule.call(req, globalPermissions, docPermissions));
4315
- } catch {
4316
- return false;
4317
- }
4318
- }
4319
4654
  return false;
4320
4655
  }
4321
4656
  async function evaluateEffectiveFieldAuthorization(args) {
@@ -4659,7 +4994,8 @@ function planAuthorizedModelProjection(args) {
4659
4994
  internalFetch: args.internalFetch,
4660
4995
  globalPermissions: getAuthorizationPermissions(args.authorization, args.binding)
4661
4996
  },
4662
- authorization.outputFields
4997
+ authorization.outputFields,
4998
+ readAuthorizationFastPath(args.authorization, args.binding)?.mode === "active"
4663
4999
  );
4664
5000
  plan.authorization = args.authorization;
4665
5001
  plan.authorizationBinding = Object.freeze({ ...args.binding, scopePath: Object.freeze(scope2) });
@@ -4672,7 +5008,7 @@ function planAuthorizedModelProjection(args) {
4672
5008
  });
4673
5009
  return plan;
4674
5010
  }
4675
- function planCatalogProjection(args, outputFields = { mode: "request" }) {
5011
+ function planCatalogProjection(args, outputFields = { mode: "request" }, safeDefinitions = false) {
4676
5012
  const { snapshot, outputAccess, virtualAccess, docPermissionsAccess, receivingModelName } = args;
4677
5013
  const catalog = snapshot.catalog;
4678
5014
  const scope2 = (args.scopePath ?? []).filter((part) => part !== "sub");
@@ -4727,7 +5063,9 @@ function planCatalogProjection(args, outputFields = { mode: "request" }) {
4727
5063
  globalPermissions,
4728
5064
  modelPermissionPrefix: snapshot.modelPermissionPrefix
4729
5065
  });
4730
- states2[relative] = state;
5066
+ if (safeDefinitions)
5067
+ Object.defineProperty(states2, relative, { value: state, enumerable: true, configurable: true, writable: true });
5068
+ else states2[relative] = state;
4731
5069
  if (state === "denied" || relative === "_id") continue;
4732
5070
  if (virtual(path)) virtualLeaves.push(relative);
4733
5071
  else persisted.push(relative);
@@ -4777,7 +5115,7 @@ function planCatalogProjection(args, outputFields = { mode: "request" }) {
4777
5115
  const childIncludes = includes.filter((p) => p.startsWith(`${name}.`)).map((p) => p.slice(name.length + 1));
4778
5116
  const childExcludes = excludes.filter((p) => p.startsWith(`${name}.`)).map((p) => `-${p.slice(name.length + 1)}`);
4779
5117
  const childSelect = mode === "include" && !includes.includes(name) ? [...childIncludes, ...childExcludes] : childExcludes;
4780
- children[name] = planCatalogProjection(
5118
+ const child = planCatalogProjection(
4781
5119
  {
4782
5120
  ...args,
4783
5121
  scopePath: [...args.scopePath ?? [], name, "sub"],
@@ -4786,8 +5124,12 @@ function planCatalogProjection(args, outputFields = { mode: "request" }) {
4786
5124
  related: [],
4787
5125
  internalFetch: { baseFields: [] }
4788
5126
  },
4789
- outputFields
5127
+ outputFields,
5128
+ safeDefinitions
4790
5129
  );
5130
+ if (safeDefinitions)
5131
+ Object.defineProperty(children, name, { value: child, enumerable: true, configurable: true, writable: true });
5132
+ else children[name] = child;
4791
5133
  }
4792
5134
  const internal = args.internalFetch ?? {};
4793
5135
  const fetchIdRetained = scope2.length === 0 || catalog.paths.includes(full("_id")) || !!catalog.dynamicPaths?.some((p) => p.endsWith("._id") && matchesCatalogPattern(p, full("_id")));
@@ -4886,7 +5228,8 @@ var init_output_projection = __esm({
4886
5228
  // src/acl/output-field-policy.ts
4887
5229
  function callFieldPolicy(authorization, binding) {
4888
5230
  assertAuthorizationBinding(authorization, binding);
4889
- let policy = fieldPolicies.get(authorization);
5231
+ const owner = serviceOutputFieldPolicyOwner(authorization, binding);
5232
+ let policy = fieldPolicies.get(owner);
4890
5233
  if (!policy) {
4891
5234
  const view = readServiceOutputFieldAuthorization(authorization, binding);
4892
5235
  policy = {
@@ -4898,7 +5241,7 @@ function callFieldPolicy(authorization, binding) {
4898
5241
  reusable: view.reusable,
4899
5242
  accesses: /* @__PURE__ */ new Map()
4900
5243
  };
4901
- if (view.reusable) fieldPolicies.set(authorization, policy);
5244
+ if (view.reusable) fieldPolicies.set(owner, policy);
4902
5245
  }
4903
5246
  return policy;
4904
5247
  }
@@ -5014,6 +5357,466 @@ var init_output_field_policy = __esm({
5014
5357
  }
5015
5358
  });
5016
5359
 
5360
+ // src/acl/trusted-output-materialization.ts
5361
+ function isBorrowableAuthorizationRecord(value) {
5362
+ if (!value || typeof value !== "object" || import_node_util7.types.isProxy(value)) return false;
5363
+ const prototype = Object.getPrototypeOf(value);
5364
+ if (prototype !== Object.prototype && prototype !== null) return false;
5365
+ const keys2 = Reflect.ownKeys(value);
5366
+ if (keys2.length > 2e4) return false;
5367
+ for (const key of keys2) {
5368
+ if (typeof key !== "string" || unsafeKeys2.has(key)) return false;
5369
+ const slot = Object.getOwnPropertyDescriptor(value, key);
5370
+ if (!("value" in slot) || !slot.enumerable && !isGeneratedPermissionsAliasSlot(value, key, slot)) return false;
5371
+ }
5372
+ return true;
5373
+ }
5374
+ function prepareTrustedAuthorizationSource(input) {
5375
+ if (input && typeof input === "object" && !import_node_util7.types.isProxy(input) && input instanceof import_mongoose5.Document) {
5376
+ let raw;
5377
+ try {
5378
+ raw = input.toObject({ virtuals: false, flattenMaps: true });
5379
+ } catch {
5380
+ raw = input._doc;
5381
+ return { kind: "copied", source: deepIsolateValue(raw, /* @__PURE__ */ new WeakMap(), true) };
5382
+ }
5383
+ return isBorrowableAuthorizationRecord(raw) ? { kind: "trusted", source: raw } : { kind: "copied", source: deepIsolateValue(raw, /* @__PURE__ */ new WeakMap(), true) };
5384
+ }
5385
+ return isBorrowableAuthorizationRecord(input) ? { kind: "trusted", source: input } : { kind: "copied", source: isolateDocForOutput(input) };
5386
+ }
5387
+ function createTrustedOutputBudget() {
5388
+ const budget = Object.freeze(/* @__PURE__ */ Object.create(null));
5389
+ budgets.set(budget, { slots: 0, failed: false });
5390
+ return budget;
5391
+ }
5392
+ function visitTrustedOutput(budget, depth, slots = 1) {
5393
+ const record3 = budgets.get(budget);
5394
+ if (!record3) authorizationError("invalid selected output budget");
5395
+ if (record3.failed || depth > 100 || (record3.slots += slots) > 2e4) {
5396
+ record3.failed = true;
5397
+ authorizationError("selected output exceeds structural limits");
5398
+ }
5399
+ }
5400
+ function defineTrustedOutputValue(output, key, value) {
5401
+ Object.defineProperty(output, key, { value, enumerable: true, configurable: true, writable: true });
5402
+ }
5403
+ function shallowTrustedOutputArray(input, budget, depth) {
5404
+ if (import_node_util7.types.isProxy(input)) authorizationError("unsupported selected proxy");
5405
+ const length = Object.getOwnPropertyDescriptor(input, "length").value;
5406
+ visitTrustedOutput(budget, depth, length + 1);
5407
+ for (const key of Reflect.ownKeys(input)) {
5408
+ if (key === "length") continue;
5409
+ if (typeof key !== "string" || !/^(0|[1-9]\d*)$/.test(key)) authorizationError("invalid selected array property");
5410
+ const slot = Object.getOwnPropertyDescriptor(input, key);
5411
+ if (!("value" in slot) || !slot.enumerable) authorizationError("accessor/non-enumerable selected value");
5412
+ }
5413
+ const output = [];
5414
+ for (let index = 0; index < length; index++) {
5415
+ const slot = Object.getOwnPropertyDescriptor(input, String(index));
5416
+ defineTrustedOutputValue(output, String(index), slot && "value" in slot ? slot.value : void 0);
5417
+ }
5418
+ return output;
5419
+ }
5420
+ function trustedMapOutputScope(value, fields, budget, depth) {
5421
+ if (!value || typeof value !== "object" || import_node_util7.types.isProxy(value) || !import_node_util7.types.isMap(value)) return value;
5422
+ const output = {};
5423
+ visitTrustedOutput(budget, depth);
5424
+ for (const key of fields) {
5425
+ visitTrustedOutput(budget, depth + 1);
5426
+ if (unsafeKeys2.has(key)) continue;
5427
+ if (Map.prototype.has.call(value, key)) defineTrustedOutputValue(output, key, Map.prototype.get.call(value, key));
5428
+ }
5429
+ return output;
5430
+ }
5431
+ function shallowTrustedOutput(source, budget, depth = 0) {
5432
+ visitTrustedOutput(budget, depth);
5433
+ const output = {};
5434
+ for (const key of Reflect.ownKeys(source)) {
5435
+ visitTrustedOutput(budget, depth + 1);
5436
+ if (typeof key !== "string" || unsafeKeys2.has(key)) authorizationError("unsafe selected output root");
5437
+ const slot = Object.getOwnPropertyDescriptor(source, key);
5438
+ if (isGeneratedPermissionsAliasSlot(source, key, slot)) continue;
5439
+ if (!("value" in slot) || !slot.enumerable) authorizationError("changed borrowed output root");
5440
+ defineTrustedOutputValue(output, key, slot.value);
5441
+ }
5442
+ return output;
5443
+ }
5444
+ function setTrustedOutputPath(output, path, value, budget, depth = 0, onSpine) {
5445
+ const parts = path.split(".");
5446
+ if (parts.some((key) => !key || unsafeKeys2.has(key))) authorizationError("unsafe selected output path");
5447
+ let current = output;
5448
+ const spines = [];
5449
+ for (const [index, key] of parts.slice(0, -1).entries()) {
5450
+ visitTrustedOutput(budget, depth + index + 1);
5451
+ const slot = Object.getOwnPropertyDescriptor(current, key);
5452
+ const source = slot && "value" in slot ? slot.value : void 0;
5453
+ const shell = isBorrowableAuthorizationRecord(source) ? shallowTrustedOutput(source, budget, depth + index + 1) : {};
5454
+ if (source && typeof source === "object") spines.push({ source, copy: shell });
5455
+ defineTrustedOutputValue(current, key, shell);
5456
+ current = shell;
5457
+ }
5458
+ visitTrustedOutput(budget, depth + parts.length);
5459
+ defineTrustedOutputValue(current, parts[parts.length - 1], value);
5460
+ for (const spine of spines.reverse()) onSpine?.(spine.source, spine.copy);
5461
+ }
5462
+ function unsetTrustedOutputPath(output, path, budget, onSpine) {
5463
+ const parts = path.split(".");
5464
+ if (parts.some((key) => !key || unsafeKeys2.has(key))) authorizationError("unsafe selected output path");
5465
+ let current = output;
5466
+ const spines = [];
5467
+ for (const [index, key] of parts.slice(0, -1).entries()) {
5468
+ const slot = Object.getOwnPropertyDescriptor(current, key);
5469
+ if (!slot || !("value" in slot) || !isBorrowableAuthorizationRecord(slot.value)) return;
5470
+ const shell = shallowTrustedOutput(slot.value, budget, index + 1);
5471
+ spines.push({ source: slot.value, copy: shell });
5472
+ defineTrustedOutputValue(current, key, shell);
5473
+ current = shell;
5474
+ }
5475
+ delete current[parts[parts.length - 1]];
5476
+ for (const spine of spines.reverse()) onSpine?.(spine.source, spine.copy);
5477
+ }
5478
+ function isBsonValue(input) {
5479
+ let prototype = Object.getPrototypeOf(input);
5480
+ for (let depth = 0; prototype && depth <= 100; depth++) {
5481
+ if (import_node_util7.types.isProxy(prototype)) return false;
5482
+ if (prototype === import_mongoose5.mongo.BSON.BSONValue.prototype) return true;
5483
+ prototype = Object.getPrototypeOf(prototype);
5484
+ }
5485
+ return false;
5486
+ }
5487
+ function selectedDataProperty(input, key, own2 = false) {
5488
+ let object = input;
5489
+ for (let depth = 0; object && depth <= 100; depth++) {
5490
+ if (import_node_util7.types.isProxy(object)) authorizationError("unsupported selected proxy");
5491
+ const slot = Object.getOwnPropertyDescriptor(object, key);
5492
+ if (slot) {
5493
+ if (!("value" in slot)) authorizationError("accessor selected BSON state");
5494
+ return slot.value;
5495
+ }
5496
+ object = own2 ? null : Object.getPrototypeOf(object);
5497
+ }
5498
+ if (object) authorizationError("unsupported selected prototype depth");
5499
+ return void 0;
5500
+ }
5501
+ function selectedBsonBytes(input) {
5502
+ if (!input || typeof input !== "object" || import_node_util7.types.isProxy(input) || !import_node_util7.types.isUint8Array(input))
5503
+ authorizationError("unsupported selected BSON bytes");
5504
+ const prototype = Object.getPrototypeOf(Uint8Array.prototype);
5505
+ const buffer = Object.getOwnPropertyDescriptor(prototype, "buffer").get.call(input);
5506
+ const offset = Object.getOwnPropertyDescriptor(prototype, "byteOffset").get.call(input);
5507
+ const length = Object.getOwnPropertyDescriptor(prototype, "byteLength").get.call(input);
5508
+ return Buffer.from(new Uint8Array(buffer, offset, length));
5509
+ }
5510
+ function copyTrustedBsonValue(value, path, budget, policy, depth, active) {
5511
+ const wireKeys = /* @__PURE__ */ new Set([
5512
+ "value",
5513
+ "code",
5514
+ "scope",
5515
+ "collection",
5516
+ "oid",
5517
+ "db",
5518
+ "fields",
5519
+ "low",
5520
+ "high",
5521
+ "unsigned",
5522
+ "buffer",
5523
+ "sub_type",
5524
+ "position",
5525
+ "pattern",
5526
+ "options",
5527
+ "bytes",
5528
+ "i0",
5529
+ "i1",
5530
+ "i2",
5531
+ "i3"
5532
+ ]);
5533
+ const defineWireValue = (output, key, value2) => {
5534
+ wireKeys.add(key);
5535
+ defineTrustedOutputValue(output, key, value2);
5536
+ };
5537
+ const prepareWire = (input, current, level, observeHook = true, entered = false, documentRoot = false, slots = 1) => {
5538
+ if (!entered) visitTrustedOutput(budget, level, slots);
5539
+ if (typeof input === "function" || typeof input === "symbol") authorizationError("unsupported selected BSON value");
5540
+ if (input === null || typeof input !== "object") return input;
5541
+ if (import_node_util7.types.isProxy(input)) authorizationError("unsupported selected proxy");
5542
+ if (!entered && active.has(input)) authorizationError("cyclic selected output");
5543
+ if (!entered) active.add(input);
5544
+ try {
5545
+ const hook = selectedDataProperty(input, "toBSON");
5546
+ if (typeof hook === "function") {
5547
+ if (!observeHook) authorizationError("chained selected BSON hooks");
5548
+ const normalized = Reflect.apply(hook, input, []);
5549
+ if (normalized !== input) return prepareWire(normalized, current, level, false, false, documentRoot);
5550
+ }
5551
+ if (isBsonValue(input)) {
5552
+ if (documentRoot) authorizationError("unsupported selected BSON document");
5553
+ let prototype2 = input;
5554
+ for (let hops = 0; prototype2 && !bsonFamilies.has(prototype2) && hops <= 100; hops++) {
5555
+ if (import_node_util7.types.isProxy(prototype2)) authorizationError("unsupported selected proxy");
5556
+ if (Object.hasOwn(prototype2, "_bsontype") || Object.hasOwn(prototype2, /* @__PURE__ */ Symbol.for("@@mdb.bson.type")))
5557
+ authorizationError("overridden selected BSON brand");
5558
+ prototype2 = Object.getPrototypeOf(prototype2);
5559
+ }
5560
+ if (!prototype2 || !bsonFamilies.has(prototype2)) authorizationError("unsupported selected BSON family");
5561
+ const family = bsonFamilies.get(prototype2);
5562
+ const output2 = Object.create(prototype2);
5563
+ Object.defineProperty(output2, "toBSON", { value: void 0 });
5564
+ const field = (key, type) => {
5565
+ const value2 = selectedDataProperty(input, key, true);
5566
+ if (typeof value2 !== type) authorizationError("unsupported selected BSON state");
5567
+ defineWireValue(output2, key, value2);
5568
+ return value2;
5569
+ };
5570
+ const bytes = (key, length) => {
5571
+ const value2 = selectedBsonBytes(selectedDataProperty(input, key, true));
5572
+ if (length !== void 0 && value2.length !== length) authorizationError("invalid selected BSON bytes");
5573
+ defineWireValue(output2, key, value2);
5574
+ };
5575
+ const method = (key) => {
5576
+ if (selectedDataProperty(input, key) !== selectedDataProperty(prototype2, key))
5577
+ authorizationError("unsupported selected BSON serializer override");
5578
+ };
5579
+ const document = (key) => {
5580
+ const raw = selectedDataProperty(input, key, true);
5581
+ const value2 = prepareWire(raw, `${current}.${key}`, level + 1, true, false, true);
5582
+ if (!value2 || typeof value2 !== "object" || !Array.isArray(value2) && Object.getPrototypeOf(value2) !== null)
5583
+ authorizationError("unsupported selected BSON document");
5584
+ defineWireValue(output2, key, value2);
5585
+ };
5586
+ switch (family) {
5587
+ case "Code": {
5588
+ field("code", "string");
5589
+ const scope2 = selectedDataProperty(input, "scope", true);
5590
+ if (scope2 != null) document("scope");
5591
+ else defineWireValue(output2, "scope", scope2);
5592
+ break;
5593
+ }
5594
+ case "DBRef": {
5595
+ field("collection", "string");
5596
+ const db = selectedDataProperty(input, "db", true);
5597
+ if (db != null) field("db", "string");
5598
+ defineWireValue(
5599
+ output2,
5600
+ "oid",
5601
+ prepareWire(selectedDataProperty(input, "oid", true), `${current}.oid`, level + 1)
5602
+ );
5603
+ document("fields");
5604
+ const ordered = /* @__PURE__ */ Object.create(null);
5605
+ defineWireValue(ordered, "$ref", output2.collection);
5606
+ defineWireValue(ordered, "$id", output2.oid);
5607
+ if (db != null) defineWireValue(ordered, "$db", output2.db);
5608
+ for (const key of Object.keys(output2.fields))
5609
+ defineWireValue(ordered, key, output2.fields[key]);
5610
+ return ordered;
5611
+ }
5612
+ case "ObjectId":
5613
+ method("serializeInto");
5614
+ if (Object.hasOwn(input, "buffer"))
5615
+ bytes("buffer", 12);
5616
+ else for (const key of ["i0", "i1", "i2", "i3"]) field(key, "number");
5617
+ break;
5618
+ case "Timestamp":
5619
+ case "Long":
5620
+ method("getLowBits");
5621
+ method("getHighBits");
5622
+ field("low", "number");
5623
+ field("high", "number");
5624
+ field("unsigned", "boolean");
5625
+ break;
5626
+ case "Decimal128":
5627
+ bytes("bytes", 16);
5628
+ break;
5629
+ case "Binary": {
5630
+ bytes("buffer");
5631
+ const position = field("position", "number");
5632
+ const subtype = field("sub_type", "number");
5633
+ if (!Number.isInteger(position) || position < 0 || position > output2.buffer.length || !Number.isInteger(subtype) || subtype < 0 || subtype > 255)
5634
+ authorizationError("invalid selected BSON binary");
5635
+ break;
5636
+ }
5637
+ case "Int32":
5638
+ method("valueOf");
5639
+ field("value", "number");
5640
+ break;
5641
+ case "Double":
5642
+ field("value", "number");
5643
+ break;
5644
+ case "BSONSymbol":
5645
+ field("value", "string");
5646
+ break;
5647
+ case "BSONRegExp":
5648
+ field("pattern", "string");
5649
+ field("options", "string");
5650
+ break;
5651
+ }
5652
+ return output2;
5653
+ }
5654
+ if (selectedDataProperty(input, "_bsontype") != null) authorizationError("unsupported selected BSON tag");
5655
+ const noHook = (value2) => {
5656
+ Object.defineProperty(value2, "toBSON", { value: void 0 });
5657
+ return value2;
5658
+ };
5659
+ if (import_node_util7.types.isDate(input)) {
5660
+ const getTime = selectedDataProperty(input, "getTime");
5661
+ if (typeof getTime !== "function") authorizationError("unsupported selected BSON date");
5662
+ const time = Reflect.apply(getTime, input, []);
5663
+ if (typeof time !== "number") authorizationError("unsupported selected BSON date");
5664
+ return noHook(new Date(time));
5665
+ }
5666
+ if (import_node_util7.types.isUint8Array(input)) return noHook(selectedBsonBytes(input));
5667
+ if (import_node_util7.types.isRegExp(input)) {
5668
+ const source = Object.getOwnPropertyDescriptor(RegExp.prototype, "source").get.call(input);
5669
+ const flags = ["hasIndices", "global", "ignoreCase", "multiline", "dotAll", "unicode", "unicodeSets", "sticky"].map(
5670
+ (name, index) => Object.getOwnPropertyDescriptor(RegExp.prototype, name)?.get?.call(input) ? "dgimsuvy"[index] : ""
5671
+ ).join("");
5672
+ return noHook(new RegExp(source, flags));
5673
+ }
5674
+ const output = /* @__PURE__ */ Object.create(null);
5675
+ if (import_node_util7.types.isMap(input)) {
5676
+ for (const [key, entry] of Map.prototype.entries.call(input)) {
5677
+ visitTrustedOutput(budget, level + 1);
5678
+ if (typeof key !== "string") authorizationError("selected Map requires string keys");
5679
+ if (protectedValueKeys.has(key) || !policy.keep(key, `${current}.${key}`)) continue;
5680
+ defineWireValue(output, key, prepareWire(entry, `${current}.${key}`, level + 1));
5681
+ }
5682
+ return output;
5683
+ }
5684
+ const array = Array.isArray(input);
5685
+ const prototype = Object.getPrototypeOf(input);
5686
+ if (!array && prototype !== Object.prototype && prototype !== null)
5687
+ authorizationError("unsupported selected object");
5688
+ const container = array ? noHook([]) : output;
5689
+ if (array) {
5690
+ const length = Object.getOwnPropertyDescriptor(input, "length").value;
5691
+ visitTrustedOutput(budget, level + 1, length);
5692
+ container.length = length;
5693
+ for (let index = 0; index < length; index++) defineWireValue(container, String(index), void 0);
5694
+ }
5695
+ for (const key of Reflect.ownKeys(input)) {
5696
+ if (array && key === "length") continue;
5697
+ visitTrustedOutput(budget, level + 1);
5698
+ if (typeof key !== "string") authorizationError("symbol selected output key");
5699
+ if (protectedValueKeys.has(key) || key === "toBSON" && (array || typeof hook === "function")) continue;
5700
+ if (array && !/^(0|[1-9]\d*)$/.test(key)) authorizationError("invalid selected array property");
5701
+ const child = array ? current : `${current}.${key}`;
5702
+ if (!array && !policy.keep(key, child)) continue;
5703
+ const slot = Object.getOwnPropertyDescriptor(input, key);
5704
+ if (!("value" in slot) || !slot.enumerable) authorizationError("accessor/non-enumerable selected value");
5705
+ defineWireValue(container, key, prepareWire(slot.value, child, level + 1, true, false, false, 0));
5706
+ }
5707
+ return container;
5708
+ } finally {
5709
+ if (!entered) active.delete(input);
5710
+ }
5711
+ };
5712
+ const prepared = prepareWire(value, path, depth, true, true);
5713
+ for (const key of wireKeys) {
5714
+ const slot = Object.getOwnPropertyDescriptor(Object.prototype, key);
5715
+ if (slot && !("value" in slot)) authorizationError("inherited accessor selected BSON output");
5716
+ }
5717
+ const wrapper = /* @__PURE__ */ Object.create(null);
5718
+ defineTrustedOutputValue(wrapper, "value", prepared);
5719
+ return import_mongoose5.mongo.BSON.deserialize(import_mongoose5.mongo.BSON.serialize(wrapper), { promoteValues: false, bsonRegExp: true }).value;
5720
+ }
5721
+ function materializeTrustedOutputValue(value, path, budget, policy, depth = 0) {
5722
+ const active = /* @__PURE__ */ new WeakSet();
5723
+ const visit = (input, current, level, slots = 1) => {
5724
+ visitTrustedOutput(budget, level, slots);
5725
+ if (typeof input === "function" || typeof input === "symbol") authorizationError("unsupported selected value");
5726
+ if (input === null || typeof input !== "object") return input;
5727
+ if (import_node_util7.types.isProxy(input)) authorizationError("unsupported selected proxy");
5728
+ if (active.has(input)) authorizationError("cyclic selected output");
5729
+ active.add(input);
5730
+ try {
5731
+ if (import_node_util7.types.isDate(input)) return new Date(input.getTime());
5732
+ if (Buffer.isBuffer(input)) return Buffer.from(input);
5733
+ if (import_node_util7.types.isRegExp(input)) {
5734
+ const output2 = new RegExp(input.source, input.flags);
5735
+ output2.lastIndex = input.lastIndex;
5736
+ return output2;
5737
+ }
5738
+ if (isBsonValue(input)) {
5739
+ try {
5740
+ return copyTrustedBsonValue(input, current, budget, policy, level, active);
5741
+ } catch (error2) {
5742
+ if (error2 instanceof ServiceAuthorizationError) throw error2;
5743
+ authorizationError("unsupported selected BSON value");
5744
+ }
5745
+ }
5746
+ if (import_node_util7.types.isMap(input)) {
5747
+ const output2 = {};
5748
+ for (const [key, entry] of Map.prototype.entries.call(input)) {
5749
+ visitTrustedOutput(budget, level + 1);
5750
+ if (typeof key !== "string") authorizationError("selected Map requires string keys");
5751
+ if (protectedValueKeys.has(key) || !policy.keep(key, `${current}.${key}`)) continue;
5752
+ defineTrustedOutputValue(output2, key, visit(entry, `${current}.${key}`, level + 1));
5753
+ }
5754
+ return output2;
5755
+ }
5756
+ const array = Array.isArray(input);
5757
+ const prototype = Object.getPrototypeOf(input);
5758
+ if (!array && prototype !== Object.prototype && prototype !== null)
5759
+ authorizationError("unsupported selected object");
5760
+ const output = array ? [] : {};
5761
+ if (array) {
5762
+ const length = Object.getOwnPropertyDescriptor(input, "length").value;
5763
+ visitTrustedOutput(budget, level + 1, length);
5764
+ output.length = length;
5765
+ }
5766
+ for (const key of Reflect.ownKeys(input)) {
5767
+ if (array && key === "length") continue;
5768
+ visitTrustedOutput(budget, level + 1);
5769
+ if (typeof key !== "string") authorizationError("symbol selected output key");
5770
+ if (protectedValueKeys.has(key)) continue;
5771
+ if (array && !/^(0|[1-9]\d*)$/.test(key)) authorizationError("invalid selected array property");
5772
+ const child = array ? current : `${current}.${key}`;
5773
+ if (!array && !policy.keep(key, child)) continue;
5774
+ const slot = Object.getOwnPropertyDescriptor(input, key);
5775
+ if (isGeneratedPermissionsAliasSlot(input, key, slot)) continue;
5776
+ if (!("value" in slot) || !slot.enumerable) authorizationError("accessor/non-enumerable selected value");
5777
+ defineTrustedOutputValue(output, key, visit(slot.value, child, level + 1, 0));
5778
+ }
5779
+ return output;
5780
+ } catch (error2) {
5781
+ if (error2 instanceof ServiceAuthorizationError) throw error2;
5782
+ authorizationError("unsupported selected value");
5783
+ } finally {
5784
+ active.delete(input);
5785
+ }
5786
+ };
5787
+ return visit(value, path, depth);
5788
+ }
5789
+ var import_node_util7, import_mongoose5, unsafeKeys2, protectedValueKeys, budgets, bsonFamilies;
5790
+ var init_trusted_output_materialization = __esm({
5791
+ "src/acl/trusted-output-materialization.ts"() {
5792
+ import_node_util7 = require("util");
5793
+ import_mongoose5 = require("mongoose");
5794
+ init_authorization_snapshot();
5795
+ init_document();
5796
+ init_permissions_alias();
5797
+ unsafeKeys2 = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype", "_doc", "$__"]);
5798
+ protectedValueKeys = /* @__PURE__ */ new Set([...unsafeKeys2, "__v"]);
5799
+ budgets = /* @__PURE__ */ new WeakMap();
5800
+ bsonFamilies = new Map(
5801
+ Object.entries({
5802
+ ObjectId: import_mongoose5.mongo.BSON.ObjectId,
5803
+ Code: import_mongoose5.mongo.BSON.Code,
5804
+ DBRef: import_mongoose5.mongo.BSON.DBRef,
5805
+ Timestamp: import_mongoose5.mongo.BSON.Timestamp,
5806
+ Long: import_mongoose5.mongo.BSON.Long,
5807
+ Decimal128: import_mongoose5.mongo.BSON.Decimal128,
5808
+ Binary: import_mongoose5.mongo.BSON.Binary,
5809
+ Double: import_mongoose5.mongo.BSON.Double,
5810
+ Int32: import_mongoose5.mongo.BSON.Int32,
5811
+ BSONRegExp: import_mongoose5.mongo.BSON.BSONRegExp,
5812
+ BSONSymbol: import_mongoose5.mongo.BSON.BSONSymbol,
5813
+ MinKey: import_mongoose5.mongo.BSON.MinKey,
5814
+ MaxKey: import_mongoose5.mongo.BSON.MaxKey
5815
+ }).map(([name, family]) => [family.prototype, name])
5816
+ );
5817
+ }
5818
+ });
5819
+
5017
5820
  // src/acl/document-authorization.ts
5018
5821
  function bindOutputDocumentOwner(handle, knownOutput, owner, binding) {
5019
5822
  lookupDocumentOwner(handle);
@@ -5030,6 +5833,7 @@ function isUnresolvedOutputDocument(handle) {
5030
5833
  return unresolvedDocuments.has(handle);
5031
5834
  }
5032
5835
  function normalizeOutputAuthorizationOptions(input, options, purpose) {
5836
+ assertNoServerModelControls(options, authorizationError);
5033
5837
  const value = authorizationRecord(options, "output options");
5034
5838
  for (const key of Reflect.ownKeys(value)) {
5035
5839
  const descriptor = Object.getOwnPropertyDescriptor(value, key);
@@ -5061,6 +5865,7 @@ function normalizeOutputAuthorizationOptions(input, options, purpose) {
5061
5865
  kind: "policy",
5062
5866
  authorization: resolveServiceAuthorization({
5063
5867
  ...input,
5868
+ configuration: typeof input.configuration === "function" ? input.configuration() : input.configuration,
5064
5869
  binding: {
5065
5870
  ...input.binding,
5066
5871
  scopePath: copyAuthorizationValue(value.scopePath)
@@ -5081,6 +5886,10 @@ function lookupDocumentOwner(handle) {
5081
5886
  return record3;
5082
5887
  }
5083
5888
  function validateStageOwner(record3) {
5889
+ if (record3.sourceState === "trusted") {
5890
+ assertAuthorizationBinding(record3.call, record3.binding);
5891
+ return;
5892
+ }
5084
5893
  if (!record3.validateSnapshot) return;
5085
5894
  if (!matchesAuthorizationSnapshot(record3.input, record3.snapshot)) authorizationError("changed document snapshot");
5086
5895
  }
@@ -5094,43 +5903,164 @@ function validateDocumentOwner(handle) {
5094
5903
  function createDocumentAuthorizationStage(call, binding, projectedSnapshot) {
5095
5904
  assertAuthorizationBinding(call, binding);
5096
5905
  authorizationRecord(projectedSnapshot, "projected document snapshot");
5906
+ return createStage(
5907
+ call,
5908
+ binding,
5909
+ projectedSnapshot,
5910
+ readAuthorizationFastPath(call, binding)?.mode === "active" && isBorrowableAuthorizationRecord(projectedSnapshot) ? "trusted" : "copied"
5911
+ );
5912
+ }
5913
+ function createStage(call, binding, source, sourceState) {
5097
5914
  const stage = Object.freeze(/* @__PURE__ */ Object.create(null));
5098
5915
  const ownedBinding = Object.freeze({ ...binding, scopePath: Object.freeze([...binding.scopePath ?? []]) });
5099
- const snapshot = copyAuthorizationValue(projectedSnapshot, "document");
5100
- stages.set(stage, {
5916
+ const owner = {
5101
5917
  call,
5102
5918
  binding: ownedBinding,
5103
- input: projectedSnapshot,
5104
- snapshot,
5105
- validateSnapshot: requiresDocumentSnapshotChecks(call, binding)
5106
- });
5919
+ input: source,
5920
+ result: void 0,
5921
+ resolutionState: "unresolved"
5922
+ };
5923
+ stages.set(
5924
+ stage,
5925
+ sourceState === "trusted" ? { ...owner, sourceState, source } : {
5926
+ ...owner,
5927
+ sourceState,
5928
+ snapshot: copyAuthorizationValue(source, "document"),
5929
+ validateSnapshot: requiresDocumentSnapshotChecks(call, binding)
5930
+ }
5931
+ );
5107
5932
  return stage;
5108
5933
  }
5934
+ function prepareQueryDocumentAuthorization(call, binding, input) {
5935
+ const prepared = prepareQueryOutputSource(call, binding, input, "hook");
5936
+ if (!prepared) return;
5937
+ authorizationRecord(prepared.source, "projected document snapshot");
5938
+ return { ...prepared, stage: createStage(call, binding, prepared.source, prepared.sourceState) };
5939
+ }
5940
+ function getQueryOutputOriginal(input, call) {
5941
+ return input && typeof input === "object" && call && querySources.get(input)?.has(call) ? queryOriginals.get(input) ?? input : input;
5942
+ }
5943
+ function getQueryReferenceOriginal(input) {
5944
+ return referenceOriginals.get(input);
5945
+ }
5946
+ function captureNormalizedReferenceOrigins(original, normalized, paths, budget) {
5947
+ const storage2 = (value) => value instanceof import_mongoose6.Document ? value._doc : value;
5948
+ const walk = (raw, copy, parts, index, depth) => {
5949
+ visitTrustedOutput(budget, depth);
5950
+ if (!raw || !copy || typeof raw !== "object" || typeof copy !== "object" || import_node_util8.types.isProxy(raw) || import_node_util8.types.isProxy(copy))
5951
+ return;
5952
+ if (Array.isArray(raw) && Array.isArray(copy)) {
5953
+ visitTrustedOutput(budget, depth, copy.length);
5954
+ for (let slot = 0; slot < copy.length; slot++) {
5955
+ const source2 = Object.getOwnPropertyDescriptor(raw, String(slot)), target2 = Object.getOwnPropertyDescriptor(copy, String(slot));
5956
+ if (source2 && target2 && "value" in source2 && "value" in target2)
5957
+ walk(source2.value, target2.value, parts, index, depth + 1);
5958
+ }
5959
+ return;
5960
+ }
5961
+ if (index === parts.length) {
5962
+ if (raw !== copy && isBorrowableAuthorizationRecord(copy)) referenceOriginals.set(copy, raw);
5963
+ return;
5964
+ }
5965
+ const source = Object.getOwnPropertyDescriptor(storage2(raw), parts[index]), target = Object.getOwnPropertyDescriptor(copy, parts[index]);
5966
+ if (source && target && "value" in source && "value" in target)
5967
+ walk(source.value, target.value, parts, index + 1, depth + 1);
5968
+ };
5969
+ for (const path of paths) walk(original, normalized, path.split("."), 0, 0);
5970
+ }
5971
+ function prepareQueryOutputSource(call, binding, input, purpose) {
5972
+ if (readAuthorizationFastPath(call, binding)?.mode !== "active") return;
5973
+ const existing = input && typeof input === "object" ? querySources.get(input)?.get(call) : void 0;
5974
+ if (existing && (purpose !== "hook" || existing.sourceState === "copied" || isBorrowableAuthorizationRecord(input)))
5975
+ return { source: input, ...existing };
5976
+ const prepared = prepareTrustedAuthorizationSource(input);
5977
+ const budget = existing?.budget ?? (!binding.scopePath?.length ? createTrustedOutputBudget() : void 0);
5978
+ if (input && typeof input === "object" && prepared.source !== input) {
5979
+ queryOriginals.set(prepared.source, input);
5980
+ if (budget && prepared.kind === "trusted")
5981
+ captureNormalizedReferenceOrigins(
5982
+ input,
5983
+ prepared.source,
5984
+ readServiceOutputPolicy(call, binding).catalog.referencePaths ?? [],
5985
+ budget
5986
+ );
5987
+ }
5988
+ let captures2 = querySources.get(prepared.source);
5989
+ if (!captures2) querySources.set(prepared.source, captures2 = /* @__PURE__ */ new WeakMap());
5990
+ captures2.set(call, { sourceState: prepared.kind, budget });
5991
+ return { source: prepared.source, sourceState: prepared.kind, budget };
5992
+ }
5993
+ function isTrustedDocumentAuthorization(handle, binding) {
5994
+ const stage = lookupStageOwner(lookupDocumentOwner(handle).stage);
5995
+ if (stage.sourceState !== "trusted") return false;
5996
+ assertAuthorizationBinding(stage.call, binding);
5997
+ return true;
5998
+ }
5999
+ function isTrustedDocumentAuthorizationStage(stage, call, binding) {
6000
+ const record3 = lookupStageOwner(stage);
6001
+ assertAuthorizationBinding(record3.call, binding);
6002
+ if (record3.call !== call) authorizationError("document call/stage mismatch");
6003
+ return record3.sourceState === "trusted";
6004
+ }
5109
6005
  function assertDocumentAuthorizationStage(stage, call, binding, projectedSnapshot) {
5110
6006
  const record3 = lookupStageOwner(stage);
5111
6007
  validateStageOwner(record3);
5112
6008
  assertAuthorizationBinding(record3.call, binding);
5113
- if (record3.call !== call || record3.input !== projectedSnapshot || record3.validateSnapshot && !matchesAuthorizationSnapshot(projectedSnapshot, record3.snapshot)) {
6009
+ if (record3.call !== call || record3.input !== projectedSnapshot || record3.sourceState === "copied" && record3.validateSnapshot && !matchesAuthorizationSnapshot(projectedSnapshot, record3.snapshot)) {
5114
6010
  authorizationError("document call/stage/snapshot mismatch");
5115
6011
  }
5116
6012
  }
5117
6013
  function resolveDocumentAuthorization(stage, resolveGrants) {
5118
6014
  const record3 = lookupStageOwner(stage);
5119
6015
  validateStageOwner(record3);
6016
+ if (record3.sourceState === "trusted") {
6017
+ if (!record3.result) {
6018
+ record3.resolutionState = "pending";
6019
+ record3.result = (async () => {
6020
+ try {
6021
+ assertAuthorizationBinding(record3.call, record3.binding);
6022
+ const result2 = resolveGrants.call(
6023
+ record3.binding.request,
6024
+ record3.source,
6025
+ getAuthorizationPermissions(record3.call, record3.binding)
6026
+ );
6027
+ const grants = result2 && typeof result2.then === "function" ? await result2 : result2;
6028
+ assertAuthorizationBinding(record3.call, record3.binding);
6029
+ const grantState = isBorrowableAuthorizationRecord(grants) ? "borrowed" : "copied";
6030
+ const value = grantState === "borrowed" ? grants : copyAuthorizationValue(authorizationRecord(grants, "document grants"));
6031
+ const handle = Object.freeze(/* @__PURE__ */ Object.create(null));
6032
+ documents.set(handle, { stage, grants: value, grantState, decisions: /* @__PURE__ */ new Map() });
6033
+ record3.resolutionState = "fulfilled";
6034
+ return handle;
6035
+ } catch (error2) {
6036
+ record3.resolutionState = "rejected";
6037
+ throw error2;
6038
+ }
6039
+ })();
6040
+ }
6041
+ return record3.result;
6042
+ }
5120
6043
  if (!record3.result) {
6044
+ record3.resolutionState = "pending";
5121
6045
  record3.result = Promise.resolve().then(async () => {
5122
- validateStageOwner(record3);
5123
- const result2 = resolveGrants.call(
5124
- record3.binding.request,
5125
- copyAuthorizationValue(record3.snapshot, "document"),
5126
- getAuthorizationPermissions(record3.call, record3.binding)
5127
- );
5128
- const grants = result2 && typeof result2.then === "function" ? await result2 : result2;
5129
- validateStageOwner(record3);
5130
- const ownedGrants = copyAuthorizationValue(authorizationRecord(grants, "document grants"));
5131
- const handle = Object.freeze(/* @__PURE__ */ Object.create(null));
5132
- documents.set(handle, { stage, grants: ownedGrants, decisions: /* @__PURE__ */ new Map() });
5133
- return handle;
6046
+ try {
6047
+ validateStageOwner(record3);
6048
+ const result2 = resolveGrants.call(
6049
+ record3.binding.request,
6050
+ copyAuthorizationValue(record3.snapshot, "document"),
6051
+ getAuthorizationPermissions(record3.call, record3.binding)
6052
+ );
6053
+ const grants = result2 && typeof result2.then === "function" ? await result2 : result2;
6054
+ validateStageOwner(record3);
6055
+ const ownedGrants = copyAuthorizationValue(authorizationRecord(grants, "document grants"));
6056
+ const handle = Object.freeze(/* @__PURE__ */ Object.create(null));
6057
+ documents.set(handle, { stage, grants: ownedGrants, grantState: "copied", decisions: /* @__PURE__ */ new Map() });
6058
+ record3.resolutionState = "fulfilled";
6059
+ return handle;
6060
+ } catch (error2) {
6061
+ record3.resolutionState = "rejected";
6062
+ throw error2;
6063
+ }
5134
6064
  });
5135
6065
  }
5136
6066
  return record3.result;
@@ -5141,7 +6071,9 @@ function readDocumentAuthorization(handle, binding) {
5141
6071
  return Object.freeze({
5142
6072
  authorization: stage.call,
5143
6073
  stage: record3.stage,
5144
- grants: copyAuthorizationValue(record3.grants),
6074
+ grants: stage.sourceState === "trusted" ? record3.grants : copyAuthorizationValue(record3.grants),
6075
+ sourceState: stage.sourceState,
6076
+ grantState: record3.grantState,
5145
6077
  ...readServiceAuthorizationAccess(stage.call, binding)
5146
6078
  });
5147
6079
  }
@@ -5150,12 +6082,14 @@ function readDocumentAuthorizationAccess(handle, binding) {
5150
6082
  return Object.freeze({
5151
6083
  authorization: stage.call,
5152
6084
  stage: record3.stage,
6085
+ sourceState: stage.sourceState,
5153
6086
  ...readServiceAuthorizationAccess(stage.call, binding)
5154
6087
  });
5155
6088
  }
5156
6089
  function memoizeDocumentFieldDecision(handle, binding, field, evaluate) {
5157
6090
  const { document: record3, stage } = validateDocumentOwner(handle);
5158
6091
  assertAuthorizationBinding(stage.call, binding);
6092
+ if (stage.sourceState === "trusted") return memoizeTrustedFieldDecision(record3, stage, binding, field, evaluate);
5159
6093
  let decision = record3.decisions.get(field);
5160
6094
  if (decision) {
5161
6095
  return decision.promise.then((result2) => {
@@ -5166,6 +6100,7 @@ function memoizeDocumentFieldDecision(handle, binding, field, evaluate) {
5166
6100
  } else {
5167
6101
  const created = {
5168
6102
  state: "pending",
6103
+ value: void 0,
5169
6104
  promise: Promise.resolve().then(async () => {
5170
6105
  validateStageOwner(stage);
5171
6106
  assertAuthorizationBinding(stage.call, binding);
@@ -5194,8 +6129,52 @@ function memoizeDocumentFieldDecision(handle, binding, field, evaluate) {
5194
6129
  }
5195
6130
  return decision.promise;
5196
6131
  }
6132
+ function memoizeTrustedFieldDecision(record3, stage, binding, field, evaluate) {
6133
+ const previous = record3.decisions.get(field);
6134
+ if (previous) return previous.state === "fulfilled" ? previous.value : previous.promise;
6135
+ let fulfill, reject;
6136
+ const decision = {
6137
+ state: "pending",
6138
+ value: void 0,
6139
+ promise: new Promise((resolve, fail3) => {
6140
+ fulfill = resolve;
6141
+ reject = fail3;
6142
+ })
6143
+ };
6144
+ record3.decisions.set(field, decision);
6145
+ const settle = (value) => {
6146
+ assertAuthorizationBinding(stage.call, binding);
6147
+ assertAuthorizationBinding(stage.call, stage.binding);
6148
+ if (typeof value !== "boolean") authorizationError("field decision must be boolean");
6149
+ decision.value = value;
6150
+ decision.state = "fulfilled";
6151
+ fulfill(value);
6152
+ return value;
6153
+ };
6154
+ const fail2 = (error2) => {
6155
+ decision.state = "rejected";
6156
+ reject(error2);
6157
+ };
6158
+ try {
6159
+ const value = evaluate.call(stage.binding.request, getAuthorizationPermissions(stage.call, binding), record3.grants);
6160
+ if (value && typeof value.then === "function") {
6161
+ void (async () => {
6162
+ try {
6163
+ settle(await value);
6164
+ } catch (error2) {
6165
+ fail2(error2);
6166
+ }
6167
+ })();
6168
+ return decision.promise;
6169
+ }
6170
+ return settle(value);
6171
+ } catch (error2) {
6172
+ fail2(error2);
6173
+ return decision.promise;
6174
+ }
6175
+ }
5197
6176
  function ordinaryDecisionBinding(binding) {
5198
- if (import_node_util7.types.isProxy(binding) || Object.getPrototypeOf(binding) !== Object.prototype) return false;
6177
+ if (import_node_util8.types.isProxy(binding) || Object.getPrototypeOf(binding) !== Object.prototype) return false;
5199
6178
  for (const key of ["request", "runtime", "model", "modelName", "scopePath"]) {
5200
6179
  const slot = Object.getOwnPropertyDescriptor(binding, key);
5201
6180
  if (slot && !("value" in slot)) return false;
@@ -5321,6 +6300,7 @@ function tryStaticRequestFieldPaths(handle, binding, access) {
5321
6300
  return decisions && [...decisions].filter(([, allowed]) => allowed).map(([field]) => field);
5322
6301
  }
5323
6302
  function unchangedOutput(output, record3) {
6303
+ if (record3.snapshotState === "trusted") return outputs.get(output) === record3;
5324
6304
  if (record3.validateSnapshot && !matchesAuthorizationSnapshot(output, record3.snapshot)) return false;
5325
6305
  const identities = outputIdentities(output);
5326
6306
  return identities.length === record3.identities.length && identities.every((identity, i) => identity === record3.identities[i]);
@@ -5336,7 +6316,7 @@ function assertDocumentAuthorization(handle, use) {
5336
6316
  authorizationError("unknown, replaced or mutated authorized output");
5337
6317
  }
5338
6318
  }
5339
- function associateDocumentAuthorization(handle, binding, output) {
6319
+ function associateDocumentAuthorization(handle, binding, output, builder) {
5340
6320
  const { stage } = validateDocumentOwner(handle);
5341
6321
  assertAuthorizationBinding(stage.call, binding);
5342
6322
  if (!output || typeof output !== "object") authorizationError("output must be an object");
@@ -5346,12 +6326,17 @@ function associateDocumentAuthorization(handle, binding, output) {
5346
6326
  authorizationError("output already associated");
5347
6327
  return;
5348
6328
  }
6329
+ const members = builder ? finishTrustedOutputMembers(builder, handle, binding, output) : void 0;
6330
+ if (stage.sourceState === "trusted") {
6331
+ outputs.set(output, { handle, snapshotState: "trusted", members: members ?? /* @__PURE__ */ new Set([output]) });
6332
+ return;
6333
+ }
5349
6334
  if (skipsInitialOutputSnapshotCopy(stage.call) && ordinaryDecisionBinding(binding)) {
5350
6335
  if (requiresOutputSnapshotChecks(stage.call, binding))
5351
6336
  authorizationError("output snapshot copy requires skipped comparisons");
5352
6337
  const identities = tryOutputIdentitiesWithoutSnapshot(output);
5353
6338
  if (identities) {
5354
- outputs.set(output, { handle, snapshotState: "omitted", identities, validateSnapshot: false });
6339
+ outputs.set(output, { handle, snapshotState: "omitted", identities, validateSnapshot: false, members });
5355
6340
  return;
5356
6341
  }
5357
6342
  }
@@ -5360,7 +6345,8 @@ function associateDocumentAuthorization(handle, binding, output) {
5360
6345
  snapshotState: "copied",
5361
6346
  snapshot: copyAuthorizationValue(output, "document"),
5362
6347
  identities: outputIdentities(output),
5363
- validateSnapshot: requiresOutputSnapshotChecks(stage.call, binding)
6348
+ validateSnapshot: requiresOutputSnapshotChecks(stage.call, binding),
6349
+ members
5364
6350
  });
5365
6351
  }
5366
6352
  function transferDocumentAuthorization(handle, use, copy) {
@@ -5370,6 +6356,13 @@ function transferDocumentAuthorization(handle, use, copy) {
5370
6356
  function isKnownAuthorizationOutput(output) {
5371
6357
  return outputs.has(output);
5372
6358
  }
6359
+ function isTrustedAuthorizationOutput(output, call) {
6360
+ const record3 = outputs.get(output);
6361
+ if (record3?.snapshotState !== "trusted") return false;
6362
+ const { stage } = validateDocumentOwner(record3.handle);
6363
+ assertAuthorizationBinding(stage.call, stage.binding);
6364
+ return !call || getAuthorizationProvenance(stage.call) === getAuthorizationProvenance(call);
6365
+ }
5373
6366
  function getAssociatedDocumentAuthorization(output, call) {
5374
6367
  const record3 = outputs.get(output);
5375
6368
  if (!record3 || !unchangedOutput(output, record3)) return void 0;
@@ -5377,13 +6370,96 @@ function getAssociatedDocumentAuthorization(output, call) {
5377
6370
  if (call && getAuthorizationProvenance(stage.call) !== getAuthorizationProvenance(call)) return void 0;
5378
6371
  return record3.handle;
5379
6372
  }
6373
+ function createTrustedOutputMemberBuilder(call, binding, budget) {
6374
+ if (readAuthorizationFastPath(call, binding)?.mode !== "active") authorizationError("invalid trusted member origin");
6375
+ const builder = Object.freeze(/* @__PURE__ */ Object.create(null));
6376
+ memberBuilders.set(builder, { call, binding, budget, members: /* @__PURE__ */ new Set(), spines: /* @__PURE__ */ new WeakMap(), finished: false });
6377
+ return builder;
6378
+ }
6379
+ function retainTrustedOutputMember(builder, output) {
6380
+ const record3 = memberBuilders.get(builder);
6381
+ if (!record3 || record3.finished) authorizationError("invalid issued member builder");
6382
+ assertAuthorizationBinding(record3.call, record3.binding);
6383
+ const association = outputs.get(output);
6384
+ if (!association || !unchangedOutput(output, association)) authorizationError("unknown issued output member");
6385
+ const { stage } = validateDocumentOwner(association.handle);
6386
+ if (getAuthorizationProvenance(stage.call) !== getAuthorizationProvenance(record3.call))
6387
+ authorizationError("issued member call mismatch");
6388
+ visitTrustedOutput(record3.budget, 0);
6389
+ if (record3.members.has(output)) return;
6390
+ record3.members.add(output);
6391
+ const add = (member) => {
6392
+ visitTrustedOutput(record3.budget, 0);
6393
+ if (!record3.members.has(member)) {
6394
+ record3.members.add(member);
6395
+ }
6396
+ };
6397
+ for (const member of association.members ?? []) if (member !== output) add(member);
6398
+ }
6399
+ function retainTrustedOutputSpine(builder, source, copy) {
6400
+ const record3 = memberBuilders.get(builder);
6401
+ if (!record3 || record3.finished) authorizationError("invalid issued spine builder");
6402
+ assertAuthorizationBinding(record3.call, record3.binding);
6403
+ const association = outputs.get(source);
6404
+ if (!association) return;
6405
+ if (!unchangedOutput(source, association)) authorizationError("changed issued spine source");
6406
+ const { stage } = validateDocumentOwner(association.handle);
6407
+ if (getAuthorizationProvenance(stage.call) !== getAuthorizationProvenance(record3.call))
6408
+ authorizationError("issued spine call mismatch");
6409
+ const child = createTrustedOutputMemberBuilder(stage.call, stage.binding, record3.budget);
6410
+ const childRecord = memberBuilders.get(child);
6411
+ for (const member of association.members ?? []) {
6412
+ if (member === source) continue;
6413
+ visitTrustedOutput(record3.budget, 0);
6414
+ childRecord.members.add(member);
6415
+ const replacement = record3.spines.get(member);
6416
+ if (replacement) {
6417
+ visitTrustedOutput(record3.budget, 0);
6418
+ childRecord.members.add(replacement);
6419
+ }
6420
+ }
6421
+ associateDocumentAuthorization(association.handle, stage.binding, copy, child);
6422
+ record3.spines.set(source, copy);
6423
+ retainTrustedOutputMember(builder, copy);
6424
+ }
6425
+ function finishTrustedOutputMembers(builder, handle, binding, output) {
6426
+ const record3 = memberBuilders.get(builder);
6427
+ const { stage } = validateDocumentOwner(handle);
6428
+ if (!record3 || record3.finished || record3.call !== stage.call) authorizationError("invalid issued member publication");
6429
+ assertAuthorizationBinding(record3.call, binding);
6430
+ if (!record3.members.has(output)) {
6431
+ visitTrustedOutput(record3.budget, 0);
6432
+ record3.members.add(output);
6433
+ }
6434
+ record3.finished = true;
6435
+ return record3.members;
6436
+ }
6437
+ function getIssuedEmbeddedDocumentAuthorization(root, child, owner, binding) {
6438
+ const rootRecord = outputs.get(root);
6439
+ if (!rootRecord || rootRecord.handle !== owner || rootRecord.snapshotState !== "trusted" || !rootRecord.members.has(child))
6440
+ return;
6441
+ const childRecord = outputs.get(child);
6442
+ if (!childRecord) return;
6443
+ const owning = owningDocuments.get(childRecord.handle);
6444
+ if (owning?.handle !== owner) return;
6445
+ const { stage } = validateDocumentOwner(childRecord.handle);
6446
+ assertAuthorizationBinding(stage.call, binding);
6447
+ return childRecord.handle;
6448
+ }
6449
+ function isIssuedOutputMember(root, member) {
6450
+ const record3 = outputs.get(root);
6451
+ if (!record3 || record3.snapshotState !== "trusted" || !record3.members.has(member)) return false;
6452
+ const { stage } = validateDocumentOwner(record3.handle);
6453
+ assertAuthorizationBinding(stage.call, stage.binding);
6454
+ return outputs.has(member);
6455
+ }
5380
6456
  function transferDocumentAuthorizationGraph(source, copy, copyOrigins) {
5381
6457
  const seen = /* @__PURE__ */ new WeakSet();
5382
6458
  const visit = (source2, copy2) => {
5383
6459
  if (!copy2 || typeof copy2 !== "object" || seen.has(copy2)) return;
5384
6460
  seen.add(copy2);
5385
6461
  source2 = copyOrigins?.get(copy2) ?? source2;
5386
- if (source2 instanceof import_mongoose5.Document) source2 = source2._doc;
6462
+ if (source2 instanceof import_mongoose6.Document) source2 = source2._doc;
5387
6463
  const original = source2 && typeof source2 === "object" ? source2 : void 0;
5388
6464
  if (!original && !copyOrigins) return;
5389
6465
  const association = original && outputs.get(original);
@@ -5418,7 +6494,7 @@ function createServiceOutputContext(diagnostic, handle, use) {
5418
6494
  assertDocumentAuthorization(handle, use);
5419
6495
  const rootOutput = use.output;
5420
6496
  const root = outputs.get(rootOutput);
5421
- const graph = new Set(root.identities);
6497
+ const graph = root.snapshotState === "trusted" ? root.members : new Set(root.identities);
5422
6498
  const { stage } = validateDocumentOwner(handle);
5423
6499
  const call = stage.call;
5424
6500
  const context = { ...diagnostic };
@@ -5435,6 +6511,8 @@ function createServiceOutputContext(diagnostic, handle, use) {
5435
6511
  try {
5436
6512
  validateStageOwner(lookupStageOwner(lookupDocumentOwner(handle).stage));
5437
6513
  const { stage: child } = validateDocumentOwner(association.handle);
6514
+ assertAuthorizationBinding(call, use.binding);
6515
+ assertAuthorizationBinding(child.call, child.binding);
5438
6516
  if (getAuthorizationProvenance(child.call) !== getAuthorizationProvenance(call)) return void 0;
5439
6517
  return association.handle;
5440
6518
  } catch {
@@ -5445,26 +6523,41 @@ function createServiceOutputContext(diagnostic, handle, use) {
5445
6523
  });
5446
6524
  return context;
5447
6525
  }
5448
- var import_node_util7, import_mongoose5, stages, documents, outputs, unresolvedDocuments, owningDocuments;
6526
+ var import_node_util8, import_mongoose6, stages, documents, outputs, unresolvedDocuments, owningDocuments, querySources, queryOriginals, referenceOriginals, memberBuilders;
5449
6527
  var init_document_authorization = __esm({
5450
6528
  "src/acl/document-authorization.ts"() {
5451
- import_node_util7 = require("util");
5452
- import_mongoose5 = require("mongoose");
6529
+ import_node_util8 = require("util");
6530
+ import_mongoose6 = require("mongoose");
5453
6531
  init_service_authorization();
5454
6532
  init_authorization_snapshot();
5455
6533
  init_output_projection();
5456
6534
  init_output_field_policy();
6535
+ init_public_admission();
6536
+ init_trusted_output_materialization();
5457
6537
  stages = /* @__PURE__ */ new WeakMap();
5458
6538
  documents = /* @__PURE__ */ new WeakMap();
5459
6539
  outputs = /* @__PURE__ */ new WeakMap();
5460
6540
  unresolvedDocuments = /* @__PURE__ */ new WeakSet();
5461
6541
  owningDocuments = /* @__PURE__ */ new WeakMap();
6542
+ querySources = /* @__PURE__ */ new WeakMap();
6543
+ queryOriginals = /* @__PURE__ */ new WeakMap();
6544
+ referenceOriginals = /* @__PURE__ */ new WeakMap();
6545
+ memberBuilders = /* @__PURE__ */ new WeakMap();
5462
6546
  }
5463
6547
  });
5464
6548
 
5465
6549
  // src/output/include-output.ts
5466
- function prepareIncludeOutput(doc) {
6550
+ function prepareIncludeOutput(doc, call, binding) {
5467
6551
  if (stateFor(doc)) return doc;
6552
+ const prepared = call && binding ? prepareQueryOutputSource(call, binding, doc) : void 0;
6553
+ if (prepared) {
6554
+ const source2 = prepared.source;
6555
+ const budget = prepared.budget ?? createTrustedOutputBudget();
6556
+ const trusted = prepared.sourceState === "trusted" ? { call, binding, budget } : void 0;
6557
+ const working2 = trusted ? shallowTrustedOutput(source2, budget) : deepIsolateValue(source2);
6558
+ outputs2.set(working2, { original: getQueryOutputOriginal(doc, call), source: source2, attachments: [], trusted });
6559
+ return working2;
6560
+ }
5468
6561
  const source = isolateDocForOutput(doc);
5469
6562
  transferDocumentAuthorizationGraph(doc, source);
5470
6563
  const working = deepIsolateValue(source);
@@ -5475,13 +6568,59 @@ function attachIncludeOutput(doc, path, value) {
5475
6568
  const state = stateFor(doc);
5476
6569
  if (!state) throw new Error("Include attachment requires a prepared output row");
5477
6570
  state.attachments.push({ path, value });
5478
- (0, import_utils21.set)(doc, path, deepIsolateValue(value));
6571
+ if (state.trusted) setTrustedOutputPath(doc, path, value, state.trusted.budget);
6572
+ else (0, import_utils21.set)(doc, path, deepIsolateValue(value));
6573
+ }
6574
+ function restoreTrustedIncludeOutput(doc, output, materialization) {
6575
+ const state = stateFor(doc);
6576
+ if (!state?.attachments.length) return;
6577
+ for (const { path, value } of state.attachments) {
6578
+ const target = state.trusted ? readServiceAuthorization(state.trusted.call, state.trusted.binding).relatedTargets.find(
6579
+ (entry) => entry.path === path
6580
+ ) : void 0;
6581
+ const active = /* @__PURE__ */ new WeakSet();
6582
+ const retain = (input, depth) => {
6583
+ visitTrustedOutput(materialization.budget, depth);
6584
+ if (Array.isArray(input)) {
6585
+ if (active.has(input)) authorizationError("cyclic include output");
6586
+ active.add(input);
6587
+ try {
6588
+ return shallowTrustedOutputArray(input, materialization.budget, depth).map(
6589
+ (entry) => retain(entry, depth + 1)
6590
+ );
6591
+ } finally {
6592
+ active.delete(input);
6593
+ }
6594
+ }
6595
+ if (input && typeof input === "object") {
6596
+ const handle = target ? getAssociatedDocumentAuthorization(input, state.trusted.call) : void 0;
6597
+ if (!handle) authorizationError("unknown finalized include output");
6598
+ readDocumentAuthorizationAccess(handle, {
6599
+ ...state.trusted.binding,
6600
+ modelName: target.modelName,
6601
+ model: target.model,
6602
+ scopePath: []
6603
+ });
6604
+ retainTrustedOutputMember(materialization.members, input);
6605
+ return input;
6606
+ }
6607
+ return materializeTrustedOutputValue(input, path, materialization.budget, { keep: () => true }, depth);
6608
+ };
6609
+ setTrustedOutputPath(
6610
+ output,
6611
+ path,
6612
+ retain(value, materialization.depth + 1),
6613
+ materialization.budget,
6614
+ materialization.depth,
6615
+ (source, copy) => retainTrustedOutputSpine(materialization.members, source, copy)
6616
+ );
6617
+ }
5479
6618
  }
5480
6619
  function getIncludeSource(doc) {
5481
6620
  return stateFor(doc)?.source ?? doc;
5482
6621
  }
5483
- function getIncludeOriginal(doc) {
5484
- return stateFor(doc)?.original ?? doc;
6622
+ function getIncludeOriginal(doc, call) {
6623
+ return stateFor(doc)?.original ?? getQueryOutputOriginal(doc, call);
5485
6624
  }
5486
6625
  function restoreIncludeOutput(doc, output) {
5487
6626
  const attachments = stateFor(doc)?.attachments;
@@ -5499,6 +6638,10 @@ var init_include_output = __esm({
5499
6638
  "src/output/include-output.ts"() {
5500
6639
  import_utils21 = require("@web-ts-toolkit/utils");
5501
6640
  init_document_authorization();
6641
+ init_document_authorization();
6642
+ init_service_authorization();
6643
+ init_authorization_snapshot();
6644
+ init_trusted_output_materialization();
5502
6645
  init_document();
5503
6646
  outputs2 = /* @__PURE__ */ new WeakMap();
5504
6647
  stateFor = (doc) => doc !== null && typeof doc === "object" ? outputs2.get(doc) : void 0;
@@ -5543,48 +6686,47 @@ function captureModelAuthorizationConfiguration(runtime, modelName, options, pop
5543
6686
  const model = runtime.getModelInstance(modelName);
5544
6687
  if (!model) return authorizationError(`unknown receiving model: ${modelName}`);
5545
6688
  const virtuals = options.virtuals;
5546
- return copyAuthorizationValue(
5547
- {
5548
- catalog: captureAuthorizationFieldCatalog(model.schema, virtuals, options.documentPermissionField),
5549
- virtualPopulateSnapshot: captureVirtualPopulateSnapshot(
5550
- runtime,
5551
- modelName,
5552
- options,
5553
- populatePolicyDefaults
5554
- ),
5555
- populatePolicyDefaults,
5556
- ...resolvePopulatePolicy(options, populatePolicyDefaults),
5557
- permissionSchema: options.permissionSchema === void 0 ? runtime.getDefaultModelOption("permissionSchema") : options.permissionSchema,
5558
- virtuals,
5559
- alwaysSelectFields: options.alwaysSelectFields,
5560
- modelPermissionPrefix: options.modelPermissionPrefix,
5561
- requireExplicitSelect: options.requireExplicitSelect,
5562
- documentPermissionField: options.documentPermissionField,
5563
- docPermissions: options.docPermissions,
5564
- exposedDocPermissionKeys: options.exposedDocPermissionKeys,
5565
- stripPermissionsField: options.stripPermissionsField,
5566
- disableFieldPermissions: options.disableFieldPermissions,
5567
- unsafeSkipListDocumentSnapshotChecks: options.unsafeSkipListDocumentSnapshotChecks === true,
5568
- unsafeSkipReadDocumentSnapshotChecks: options.unsafeSkipReadDocumentSnapshotChecks === true,
5569
- unsafeSkipListOutputSnapshotChecks: options.unsafeSkipListOutputSnapshotChecks === true,
5570
- unsafeSkipReadOutputSnapshotChecks: options.unsafeSkipReadOutputSnapshotChecks === true,
5571
- unsafeSkipListNestedDocumentSnapshotChecks: options.unsafeSkipListNestedDocumentSnapshotChecks === true,
5572
- unsafeSkipReadNestedDocumentSnapshotChecks: options.unsafeSkipReadNestedDocumentSnapshotChecks === true,
5573
- unsafeSkipListInitialOutputSnapshotCopy: options.unsafeSkipListInitialOutputSnapshotCopy === true,
5574
- unsafeSkipReadInitialOutputSnapshotCopy: options.unsafeSkipReadInitialOutputSnapshotCopy === true,
5575
- overrideFilter: options.overrideFilter,
5576
- baseFilter: options.baseFilter,
5577
- idField: options.idField,
5578
- resolveIdFilter: options.resolveIdFilter,
5579
- operationAccess: options.operationAccess,
5580
- // A defined stored parent (including {}) wins over exact runtime defaults.
5581
- // Keep only operation fallback data; resolve each access without a live lookup.
5582
- operationAccessDefaults: options.operationAccess === void 0 ? runtime.getDefaultModelOption("operationAccess") : void 0,
5583
- hydration: options.hydration,
5584
- defaults: options.defaults
5585
- },
5586
- true
5587
- );
6689
+ return captureAuthorizationConfiguration({
6690
+ catalog: captureAuthorizationFieldCatalog(model.schema, virtuals, options.documentPermissionField),
6691
+ virtualPopulateSnapshot: captureVirtualPopulateSnapshot(
6692
+ runtime,
6693
+ modelName,
6694
+ options,
6695
+ populatePolicyDefaults
6696
+ ),
6697
+ populatePolicyDefaults,
6698
+ ...resolvePopulatePolicy(options, populatePolicyDefaults),
6699
+ permissionSchema: options.permissionSchema === void 0 ? runtime.getDefaultModelOption("permissionSchema") : options.permissionSchema,
6700
+ virtuals,
6701
+ alwaysSelectFields: options.alwaysSelectFields,
6702
+ modelPermissionPrefix: options.modelPermissionPrefix,
6703
+ requireExplicitSelect: options.requireExplicitSelect,
6704
+ documentPermissionField: options.documentPermissionField,
6705
+ docPermissions: options.docPermissions,
6706
+ exposedDocPermissionKeys: options.exposedDocPermissionKeys,
6707
+ stripPermissionsField: options.stripPermissionsField,
6708
+ disableFieldPermissions: options.disableFieldPermissions,
6709
+ unsafeSkipListDocumentSnapshotChecks: options.unsafeSkipListDocumentSnapshotChecks === true,
6710
+ unsafeSkipReadDocumentSnapshotChecks: options.unsafeSkipReadDocumentSnapshotChecks === true,
6711
+ unsafeSkipListOutputSnapshotChecks: options.unsafeSkipListOutputSnapshotChecks === true,
6712
+ unsafeSkipReadOutputSnapshotChecks: options.unsafeSkipReadOutputSnapshotChecks === true,
6713
+ unsafeSkipListNestedDocumentSnapshotChecks: options.unsafeSkipListNestedDocumentSnapshotChecks === true,
6714
+ unsafeSkipReadNestedDocumentSnapshotChecks: options.unsafeSkipReadNestedDocumentSnapshotChecks === true,
6715
+ unsafeSkipListInitialOutputSnapshotCopy: options.unsafeSkipListInitialOutputSnapshotCopy === true,
6716
+ unsafeSkipReadInitialOutputSnapshotCopy: options.unsafeSkipReadInitialOutputSnapshotCopy === true,
6717
+ unsafeUseListAuthorizationFastPath: options.unsafeUseListAuthorizationFastPath === true,
6718
+ unsafeUseReadAuthorizationFastPath: options.unsafeUseReadAuthorizationFastPath === true,
6719
+ overrideFilter: options.overrideFilter,
6720
+ baseFilter: options.baseFilter,
6721
+ idField: options.idField,
6722
+ resolveIdFilter: options.resolveIdFilter,
6723
+ operationAccess: options.operationAccess,
6724
+ // A defined stored parent (including {}) wins over exact runtime defaults.
6725
+ // Keep only operation fallback data; resolve each access without a live lookup.
6726
+ operationAccessDefaults: options.operationAccess === void 0 ? runtime.getDefaultModelOption("operationAccess") : void 0,
6727
+ hydration: options.hydration,
6728
+ defaults: options.defaults
6729
+ });
5588
6730
  }
5589
6731
  function planModelOutputForHelper(args) {
5590
6732
  const { request, runtime, modelName, access } = args;
@@ -5615,6 +6757,7 @@ var init_model_output_planning = __esm({
5615
6757
  init_manager();
5616
6758
  init_field_catalog();
5617
6759
  init_authorization_snapshot();
6760
+ init_captured_authorization_configuration();
5618
6761
  init_virtual_populate_dependencies();
5619
6762
  init_document_authorization();
5620
6763
  init_output_projection();
@@ -5678,7 +6821,7 @@ function optimizeAndFilter(clausesInput) {
5678
6821
  }
5679
6822
  let canMerge = true;
5680
6823
  for (const [key, value] of Object.entries(clause)) {
5681
- if ((0, import_utils25.hasOwn)(mergedClause, key) && !(0, import_node_util8.isDeepStrictEqual)(mergedClause[key], value)) {
6824
+ if ((0, import_utils25.hasOwn)(mergedClause, key) && !(0, import_node_util9.isDeepStrictEqual)(mergedClause[key], value)) {
5682
6825
  canMerge = false;
5683
6826
  break;
5684
6827
  }
@@ -5832,11 +6975,11 @@ async function collectSchemaFields({
5832
6975
  }
5833
6976
  return fields;
5834
6977
  }
5835
- var import_utils25, import_node_util8, permissionFieldOwners;
6978
+ var import_utils25, import_node_util9, permissionFieldOwners;
5836
6979
  var init_core_shared = __esm({
5837
6980
  "src/core-shared.ts"() {
5838
6981
  import_utils25 = require("@web-ts-toolkit/utils");
5839
- import_node_util8 = require("util");
6982
+ import_node_util9 = require("util");
5840
6983
  init_helpers();
5841
6984
  init_options();
5842
6985
  init_runtime_context();
@@ -6203,10 +7346,10 @@ function projectVirtualPopulateView(source, selection, structurePaths = []) {
6203
7346
  }
6204
7347
  function equivalentVirtualPopulatePredicate(left, right) {
6205
7348
  if (Object.is(left, right)) return true;
6206
- if (left instanceof import_mongoose7.mongo.BSON.BSONValue || right instanceof import_mongoose7.mongo.BSON.BSONValue) {
6207
- if (!(left instanceof import_mongoose7.mongo.BSON.BSONValue) || !(right instanceof import_mongoose7.mongo.BSON.BSONValue)) return false;
6208
- return Buffer.from(import_mongoose7.mongo.BSON.serialize({ value: left })).equals(
6209
- Buffer.from(import_mongoose7.mongo.BSON.serialize({ value: right }))
7349
+ if (left instanceof import_mongoose8.mongo.BSON.BSONValue || right instanceof import_mongoose8.mongo.BSON.BSONValue) {
7350
+ if (!(left instanceof import_mongoose8.mongo.BSON.BSONValue) || !(right instanceof import_mongoose8.mongo.BSON.BSONValue)) return false;
7351
+ return Buffer.from(import_mongoose8.mongo.BSON.serialize({ value: left })).equals(
7352
+ Buffer.from(import_mongoose8.mongo.BSON.serialize({ value: right }))
6210
7353
  );
6211
7354
  }
6212
7355
  if (Array.isArray(left) || Array.isArray(right))
@@ -6221,7 +7364,7 @@ function equivalentVirtualPopulatePredicate(left, right) {
6221
7364
  )
6222
7365
  );
6223
7366
  }
6224
- return (0, import_node_util9.isDeepStrictEqual)(left, right);
7367
+ return (0, import_node_util10.isDeepStrictEqual)(left, right);
6225
7368
  }
6226
7369
  function createVirtualPopulateBatch(owner) {
6227
7370
  const batch = Object.freeze(/* @__PURE__ */ Object.create(null));
@@ -6596,11 +7739,11 @@ async function loadVirtualPopulateOutputRows(owner, inputs, plan, publicPopulate
6596
7739
  }
6597
7740
  return output;
6598
7741
  }
6599
- var import_mongoose7, import_node_util9, import_utils28, batches, rows, outputRows, fetchedPublicIdentities, publicViewIdentities, familyRawFetches, addressKey, storage, originalRef, copyOriginalValue, readPolicy, compatible, idKey, logUnavailable;
7742
+ var import_mongoose8, import_node_util10, import_utils28, batches, rows, outputRows, fetchedPublicIdentities, publicViewIdentities, familyRawFetches, addressKey, storage, originalRef, copyOriginalValue, readPolicy, compatible, idKey, logUnavailable;
6600
7743
  var init_virtual_populate_execution = __esm({
6601
7744
  "src/acl/virtual-populate-execution.ts"() {
6602
- import_mongoose7 = require("mongoose");
6603
- import_node_util9 = require("util");
7745
+ import_mongoose8 = require("mongoose");
7746
+ import_node_util10 = require("util");
6604
7747
  import_utils28 = require("@web-ts-toolkit/utils");
6605
7748
  init_cache();
6606
7749
  init_core_shared();
@@ -6618,7 +7761,7 @@ var init_virtual_populate_execution = __esm({
6618
7761
  publicViewIdentities = /* @__PURE__ */ new WeakMap();
6619
7762
  familyRawFetches = /* @__PURE__ */ new WeakMap();
6620
7763
  addressKey = (address) => JSON.stringify(address);
6621
- storage = (value) => value instanceof import_mongoose7.Document ? value._doc : (0, import_utils28.isPlainObject)(value) ? value : void 0;
7764
+ storage = (value) => value instanceof import_mongoose8.Document ? value._doc : (0, import_utils28.isPlainObject)(value) ? value : void 0;
6622
7765
  originalRef = (source, key) => {
6623
7766
  const record3 = storage(source);
6624
7767
  return {
@@ -6659,7 +7802,11 @@ function prepareOutputDocumentAuthorization(authorization, binding, configuratio
6659
7802
  const invariant = /^[A-Za-z0-9_-]+$/.test(access.docPermissionsAccess) && (docPermissions == null || (0, import_utils29.isPlainObject)(docPermissions));
6660
7803
  const option = invariant ? getCapturedAuthorizationOption(configuration, key) : void 0;
6661
7804
  const hook = typeof option === "function" ? option : void 0;
6662
- const resolveHook = invariant ? () => hook : () => {
7805
+ const trusted = readAuthorizationFastPath(authorization, binding)?.mode === "active";
7806
+ const resolveHook = invariant ? () => hook : trusted ? () => {
7807
+ const option2 = getCapturedAuthorizationOption(configuration, key);
7808
+ return typeof option2 === "function" ? option2 : void 0;
7809
+ } : () => {
6663
7810
  const slice = { catalog: configuration.catalog, ...copyAuthorizationValue({ docPermissions }, true) };
6664
7811
  const option2 = getCapturedAuthorizationOption(slice, key);
6665
7812
  return typeof option2 === "function" ? option2 : void 0;
@@ -6706,6 +7853,32 @@ function evaluateRequestRule(handle, binding, entry, prefix, access) {
6706
7853
  if (owner && !entry.path.startsWith(`${(binding.scopePath ?? []).join(".")}.`)) {
6707
7854
  return evaluateRequestRule(owner.handle, owner.binding, entry, prefix, access);
6708
7855
  }
7856
+ if (isTrustedDocumentAuthorization(handle, binding))
7857
+ return memoizeDocumentFieldDecision(
7858
+ handle,
7859
+ binding,
7860
+ `request:${access}:${entry.path}`,
7861
+ function(permissions, grants) {
7862
+ const { authorization } = readDocumentAuthorizationAccess(handle, binding);
7863
+ const classification = requestRuleClassification(entry, authorization, permissions, prefix);
7864
+ const allowed = classification?.decision ?? evaluateScopedAccessRuleValue({
7865
+ req: this,
7866
+ rule: entry.rule,
7867
+ globalPermissions: permissions,
7868
+ docPermissions: grants,
7869
+ modelPermissionPrefix: prefix
7870
+ });
7871
+ if (typeof allowed !== "boolean")
7872
+ return (async () => {
7873
+ const result2 = await allowed;
7874
+ assertOwningOutputDocuments(handle);
7875
+ readDocumentAuthorizationAccess(handle, binding);
7876
+ return result2;
7877
+ })();
7878
+ assertOwningOutputDocuments(handle);
7879
+ return allowed;
7880
+ }
7881
+ );
6709
7882
  return memoizeDocumentFieldDecision(
6710
7883
  handle,
6711
7884
  binding,
@@ -6732,6 +7905,32 @@ function evaluateAuthorizedOutputField(handle, binding, field) {
6732
7905
  const { authorization } = readDocumentAuthorizationAccess(handle, binding);
6733
7906
  assertOwningOutputDocuments(handle);
6734
7907
  const path = [...binding.scopePath ?? [], field].join(".");
7908
+ const trusted = isTrustedDocumentAuthorization(handle, binding);
7909
+ if (trusted)
7910
+ return memoizeDocumentFieldDecision(handle, binding, `output:${path}`, function(permissions) {
7911
+ const policy = callFieldPolicy(authorization, binding);
7912
+ const { outputAccess } = readDocumentAuthorizationAccess(handle, binding);
7913
+ const prepared = prepareOutputPath(policy, authorization, binding, path, outputAccess);
7914
+ const unresolved = isUnresolvedOutputDocument(handle);
7915
+ const state = unresolved ? prepared.state ?? classifyEffectiveFieldAuthorization({
7916
+ path,
7917
+ rules: prepared.entries.map((entry) => entry.rule),
7918
+ modelPermissionPrefix: policy.prefix,
7919
+ outputFields: policy.outputFields,
7920
+ globalPermissions: permissions
7921
+ }) : void 0;
7922
+ if (unresolved && state !== "granted") return false;
7923
+ if (prepared.backendGrant) return true;
7924
+ const finish = () => {
7925
+ assertOwningOutputDocuments(handle);
7926
+ readDocumentAuthorizationAccess(handle, binding);
7927
+ };
7928
+ return orderedRequestRules(
7929
+ prepared.entries,
7930
+ (entry) => evaluateRequestRule(handle, binding, entry, policy.prefix, outputAccess),
7931
+ finish
7932
+ );
7933
+ });
6735
7934
  const decision = memoizeDocumentFieldDecision(handle, binding, `output:${path}`, async function(permissions) {
6736
7935
  const policy = callFieldPolicy(authorization, binding);
6737
7936
  const { outputAccess } = readDocumentAuthorizationAccess(handle, binding);
@@ -6764,10 +7963,38 @@ function evaluateAuthorizedOutputField(handle, binding, field) {
6764
7963
  return allowed;
6765
7964
  }) : decision;
6766
7965
  }
7966
+ function orderedRequestRules(entries, evaluate, check) {
7967
+ for (let index = 0; index < entries.length; index++) {
7968
+ const value = evaluate(entries[index]);
7969
+ if (typeof value !== "boolean")
7970
+ return (async () => {
7971
+ if (!await value) {
7972
+ check();
7973
+ return false;
7974
+ }
7975
+ check();
7976
+ for (let next = index + 1; next < entries.length; next++) {
7977
+ const result2 = evaluate(entries[next]);
7978
+ if (!(typeof result2 === "boolean" ? result2 : await result2)) {
7979
+ check();
7980
+ return false;
7981
+ }
7982
+ check();
7983
+ }
7984
+ return true;
7985
+ })();
7986
+ if (!value) {
7987
+ check();
7988
+ return false;
7989
+ }
7990
+ }
7991
+ check();
7992
+ return true;
7993
+ }
6767
7994
  async function requestOutputFieldPaths(handle, binding, access) {
6768
7995
  const staticFields = tryStaticRequestFieldPaths(handle, binding, access);
6769
7996
  if (staticFields) {
6770
- await Promise.resolve();
7997
+ if (!isTrustedDocumentAuthorization(handle, binding)) await Promise.resolve();
6771
7998
  readDocumentAuthorizationAccess(handle, binding);
6772
7999
  return staticFields;
6773
8000
  }
@@ -6779,7 +8006,8 @@ async function requestOutputFieldPaths(handle, binding, access) {
6779
8006
  const { entries } = prepareOutputPath(policy, authorization, binding, path, access);
6780
8007
  let allowed = true;
6781
8008
  for (const entry of entries) {
6782
- if (!await evaluateRequestRule(handle, binding, entry, policy.prefix, access)) {
8009
+ const decision = evaluateRequestRule(handle, binding, entry, policy.prefix, access);
8010
+ if (!(typeof decision === "boolean" ? decision : await decision)) {
6783
8011
  allowed = false;
6784
8012
  break;
6785
8013
  }
@@ -6795,6 +8023,33 @@ function authorizeEmbeddedOutputPlan(parent, child) {
6795
8023
  ...parent.authorizationBinding,
6796
8024
  scopePath: child.responseScopePath ?? child.scopePath.filter((p) => p !== "sub")
6797
8025
  };
8026
+ assertAuthorizationBinding(parent.authorization, parent.authorizationBinding);
8027
+ if (readAuthorizationFastPath(parent.authorization, parent.authorizationBinding)?.mode === "active") {
8028
+ if (!Object.values(parent.childPlans).includes(child)) authorizationError("unknown embedded output plan");
8029
+ let scopes = embeddedPlans.get(parent);
8030
+ if (!scopes) embeddedPlans.set(parent, scopes = /* @__PURE__ */ new WeakMap());
8031
+ const previous = scopes.get(child);
8032
+ if (previous) {
8033
+ assertAuthorizationBinding(previous.authorization, binding);
8034
+ return previous;
8035
+ }
8036
+ const view2 = readServiceAuthorization(parent.authorization, parent.authorizationBinding);
8037
+ const authorization2 = deriveTrustedQueryAuthorization({
8038
+ binding,
8039
+ ...view2,
8040
+ requestPermissions: getAuthorizationPermissions(parent.authorization, parent.authorizationBinding),
8041
+ parent: parent.authorization,
8042
+ snapshotDerivation: { kind: "embedded", parentBinding: parent.authorizationBinding }
8043
+ });
8044
+ if (!authorization2) authorizationError("invalid trusted embedded edge");
8045
+ const scoped = {
8046
+ ...child,
8047
+ authorization: authorization2,
8048
+ authorizationBinding: Object.freeze({ ...binding, scopePath: Object.freeze([...binding.scopePath ?? []]) })
8049
+ };
8050
+ scopes.set(child, scoped);
8051
+ return scoped;
8052
+ }
6798
8053
  const view = readServiceAuthorization(parent.authorization, parent.authorizationBinding);
6799
8054
  const authorization = resolveServiceAuthorization({
6800
8055
  binding,
@@ -6812,11 +8067,24 @@ function hasWholeOutputValueGrant(plan, field) {
6812
8067
  const { outputFields } = readServiceOutputPolicy(plan.authorization, binding);
6813
8068
  return hasExplicitFieldGrant(outputFields, [...binding.scopePath ?? [], field].join("."));
6814
8069
  }
6815
- function copyOutputValue(value, plan, path) {
8070
+ function copyOutputValue(value, plan, path, trusted) {
6816
8071
  const { catalog } = readServiceOutputPolicy(plan.authorization, plan.authorizationBinding);
6817
8072
  const virtualValue = catalog.virtualPaths?.some((p) => matchesCatalogPattern(p, path));
6818
8073
  const opaque = catalog.opaquePaths?.some((p) => matchesCatalogPattern(p, path));
6819
8074
  const excluded = plan.effectiveSelectNorm.filter((token) => token.startsWith("-")).map((token) => [...plan.authorizationBinding.scopePath ?? [], token.slice(1)].join("."));
8075
+ if (trusted)
8076
+ return materializeTrustedOutputValue(
8077
+ value,
8078
+ path,
8079
+ trusted.budget,
8080
+ {
8081
+ keep(key, child) {
8082
+ if (excluded.some((entry) => child === entry || child.startsWith(`${entry}.`))) return false;
8083
+ return (opaque || isSafeOutputPath(key)) && !catalog.protectedPaths?.some((p) => matchesCatalogPattern(p, child, true)) && (opaque || virtualValue || isCatalogOutputPath(catalog, child));
8084
+ }
8085
+ },
8086
+ trusted.depth
8087
+ );
6820
8088
  const visit = (input, current) => {
6821
8089
  if (Array.isArray(input)) return input.map((entry) => visit(entry, current));
6822
8090
  if (input instanceof Map) return visit(Object.fromEntries(input), current);
@@ -6834,7 +8102,45 @@ function copyOutputValue(value, plan, path) {
6834
8102
  };
6835
8103
  return visit(value, path);
6836
8104
  }
6837
- function copyAuthorizedReference(value, plan, path) {
8105
+ function copyAuthorizedReference(value, plan, path, trusted) {
8106
+ if (trusted) {
8107
+ const active = /* @__PURE__ */ new WeakSet();
8108
+ const { relatedTargets } = readServiceAuthorization(plan.authorization, plan.authorizationBinding);
8109
+ const target = relatedTargets.find((entry) => entry.path === path);
8110
+ const one = (input, depth) => {
8111
+ visitTrustedOutput(trusted.budget, depth);
8112
+ if (input && typeof input === "object" && import_node_util11.types.isProxy(input)) authorizationError("unsupported selected proxy");
8113
+ if (Array.isArray(input)) {
8114
+ if (active.has(input)) authorizationError("cyclic selected output");
8115
+ active.add(input);
8116
+ try {
8117
+ return shallowTrustedOutputArray(input, trusted.budget, depth).map((entry) => one(entry, depth + 1));
8118
+ } finally {
8119
+ active.delete(input);
8120
+ }
8121
+ }
8122
+ if ((0, import_utils29.isPlainObject)(input)) {
8123
+ const handle2 = target && (!trusted.rootOutput || isIssuedOutputMember(trusted.rootOutput, input)) ? getAssociatedDocumentAuthorization(input, plan.authorization) : void 0;
8124
+ if (handle2) {
8125
+ const expected = {
8126
+ ...plan.authorizationBinding,
8127
+ model: target.model,
8128
+ modelName: target.modelName,
8129
+ scopePath: []
8130
+ };
8131
+ readDocumentAuthorizationAccess(handle2, expected);
8132
+ retainTrustedOutputMember(trusted.members, input);
8133
+ return input;
8134
+ }
8135
+ const id = Object.getOwnPropertyDescriptor(input, "_id");
8136
+ if (!id) return void 0;
8137
+ if (!("value" in id)) authorizationError("unsupported selected reference");
8138
+ return materializeTrustedOutputValue(id.value, path, trusted.budget, { keep: () => true }, depth + 1);
8139
+ }
8140
+ return materializeTrustedOutputValue(input, path, trusted.budget, { keep: () => true }, depth);
8141
+ };
8142
+ return one(value, trusted.depth);
8143
+ }
6838
8144
  if (Array.isArray(value)) return value.map((entry) => copyAuthorizedReference(entry, plan, path));
6839
8145
  if (!(0, import_utils29.isPlainObject)(value)) return deepIsolateValue(value);
6840
8146
  const handle = getAssociatedDocumentAuthorization(value, plan.authorization);
@@ -6845,13 +8151,32 @@ function copyAuthorizedReference(value, plan, path) {
6845
8151
  }
6846
8152
  return Object.prototype.hasOwnProperty.call(value, "_id") ? deepIsolateValue(value._id) : void 0;
6847
8153
  }
6848
- function retainOutputMetadata(output, source, configuration, scope2) {
8154
+ function retainOutputMetadata(output, source, configuration, scope2, trusted) {
6849
8155
  if (scope2.length || configuration.stripPermissionsField) return;
6850
8156
  const parts = (configuration.documentPermissionField ?? "_permissions").split(".");
6851
8157
  let value = source;
6852
8158
  for (const part of parts) value = (0, import_utils29.isPlainObject)(value) ? value[part] : void 0;
6853
8159
  if (!(0, import_utils29.isPlainObject)(value)) return;
6854
8160
  const keys2 = configuration.exposedDocPermissionKeys;
8161
+ if (trusted) {
8162
+ const metadata2 = {};
8163
+ for (const key of Object.keys(value)) {
8164
+ visitTrustedOutput(trusted.budget, trusted.depth + 1);
8165
+ if (key === "_view" || key === "_edit" ? configuration.disableFieldPermissions : keys2 && !keys2.includes(key))
8166
+ continue;
8167
+ defineTrustedOutputValue(metadata2, key, value[key]);
8168
+ }
8169
+ setTrustedOutputPath(
8170
+ output,
8171
+ parts.join("."),
8172
+ metadata2,
8173
+ trusted.budget,
8174
+ trusted.depth,
8175
+ (source2, copy2) => retainTrustedOutputSpine(trusted.members, source2, copy2)
8176
+ );
8177
+ attachPermissionsAlias(output, parts.join("."));
8178
+ return;
8179
+ }
6855
8180
  const metadata = Object.fromEntries(
6856
8181
  Object.entries(value).filter(
6857
8182
  ([key]) => key === "_view" || key === "_edit" ? !configuration.disableFieldPermissions : !keys2 || keys2.includes(key)
@@ -6872,7 +8197,7 @@ function helperPlan(authorization, binding) {
6872
8197
  return planAuthorizedModelProjection({ authorization, binding, effectiveSelect: [] });
6873
8198
  }
6874
8199
  function primitiveHelperFields(source, plan) {
6875
- if (import_node_util10.types.isProxy(source)) return;
8200
+ if (import_node_util11.types.isProxy(source)) return;
6876
8201
  const canonical = readStaticOutputPlanFields(plan, plan.authorization);
6877
8202
  if (!canonical) return;
6878
8203
  const fields = [];
@@ -6887,15 +8212,25 @@ function primitiveHelperFields(source, plan) {
6887
8212
  }
6888
8213
  return fields;
6889
8214
  }
6890
- async function filterExistingOutput(source, plan, handle, associated) {
8215
+ async function filterExistingOutput(source, plan, handle, associated, parentBudget, depth = 0) {
6891
8216
  const binding = plan.authorizationBinding;
8217
+ const trustedStage = isTrustedDocumentAuthorization(handle, binding);
8218
+ const budget = readAuthorizationFastPath(plan.authorization, binding)?.mode === "active" ? parentBudget ?? createTrustedOutputBudget() : void 0;
8219
+ const members = budget ? createTrustedOutputMemberBuilder(plan.authorization, binding, budget) : void 0;
8220
+ const trusted = budget && trustedStage ? {
8221
+ budget,
8222
+ members,
8223
+ depth,
8224
+ rootOutput: associated ? source : void 0
8225
+ } : void 0;
8226
+ if (trusted) visitTrustedOutput(trusted.budget, depth);
6892
8227
  const { configuration } = readServiceAuthorization(plan.authorization, binding);
6893
8228
  const output = {};
6894
8229
  const fields = [];
6895
8230
  const primitiveFields = primitiveHelperFields(source, plan);
6896
8231
  const staticDecisions = primitiveFields && tryStaticOutputFieldDecisions(handle, binding, plan, primitiveFields);
6897
8232
  if (staticDecisions) {
6898
- await Promise.resolve();
8233
+ if (!trusted) await Promise.resolve();
6899
8234
  if (associated) assertDocumentAuthorization(handle, { binding, output: source, outputAccess: plan.outputAccess });
6900
8235
  else readDocumentAuthorizationAccess(handle, binding);
6901
8236
  if (!readStaticOutputPlanFields(plan, plan.authorization)) authorizationError("changed static output plan");
@@ -6906,14 +8241,22 @@ async function filterExistingOutput(source, plan, handle, associated) {
6906
8241
  if (childPlan && !hasWholeOutputValueGrant(plan, field)) {
6907
8242
  const scoped = authorizeEmbeddedOutputPlan(plan, childPlan);
6908
8243
  const childFields = /* @__PURE__ */ new Set();
6909
- const one = async (value2) => {
8244
+ const arrays = /* @__PURE__ */ new WeakSet();
8245
+ const one = async (value2, childDepth = depth + 1) => {
6910
8246
  if (Array.isArray(value2)) {
8247
+ if (trusted && arrays.has(value2)) authorizationError("cyclic selected document output");
8248
+ const entries = trusted ? shallowTrustedOutputArray(value2, trusted.budget, childDepth) : value2;
8249
+ arrays.add(value2);
6911
8250
  const values = [];
6912
- for (const entry of value2) values.push(await one(entry) ?? null);
8251
+ try {
8252
+ for (const entry of entries) values.push(await one(entry, childDepth + 1) ?? null);
8253
+ } finally {
8254
+ arrays.delete(value2);
8255
+ }
6913
8256
  return values;
6914
8257
  }
6915
8258
  if (!(0, import_utils29.isPlainObject)(value2)) return value2 === null ? null : void 0;
6916
- const childHandle = associated ? getAssociatedDocumentAuthorization(value2) : void 0;
8259
+ const childHandle = associated ? trusted ? getIssuedEmbeddedDocumentAuthorization(source, value2, handle, scoped.authorizationBinding) : getAssociatedDocumentAuthorization(value2) : void 0;
6917
8260
  let child = scoped;
6918
8261
  if (childHandle) {
6919
8262
  const state = readDocumentAuthorizationAccess(childHandle, scoped.authorizationBinding);
@@ -6921,10 +8264,12 @@ async function filterExistingOutput(source, plan, handle, associated) {
6921
8264
  authorizationError("child call mismatch");
6922
8265
  child = helperPlan(state.authorization, scoped.authorizationBinding);
6923
8266
  }
8267
+ const prepared = !childHandle && trusted ? prepareQueryDocumentAuthorization(child.authorization, child.authorizationBinding, value2) : void 0;
6924
8268
  const resolved = childHandle ?? await resolveOutputDocumentAuthorization({
6925
8269
  authorization: child.authorization,
6926
8270
  binding: child.authorizationBinding,
6927
- snapshot: isolateDocForOutput(value2),
8271
+ snapshot: prepared?.source ?? isolateDocForOutput(value2),
8272
+ stage: prepared?.stage,
6928
8273
  context: {
6929
8274
  modelName: binding.modelName,
6930
8275
  mongooseModel: binding.model,
@@ -6933,27 +8278,48 @@ async function filterExistingOutput(source, plan, handle, associated) {
6933
8278
  owningDocument: handle,
6934
8279
  owningBinding: binding
6935
8280
  });
6936
- const result2 = await filterExistingOutput(value2, child, resolved, !!childHandle);
8281
+ const result2 = await filterExistingOutput(
8282
+ prepared?.source ?? value2,
8283
+ child,
8284
+ resolved,
8285
+ !!childHandle,
8286
+ budget,
8287
+ childDepth
8288
+ );
8289
+ if (members) retainTrustedOutputMember(members, result2.output);
6937
8290
  result2.fields.forEach((path) => childFields.add(`${field}.${path}`));
6938
8291
  return result2.output;
6939
8292
  };
6940
- const value = await one(source[field]);
6941
- if (value !== void 0) output[field] = value;
8293
+ const value = await one(
8294
+ trusted ? trustedMapOutputScope(source[field], childPlan.outputPersistedFields, trusted.budget, depth + 1) : source[field]
8295
+ );
8296
+ if (value !== void 0) {
8297
+ if (trusted) defineTrustedOutputValue(output, field, value);
8298
+ else output[field] = value;
8299
+ }
6942
8300
  fields.push(...childFields);
6943
8301
  } else if (staticDecisions ? staticDecisions.get(field) === true : await evaluateAuthorizedOutputField(handle, binding, field)) {
6944
8302
  const path = [...binding.scopePath ?? [], field].join(".");
6945
- output[field] = configuration.catalog.referencePaths?.some((p) => matchesCatalogPattern(p, path)) ? copyAuthorizedReference(source[field], plan, path) : copyOutputValue(source[field], plan, path);
6946
- if (associated) transferDocumentAuthorizationGraph(source[field], output[field]);
8303
+ const value = configuration.catalog.referencePaths?.some((p) => matchesCatalogPattern(p, path)) ? copyAuthorizedReference(source[field], plan, path, trusted) : copyOutputValue(source[field], plan, path, trusted);
8304
+ if (trusted) defineTrustedOutputValue(output, field, value);
8305
+ else output[field] = value;
8306
+ if (associated && !trusted) transferDocumentAuthorizationGraph(source[field], output[field]);
6947
8307
  if (output[field] !== void 0) fields.push(field);
6948
8308
  else delete output[field];
6949
8309
  }
6950
8310
  }
6951
8311
  if (plan.fetchIdRetained && Object.prototype.hasOwnProperty.call(source, "_id")) {
6952
- output._id = deepIsolateValue(source._id);
8312
+ const id = trusted ? materializeTrustedOutputValue(source._id, "_id", trusted.budget, { keep: () => true }, depth + 1) : deepIsolateValue(source._id);
8313
+ if (trusted) defineTrustedOutputValue(output, "_id", id);
8314
+ else output._id = id;
6953
8315
  fields.push("_id");
6954
8316
  }
6955
- retainOutputMetadata(output, source, configuration, binding.scopePath ?? []);
6956
- if (associated)
8317
+ retainOutputMetadata(output, source, configuration, binding.scopePath ?? [], trusted);
8318
+ if (trusted) associateDocumentAuthorization(handle, binding, output, trusted.members);
8319
+ else if (members) {
8320
+ if (associated) assertDocumentAuthorization(handle, { binding, output: source, outputAccess: plan.outputAccess });
8321
+ associateDocumentAuthorization(handle, binding, output, members);
8322
+ } else if (associated)
6957
8323
  transferDocumentAuthorization(
6958
8324
  handle,
6959
8325
  { binding, output: source, outputAccess: plan.outputAccess, authorization: plan.authorization },
@@ -6970,7 +8336,7 @@ async function filterModelOutputForHelper(args) {
6970
8336
  const normalized = normalizeOutputAuthorizationOptions(
6971
8337
  {
6972
8338
  binding: receiver,
6973
- configuration: captureModelAuthorizationConfiguration(runtime, modelName),
8339
+ configuration: () => captureModelAuthorizationConfiguration(runtime, modelName),
6974
8340
  requestPermissions: args.permissions,
6975
8341
  access: { operation: access, virtualAccess: access, outputAccess: access, docPermissionsAccess: access }
6976
8342
  },
@@ -7003,10 +8369,10 @@ async function filterModelOutputForHelper(args) {
7003
8369
  });
7004
8370
  return filterExistingOutput(source, plan, handle, false);
7005
8371
  }
7006
- var import_node_util10, import_utils29;
8372
+ var import_node_util11, import_utils29, embeddedPlans;
7007
8373
  var init_output_field_filter = __esm({
7008
8374
  "src/acl/output-field-filter.ts"() {
7009
- import_node_util10 = require("util");
8375
+ import_node_util11 = require("util");
7010
8376
  import_utils29 = require("@web-ts-toolkit/utils");
7011
8377
  init_permissions_alias();
7012
8378
  init_document();
@@ -7020,6 +8386,8 @@ var init_output_field_filter = __esm({
7020
8386
  init_field_catalog();
7021
8387
  init_output_projection();
7022
8388
  init_output_field_policy();
8389
+ init_trusted_output_materialization();
8390
+ embeddedPlans = /* @__PURE__ */ new WeakMap();
7023
8391
  }
7024
8392
  });
7025
8393
 
@@ -7102,19 +8470,31 @@ function prepareFinalizer(args, sharedContext = false) {
7102
8470
  const { authorization, authorizationBinding: binding } = args.plan;
7103
8471
  const policy = authorization && binding ? readServiceOutputPolicy(authorization, binding) : void 0;
7104
8472
  assertFinalizerCall(args, { authorization, policy });
8473
+ const trustedCall = !!authorization && readAuthorizationFastPath(authorization, binding)?.mode === "active";
8474
+ const reusable = trustedCall ? trustedFinalizerScopes.get(args.plan) : void 0;
8475
+ if (reusable) {
8476
+ if (reusable.authorization !== authorization) authorizationError("changed trusted finalizer scope");
8477
+ return { ...reusable, baseContext: { ...args.context }, sharedContext };
8478
+ }
7105
8479
  const configuration = authorization ? readServiceFinalizerConfiguration(authorization, binding) : void 0;
7106
8480
  const snapshot = configuration ? configuration : deepIsolateValue(args.snapshot);
7107
- return {
8481
+ const prepared = {
7108
8482
  authorization,
7109
8483
  policy,
7110
8484
  snapshot,
7111
- baseContext: deepIsolateValue(args.context ?? {}),
8485
+ baseContext: trustedCall ? { ...args.context } : deepIsolateValue(args.context ?? {}),
7112
8486
  sharedContext,
7113
8487
  scopeVirtualNames: getScopeVirtualNames(snapshot, args.scopePath),
7114
8488
  scopedSchema: configuration ? null : getScopedPermissionSchema2(snapshot.permissionSchema, args.scopePath),
7115
8489
  permissions: authorization ? getAuthorizationPermissions(authorization, binding) : void 0,
7116
- resolveDocument: authorization ? prepareOutputDocumentAuthorization(authorization, binding, configuration) : void 0
8490
+ resolveDocument: authorization ? prepareOutputDocumentAuthorization(authorization, binding, configuration) : void 0,
8491
+ trustedCall
7117
8492
  };
8493
+ if (trustedCall) {
8494
+ const { baseContext: _context, sharedContext: _shared, ...scope2 } = prepared;
8495
+ trustedFinalizerScopes.set(args.plan, scope2);
8496
+ }
8497
+ return prepared;
7118
8498
  }
7119
8499
  async function finalizeSingleDoc(args, input, prepared) {
7120
8500
  assertFinalizerCall(args, prepared);
@@ -7125,16 +8505,32 @@ async function finalizeSingleDoc(args, input, prepared) {
7125
8505
  const snapshot = prepared.snapshot;
7126
8506
  const limit = args.resolvedLimit;
7127
8507
  const gate = args.sharedGate;
7128
- const original = getIncludeOriginal(input);
8508
+ const original = getIncludeOriginal(input, prepared.authorization);
7129
8509
  const privateRow = args.virtualPopulateRow ?? (original && typeof original === "object" ? getVirtualPopulateRow(original) : void 0);
7130
8510
  const privateAddress = args.virtualPopulateAddress ?? [];
7131
- const isolated = isolateDocForOutput(input);
7132
- const output = (0, import_utils30.isPlainObject)(isolated) ? isolated : {};
7133
- if (captured && (0, import_utils30.isPlainObject)(input))
8511
+ const querySource = captured && !args.documentAuthorizationStage ? prepareQueryDocumentAuthorization(plan.authorization, binding, input) : void 0;
8512
+ const stage = args.documentAuthorizationStage ?? querySource?.stage;
8513
+ const source = querySource?.source ?? input;
8514
+ const trustedSource = !!stage && isTrustedDocumentAuthorizationStage(stage, plan.authorization, binding);
8515
+ const budget = prepared.trustedCall ? args.materialization?.budget ?? args.trustedOutputBudget ?? querySource?.budget ?? createTrustedOutputBudget() : void 0;
8516
+ const depth = args.materialization?.depth ?? 0;
8517
+ const lineage = args.materialization?.lineage ?? /* @__PURE__ */ new Set();
8518
+ if (budget) {
8519
+ visitTrustedOutput(budget, depth);
8520
+ if (source && typeof source === "object" && lineage.has(source))
8521
+ authorizationError("cyclic selected document output");
8522
+ }
8523
+ const nextLineage = new Set(lineage);
8524
+ if (source && typeof source === "object") nextLineage.add(source);
8525
+ const members = budget ? createTrustedOutputMemberBuilder(plan.authorization, binding, budget) : void 0;
8526
+ const trusted = trustedSource ? { budget, members, depth } : void 0;
8527
+ const isolated = trustedSource ? void 0 : isolateDocForOutput(source);
8528
+ let output = (0, import_utils30.isPlainObject)(isolated) ? isolated : {};
8529
+ if (captured && !trustedSource && (0, import_utils30.isPlainObject)(input))
7134
8530
  for (const key of Object.keys(output)) {
7135
8531
  transferDocumentAuthorizationGraph(input[key], output[key]);
7136
8532
  }
7137
- const baseContext = prepared.sharedContext ? deepIsolateValue(prepared.baseContext) : prepared.baseContext;
8533
+ const baseContext = prepared.trustedCall ? { ...prepared.baseContext } : prepared.sharedContext ? deepIsolateValue(prepared.baseContext) : prepared.baseContext;
7138
8534
  const operation = captured?.access.operation ?? baseContext.operation ?? args.operation ?? args.virtualAccess;
7139
8535
  const scopeContext = {
7140
8536
  ...baseContext,
@@ -7150,21 +8546,22 @@ async function finalizeSingleDoc(args, input, prepared) {
7150
8546
  let documentAuthorization;
7151
8547
  let metadataSource = output;
7152
8548
  if (captured) {
7153
- const projected = args.documentAuthorizationStage ? input : deepIsolateValue(output);
7154
- metadataSource = deepIsolateValue(output);
8549
+ const projected = stage ? source : deepIsolateValue(output);
8550
+ metadataSource = trustedSource ? source : deepIsolateValue(output);
7155
8551
  documentAuthorization = await prepared.resolveDocument({
7156
8552
  authorization: plan.authorization,
7157
8553
  binding,
7158
8554
  snapshot: projected,
7159
8555
  context: scopeContext,
7160
- stage: args.documentAuthorizationStage,
8556
+ stage,
7161
8557
  owningDocument: args.owningDocument,
7162
8558
  owningBinding: args.owningBinding,
7163
8559
  knownOutput: !args.documentAuthorizationStage && !!input && typeof input === "object" && isKnownAuthorizationOutput(input)
7164
8560
  });
7165
8561
  }
7166
8562
  const docGrants = documentAuthorization ? readDocumentAuthorization(documentAuthorization, binding).grants : await resolveDocPermissions(args, output, scopeContext);
7167
- scopeContext.docPermissions = deepIsolateValue(docGrants);
8563
+ if (trusted) output = shallowTrustedOutput(source, trusted.budget, depth);
8564
+ scopeContext.docPermissions = trusted ? docGrants : deepIsolateValue(docGrants);
7168
8565
  const globalPerms = prepared.permissions ?? resolveGlobalPermissions(args);
7169
8566
  const modelPermissionPrefix = captured ? "" : deepIsolateValue(snapshot.modelPermissionPrefix ?? "");
7170
8567
  const documentPermissionField = captured ? "_permissions" : deepIsolateValue(snapshot.documentPermissionField ?? "_permissions");
@@ -7172,21 +8569,26 @@ async function finalizeSingleDoc(args, input, prepared) {
7172
8569
  const childPlans = plan.childPlans ?? {};
7173
8570
  for (const [containerName, childPlan] of Object.entries(childPlans)) {
7174
8571
  if (!(containerName in output)) continue;
7175
- const rawContainer = output[containerName];
8572
+ let rawContainer = output[containerName];
7176
8573
  if (rawContainer === void 0 || rawContainer === null) continue;
7177
8574
  if (captured && hasWholeOutputValueGrant(plan, containerName)) {
7178
8575
  output[containerName] = copyOutputValue(
7179
8576
  rawContainer,
7180
8577
  plan,
7181
- [...binding.scopePath ?? [], containerName].join(".")
8578
+ [...binding.scopePath ?? [], containerName].join("."),
8579
+ trusted
7182
8580
  );
7183
8581
  continue;
7184
8582
  }
8583
+ if (trusted)
8584
+ rawContainer = trustedMapOutputScope(rawContainer, childPlan.outputPersistedFields, trusted.budget, depth + 1);
7185
8585
  if (captured && !(0, import_utils30.isPlainObject)(rawContainer) && !Array.isArray(rawContainer)) {
8586
+ if (trusted && (typeof rawContainer === "object" || typeof rawContainer === "function" || typeof rawContainer === "symbol"))
8587
+ authorizationError("unsupported selected embedded value");
7186
8588
  delete output[containerName];
7187
8589
  continue;
7188
8590
  }
7189
- retainRawAssociation(output, containerName, rawContainer);
8591
+ if (!trusted) retainRawAssociation(output, containerName, rawContainer);
7190
8592
  const childBase = {
7191
8593
  ...args,
7192
8594
  scopePath: [...childPlan.scopePath ?? [...scopePath, containerName, "sub"]],
@@ -7199,16 +8601,34 @@ async function finalizeSingleDoc(args, input, prepared) {
7199
8601
  context: scopeContext,
7200
8602
  documentAuthorizationStage: void 0,
7201
8603
  onFinalized: void 0,
8604
+ completeTrustedOutput: void 0,
8605
+ trustedOutputBudget: void 0,
7202
8606
  owningDocument: documentAuthorization,
7203
8607
  owningBinding: binding,
7204
8608
  related: [],
7205
- virtualPopulateRow: privateRow
8609
+ virtualPopulateRow: privateRow,
8610
+ materialization: budget ? { budget, depth: depth + 1, lineage: nextLineage } : void 0
7206
8611
  };
7207
8612
  let childPreparation;
7208
- const finalizeOneChild = async (rawChild, address) => {
7209
- if (captured && Array.isArray(rawChild))
7210
- return mapWithConcurrencyLimit(rawChild, limit, (entry, index) => finalizeOneChild(entry, [...address, index]));
7211
- if (!(0, import_utils30.isPlainObject)(rawChild) && !Array.isArray(rawChild)) return captured ? null : deepIsolateValue(rawChild);
8613
+ const finalizeOneChild = async (rawChild, address, childDepth = depth + 1, childLineage = nextLineage) => {
8614
+ if (budget) visitTrustedOutput(budget, childDepth);
8615
+ if (captured && Array.isArray(rawChild)) {
8616
+ if (budget) {
8617
+ if (childLineage.has(rawChild)) authorizationError("cyclic selected document output");
8618
+ }
8619
+ const arrayLineage = new Set(childLineage);
8620
+ arrayLineage.add(rawChild);
8621
+ return mapWithConcurrencyLimit(
8622
+ budget ? shallowTrustedOutputArray(rawChild, budget, childDepth) : rawChild,
8623
+ limit,
8624
+ (entry, index) => finalizeOneChild(entry, [...address, index], childDepth + 1, arrayLineage)
8625
+ );
8626
+ }
8627
+ if (!(0, import_utils30.isPlainObject)(rawChild) && !Array.isArray(rawChild)) {
8628
+ if (trusted && rawChild != null && (typeof rawChild === "object" || typeof rawChild === "function" || typeof rawChild === "symbol"))
8629
+ authorizationError("unsupported selected embedded value");
8630
+ return captured ? null : deepIsolateValue(rawChild);
8631
+ }
7212
8632
  if (args.traversal?.finalizeEmbeddedChildren) {
7213
8633
  return args.traversal.finalizeEmbeddedChildren({
7214
8634
  containerName,
@@ -7225,18 +8645,24 @@ async function finalizeSingleDoc(args, input, prepared) {
7225
8645
  } : { ...args, virtualPopulateRow: privateRow, virtualPopulateAddress: address }
7226
8646
  });
7227
8647
  }
7228
- return finalizeSingleDoc(
7229
- { ...childBase, virtualPopulateAddress: address },
8648
+ const finalized = await finalizeSingleDoc(
8649
+ {
8650
+ ...childBase,
8651
+ virtualPopulateAddress: address,
8652
+ materialization: budget ? { budget, depth: childDepth, lineage: childLineage } : void 0
8653
+ },
7230
8654
  rawChild,
7231
8655
  childPreparation ??= prepareFinalizer(
7232
8656
  childBase,
7233
8657
  Array.isArray(rawContainer) && (rawContainer.length > 1 || Array.isArray(rawContainer[0]))
7234
8658
  )
7235
8659
  );
8660
+ if (members) retainTrustedOutputMember(members, finalized);
8661
+ return finalized;
7236
8662
  };
7237
8663
  if (Array.isArray(rawContainer)) {
7238
8664
  const finalized = await mapWithConcurrencyLimit(
7239
- rawContainer,
8665
+ budget ? shallowTrustedOutputArray(rawContainer, budget, depth + 1) : rawContainer,
7240
8666
  limit,
7241
8667
  (entry, index) => finalizeOneChild(entry, [...privateAddress, containerName, index])
7242
8668
  );
@@ -7262,7 +8688,7 @@ async function finalizeSingleDoc(args, input, prepared) {
7262
8688
  if (typeof rawRelated === "string" || typeof rawRelated === "number" || typeof rawRelated === "bigint") continue;
7263
8689
  const bsontype = rawRelated?._bsontype;
7264
8690
  if (typeof bsontype === "string") continue;
7265
- retainRawAssociation(output, target.path, rawRelated);
8691
+ if (!trusted) retainRawAssociation(output, target.path, rawRelated);
7266
8692
  const relatedBase = {
7267
8693
  ...args,
7268
8694
  receivingModelName: target.plan.receivingModelName ?? args.receivingModelName,
@@ -7277,6 +8703,8 @@ async function finalizeSingleDoc(args, input, prepared) {
7277
8703
  docPermissions: void 0,
7278
8704
  documentAuthorizationStage: void 0,
7279
8705
  onFinalized: void 0,
8706
+ completeTrustedOutput: void 0,
8707
+ trustedOutputBudget: void 0,
7280
8708
  owningDocument: void 0,
7281
8709
  owningBinding: void 0,
7282
8710
  virtualPopulateRow: void 0,
@@ -7288,7 +8716,7 @@ async function finalizeSingleDoc(args, input, prepared) {
7288
8716
  const finalizeOneRelated = async (rawChild, originalChild = rawChild) => {
7289
8717
  if (!(0, import_utils30.isPlainObject)(rawChild) && !Array.isArray(rawChild)) return rawChild;
7290
8718
  if (typeof rawChild?._bsontype === "string") return rawChild;
7291
- const childOriginal = getIncludeOriginal(originalChild);
8719
+ const childOriginal = getIncludeOriginal(originalChild, target.plan.authorization);
7292
8720
  const childRow = childOriginal && typeof childOriginal === "object" ? getVirtualPopulateRow(childOriginal) : void 0;
7293
8721
  if (args.traversal?.finalizeRelatedValue) {
7294
8722
  return args.traversal.finalizeRelatedValue({
@@ -7298,11 +8726,13 @@ async function finalizeSingleDoc(args, input, prepared) {
7298
8726
  parentArgs: { ...args, virtualPopulateRow: childRow, virtualPopulateAddress: [] }
7299
8727
  });
7300
8728
  }
7301
- return finalizeSingleDoc(
8729
+ const finalized2 = await finalizeSingleDoc(
7302
8730
  { ...relatedBase, virtualPopulateRow: childRow },
7303
8731
  rawChild,
7304
8732
  relatedPreparation ??= prepareFinalizer(relatedBase, Array.isArray(rawRelated) && rawRelated.length > 1)
7305
8733
  );
8734
+ if (members) retainTrustedOutputMember(members, finalized2);
8735
+ return finalized2;
7306
8736
  };
7307
8737
  let finalized;
7308
8738
  if (Array.isArray(rawRelated)) {
@@ -7317,7 +8747,16 @@ async function finalizeSingleDoc(args, input, prepared) {
7317
8747
  continue;
7318
8748
  }
7319
8749
  try {
7320
- if (target.path.includes(".")) (0, import_utils30.set)(output, target.path, finalized);
8750
+ if (trusted)
8751
+ setTrustedOutputPath(
8752
+ output,
8753
+ target.path,
8754
+ finalized,
8755
+ trusted.budget,
8756
+ depth,
8757
+ (source2, copy) => retainTrustedOutputSpine(trusted.members, source2, copy)
8758
+ );
8759
+ else if (target.path.includes(".")) (0, import_utils30.set)(output, target.path, finalized);
7321
8760
  else output[target.path] = finalized;
7322
8761
  } catch {
7323
8762
  }
@@ -7341,7 +8780,8 @@ async function finalizeSingleDoc(args, input, prepared) {
7341
8780
  for (const dep of dependsOn) {
7342
8781
  if (typeof dep !== "string" || isAbsentDependency(stableBase ?? output, dep)) return;
7343
8782
  }
7344
- const allowed = documentAuthorization ? await evaluateAuthorizedOutputField(documentAuthorization, binding, candidate.name) : await evaluateEffectiveFieldAuthorization({
8783
+ const candidateDecision = documentAuthorization ? evaluateAuthorizedOutputField(documentAuthorization, binding, candidate.name) : void 0;
8784
+ const allowed = documentAuthorization ? typeof candidateDecision === "boolean" ? candidateDecision : await candidateDecision : await evaluateEffectiveFieldAuthorization({
7345
8785
  req: args.request,
7346
8786
  path: candidate.name,
7347
8787
  rules: [extractScopedOutputRule(scopedSchema, candidate.name, args.outputAccess)],
@@ -7356,8 +8796,8 @@ async function finalizeSingleDoc(args, input, prepared) {
7356
8796
  if (!privateInputs.available) return;
7357
8797
  const isolatedView = deepIsolateValue(stableBase ??= deepIsolateValue(output));
7358
8798
  const virtualContext = {
7359
- ...deepIsolateValue(scopeContext),
7360
- docPermissions: deepIsolateValue(docGrants)
8799
+ ...trusted ? scopeContext : deepIsolateValue(scopeContext),
8800
+ docPermissions: trusted ? docGrants : deepIsolateValue(docGrants)
7361
8801
  };
7362
8802
  const outcome = await runVirtualGetter({
7363
8803
  req: args.request,
@@ -7378,7 +8818,15 @@ async function finalizeSingleDoc(args, input, prepared) {
7378
8818
  });
7379
8819
  if (!outcome.ok) return;
7380
8820
  if (outcome.value === void 0) return;
7381
- staged.set(candidate.name, deepIsolateValue(outcome.value));
8821
+ if (trusted) {
8822
+ try {
8823
+ staged.set(
8824
+ candidate.name,
8825
+ copyOutputValue(outcome.value, plan, [...binding.scopePath ?? [], candidate.name].join("."), trusted)
8826
+ );
8827
+ } catch {
8828
+ }
8829
+ } else staged.set(candidate.name, deepIsolateValue(outcome.value));
7382
8830
  };
7383
8831
  await mapWithConcurrencyLimit(
7384
8832
  candidates,
@@ -7389,7 +8837,8 @@ async function finalizeSingleDoc(args, input, prepared) {
7389
8837
  );
7390
8838
  for (const [name, stagedValue] of staged) {
7391
8839
  try {
7392
- setDocValue(output, name, stagedValue);
8840
+ if (trusted) defineTrustedOutputValue(output, name, stagedValue);
8841
+ else setDocValue(output, name, stagedValue);
7393
8842
  } catch {
7394
8843
  if (name in output) delete output[name];
7395
8844
  }
@@ -7398,7 +8847,7 @@ async function finalizeSingleDoc(args, input, prepared) {
7398
8847
  const eligibleVirtuals = new Set(plan.outputVirtualNames ?? []);
7399
8848
  const staticDecisions = documentAuthorization ? tryStaticOutputFieldDecisions(documentAuthorization, binding, plan, [...eligiblePersisted]) : void 0;
7400
8849
  if (staticDecisions) {
7401
- await Promise.resolve();
8850
+ if (!trusted) await Promise.resolve();
7402
8851
  assertFinalizerCall(args, prepared);
7403
8852
  readDocumentAuthorizationAccess(documentAuthorization, binding);
7404
8853
  if (!readStaticOutputPlanFields(plan, prepared.authorization)) authorizationError("changed static output plan");
@@ -7406,8 +8855,11 @@ async function finalizeSingleDoc(args, input, prepared) {
7406
8855
  const allowedPersisted = [];
7407
8856
  for (const field of eligiblePersisted) {
7408
8857
  if (documentAuthorization) {
7409
- if (plan.childPlans[field] || (staticDecisions ? staticDecisions.get(field) === true : await evaluateAuthorizedOutputField(documentAuthorization, binding, field)))
7410
- allowedPersisted.push(field);
8858
+ if (plan.childPlans[field]) allowedPersisted.push(field);
8859
+ else {
8860
+ const decision = staticDecisions ? staticDecisions.get(field) === true : evaluateAuthorizedOutputField(documentAuthorization, binding, field);
8861
+ if (typeof decision === "boolean" ? decision : await decision) allowedPersisted.push(field);
8862
+ }
7411
8863
  continue;
7412
8864
  }
7413
8865
  const rule = extractScopedOutputRule(scopedSchema, field, args.outputAccess);
@@ -7452,28 +8904,37 @@ async function finalizeSingleDoc(args, input, prepared) {
7452
8904
  }
7453
8905
  }
7454
8906
  if (!(key in output)) continue;
7455
- if (captured && !plan.childPlans[key]) {
8907
+ if (trusted && staged.has(key)) {
8908
+ defineTrustedOutputValue(trimmed, key, output[key]);
8909
+ } else if (captured && !plan.childPlans[key]) {
7456
8910
  const path = [...binding.scopePath ?? [], key].join(".");
7457
- trimmed[key] = captured.catalog.referencePaths?.some((p) => matchesCatalogPattern(p, path)) ? copyAuthorizedReference(output[key], plan, path) : copyOutputValue(output[key], plan, path);
8911
+ const value = captured.catalog.referencePaths?.some((p) => matchesCatalogPattern(p, path)) ? copyAuthorizedReference(output[key], plan, path, trusted) : copyOutputValue(output[key], plan, path, trusted);
8912
+ if (trusted) defineTrustedOutputValue(trimmed, key, value);
8913
+ else trimmed[key] = value;
7458
8914
  if (trimmed[key] === void 0) delete trimmed[key];
7459
- } else trimmed[key] = output[key];
8915
+ } else if (trusted) defineTrustedOutputValue(trimmed, key, output[key]);
8916
+ else trimmed[key] = output[key];
7460
8917
  }
7461
8918
  if (documentAuthorization) {
7462
- retainOutputMetadata(
7463
- trimmed,
7464
- metadataSource,
7465
- copyAuthorizationValue(
7466
- {
7467
- documentPermissionField: snapshot.documentPermissionField,
7468
- stripPermissionsField: snapshot.stripPermissionsField,
7469
- exposedDocPermissionKeys: snapshot.exposedDocPermissionKeys,
7470
- disableFieldPermissions: snapshot.disableFieldPermissions
7471
- },
7472
- true
7473
- ),
7474
- binding.scopePath ?? []
7475
- );
7476
- associateDocumentAuthorization(documentAuthorization, binding, trimmed);
8919
+ if (trusted && args.completeTrustedOutput)
8920
+ await args.completeTrustedOutput(trimmed, documentAuthorization, trusted);
8921
+ else
8922
+ retainOutputMetadata(
8923
+ trimmed,
8924
+ metadataSource,
8925
+ trusted ? snapshot : copyAuthorizationValue(
8926
+ {
8927
+ documentPermissionField: snapshot.documentPermissionField,
8928
+ stripPermissionsField: snapshot.stripPermissionsField,
8929
+ exposedDocPermissionKeys: snapshot.exposedDocPermissionKeys,
8930
+ disableFieldPermissions: snapshot.disableFieldPermissions
8931
+ },
8932
+ true
8933
+ ),
8934
+ binding.scopePath ?? [],
8935
+ trusted
8936
+ );
8937
+ associateDocumentAuthorization(documentAuthorization, binding, trimmed, members);
7477
8938
  args.onFinalized?.(
7478
8939
  trimmed,
7479
8940
  createServiceOutputContext(scopeContext, documentAuthorization, {
@@ -7535,7 +8996,7 @@ async function finalizeModelOutputs(args) {
7535
8996
  );
7536
8997
  });
7537
8998
  }
7538
- var import_utils30, isVirtualContainerValue3, getScopeVirtualsObject2, getScopeVirtualNames, getScopedPermissionSchema2, resolveGlobalPermissions, resolveDocPermissions, isAbsentDependency, __finalizeInternals;
8999
+ var import_utils30, trustedFinalizerScopes, isVirtualContainerValue3, getScopeVirtualsObject2, getScopeVirtualNames, getScopedPermissionSchema2, resolveGlobalPermissions, resolveDocPermissions, isAbsentDependency, __finalizeInternals;
7539
9000
  var init_finalize_model_output = __esm({
7540
9001
  "src/output/finalize-model-output.ts"() {
7541
9002
  import_utils30 = require("@web-ts-toolkit/utils");
@@ -7552,6 +9013,8 @@ var init_finalize_model_output = __esm({
7552
9013
  init_output_projection();
7553
9014
  init_virtual_populate_execution();
7554
9015
  init_include_output();
9016
+ init_trusted_output_materialization();
9017
+ trustedFinalizerScopes = /* @__PURE__ */ new WeakMap();
7555
9018
  isVirtualContainerValue3 = (value) => (0, import_utils30.isPlainObject)(value) && "sub" in value;
7556
9019
  getScopeVirtualsObject2 = (rootVirtuals, scopePath) => {
7557
9020
  if (!rootVirtuals || !(0, import_utils30.isPlainObject)(rootVirtuals)) return null;
@@ -7800,6 +9263,7 @@ init_document_authorization();
7800
9263
  // src/acl/field-helper-options.ts
7801
9264
  init_authorization_snapshot();
7802
9265
  init_field_catalog();
9266
+ init_public_admission();
7803
9267
  function assertFieldHelperCall(helper, count, maximum, options, family = "model") {
7804
9268
  const replacement = family === "model" ? "Use named output options (authorization.outputFields or documentAuthorization), and scopePath for scope." : family === "data" ? "Use named DataFieldOptions ({ scopePath }); data helpers are request-only and legacy elevation is unsupported." : "Use named PopulatePlanningOptions ({ scopePath }); genPopulate is request-only.";
7805
9269
  const removed = () => {
@@ -7809,12 +9273,14 @@ function assertFieldHelperCall(helper, count, maximum, options, family = "model"
7809
9273
  throw error2;
7810
9274
  };
7811
9275
  if (count > maximum || options === null || typeof options !== "object" || Array.isArray(options)) removed();
9276
+ assertNoServerModelControls(options, authorizationError);
7812
9277
  const value = authorizationRecord(options, `${helper} options`);
7813
9278
  for (const key of ["skipChecks", "subPaths", "baseFields"]) {
7814
9279
  if (key in value) removed();
7815
9280
  }
7816
9281
  }
7817
9282
  function requestFieldScope(options) {
9283
+ assertNoServerModelControls(options, authorizationError);
7818
9284
  const value = authorizationRecord(options, "request field options");
7819
9285
  for (const key of Reflect.ownKeys(value)) {
7820
9286
  const descriptor = Object.getOwnPropertyDescriptor(value, key);
@@ -8398,6 +9864,7 @@ init_populate_policy2();
8398
9864
  var cores = /* @__PURE__ */ new WeakMap();
8399
9865
  var construction = new import_node_async_hooks4.AsyncLocalStorage();
8400
9866
  var dispatch = new import_node_async_hooks4.AsyncLocalStorage();
9867
+ var queryEntries = /* @__PURE__ */ new Set(["find", "findOne", "findById", "_list", "_read", "_readFilter"]);
8401
9868
  var operationGuard = new import_node_async_hooks4.AsyncLocalStorage();
8402
9869
  function withCapturedModelOperationGuard(core, modelName, access, guard2, permissions, run) {
8403
9870
  return operationGuard.run({ captured: { core, modelName, access, guard: guard2, permissions } }, run);
@@ -8441,7 +9908,7 @@ function bindModelOwnerMethods(receiver, runtime) {
8441
9908
  writable: true,
8442
9909
  value: (...args) => runWithRuntime(runtime, () => {
8443
9910
  const invoke = () => Reflect.apply(method, receiver, args);
8444
- return dispatch.getStore()?.receiver === receiver ? invoke() : dispatch.run({ receiver }, invoke);
9911
+ return dispatch.getStore()?.receiver === receiver && !queryEntries.has(key) ? invoke() : dispatch.run({ receiver }, invoke);
8445
9912
  })
8446
9913
  });
8447
9914
  }
@@ -8463,7 +9930,7 @@ function modelServicePopulatePolicyDefaults(receiver, runtime) {
8463
9930
  init_request_work();
8464
9931
 
8465
9932
  // src/services/grouped-count.ts
8466
- var import_mongoose6 = require("mongoose");
9933
+ var import_mongoose7 = require("mongoose");
8467
9934
  init_authorization_snapshot();
8468
9935
  var MAX_GROUPS = 1e3;
8469
9936
  var MAX_KEYS = 1e4;
@@ -8510,10 +9977,10 @@ var KeyBudget = class {
8510
9977
  charge(8);
8511
9978
  } else if (Buffer.isBuffer(input)) {
8512
9979
  charge(input.length);
8513
- } else if (input instanceof import_mongoose6.mongo.BSON.BSONValue) {
8514
- if (input instanceof import_mongoose6.mongo.BSON.Code || input instanceof import_mongoose6.mongo.BSON.DBRef || input instanceof import_mongoose6.mongo.BSON.BSONRegExp)
9980
+ } else if (input instanceof import_mongoose7.mongo.BSON.BSONValue) {
9981
+ if (input instanceof import_mongoose7.mongo.BSON.Code || input instanceof import_mongoose7.mongo.BSON.DBRef || input instanceof import_mongoose7.mongo.BSON.BSONRegExp)
8515
9982
  invalid("unsupported equality key");
8516
- charge(import_mongoose6.mongo.BSON.calculateObjectSize({ value: input }));
9983
+ charge(import_mongoose7.mongo.BSON.calculateObjectSize({ value: input }));
8517
9984
  } else {
8518
9985
  const array = Array.isArray(input);
8519
9986
  if (array && input.length > MAX_KEYS) invalid(`key array exceeds ${MAX_KEYS} entries`);
@@ -8536,7 +10003,7 @@ var KeyBudget = class {
8536
10003
  }
8537
10004
  const alias = String(snapshot);
8538
10005
  const aliasBytes = Buffer.byteLength(alias);
8539
- const bsonBytes = import_mongoose6.mongo.BSON.calculateObjectSize({ value: snapshot }, { ignoreUndefined: false });
10006
+ const bsonBytes = import_mongoose7.mongo.BSON.calculateObjectSize({ value: snapshot }, { ignoreUndefined: false });
8540
10007
  if (Math.max(aliasBytes, bsonBytes) > MAX_KEY_BYTES) invalid(`key exceeds ${MAX_KEY_BYTES} bytes`);
8541
10008
  this.bytes += aliasBytes + bsonBytes;
8542
10009
  if (this.bytes > MAX_TOTAL_KEY_BYTES) invalid(`key payload exceeds ${MAX_TOTAL_KEY_BYTES} bytes`);
@@ -9121,7 +10588,8 @@ async function executePreparedGroupedCount(receiver, execution, query, foreignFi
9121
10588
  // src/services/base.ts
9122
10589
  var VIRT_ASSOCIATION_FIELD = /* @__PURE__ */ Symbol("accessRouter.virtAssociationField");
9123
10590
  var VIRT_ASSOCIATION_VALUES = /* @__PURE__ */ Symbol("accessRouter.virtAssociationValues");
9124
- var copyAuthorizedOutput = (value) => {
10591
+ var copyAuthorizedOutput = (value, call) => {
10592
+ if (value && typeof value === "object" && call && isTrustedAuthorizationOutput(value, call)) return value;
9125
10593
  const copy = deepIsolateValue(value);
9126
10594
  transferDocumentAuthorizationGraph(value, copy);
9127
10595
  return copy;
@@ -9751,7 +11219,9 @@ var Base = class {
9751
11219
  const includes = (0, import_utils26.compact)((0, import_utils26.castArray)(include));
9752
11220
  if (includes.length === 0) return docs;
9753
11221
  const isSingle = !(0, import_utils26.isArray)(docs);
9754
- let docList = (isSingle ? [docs] : docs).map(prepareIncludeOutput);
11222
+ let docList = (isSingle ? [docs] : docs).map(
11223
+ (doc) => prepareIncludeOutput(doc, parentAuthorization, parentAuthorization ? this.relatedBinding() : void 0)
11224
+ );
9755
11225
  for (let x = 0; x < includes.length; x++) {
9756
11226
  const include2 = includes[x];
9757
11227
  if (isCorrelatedInclude(include2)) {
@@ -9847,7 +11317,9 @@ var Base = class {
9847
11317
  );
9848
11318
  if (!trustedResult.success && trustedResult.code === "bad_request" /* BadRequest */) throw new ClientRequestError(trustedResult);
9849
11319
  if (!trustedResult.success) return docs;
9850
- const finalizedRows = trustedResult.data.map((row) => copyAuthorizedOutput(row));
11320
+ const finalizedRows = trustedResult.data.map(
11321
+ (row) => copyAuthorizedOutput(row, parentAuthorization)
11322
+ );
9851
11323
  let index;
9852
11324
  const paired = trustedResult[VIRT_ASSOCIATION_VALUES];
9853
11325
  if (Array.isArray(paired) && paired.length === finalizedRows.length) {
@@ -9867,7 +11339,7 @@ var Base = class {
9867
11339
  for (let y = 0; y < docs.length; y++) {
9868
11340
  const doc = docs[y];
9869
11341
  const matches = this.getIndexedMatches(index, (0, import_utils26.get)(doc, localField));
9870
- const isolated = matches.map((m) => copyAuthorizedOutput(m));
11342
+ const isolated = matches.map((m) => copyAuthorizedOutput(m, parentAuthorization));
9871
11343
  attachIncludeOutput(doc, path, op === "list" ? isolated : isolated[0]);
9872
11344
  }
9873
11345
  return docs;
@@ -9928,7 +11400,9 @@ var Base = class {
9928
11400
  );
9929
11401
  }
9930
11402
  const state = this.getCorrelatedExecState();
9931
- docs = docs.map(prepareIncludeOutput);
11403
+ docs = docs.map(
11404
+ (doc) => prepareIncludeOutput(doc, parentAuthorization, parentAuthorization ? this.relatedBinding() : void 0)
11405
+ );
9932
11406
  const resolvedSnapshots = snapshots2 ?? docs.map((doc) => (0, import_utils26.cloneDeep)(toObject(getIncludeSource(doc))));
9933
11407
  for (const include of correlatedIncludes) {
9934
11408
  switch (include.op) {
@@ -10420,7 +11894,6 @@ init_document_authorization();
10420
11894
  init_output_field_filter();
10421
11895
  init_field_authorization();
10422
11896
  init_authorization_snapshot();
10423
- init_unsafe_snapshot_options();
10424
11897
  init_public_admission();
10425
11898
 
10426
11899
  // src/acl/subdocument-output.ts
@@ -10554,6 +12027,7 @@ init_core_shared();
10554
12027
  init_finalize_model_output();
10555
12028
  init_permissions_alias();
10556
12029
  init_include_output();
12030
+ init_trusted_output_materialization();
10557
12031
  init_populate_target();
10558
12032
  init_document();
10559
12033
  init_populate_target();
@@ -10594,7 +12068,7 @@ function applyUpdate(target, data, allowedFields) {
10594
12068
 
10595
12069
  // src/acl/model-input-admission.ts
10596
12070
  var import_utils33 = require("@web-ts-toolkit/utils");
10597
- var import_mongoose8 = require("mongoose");
12071
+ var import_mongoose9 = require("mongoose");
10598
12072
  init_document();
10599
12073
  init_request_work();
10600
12074
  init_logger_helpers();
@@ -10720,7 +12194,7 @@ function inputValue(value) {
10720
12194
  authorizationError("input values must be persisted data, not functions or symbols");
10721
12195
  }
10722
12196
  if (isMongooseDocument(value)) return value.toObject({ virtuals: false, flattenMaps: true });
10723
- if (value && typeof value === "object" && !record2(value) && !Array.isArray(value) && !(value instanceof Map) && !(value instanceof Date) && !(value instanceof RegExp) && !ArrayBuffer.isView(value) && !(value instanceof ArrayBuffer) && !(value instanceof import_mongoose8.mongo.BSON.BSONValue))
12197
+ if (value && typeof value === "object" && !record2(value) && !Array.isArray(value) && !(value instanceof Map) && !(value instanceof Date) && !(value instanceof RegExp) && !ArrayBuffer.isView(value) && !(value instanceof ArrayBuffer) && !(value instanceof import_mongoose9.mongo.BSON.BSONValue))
10724
12198
  return Object.fromEntries(Object.entries(value));
10725
12199
  return value;
10726
12200
  }
@@ -11615,11 +13089,7 @@ var Service = class extends Base {
11615
13089
  ["args", args],
11616
13090
  ["options", options]
11617
13091
  ]) {
11618
- if (value !== null && (typeof value === "object" || typeof value === "function")) {
11619
- for (const key of unsafeSnapshotOptions) {
11620
- if (key in value) authorizationError(`${slot}.${key} is server model configuration only`);
11621
- }
11622
- }
13092
+ assertNoServerModelControls(value, authorizationError);
11623
13093
  if (value !== null && (typeof value === "object" || typeof value === "function") && "authorization" in value && (slot === "args" || !authorizationOptions)) {
11624
13094
  authorizationError(`${slot}.authorization is unsupported here; inputFields requires model mutation options`);
11625
13095
  }
@@ -11726,8 +13196,11 @@ var Service = class extends Base {
11726
13196
  const { authorization, authorizationBinding: binding } = plan;
11727
13197
  const access = readServiceAuthorizationAccess(authorization, binding);
11728
13198
  const configuration = readServiceOutputMetadata(authorization, binding);
11729
- const source = getIncludeSource(args.doc);
11730
- const snapshot = isolateDocForOutput(source);
13199
+ const source = args.copiedQuerySource?.source ?? getIncludeSource(args.doc);
13200
+ const prepared = prepareQueryOutputSource(authorization, binding, source, "hook");
13201
+ if (prepared?.sourceState === "trusted")
13202
+ return this.finalizeTrustedDirectOutput(args, prepared.source, prepared.budget);
13203
+ const snapshot = prepared?.source ?? isolateDocForOutput(source);
11731
13204
  for (const key of Object.keys(snapshot))
11732
13205
  transferDocumentAuthorizationGraph(getDocValue(source, key), snapshot[key]);
11733
13206
  if (args.privateAssociationField) unsetDocPath(snapshot, args.privateAssociationField);
@@ -11736,7 +13209,8 @@ var Service = class extends Base {
11736
13209
  authorization,
11737
13210
  binding,
11738
13211
  snapshot,
11739
- context
13212
+ context,
13213
+ stage: args.copiedQuerySource?.stage ?? (prepared ? prepareQueryDocumentAuthorization(authorization, binding, snapshot).stage : void 0)
11740
13214
  });
11741
13215
  const { stage, grants } = readDocumentAuthorization(handle, binding);
11742
13216
  context.docPermissions = deepIsolateValue(grants);
@@ -11753,7 +13227,7 @@ var Service = class extends Base {
11753
13227
  context,
11754
13228
  operation: access.operation,
11755
13229
  documentAuthorizationStage: stage,
11756
- virtualPopulateRow: getVirtualPopulateRow(getIncludeOriginal(args.doc)),
13230
+ virtualPopulateRow: getVirtualPopulateRow(getIncludeOriginal(args.doc, authorization)),
11757
13231
  sharedGate: gate,
11758
13232
  concurrencyLimit: this.getVirtualHookConcurrencyLimit(),
11759
13233
  onFinalized: (_output, outputContext) => {
@@ -11801,6 +13275,104 @@ var Service = class extends Base {
11801
13275
  })
11802
13276
  };
11803
13277
  }
13278
+ /** Same modern finalizer/evaluators; source/grants/attachments are borrowed only by authenticated trusted rows. */
13279
+ async finalizeTrustedDirectOutput(args, borrowedSource, sourceBudget) {
13280
+ const { plan, context } = args;
13281
+ const binding = plan.authorizationBinding, authorization = plan.authorization;
13282
+ const access = readServiceAuthorizationAccess(authorization, binding);
13283
+ const configuration = readServiceOutputMetadata(authorization, binding);
13284
+ const budget = sourceBudget ?? createTrustedOutputBudget();
13285
+ let source = borrowedSource;
13286
+ if (args.privateAssociationField) {
13287
+ source = shallowTrustedOutput(source, budget);
13288
+ unsetTrustedOutputPath(source, args.privateAssociationField, budget);
13289
+ }
13290
+ const prepared = prepareQueryDocumentAuthorization(authorization, binding, source);
13291
+ if (prepared.sourceState === "copied") return this.finalizeDirectOutput({ ...args, copiedQuerySource: prepared });
13292
+ let finalizedContext;
13293
+ const data = await finalizeModelOutput({
13294
+ receivingModelName: this.modelName,
13295
+ input: prepared.source,
13296
+ plan,
13297
+ snapshot: configuration,
13298
+ virtualAccess: access.virtualAccess,
13299
+ outputAccess: access.outputAccess,
13300
+ docPermissionsAccess: access.docPermissionsAccess,
13301
+ request: this.req,
13302
+ context,
13303
+ operation: access.operation,
13304
+ documentAuthorizationStage: prepared.stage,
13305
+ virtualPopulateRow: getVirtualPopulateRow(getIncludeOriginal(args.doc, authorization)),
13306
+ trustedOutputBudget: budget,
13307
+ completeTrustedOutput: async (output, handle, materialization) => {
13308
+ const { grants } = readDocumentAuthorization(handle, binding);
13309
+ context.docPermissions = grants;
13310
+ restoreTrustedIncludeOutput(args.doc, output, materialization);
13311
+ const field = configuration.documentPermissionField ?? "_permissions";
13312
+ if (configuration.stripPermissionsField)
13313
+ unsetTrustedOutputPath(
13314
+ output,
13315
+ field,
13316
+ budget,
13317
+ (source2, copy) => retainTrustedOutputSpine(materialization.members, source2, copy)
13318
+ );
13319
+ else {
13320
+ const exposed = configuration.exposedDocPermissionKeys;
13321
+ const metadata = {};
13322
+ if (args.includePermissions || args.includeFieldPermissions) {
13323
+ for (const key of Object.keys(grants)) {
13324
+ visitTrustedOutput(budget, 1);
13325
+ if (exposed && key !== "_view" && key !== "_edit" && !exposed.includes(key)) continue;
13326
+ defineTrustedOutputValue(metadata, key, grants[key]);
13327
+ }
13328
+ }
13329
+ if (args.includeFieldPermissions && !configuration.disableFieldPermissions) {
13330
+ const rowAccess = this.asServiceHookContext(context).fieldPermissionAccess ?? await this.getFieldPermissionAccess([source._id]);
13331
+ const id = String(source._id);
13332
+ const views = rowAccess.readIds?.has(id) ? await requestOutputFieldPaths(handle, binding, "read") : [];
13333
+ const edits = rowAccess.updateIds?.has(id) ? await requestOutputFieldPaths(handle, binding, "update") : [];
13334
+ const map2 = (paths) => {
13335
+ visitTrustedOutput(budget, 1, paths.length || 1);
13336
+ return paths.length ? Object.fromEntries(paths.map((path) => [path, true])) : { $: "_" };
13337
+ };
13338
+ defineTrustedOutputValue(metadata, "_view", map2(views));
13339
+ defineTrustedOutputValue(metadata, "_edit", map2(edits));
13340
+ } else if (!args.includePermissions) {
13341
+ defineTrustedOutputValue(metadata, "_view", { $: "_" });
13342
+ defineTrustedOutputValue(metadata, "_edit", { $: "_" });
13343
+ }
13344
+ setTrustedOutputPath(
13345
+ output,
13346
+ field,
13347
+ metadata,
13348
+ budget,
13349
+ 0,
13350
+ (source2, copy) => retainTrustedOutputSpine(materialization.members, source2, copy)
13351
+ );
13352
+ attachPermissionsAlias(output, field);
13353
+ }
13354
+ },
13355
+ onFinalized: (_output, outputContext) => {
13356
+ finalizedContext = outputContext;
13357
+ }
13358
+ });
13359
+ return { data, context: finalizedContext };
13360
+ }
13361
+ /** Actual correlated inputs only, not an unconditional whole-source diagnostic snapshot. */
13362
+ captureTrustedCorrelatedSource(doc, fields) {
13363
+ const output = {}, budget = createTrustedOutputBudget();
13364
+ for (const field of fields) {
13365
+ const value = (0, import_utils36.get)(doc, field);
13366
+ if (value !== void 0)
13367
+ setTrustedOutputPath(
13368
+ output,
13369
+ field,
13370
+ materializeTrustedOutputValue(value, field, budget, { keep: () => true }),
13371
+ budget
13372
+ );
13373
+ }
13374
+ return output;
13375
+ }
11804
13376
  getEffectiveAllowedSortFields(allowedSortFields) {
11805
13377
  const extra = this.options?.sortableFields ?? [];
11806
13378
  const merged = extra.length > 0 ? [...allowedSortFields, ...extra] : allowedSortFields;
@@ -12149,7 +13721,7 @@ var Service = class extends Base {
12149
13721
  if (typeof record3._bsontype === "string") return true;
12150
13722
  return false;
12151
13723
  }
12152
- async finalizeSinglePopulateTarget(rawTarget, meta, parentOperation, parentContext, hookLimit, sharedGate, originalTarget = rawTarget) {
13724
+ async finalizeSinglePopulateTarget(rawTarget, meta, parentOperation, parentContext, hookLimit, sharedGate, originalTarget = rawTarget, trustedCacheOrigins = false) {
12153
13725
  if (rawTarget === null || rawTarget === void 0) return rawTarget;
12154
13726
  if (this.isScalarPopulateValue(rawTarget)) return rawTarget;
12155
13727
  const isDoc = (() => {
@@ -12170,10 +13742,12 @@ var Service = class extends Base {
12170
13742
  this.populateOutputCache.set(meta, cache);
12171
13743
  }
12172
13744
  const originalKey = originalTarget && typeof originalTarget === "object" ? originalTarget : rawTarget;
12173
- const cacheKey = getVirtualPopulatePublicIdentity(originalKey) ?? originalKey;
13745
+ const cacheKey = trustedCacheOrigins ? getVirtualPopulatePublicIdentity(rawTarget) ?? getQueryReferenceOriginal(rawTarget) ?? rawTarget : getVirtualPopulatePublicIdentity(originalKey) ?? originalKey;
12174
13746
  const existing = cache.get(cacheKey);
12175
13747
  if (existing) {
12176
13748
  const source = await existing;
13749
+ if (source && typeof source === "object" && isTrustedAuthorizationOutput(source, meta.plan.authorization))
13750
+ return source;
12177
13751
  const copy2 = deepIsolateValue(source);
12178
13752
  transferDocumentAuthorizationGraph(source, copy2);
12179
13753
  return copy2;
@@ -12211,11 +13785,13 @@ var Service = class extends Base {
12211
13785
  });
12212
13786
  cache.set(cacheKey, pending);
12213
13787
  const finalized = await pending;
13788
+ if (finalized && typeof finalized === "object" && isTrustedAuthorizationOutput(finalized, meta.plan.authorization))
13789
+ return finalized;
12214
13790
  const copy = deepIsolateValue(finalized);
12215
13791
  transferDocumentAuthorizationGraph(finalized, copy);
12216
13792
  return copy;
12217
13793
  }
12218
- async finalizePopulatePath(current, segments, segIdx, meta, parentOperation, parentContext, hookLimit, sharedGate, original = current) {
13794
+ async finalizePopulatePath(current, segments, segIdx, meta, parentOperation, parentContext, hookLimit, sharedGate, original = current, trustedCacheOrigins = false) {
12219
13795
  if (current === null || current === void 0) return;
12220
13796
  if (Array.isArray(current)) {
12221
13797
  for (const [index, el] of current.entries()) {
@@ -12228,7 +13804,8 @@ var Service = class extends Base {
12228
13804
  parentContext,
12229
13805
  hookLimit,
12230
13806
  sharedGate,
12231
- Array.isArray(original) ? original[index] : void 0
13807
+ Array.isArray(original) ? original[index] : void 0,
13808
+ trustedCacheOrigins
12232
13809
  );
12233
13810
  }
12234
13811
  return;
@@ -12270,7 +13847,8 @@ var Service = class extends Base {
12270
13847
  parentContext,
12271
13848
  hookLimit,
12272
13849
  sharedGate,
12273
- Array.isArray(originalChild) ? originalChild[index] : void 0
13850
+ Array.isArray(originalChild) ? originalChild[index] : void 0,
13851
+ trustedCacheOrigins
12274
13852
  )
12275
13853
  );
12276
13854
  }
@@ -12287,7 +13865,8 @@ var Service = class extends Base {
12287
13865
  parentContext,
12288
13866
  hookLimit,
12289
13867
  sharedGate,
12290
- originalChild
13868
+ originalChild,
13869
+ trustedCacheOrigins
12291
13870
  );
12292
13871
  try {
12293
13872
  setDocValue(current, key, finalized);
@@ -12304,11 +13883,12 @@ var Service = class extends Base {
12304
13883
  parentContext,
12305
13884
  hookLimit,
12306
13885
  sharedGate,
12307
- originalChild
13886
+ originalChild,
13887
+ trustedCacheOrigins
12308
13888
  );
12309
13889
  }
12310
13890
  }
12311
- async finalizePopulateForSingleDoc(doc, populateEntries, parentContext, parentOperation, hookLimit, sharedGate) {
13891
+ async finalizePopulateForSingleDoc(doc, populateEntries, parentContext, parentOperation, hookLimit, sharedGate, trustedCacheOrigins = false, parentAuthorization) {
12312
13892
  if (!doc || !Array.isArray(populateEntries) || populateEntries.length === 0) return;
12313
13893
  for (const entry of populateEntries) {
12314
13894
  if (!entry || typeof entry.path !== "string") continue;
@@ -12325,7 +13905,8 @@ var Service = class extends Base {
12325
13905
  parentContext,
12326
13906
  hookLimit,
12327
13907
  sharedGate,
12328
- getIncludeOriginal(doc)
13908
+ getIncludeOriginal(doc, parentAuthorization),
13909
+ trustedCacheOrigins
12329
13910
  );
12330
13911
  }
12331
13912
  }
@@ -12468,16 +14049,18 @@ var Service = class extends Base {
12468
14049
  void 0,
12469
14050
  findOneAssociationField ? [findOneAssociationField] : []
12470
14051
  );
14052
+ const trustedQuery = readAuthorizationFastPath(state.authorization, state.binding)?.mode === "active";
14053
+ if (trustedQuery) doc = prepareQueryOutputSource(state.authorization, state.binding, doc).source;
12471
14054
  const context = {
12472
14055
  mongooseModel: this.model.mongooseModel,
12473
14056
  modelName: this.modelName,
12474
14057
  // VIRT-00A D1: operation stays initiating (`read`), never the
12475
14058
  // fallback/effective visibility. Effective accesses carry `access`.
12476
14059
  operation: state.access.operation,
12477
- originalDocumentSnapshot: toObject(doc),
14060
+ originalDocumentSnapshot: trustedQuery ? doc : toObject(doc),
12478
14061
  resolvedQuery: query
12479
14062
  };
12480
- const correlatedSnapshots = [(0, import_utils36.cloneDeep)(toObject(doc))];
14063
+ const correlatedSnapshots = trustedQuery ? correlatedIncludes.length ? [this.captureTrustedCorrelatedSource(doc, correlatedReferenceFields)] : [] : [(0, import_utils36.cloneDeep)(toObject(doc))];
12481
14064
  try {
12482
14065
  doc = await this.includeDocs(doc, includes, state.authorization);
12483
14066
  if (correlatedIncludes.length > 0) {
@@ -12507,7 +14090,9 @@ var Service = class extends Base {
12507
14090
  context,
12508
14091
  "read",
12509
14092
  findOneHookLimit,
12510
- findOneGate
14093
+ findOneGate,
14094
+ trustedQuery && prepareQueryOutputSource(state.authorization, state.binding, getIncludeSource(doc)).sourceState === "trusted",
14095
+ state.authorization
12511
14096
  );
12512
14097
  } catch (error2) {
12513
14098
  const result2 = this.getClientRequestErrorResult(error2);
@@ -12718,8 +14303,12 @@ var Service = class extends Base {
12718
14303
  void 0,
12719
14304
  findAssociationField ? [findAssociationField] : []
12720
14305
  );
14306
+ const trustedQuery = readAuthorizationFastPath(state.authorization, state.binding)?.mode === "active";
14307
+ if (trustedQuery)
14308
+ docs = docs.map((doc) => prepareQueryOutputSource(state.authorization, state.binding, doc).source);
14309
+ const diagnosticSources = trustedQuery ? [...docs] : void 0;
12721
14310
  const capturedAssociation = findAssociationField ? this.captureAssociationValues(docs, findAssociationField) : void 0;
12722
- const correlatedSnapshots = docs.map((doc) => (0, import_utils36.cloneDeep)(toObject(doc)));
14311
+ const correlatedSnapshots = trustedQuery ? correlatedIncludes.length ? docs.map((doc) => this.captureTrustedCorrelatedSource(doc, correlatedReferenceFields)) : [] : docs.map((doc) => (0, import_utils36.cloneDeep)(toObject(doc)));
12723
14312
  try {
12724
14313
  docs = await this.includeDocs(docs, includes, state.authorization);
12725
14314
  if (correlatedIncludes.length > 0) {
@@ -12762,11 +14351,11 @@ var Service = class extends Base {
12762
14351
  } catch {
12763
14352
  }
12764
14353
  }
12765
- const contexts = correlatedSnapshots.map((doc) => ({
14354
+ const contexts = (diagnosticSources ?? correlatedSnapshots).map((doc) => ({
12766
14355
  mongooseModel: this.model.mongooseModel,
12767
14356
  modelName: this.modelName,
12768
14357
  operation: "list",
12769
- originalDocumentSnapshot: toObject(doc),
14358
+ originalDocumentSnapshot: trustedQuery ? doc : toObject(doc),
12770
14359
  resolvedQuery: query
12771
14360
  }));
12772
14361
  const outputContexts = [];
@@ -12782,7 +14371,9 @@ var Service = class extends Base {
12782
14371
  contexts[i],
12783
14372
  "list",
12784
14373
  hookLimit,
12785
- sharedGate
14374
+ sharedGate,
14375
+ trustedQuery && prepareQueryOutputSource(state.authorization, state.binding, getIncludeSource(doc)).sourceState === "trusted",
14376
+ state.authorization
12786
14377
  );
12787
14378
  }
12788
14379
  const output = await this.finalizeDirectOutput({