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

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.mjs CHANGED
@@ -9,7 +9,33 @@ var __export = (target, all) => {
9
9
  };
10
10
 
11
11
  // src/acl/unsafe-snapshot-options.ts
12
- var unsafeSnapshotCheckOptions, unsafeInitialOutputCopyOptions, unsafeSnapshotOptions;
12
+ function authorizationFastPathPrerequisites(origin) {
13
+ const operation = origin === "read" ? "Read" : "List";
14
+ return [
15
+ `unsafeSkip${operation}DocumentSnapshotChecks`,
16
+ `unsafeSkip${operation}OutputSnapshotChecks`,
17
+ `unsafeSkip${operation}NestedDocumentSnapshotChecks`,
18
+ `unsafeSkip${operation}InitialOutputSnapshotCopy`
19
+ ];
20
+ }
21
+ function captureAuthorizationFastPath(options, origin) {
22
+ const literalTrue = (key2) => {
23
+ const descriptor = Object.getOwnPropertyDescriptor(options, key2);
24
+ return !!descriptor && "value" in descriptor && descriptor.value === true;
25
+ };
26
+ const key = origin === "read" ? unsafeAuthorizationFastPathOptions[1] : unsafeAuthorizationFastPathOptions[0];
27
+ const requested = literalTrue(key);
28
+ const prerequisites = authorizationFastPathPrerequisites(origin).reduce(
29
+ (mask, key2, index) => mask | (literalTrue(key2) ? 1 << index : 0),
30
+ 0
31
+ );
32
+ return Object.freeze({
33
+ origin,
34
+ mode: !requested ? "off" : prerequisites === 15 ? "active" : "dormant",
35
+ prerequisites
36
+ });
37
+ }
38
+ var unsafeSnapshotCheckOptions, unsafeInitialOutputCopyOptions, unsafeSnapshotOptions, unsafeAuthorizationFastPathOptions, unsafeServerOptions;
13
39
  var init_unsafe_snapshot_options = __esm({
14
40
  "src/acl/unsafe-snapshot-options.ts"() {
15
41
  unsafeSnapshotCheckOptions = [
@@ -25,6 +51,11 @@ var init_unsafe_snapshot_options = __esm({
25
51
  "unsafeSkipReadInitialOutputSnapshotCopy"
26
52
  ];
27
53
  unsafeSnapshotOptions = [...unsafeSnapshotCheckOptions, ...unsafeInitialOutputCopyOptions];
54
+ unsafeAuthorizationFastPathOptions = [
55
+ "unsafeUseListAuthorizationFastPath",
56
+ "unsafeUseReadAuthorizationFastPath"
57
+ ];
58
+ unsafeServerOptions = [...unsafeSnapshotOptions, ...unsafeAuthorizationFastPathOptions];
28
59
  }
29
60
  });
30
61
 
@@ -32,41 +63,100 @@ var init_unsafe_snapshot_options = __esm({
32
63
  import JsonRouter from "@web-ts-toolkit/express-json-router";
33
64
  import { isPlainObject } from "@web-ts-toolkit/utils";
34
65
  function assertPublicAdmission(input, kind = "envelope") {
35
- const pending = [{ value: input, kind, path: "request" }];
66
+ assertPublicControlAdmission(input, kind);
67
+ }
68
+ function assertPublicControlAdmission(input, kind) {
69
+ walkControlAdmission(
70
+ input,
71
+ kind,
72
+ (record3, path) => {
73
+ for (const key of privateControls) {
74
+ if (key in record3) {
75
+ throw new PublicAdmissionError(
76
+ 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`
77
+ );
78
+ }
79
+ }
80
+ },
81
+ (detail) => {
82
+ throw new PublicAdmissionError(detail);
83
+ }
84
+ );
85
+ }
86
+ function assertNoServerModelControls(input, reject, kind = "envelope") {
87
+ walkControlAdmission(
88
+ input,
89
+ kind,
90
+ (record3, path) => {
91
+ for (const key of unsafeServerOptions)
92
+ if (key in record3) reject(`${path}.${key} is server model configuration only`);
93
+ },
94
+ reject
95
+ );
96
+ }
97
+ function walkControlAdmission(input, kind, check, reject) {
98
+ const pending = [{ value: input, kind, path: "request", depth: 0 }];
36
99
  const seen = /* @__PURE__ */ new WeakMap();
100
+ let slots = 1;
37
101
  while (pending.length) {
38
- const { value, kind: slot, path } = pending.pop();
102
+ const { value, kind: slot, path, depth } = pending.pop();
39
103
  if (!value || typeof value !== "object" && typeof value !== "function") continue;
40
104
  const kinds = seen.get(value) ?? /* @__PURE__ */ new Set();
41
105
  if (kinds.has(slot)) continue;
42
106
  kinds.add(slot);
43
107
  seen.set(value, kinds);
44
108
  const add = (child, childKind, key) => {
45
- pending.push({ value: child, kind: childKind, path: `${path}.${key}` });
109
+ if (child === void 0 || child === null) return;
110
+ if (++slots > 2e4 || depth >= 100) reject("control admission exceeds structural limits");
111
+ pending.push({ value: child, kind: childKind, path: `${path}.${key}`, depth: depth + 1 });
46
112
  };
47
113
  const record3 = value;
48
- if (slot !== "data") {
49
- for (const key of privateControls) {
50
- if (key in record3) {
51
- throw new PublicAdmissionError(
52
- 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`
53
- );
54
- }
114
+ if (slot !== "data" && slot !== "policies") check(record3, path);
115
+ const read = (key) => {
116
+ let owner = value;
117
+ for (let depth2 = 0; owner; depth2++, owner = Object.getPrototypeOf(owner)) {
118
+ if (depth2 > 100) reject("control admission prototype depth exceeded");
119
+ const descriptor = Object.getOwnPropertyDescriptor(owner, key);
120
+ if (!descriptor) continue;
121
+ if (!("value" in descriptor)) reject(`accessor control/data property: ${path}.${key}`);
122
+ return descriptor.value;
55
123
  }
56
- }
124
+ return void 0;
125
+ };
57
126
  if (Array.isArray(value)) {
58
- value.forEach((child, index) => add(child, slot, String(index)));
127
+ if (value.length > 2e4) reject("control admission array exceeds structural limits");
128
+ for (let index = 0; index < value.length; index++) {
129
+ if (index in value) add(read(String(index)), slot, String(index));
130
+ }
59
131
  continue;
60
132
  }
61
133
  if (slot === "data") {
62
134
  if (!isPlainObject(value)) continue;
63
- for (const [key, child] of Object.entries(value)) add(child, key === "$$sq" ? "envelope" : "data", key);
135
+ add(read("$$sq"), "envelope", "$$sq");
136
+ for (const key of Object.keys(value)) if (key !== "$$sq") add(read(key), "data", key);
137
+ continue;
138
+ }
139
+ if (slot === "defaults") {
140
+ const keys2 = /* @__PURE__ */ new Set([...Object.keys(value), ...defaultControlBuckets]);
141
+ if (keys2.size > 2e4) reject("control admission defaults exceeds structural limits");
142
+ for (const key of keys2) if (key in record3) add(read(key), "envelope", key);
143
+ continue;
144
+ }
145
+ if (slot === "policies") {
146
+ for (const key of Object.keys(value)) add(read(key), "policy", key);
147
+ continue;
148
+ }
149
+ if (slot === "policy") {
150
+ for (const key of ["rows", "outputFields", "inputFields", "operation"]) add(read(key), "policy", key);
151
+ add(read("related"), "policies", "related");
152
+ add(read("filter"), "data", "filter");
64
153
  continue;
65
154
  }
66
- for (const key of ["args", "options", "sqOptions"]) add(record3[key], "envelope", key);
67
- add(record3.include, "include", "include");
68
- add(record3.populate, "populate", "populate");
69
- for (const key of ["filter", "match", "data"]) add(record3[key], "data", key);
155
+ for (const key of ["args", "options", "sqOptions"]) add(read(key), "envelope", key);
156
+ add(read("include"), "include", "include");
157
+ add(read("populate"), "populate", "populate");
158
+ add(read("authorization"), "policy", "authorization");
159
+ for (const key of ["filter", "match", "data"]) add(read(key), "data", key);
70
160
  }
71
161
  }
72
162
  function assertHydrationDefaults(defaults2) {
@@ -100,11 +190,8 @@ function assertHydrationDefaults(defaults2) {
100
190
  }
101
191
  }
102
192
  function assertPublicDefaults(defaults2) {
193
+ assertPublicControlAdmission(defaults2, "defaults");
103
194
  assertHydrationDefaults(defaults2);
104
- assertPublicAdmission(defaults2);
105
- if (defaults2 && typeof defaults2 === "object") {
106
- for (const value of Object.values(defaults2)) assertPublicAdmission(value);
107
- }
108
195
  }
109
196
  function pickPublicKeys(input, keys2) {
110
197
  const result2 = {};
@@ -129,7 +216,7 @@ function requestOnlyServiceOptions(options) {
129
216
  authorization: requestAuthorization
130
217
  };
131
218
  }
132
- var privateControls, PublicAdmissionError, listArgs, readArgs, listOptions, readOptions, requestAuthorization;
219
+ var privateControls, PublicAdmissionError, defaultControlBuckets, listArgs, readArgs, listOptions, readOptions, requestAuthorization;
133
220
  var init_public_admission = __esm({
134
221
  "src/validation/public-admission.ts"() {
135
222
  init_unsafe_snapshot_options();
@@ -150,7 +237,7 @@ var init_public_admission = __esm({
150
237
  "skipParsing",
151
238
  "skipAuthorization",
152
239
  "alreadyAuthorized",
153
- ...unsafeSnapshotOptions,
240
+ ...unsafeServerOptions,
154
241
  "operation"
155
242
  ];
156
243
  PublicAdmissionError = class extends JsonRouter.clientErrors.BadRequestError {
@@ -160,6 +247,31 @@ var init_public_admission = __esm({
160
247
  this.result = { success: false, kind: "error", code: "bad_request" /* BadRequest */, errors };
161
248
  }
162
249
  };
250
+ defaultControlBuckets = [
251
+ "findOneArgs",
252
+ "findOneOptions",
253
+ "findByIdArgs",
254
+ "findByIdOptions",
255
+ "findArgs",
256
+ "findOptions",
257
+ "createArgs",
258
+ "createOptions",
259
+ "updateOneArgs",
260
+ "updateOneOptions",
261
+ "upsertOptions",
262
+ "updateByIdArgs",
263
+ "upsertArgs",
264
+ "updateByIdOptions",
265
+ "existsOptions",
266
+ "publicListArgs",
267
+ "publicListOptions",
268
+ "publicCreateArgs",
269
+ "publicCreateOptions",
270
+ "publicReadArgs",
271
+ "publicReadOptions",
272
+ "publicUpdateArgs",
273
+ "publicUpdateOptions"
274
+ ];
163
275
  listArgs = ["select", "populate", "include", "sort", "skip", "limit", "page", "pageSize", "tasks"];
164
276
  readArgs = ["select", "populate", "include", "sort", "tasks"];
165
277
  listOptions = [
@@ -366,6 +478,9 @@ var init_concurrency = __esm({
366
478
 
367
479
  // src/output/permissions-alias.ts
368
480
  import { get } from "@web-ts-toolkit/utils";
481
+ function isGeneratedPermissionsAliasSlot(output, key, slot) {
482
+ return key === "permissions" && aliases.has(output) && "value" in slot && !slot.enumerable;
483
+ }
369
484
  function attachPermissionsAlias(output, field) {
370
485
  if ("permissions" in output) return;
371
486
  const metadata = get(output, field);
@@ -2752,7 +2867,7 @@ var init_runtime = __esm({
2752
2867
  ([key, value]) => value !== void 0 || key === "operationAccess" || isPopulatePolicyKey(key)
2753
2868
  )
2754
2869
  );
2755
- for (const key of unsafeSnapshotOptions) if (key in result2) result2[key] = result2[key] === true;
2870
+ for (const key of unsafeServerOptions) if (key in result2) result2[key] = result2[key] === true;
2756
2871
  return cloneOptionsSnapshot(result2);
2757
2872
  };
2758
2873
  defaultDataOptions = {
@@ -3113,7 +3228,9 @@ var init_runtime = __esm({
3113
3228
  unsafeSkipListNestedDocumentSnapshotChecks: false,
3114
3229
  unsafeSkipReadNestedDocumentSnapshotChecks: false,
3115
3230
  unsafeSkipListInitialOutputSnapshotCopy: false,
3116
- unsafeSkipReadInitialOutputSnapshotCopy: false
3231
+ unsafeSkipReadInitialOutputSnapshotCopy: false,
3232
+ unsafeUseListAuthorizationFastPath: false,
3233
+ unsafeUseReadAuthorizationFastPath: false
3117
3234
  }).build();
3118
3235
  this.modelOptions = {};
3119
3236
  this.modelOptionOverrides = {};
@@ -3301,6 +3418,12 @@ var init_runtime = __esm({
3301
3418
  }
3302
3419
  setDefaultModelOption(key, value) {
3303
3420
  const keyStr = String(key);
3421
+ if (keyStr === "defaults") assertPublicDefaults(value);
3422
+ else if (keyStr.startsWith("defaults.")) {
3423
+ const proposed = {};
3424
+ set4(proposed, keyStr.slice("defaults.".length), value);
3425
+ assertPublicDefaults(proposed);
3426
+ }
3304
3427
  const draft = new OptionsManager(
3305
3428
  this.getDefaultModelOptions()
3306
3429
  ).build();
@@ -3325,7 +3448,7 @@ var init_runtime = __esm({
3325
3448
  for (const key of populatePolicyKeys) delete inherited[key];
3326
3449
  const effective = { ...defaultModelOptions, ...inherited, ...overrides, modelName };
3327
3450
  effective.basePath = normalizeBasePath(modelName, effective.basePath);
3328
- for (const key of unsafeSnapshotOptions) effective[key] = effective[key] === true;
3451
+ for (const key of unsafeServerOptions) effective[key] = effective[key] === true;
3329
3452
  refreshPermissionMetadata(effective);
3330
3453
  return cloneOptionsSnapshot(effective);
3331
3454
  }
@@ -3340,7 +3463,7 @@ var init_runtime = __esm({
3340
3463
  }
3341
3464
  publishDefaultModelOptions(options) {
3342
3465
  const next = { ...options };
3343
- for (const key of unsafeSnapshotOptions) if (key in next) next[key] = next[key] === true;
3466
+ for (const key of unsafeServerOptions) if (key in next) next[key] = next[key] === true;
3344
3467
  const defaults2 = cloneOptionsSnapshot(next);
3345
3468
  const models = new Map(
3346
3469
  Object.keys(this.modelOptions).map((name) => [name, this.resolveModelOptions(name, void 0, defaults2)])
@@ -3370,6 +3493,7 @@ var init_runtime = __esm({
3370
3493
  deferSnapshotWarnings(publish) {
3371
3494
  if (this.pendingSnapshotWarnings) return publish();
3372
3495
  const copyModes = this.initialOutputCopyModes();
3496
+ const fastModes = this.authorizationFastPathModes();
3373
3497
  const pending = [];
3374
3498
  this.pendingSnapshotWarnings = pending;
3375
3499
  let result2;
@@ -3379,6 +3503,7 @@ var init_runtime = __esm({
3379
3503
  this.pendingSnapshotWarnings = void 0;
3380
3504
  }
3381
3505
  const nextCopyModes = this.initialOutputCopyModes();
3506
+ const nextFastModes = this.authorizationFastPathModes();
3382
3507
  for (const { modelName, key } of pending) this.warnSnapshotFlag(modelName, key);
3383
3508
  for (const [modelName, modes] of nextCopyModes) {
3384
3509
  for (const operation of ["List", "Read"]) {
@@ -3395,8 +3520,38 @@ var init_runtime = __esm({
3395
3520
  }
3396
3521
  }
3397
3522
  }
3523
+ for (const [modelName, modes] of nextFastModes) {
3524
+ for (const origin of ["list", "read"]) {
3525
+ const captured = modes[origin];
3526
+ const previous = fastModes.get(modelName)?.[origin];
3527
+ if (captured.mode === "off" || captured.mode === previous?.mode && (captured.mode !== "dormant" || captured.prerequisites === previous.prerequisites))
3528
+ continue;
3529
+ const key = origin === "read" ? "unsafeUseReadAuthorizationFastPath" : "unsafeUseListAuthorizationFastPath";
3530
+ const missing = authorizationFastPathPrerequisites(origin).filter(
3531
+ (_, index) => !(captured.prerequisites & 1 << index)
3532
+ );
3533
+ try {
3534
+ this.getGlobalOption("logger")?.warn?.(
3535
+ 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.`,
3536
+ { modelName }
3537
+ );
3538
+ } catch {
3539
+ }
3540
+ }
3541
+ }
3398
3542
  return result2;
3399
3543
  }
3544
+ authorizationFastPathModes() {
3545
+ return new Map(
3546
+ Object.entries(this.modelOptions).map(([modelName, manager]) => {
3547
+ const options = manager.fetch();
3548
+ return [
3549
+ modelName,
3550
+ { list: captureAuthorizationFastPath(options, "list"), read: captureAuthorizationFastPath(options, "read") }
3551
+ ];
3552
+ })
3553
+ );
3554
+ }
3400
3555
  initialOutputCopyModes() {
3401
3556
  return new Map(
3402
3557
  Object.entries(this.modelOptions).map(([modelName, options]) => {
@@ -3850,6 +4005,23 @@ var init_permission = __esm({
3850
4005
  }
3851
4006
  });
3852
4007
 
4008
+ // src/acl/captured-authorization-configuration.ts
4009
+ function captureAuthorizationConfiguration(value) {
4010
+ const capture = copyAuthorizationValue(value, true);
4011
+ captures.add(capture);
4012
+ return capture;
4013
+ }
4014
+ function ownedAuthorizationConfiguration(value) {
4015
+ return captures.has(value) ? value : captureAuthorizationConfiguration(value);
4016
+ }
4017
+ var captures;
4018
+ var init_captured_authorization_configuration = __esm({
4019
+ "src/acl/captured-authorization-configuration.ts"() {
4020
+ init_authorization_snapshot();
4021
+ captures = /* @__PURE__ */ new WeakSet();
4022
+ }
4023
+ });
4024
+
3853
4025
  // src/acl/service-authorization.ts
3854
4026
  function serviceAuthorizationInput(policy, targets) {
3855
4027
  const related = {};
@@ -3864,6 +4036,24 @@ function serviceAuthorizationInput(policy, targets) {
3864
4036
  }
3865
4037
  return { rows: policy.rows, outputFields: policy.outputFields, related };
3866
4038
  }
4039
+ function captureTrustedRelatedTargets(targets) {
4040
+ let slots = 0;
4041
+ const capture = (entries, depth) => {
4042
+ if (depth > 100 || (slots += entries.length) > 2e4)
4043
+ authorizationError("related capture exceeds structural limits");
4044
+ return Object.freeze(
4045
+ entries.map((entry) => {
4046
+ const { configuration, relatedTargets, ...rest } = entry;
4047
+ return Object.freeze({
4048
+ ...copyAuthorizationValue(rest, true),
4049
+ configuration: ownedAuthorizationConfiguration(configuration),
4050
+ relatedTargets: relatedTargets ? capture(relatedTargets, depth + 1) : void 0
4051
+ });
4052
+ })
4053
+ );
4054
+ };
4055
+ return capture(targets, 0);
4056
+ }
3867
4057
  function hasStableConfigurationCopies(value) {
3868
4058
  if (value === null || typeof value !== "object") return true;
3869
4059
  if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype) return false;
@@ -3932,6 +4122,8 @@ function assertCatalogPath(path, configuration) {
3932
4122
  }
3933
4123
  }
3934
4124
  function assertAuthorizationKeys(value, keys2, label) {
4125
+ for (const key of unsafeServerOptions)
4126
+ if (key in value) authorizationError(`${label}.${key} is server model configuration only`);
3935
4127
  for (const key of Object.keys(value)) if (!keys2.includes(key)) authorizationError(`unsupported ${label} key: ${key}`);
3936
4128
  }
3937
4129
  function normalizeRows(value) {
@@ -4050,7 +4242,7 @@ function nestedQueryResponse(input, access) {
4050
4242
  }
4051
4243
  if (edge.kind === "related") {
4052
4244
  const target = parent.relatedTargets.find((target2) => target2.path === edge.path);
4053
- return !!target && target.kind !== "count" && target.modelName === input.binding.modelName && scope(input.binding).length === 0;
4245
+ return !!target && target.kind !== "count" && target.modelName === input.binding.modelName && (target.model === void 0 || target.model === input.binding.model) && scope(input.binding).length === 0;
4054
4246
  }
4055
4247
  if (edge.kind !== "embedded") return false;
4056
4248
  assertAuthorizationBinding(input.parent, { ...input.binding, scopePath: parent.binding.scopePath });
@@ -4059,10 +4251,74 @@ function nestedQueryResponse(input, access) {
4059
4251
  (key) => access[key] === parent.output.access[key]
4060
4252
  );
4061
4253
  }
4254
+ function deriveTrustedQueryAuthorization(input) {
4255
+ if (!input.parent || !input.snapshotDerivation) return;
4256
+ const access = captureAuthorizationAccess(input.access);
4257
+ const parent = callRecord(input.parent);
4258
+ const retry = input.snapshotDerivation.kind === "retry" && parent.readResponse && access.operation === "read" && (input.applicability ?? "service") === "service" && queryOutputAccess(access);
4259
+ if (retry) {
4260
+ assertAuthorizationBinding(input.parent, input.snapshotDerivation.parentBinding);
4261
+ assertAuthorizationBinding(input.parent, input.binding);
4262
+ } else if (!nestedQueryResponse(input, access)) return;
4263
+ if (parent.authorizationFastPath?.mode !== "active") return;
4264
+ if (parent.binding.request !== input.binding.request || parent.binding.runtime !== input.binding.runtime) {
4265
+ authorizationError("derived call request/runtime mismatch");
4266
+ }
4267
+ const edge = input.snapshotDerivation;
4268
+ const target = edge.kind === "related" ? parent.relatedTargets.find((entry) => entry.path === edge.path) : void 0;
4269
+ const scopePath = Array.from(scope(input.binding));
4270
+ for (const part of scopePath) {
4271
+ assertAuthorizationPath(part);
4272
+ if (part.includes(".")) authorizationError("scopePath requires response segments");
4273
+ }
4274
+ if (edge.kind === "embedded" && !isCatalogOutputPath(parent.output.catalog, scopePath.join(".")))
4275
+ authorizationError("unknown output scope");
4276
+ const configuration = target?.configuration ?? parent.configuration;
4277
+ const relatedTargets = target?.relatedTargets ?? (target ? [] : parent.relatedTargets);
4278
+ const policy = target ? parent.policy.related[target.path] ?? Object.freeze({
4279
+ rows: Object.freeze({ mode: "request" }),
4280
+ outputFields: Object.freeze({ mode: "request" }),
4281
+ inputFields: Object.freeze({ mode: "request" }),
4282
+ related: Object.freeze({})
4283
+ }) : parent.policy;
4284
+ const catalog = target ? captureAuthorizationCatalog(configuration.catalog) : parent.output.catalog;
4285
+ const call = Object.freeze(/* @__PURE__ */ Object.create(null));
4286
+ calls.set(call, {
4287
+ binding: Object.freeze({ ...input.binding, scopePath: Object.freeze(scopePath) }),
4288
+ access,
4289
+ configuration,
4290
+ policy,
4291
+ relatedTargets,
4292
+ output: Object.freeze({ access, catalog, outputFields: policy.outputFields }),
4293
+ permissions: parent.permissions,
4294
+ provenance: parent.provenance,
4295
+ readResponse: edge.kind === "retry" && parent.readResponse,
4296
+ nestedResponse: true,
4297
+ responseSnapshots: parent.responseSnapshots,
4298
+ authorizationFastPath: parent.authorizationFastPath,
4299
+ fieldPolicyOwner: target ? call : parent.fieldPolicyOwner ?? input.parent,
4300
+ trustedView: void 0,
4301
+ reusableFieldConfiguration: void 0,
4302
+ validateDocumentSnapshots: false,
4303
+ validateOutputSnapshots: false,
4304
+ skipInitialOutputSnapshotCopy: true
4305
+ });
4306
+ return call;
4307
+ }
4062
4308
  function resolveServiceAuthorization(input) {
4309
+ assertNoServerModelControls(input.authorization, authorizationError, "policy");
4310
+ const derived = deriveTrustedQueryAuthorization(input);
4311
+ if (derived) return derived;
4312
+ const fastPaths = {
4313
+ list: captureAuthorizationFastPath(input.configuration, "list"),
4314
+ read: captureAuthorizationFastPath(input.configuration, "read")
4315
+ };
4316
+ const candidateAccess = captureAuthorizationAccess(input.access);
4317
+ const rootQuery = !input.parent && (input.applicability ?? "service") === "service" && !scope(input.binding).length;
4318
+ 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");
4063
4319
  const raw = copyAuthorizationValue(input.authorization);
4064
- const configuration = copyAuthorizationValue(input.configuration, true);
4065
- const targets = copyAuthorizationValue(input.relatedTargets ?? [], true);
4320
+ const configuration = trustedCapture ? ownedAuthorizationConfiguration(input.configuration) : copyAuthorizationValue(input.configuration, true);
4321
+ const targets = trustedCapture ? captureTrustedRelatedTargets(input.relatedTargets ?? []) : copyAuthorizationValue(input.relatedTargets ?? [], true);
4066
4322
  const access = copyAuthorizationValue(input.access);
4067
4323
  const outputAccess = captureAuthorizationAccess(access);
4068
4324
  const catalog = captureAuthorizationCatalog(configuration.catalog);
@@ -4097,6 +4353,7 @@ function resolveServiceAuthorization(input) {
4097
4353
  skipNested: configuration.unsafeSkipReadNestedDocumentSnapshotChecks === true,
4098
4354
  skipInitialOutputCopy: configuration.unsafeSkipReadOutputSnapshotChecks === true && configuration.unsafeSkipReadInitialOutputSnapshotCopy === true
4099
4355
  }) : void 0;
4356
+ const authorizationFastPath = input.parent ? nestedResponse || readResponse && input.snapshotDerivation?.kind === "retry" ? callRecord(input.parent).authorizationFastPath : void 0 : listResponse ? fastPaths.list : readResponse ? fastPaths.read : void 0;
4100
4357
  const call = Object.freeze(/* @__PURE__ */ Object.create(null));
4101
4358
  calls.set(call, {
4102
4359
  binding: Object.freeze({ ...input.binding, scopePath: Object.freeze(scopePath) }),
@@ -4111,6 +4368,10 @@ function resolveServiceAuthorization(input) {
4111
4368
  readResponse,
4112
4369
  nestedResponse,
4113
4370
  responseSnapshots,
4371
+ authorizationFastPath,
4372
+ fieldPolicyOwner: void 0,
4373
+ trustedView: void 0,
4374
+ reusableFieldConfiguration: void 0,
4114
4375
  validateOutputSnapshots: responseSnapshots?.skipOutput !== true,
4115
4376
  skipInitialOutputSnapshotCopy: responseSnapshots?.skipInitialOutputCopy === true,
4116
4377
  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)
@@ -4120,6 +4381,7 @@ function resolveServiceAuthorization(input) {
4120
4381
  function readServiceAuthorization(call, binding) {
4121
4382
  assertAuthorizationBinding(call, binding);
4122
4383
  const record3 = callRecord(call);
4384
+ if (record3.authorizationFastPath?.mode === "active") return readTrustedServiceAuthorization(call, binding);
4123
4385
  return copyAuthorizationValue(
4124
4386
  {
4125
4387
  authorization: record3.policy,
@@ -4130,6 +4392,27 @@ function readServiceAuthorization(call, binding) {
4130
4392
  true
4131
4393
  );
4132
4394
  }
4395
+ function readTrustedServiceAuthorization(call, binding) {
4396
+ assertAuthorizationBinding(call, binding);
4397
+ const record3 = callRecord(call);
4398
+ if (record3.authorizationFastPath?.mode !== "active") return;
4399
+ if (!record3.trustedView) {
4400
+ record3.trustedView = Object.freeze({
4401
+ authorization: record3.policy,
4402
+ configuration: record3.configuration,
4403
+ access: record3.access,
4404
+ relatedTargets: record3.relatedTargets
4405
+ });
4406
+ trustedViews.add(record3.trustedView);
4407
+ }
4408
+ if (!trustedViews.has(record3.trustedView)) authorizationError("invalid trusted configuration view");
4409
+ return record3.trustedView;
4410
+ }
4411
+ function serviceOutputFieldPolicyOwner(call, binding) {
4412
+ const record3 = callRecord(call);
4413
+ if (record3.authorizationFastPath?.mode === "active") assertAuthorizationBinding(call, binding);
4414
+ return record3.fieldPolicyOwner ?? call;
4415
+ }
4133
4416
  function readServiceAuthorizationAccess(call, binding) {
4134
4417
  assertAuthorizationBinding(call, binding);
4135
4418
  return callRecord(call).output.access;
@@ -4138,6 +4421,10 @@ function requiresDocumentSnapshotChecks(call, binding) {
4138
4421
  assertAuthorizationBinding(call, binding);
4139
4422
  return callRecord(call).validateDocumentSnapshots;
4140
4423
  }
4424
+ function readAuthorizationFastPath(call, binding) {
4425
+ assertAuthorizationBinding(call, binding);
4426
+ return callRecord(call).authorizationFastPath;
4427
+ }
4141
4428
  function requiresOutputSnapshotChecks(call, binding) {
4142
4429
  assertAuthorizationBinding(call, binding);
4143
4430
  return callRecord(call).validateOutputSnapshots;
@@ -4148,7 +4435,10 @@ function skipsInitialOutputSnapshotCopy(call) {
4148
4435
  }
4149
4436
  function readServiceAuthorizationHydration(call, binding) {
4150
4437
  assertAuthorizationBinding(call, binding);
4151
- return copyAuthorizationValue({ hydration: callRecord(call).configuration.hydration }, true);
4438
+ const record3 = callRecord(call);
4439
+ if (record3.authorizationFastPath?.mode === "active")
4440
+ return Object.freeze({ hydration: record3.configuration.hydration });
4441
+ return copyAuthorizationValue({ hydration: record3.configuration.hydration }, true);
4152
4442
  }
4153
4443
  function outputMetadata(configuration) {
4154
4444
  return {
@@ -4160,11 +4450,18 @@ function outputMetadata(configuration) {
4160
4450
  }
4161
4451
  function readServiceOutputMetadata(call, binding) {
4162
4452
  assertAuthorizationBinding(call, binding);
4163
- return copyAuthorizationValue(outputMetadata(callRecord(call).configuration), true);
4453
+ const record3 = callRecord(call);
4454
+ if (record3.authorizationFastPath?.mode === "active") return Object.freeze(outputMetadata(record3.configuration));
4455
+ return copyAuthorizationValue(outputMetadata(record3.configuration), true);
4164
4456
  }
4165
4457
  function readServiceDocumentPermissions(call, binding) {
4166
4458
  assertAuthorizationBinding(call, binding);
4167
4459
  const record3 = callRecord(call);
4460
+ if (record3.authorizationFastPath?.mode === "active")
4461
+ return Object.freeze({
4462
+ catalog: record3.output.catalog,
4463
+ docPermissions: record3.configuration.docPermissions
4464
+ });
4168
4465
  return Object.freeze({
4169
4466
  catalog: record3.output.catalog,
4170
4467
  ...copyAuthorizationValue({ docPermissions: record3.configuration.docPermissions }, true)
@@ -4173,6 +4470,13 @@ function readServiceDocumentPermissions(call, binding) {
4173
4470
  function readServiceFinalizerConfiguration(call, binding) {
4174
4471
  assertAuthorizationBinding(call, binding);
4175
4472
  const record3 = callRecord(call);
4473
+ if (record3.authorizationFastPath?.mode === "active")
4474
+ return Object.freeze({
4475
+ catalog: record3.output.catalog,
4476
+ ...outputMetadata(record3.configuration),
4477
+ virtuals: record3.configuration.virtuals,
4478
+ docPermissions: record3.configuration.docPermissions
4479
+ });
4176
4480
  return Object.freeze({
4177
4481
  catalog: record3.output.catalog,
4178
4482
  ...copyAuthorizationValue(
@@ -4192,6 +4496,15 @@ function readServiceOutputPolicy(call, binding) {
4192
4496
  function readServiceOutputFieldAuthorization(call, binding) {
4193
4497
  assertAuthorizationBinding(call, binding);
4194
4498
  const record3 = callRecord(call);
4499
+ if (record3.authorizationFastPath?.mode === "active")
4500
+ return Object.freeze({
4501
+ access: record3.output.access,
4502
+ catalog: record3.output.catalog,
4503
+ outputFields: record3.output.outputFields,
4504
+ reusable: true,
4505
+ permissionSchema: record3.configuration.permissionSchema,
4506
+ modelPermissionPrefix: record3.configuration.modelPermissionPrefix
4507
+ });
4195
4508
  const reusable = reusableOutputFieldConfiguration(record3);
4196
4509
  return Object.freeze({
4197
4510
  access: record3.output.access,
@@ -4215,7 +4528,7 @@ function reusableOutputFieldConfiguration(record3) {
4215
4528
  function canPrepareStaticOutputPolicy(call, binding) {
4216
4529
  assertAuthorizationBinding(call, binding);
4217
4530
  const record3 = callRecord(call);
4218
- return reusableOutputFieldConfiguration(record3) && typeof (record3.configuration.modelPermissionPrefix ?? "") === "string";
4531
+ return (record3.authorizationFastPath?.mode === "active" || reusableOutputFieldConfiguration(record3)) && typeof (record3.configuration.modelPermissionPrefix ?? "") === "string";
4219
4532
  }
4220
4533
  function getAuthorizationPermissions(call, binding) {
4221
4534
  assertAuthorizationBinding(call, binding);
@@ -4224,14 +4537,18 @@ function getAuthorizationPermissions(call, binding) {
4224
4537
  function getAuthorizationProvenance(call) {
4225
4538
  return callRecord(call).provenance;
4226
4539
  }
4227
- var calls;
4540
+ var calls, trustedViews;
4228
4541
  var init_service_authorization = __esm({
4229
4542
  "src/acl/service-authorization.ts"() {
4230
4543
  init_permission();
4231
4544
  init_field_catalog();
4232
4545
  init_authorization_snapshot();
4546
+ init_public_admission();
4547
+ init_captured_authorization_configuration();
4548
+ init_unsafe_snapshot_options();
4233
4549
  init_authorization_snapshot();
4234
4550
  calls = /* @__PURE__ */ new WeakMap();
4551
+ trustedViews = /* @__PURE__ */ new WeakSet();
4235
4552
  }
4236
4553
  });
4237
4554
 
@@ -4285,7 +4602,32 @@ function classifyEffectiveFieldAuthorization(args) {
4285
4602
  return combineFieldAuthorizationStates(states2);
4286
4603
  }
4287
4604
  async function evaluateScopedAccessRule(args) {
4288
- const { req, rule, globalPermissions, docPermissions, modelPermissionPrefix } = args;
4605
+ if (typeof args.rule !== "function") return evaluateNonFunctionAccessRule(args);
4606
+ try {
4607
+ return Boolean(await args.rule.call(args.req, args.globalPermissions, args.docPermissions));
4608
+ } catch {
4609
+ return false;
4610
+ }
4611
+ }
4612
+ function evaluateScopedAccessRuleValue(args) {
4613
+ if (typeof args.rule !== "function") return evaluateNonFunctionAccessRule(args);
4614
+ try {
4615
+ const value = args.rule.call(args.req, args.globalPermissions, args.docPermissions);
4616
+ if (value && typeof value.then === "function")
4617
+ return (async () => {
4618
+ try {
4619
+ return Boolean(await value);
4620
+ } catch {
4621
+ return false;
4622
+ }
4623
+ })();
4624
+ return Boolean(value);
4625
+ } catch {
4626
+ return false;
4627
+ }
4628
+ }
4629
+ function evaluateNonFunctionAccessRule(args) {
4630
+ const { rule, globalPermissions, docPermissions, modelPermissionPrefix } = args;
4289
4631
  if (typeof rule === "boolean") return rule;
4290
4632
  const validator = createValidator((key) => {
4291
4633
  try {
@@ -4300,13 +4642,6 @@ async function evaluateScopedAccessRule(args) {
4300
4642
  });
4301
4643
  if (typeof rule === "string") return validator.stringHandler(rule);
4302
4644
  if (Array.isArray(rule)) return validator.arrayHandler(rule);
4303
- if (typeof rule === "function") {
4304
- try {
4305
- return Boolean(await rule.call(req, globalPermissions, docPermissions));
4306
- } catch {
4307
- return false;
4308
- }
4309
- }
4310
4645
  return false;
4311
4646
  }
4312
4647
  async function evaluateEffectiveFieldAuthorization(args) {
@@ -4651,7 +4986,8 @@ function planAuthorizedModelProjection(args) {
4651
4986
  internalFetch: args.internalFetch,
4652
4987
  globalPermissions: getAuthorizationPermissions(args.authorization, args.binding)
4653
4988
  },
4654
- authorization.outputFields
4989
+ authorization.outputFields,
4990
+ readAuthorizationFastPath(args.authorization, args.binding)?.mode === "active"
4655
4991
  );
4656
4992
  plan.authorization = args.authorization;
4657
4993
  plan.authorizationBinding = Object.freeze({ ...args.binding, scopePath: Object.freeze(scope2) });
@@ -4664,7 +5000,7 @@ function planAuthorizedModelProjection(args) {
4664
5000
  });
4665
5001
  return plan;
4666
5002
  }
4667
- function planCatalogProjection(args, outputFields = { mode: "request" }) {
5003
+ function planCatalogProjection(args, outputFields = { mode: "request" }, safeDefinitions = false) {
4668
5004
  const { snapshot, outputAccess, virtualAccess, docPermissionsAccess, receivingModelName } = args;
4669
5005
  const catalog = snapshot.catalog;
4670
5006
  const scope2 = (args.scopePath ?? []).filter((part) => part !== "sub");
@@ -4719,7 +5055,9 @@ function planCatalogProjection(args, outputFields = { mode: "request" }) {
4719
5055
  globalPermissions,
4720
5056
  modelPermissionPrefix: snapshot.modelPermissionPrefix
4721
5057
  });
4722
- states2[relative] = state;
5058
+ if (safeDefinitions)
5059
+ Object.defineProperty(states2, relative, { value: state, enumerable: true, configurable: true, writable: true });
5060
+ else states2[relative] = state;
4723
5061
  if (state === "denied" || relative === "_id") continue;
4724
5062
  if (virtual(path)) virtualLeaves.push(relative);
4725
5063
  else persisted.push(relative);
@@ -4769,7 +5107,7 @@ function planCatalogProjection(args, outputFields = { mode: "request" }) {
4769
5107
  const childIncludes = includes.filter((p) => p.startsWith(`${name}.`)).map((p) => p.slice(name.length + 1));
4770
5108
  const childExcludes = excludes.filter((p) => p.startsWith(`${name}.`)).map((p) => `-${p.slice(name.length + 1)}`);
4771
5109
  const childSelect = mode === "include" && !includes.includes(name) ? [...childIncludes, ...childExcludes] : childExcludes;
4772
- children[name] = planCatalogProjection(
5110
+ const child = planCatalogProjection(
4773
5111
  {
4774
5112
  ...args,
4775
5113
  scopePath: [...args.scopePath ?? [], name, "sub"],
@@ -4778,8 +5116,12 @@ function planCatalogProjection(args, outputFields = { mode: "request" }) {
4778
5116
  related: [],
4779
5117
  internalFetch: { baseFields: [] }
4780
5118
  },
4781
- outputFields
5119
+ outputFields,
5120
+ safeDefinitions
4782
5121
  );
5122
+ if (safeDefinitions)
5123
+ Object.defineProperty(children, name, { value: child, enumerable: true, configurable: true, writable: true });
5124
+ else children[name] = child;
4783
5125
  }
4784
5126
  const internal = args.internalFetch ?? {};
4785
5127
  const fetchIdRetained = scope2.length === 0 || catalog.paths.includes(full("_id")) || !!catalog.dynamicPaths?.some((p) => p.endsWith("._id") && matchesCatalogPattern(p, full("_id")));
@@ -4879,7 +5221,8 @@ import { types as types5 } from "util";
4879
5221
  import { isPlainObject as isPlainObject16 } from "@web-ts-toolkit/utils";
4880
5222
  function callFieldPolicy(authorization, binding) {
4881
5223
  assertAuthorizationBinding(authorization, binding);
4882
- let policy = fieldPolicies.get(authorization);
5224
+ const owner = serviceOutputFieldPolicyOwner(authorization, binding);
5225
+ let policy = fieldPolicies.get(owner);
4883
5226
  if (!policy) {
4884
5227
  const view = readServiceOutputFieldAuthorization(authorization, binding);
4885
5228
  policy = {
@@ -4891,7 +5234,7 @@ function callFieldPolicy(authorization, binding) {
4891
5234
  reusable: view.reusable,
4892
5235
  accesses: /* @__PURE__ */ new Map()
4893
5236
  };
4894
- if (view.reusable) fieldPolicies.set(authorization, policy);
5237
+ if (view.reusable) fieldPolicies.set(owner, policy);
4895
5238
  }
4896
5239
  return policy;
4897
5240
  }
@@ -5005,9 +5348,469 @@ var init_output_field_policy = __esm({
5005
5348
  }
5006
5349
  });
5007
5350
 
5008
- // src/acl/document-authorization.ts
5351
+ // src/acl/trusted-output-materialization.ts
5009
5352
  import { types as types6 } from "util";
5010
- import { Document as Document3 } from "mongoose";
5353
+ import { Document as Document3, mongo as mongo3 } from "mongoose";
5354
+ function isBorrowableAuthorizationRecord(value) {
5355
+ if (!value || typeof value !== "object" || types6.isProxy(value)) return false;
5356
+ const prototype = Object.getPrototypeOf(value);
5357
+ if (prototype !== Object.prototype && prototype !== null) return false;
5358
+ const keys2 = Reflect.ownKeys(value);
5359
+ if (keys2.length > 2e4) return false;
5360
+ for (const key of keys2) {
5361
+ if (typeof key !== "string" || unsafeKeys2.has(key)) return false;
5362
+ const slot = Object.getOwnPropertyDescriptor(value, key);
5363
+ if (!("value" in slot) || !slot.enumerable && !isGeneratedPermissionsAliasSlot(value, key, slot)) return false;
5364
+ }
5365
+ return true;
5366
+ }
5367
+ function prepareTrustedAuthorizationSource(input) {
5368
+ if (input && typeof input === "object" && !types6.isProxy(input) && input instanceof Document3) {
5369
+ let raw;
5370
+ try {
5371
+ raw = input.toObject({ virtuals: false, flattenMaps: true });
5372
+ } catch {
5373
+ raw = input._doc;
5374
+ return { kind: "copied", source: deepIsolateValue(raw, /* @__PURE__ */ new WeakMap(), true) };
5375
+ }
5376
+ return isBorrowableAuthorizationRecord(raw) ? { kind: "trusted", source: raw } : { kind: "copied", source: deepIsolateValue(raw, /* @__PURE__ */ new WeakMap(), true) };
5377
+ }
5378
+ return isBorrowableAuthorizationRecord(input) ? { kind: "trusted", source: input } : { kind: "copied", source: isolateDocForOutput(input) };
5379
+ }
5380
+ function createTrustedOutputBudget() {
5381
+ const budget = Object.freeze(/* @__PURE__ */ Object.create(null));
5382
+ budgets.set(budget, { slots: 0, failed: false });
5383
+ return budget;
5384
+ }
5385
+ function visitTrustedOutput(budget, depth, slots = 1) {
5386
+ const record3 = budgets.get(budget);
5387
+ if (!record3) authorizationError("invalid selected output budget");
5388
+ if (record3.failed || depth > 100 || (record3.slots += slots) > 2e4) {
5389
+ record3.failed = true;
5390
+ authorizationError("selected output exceeds structural limits");
5391
+ }
5392
+ }
5393
+ function defineTrustedOutputValue(output, key, value) {
5394
+ Object.defineProperty(output, key, { value, enumerable: true, configurable: true, writable: true });
5395
+ }
5396
+ function shallowTrustedOutputArray(input, budget, depth) {
5397
+ if (types6.isProxy(input)) authorizationError("unsupported selected proxy");
5398
+ const length = Object.getOwnPropertyDescriptor(input, "length").value;
5399
+ visitTrustedOutput(budget, depth, length + 1);
5400
+ for (const key of Reflect.ownKeys(input)) {
5401
+ if (key === "length") continue;
5402
+ if (typeof key !== "string" || !/^(0|[1-9]\d*)$/.test(key)) authorizationError("invalid selected array property");
5403
+ const slot = Object.getOwnPropertyDescriptor(input, key);
5404
+ if (!("value" in slot) || !slot.enumerable) authorizationError("accessor/non-enumerable selected value");
5405
+ }
5406
+ const output = [];
5407
+ for (let index = 0; index < length; index++) {
5408
+ const slot = Object.getOwnPropertyDescriptor(input, String(index));
5409
+ defineTrustedOutputValue(output, String(index), slot && "value" in slot ? slot.value : void 0);
5410
+ }
5411
+ return output;
5412
+ }
5413
+ function trustedMapOutputScope(value, fields, budget, depth) {
5414
+ if (!value || typeof value !== "object" || types6.isProxy(value) || !types6.isMap(value)) return value;
5415
+ const output = {};
5416
+ visitTrustedOutput(budget, depth);
5417
+ for (const key of fields) {
5418
+ visitTrustedOutput(budget, depth + 1);
5419
+ if (unsafeKeys2.has(key)) continue;
5420
+ if (Map.prototype.has.call(value, key)) defineTrustedOutputValue(output, key, Map.prototype.get.call(value, key));
5421
+ }
5422
+ return output;
5423
+ }
5424
+ function shallowTrustedOutput(source, budget, depth = 0) {
5425
+ visitTrustedOutput(budget, depth);
5426
+ const output = {};
5427
+ for (const key of Reflect.ownKeys(source)) {
5428
+ visitTrustedOutput(budget, depth + 1);
5429
+ if (typeof key !== "string" || unsafeKeys2.has(key)) authorizationError("unsafe selected output root");
5430
+ const slot = Object.getOwnPropertyDescriptor(source, key);
5431
+ if (isGeneratedPermissionsAliasSlot(source, key, slot)) continue;
5432
+ if (!("value" in slot) || !slot.enumerable) authorizationError("changed borrowed output root");
5433
+ defineTrustedOutputValue(output, key, slot.value);
5434
+ }
5435
+ return output;
5436
+ }
5437
+ function setTrustedOutputPath(output, path, value, budget, depth = 0, onSpine) {
5438
+ const parts = path.split(".");
5439
+ if (parts.some((key) => !key || unsafeKeys2.has(key))) authorizationError("unsafe selected output path");
5440
+ let current = output;
5441
+ const spines = [];
5442
+ for (const [index, key] of parts.slice(0, -1).entries()) {
5443
+ visitTrustedOutput(budget, depth + index + 1);
5444
+ const slot = Object.getOwnPropertyDescriptor(current, key);
5445
+ const source = slot && "value" in slot ? slot.value : void 0;
5446
+ const shell = isBorrowableAuthorizationRecord(source) ? shallowTrustedOutput(source, budget, depth + index + 1) : {};
5447
+ if (source && typeof source === "object") spines.push({ source, copy: shell });
5448
+ defineTrustedOutputValue(current, key, shell);
5449
+ current = shell;
5450
+ }
5451
+ visitTrustedOutput(budget, depth + parts.length);
5452
+ defineTrustedOutputValue(current, parts[parts.length - 1], value);
5453
+ for (const spine of spines.reverse()) onSpine?.(spine.source, spine.copy);
5454
+ }
5455
+ function unsetTrustedOutputPath(output, path, budget, onSpine) {
5456
+ const parts = path.split(".");
5457
+ if (parts.some((key) => !key || unsafeKeys2.has(key))) authorizationError("unsafe selected output path");
5458
+ let current = output;
5459
+ const spines = [];
5460
+ for (const [index, key] of parts.slice(0, -1).entries()) {
5461
+ const slot = Object.getOwnPropertyDescriptor(current, key);
5462
+ if (!slot || !("value" in slot) || !isBorrowableAuthorizationRecord(slot.value)) return;
5463
+ const shell = shallowTrustedOutput(slot.value, budget, index + 1);
5464
+ spines.push({ source: slot.value, copy: shell });
5465
+ defineTrustedOutputValue(current, key, shell);
5466
+ current = shell;
5467
+ }
5468
+ delete current[parts[parts.length - 1]];
5469
+ for (const spine of spines.reverse()) onSpine?.(spine.source, spine.copy);
5470
+ }
5471
+ function isBsonValue(input) {
5472
+ let prototype = Object.getPrototypeOf(input);
5473
+ for (let depth = 0; prototype && depth <= 100; depth++) {
5474
+ if (types6.isProxy(prototype)) return false;
5475
+ if (prototype === mongo3.BSON.BSONValue.prototype) return true;
5476
+ prototype = Object.getPrototypeOf(prototype);
5477
+ }
5478
+ return false;
5479
+ }
5480
+ function selectedDataProperty(input, key, own2 = false) {
5481
+ let object = input;
5482
+ for (let depth = 0; object && depth <= 100; depth++) {
5483
+ if (types6.isProxy(object)) authorizationError("unsupported selected proxy");
5484
+ const slot = Object.getOwnPropertyDescriptor(object, key);
5485
+ if (slot) {
5486
+ if (!("value" in slot)) authorizationError("accessor selected BSON state");
5487
+ return slot.value;
5488
+ }
5489
+ object = own2 ? null : Object.getPrototypeOf(object);
5490
+ }
5491
+ if (object) authorizationError("unsupported selected prototype depth");
5492
+ return void 0;
5493
+ }
5494
+ function selectedBsonBytes(input) {
5495
+ if (!input || typeof input !== "object" || types6.isProxy(input) || !types6.isUint8Array(input))
5496
+ authorizationError("unsupported selected BSON bytes");
5497
+ const prototype = Object.getPrototypeOf(Uint8Array.prototype);
5498
+ const buffer = Object.getOwnPropertyDescriptor(prototype, "buffer").get.call(input);
5499
+ const offset = Object.getOwnPropertyDescriptor(prototype, "byteOffset").get.call(input);
5500
+ const length = Object.getOwnPropertyDescriptor(prototype, "byteLength").get.call(input);
5501
+ return Buffer.from(new Uint8Array(buffer, offset, length));
5502
+ }
5503
+ function copyTrustedBsonValue(value, path, budget, policy, depth, active) {
5504
+ const wireKeys = /* @__PURE__ */ new Set([
5505
+ "value",
5506
+ "code",
5507
+ "scope",
5508
+ "collection",
5509
+ "oid",
5510
+ "db",
5511
+ "fields",
5512
+ "low",
5513
+ "high",
5514
+ "unsigned",
5515
+ "buffer",
5516
+ "sub_type",
5517
+ "position",
5518
+ "pattern",
5519
+ "options",
5520
+ "bytes",
5521
+ "i0",
5522
+ "i1",
5523
+ "i2",
5524
+ "i3"
5525
+ ]);
5526
+ const defineWireValue = (output, key, value2) => {
5527
+ wireKeys.add(key);
5528
+ defineTrustedOutputValue(output, key, value2);
5529
+ };
5530
+ const prepareWire = (input, current, level, observeHook = true, entered = false, documentRoot = false, slots = 1) => {
5531
+ if (!entered) visitTrustedOutput(budget, level, slots);
5532
+ if (typeof input === "function" || typeof input === "symbol") authorizationError("unsupported selected BSON value");
5533
+ if (input === null || typeof input !== "object") return input;
5534
+ if (types6.isProxy(input)) authorizationError("unsupported selected proxy");
5535
+ if (!entered && active.has(input)) authorizationError("cyclic selected output");
5536
+ if (!entered) active.add(input);
5537
+ try {
5538
+ const hook = selectedDataProperty(input, "toBSON");
5539
+ if (typeof hook === "function") {
5540
+ if (!observeHook) authorizationError("chained selected BSON hooks");
5541
+ const normalized = Reflect.apply(hook, input, []);
5542
+ if (normalized !== input) return prepareWire(normalized, current, level, false, false, documentRoot);
5543
+ }
5544
+ if (isBsonValue(input)) {
5545
+ if (documentRoot) authorizationError("unsupported selected BSON document");
5546
+ let prototype2 = input;
5547
+ for (let hops = 0; prototype2 && !bsonFamilies.has(prototype2) && hops <= 100; hops++) {
5548
+ if (types6.isProxy(prototype2)) authorizationError("unsupported selected proxy");
5549
+ if (Object.hasOwn(prototype2, "_bsontype") || Object.hasOwn(prototype2, /* @__PURE__ */ Symbol.for("@@mdb.bson.type")))
5550
+ authorizationError("overridden selected BSON brand");
5551
+ prototype2 = Object.getPrototypeOf(prototype2);
5552
+ }
5553
+ if (!prototype2 || !bsonFamilies.has(prototype2)) authorizationError("unsupported selected BSON family");
5554
+ const family = bsonFamilies.get(prototype2);
5555
+ const output2 = Object.create(prototype2);
5556
+ Object.defineProperty(output2, "toBSON", { value: void 0 });
5557
+ const field = (key, type) => {
5558
+ const value2 = selectedDataProperty(input, key, true);
5559
+ if (typeof value2 !== type) authorizationError("unsupported selected BSON state");
5560
+ defineWireValue(output2, key, value2);
5561
+ return value2;
5562
+ };
5563
+ const bytes = (key, length) => {
5564
+ const value2 = selectedBsonBytes(selectedDataProperty(input, key, true));
5565
+ if (length !== void 0 && value2.length !== length) authorizationError("invalid selected BSON bytes");
5566
+ defineWireValue(output2, key, value2);
5567
+ };
5568
+ const method = (key) => {
5569
+ if (selectedDataProperty(input, key) !== selectedDataProperty(prototype2, key))
5570
+ authorizationError("unsupported selected BSON serializer override");
5571
+ };
5572
+ const document = (key) => {
5573
+ const raw = selectedDataProperty(input, key, true);
5574
+ const value2 = prepareWire(raw, `${current}.${key}`, level + 1, true, false, true);
5575
+ if (!value2 || typeof value2 !== "object" || !Array.isArray(value2) && Object.getPrototypeOf(value2) !== null)
5576
+ authorizationError("unsupported selected BSON document");
5577
+ defineWireValue(output2, key, value2);
5578
+ };
5579
+ switch (family) {
5580
+ case "Code": {
5581
+ field("code", "string");
5582
+ const scope2 = selectedDataProperty(input, "scope", true);
5583
+ if (scope2 != null) document("scope");
5584
+ else defineWireValue(output2, "scope", scope2);
5585
+ break;
5586
+ }
5587
+ case "DBRef": {
5588
+ field("collection", "string");
5589
+ const db = selectedDataProperty(input, "db", true);
5590
+ if (db != null) field("db", "string");
5591
+ defineWireValue(
5592
+ output2,
5593
+ "oid",
5594
+ prepareWire(selectedDataProperty(input, "oid", true), `${current}.oid`, level + 1)
5595
+ );
5596
+ document("fields");
5597
+ const ordered = /* @__PURE__ */ Object.create(null);
5598
+ defineWireValue(ordered, "$ref", output2.collection);
5599
+ defineWireValue(ordered, "$id", output2.oid);
5600
+ if (db != null) defineWireValue(ordered, "$db", output2.db);
5601
+ for (const key of Object.keys(output2.fields))
5602
+ defineWireValue(ordered, key, output2.fields[key]);
5603
+ return ordered;
5604
+ }
5605
+ case "ObjectId":
5606
+ method("serializeInto");
5607
+ if (Object.hasOwn(input, "buffer"))
5608
+ bytes("buffer", 12);
5609
+ else for (const key of ["i0", "i1", "i2", "i3"]) field(key, "number");
5610
+ break;
5611
+ case "Timestamp":
5612
+ case "Long":
5613
+ method("getLowBits");
5614
+ method("getHighBits");
5615
+ field("low", "number");
5616
+ field("high", "number");
5617
+ field("unsigned", "boolean");
5618
+ break;
5619
+ case "Decimal128":
5620
+ bytes("bytes", 16);
5621
+ break;
5622
+ case "Binary": {
5623
+ bytes("buffer");
5624
+ const position = field("position", "number");
5625
+ const subtype = field("sub_type", "number");
5626
+ if (!Number.isInteger(position) || position < 0 || position > output2.buffer.length || !Number.isInteger(subtype) || subtype < 0 || subtype > 255)
5627
+ authorizationError("invalid selected BSON binary");
5628
+ break;
5629
+ }
5630
+ case "Int32":
5631
+ method("valueOf");
5632
+ field("value", "number");
5633
+ break;
5634
+ case "Double":
5635
+ field("value", "number");
5636
+ break;
5637
+ case "BSONSymbol":
5638
+ field("value", "string");
5639
+ break;
5640
+ case "BSONRegExp":
5641
+ field("pattern", "string");
5642
+ field("options", "string");
5643
+ break;
5644
+ }
5645
+ return output2;
5646
+ }
5647
+ if (selectedDataProperty(input, "_bsontype") != null) authorizationError("unsupported selected BSON tag");
5648
+ const noHook = (value2) => {
5649
+ Object.defineProperty(value2, "toBSON", { value: void 0 });
5650
+ return value2;
5651
+ };
5652
+ if (types6.isDate(input)) {
5653
+ const getTime = selectedDataProperty(input, "getTime");
5654
+ if (typeof getTime !== "function") authorizationError("unsupported selected BSON date");
5655
+ const time = Reflect.apply(getTime, input, []);
5656
+ if (typeof time !== "number") authorizationError("unsupported selected BSON date");
5657
+ return noHook(new Date(time));
5658
+ }
5659
+ if (types6.isUint8Array(input)) return noHook(selectedBsonBytes(input));
5660
+ if (types6.isRegExp(input)) {
5661
+ const source = Object.getOwnPropertyDescriptor(RegExp.prototype, "source").get.call(input);
5662
+ const flags = ["hasIndices", "global", "ignoreCase", "multiline", "dotAll", "unicode", "unicodeSets", "sticky"].map(
5663
+ (name, index) => Object.getOwnPropertyDescriptor(RegExp.prototype, name)?.get?.call(input) ? "dgimsuvy"[index] : ""
5664
+ ).join("");
5665
+ return noHook(new RegExp(source, flags));
5666
+ }
5667
+ const output = /* @__PURE__ */ Object.create(null);
5668
+ if (types6.isMap(input)) {
5669
+ for (const [key, entry] of Map.prototype.entries.call(input)) {
5670
+ visitTrustedOutput(budget, level + 1);
5671
+ if (typeof key !== "string") authorizationError("selected Map requires string keys");
5672
+ if (protectedValueKeys.has(key) || !policy.keep(key, `${current}.${key}`)) continue;
5673
+ defineWireValue(output, key, prepareWire(entry, `${current}.${key}`, level + 1));
5674
+ }
5675
+ return output;
5676
+ }
5677
+ const array = Array.isArray(input);
5678
+ const prototype = Object.getPrototypeOf(input);
5679
+ if (!array && prototype !== Object.prototype && prototype !== null)
5680
+ authorizationError("unsupported selected object");
5681
+ const container = array ? noHook([]) : output;
5682
+ if (array) {
5683
+ const length = Object.getOwnPropertyDescriptor(input, "length").value;
5684
+ visitTrustedOutput(budget, level + 1, length);
5685
+ container.length = length;
5686
+ for (let index = 0; index < length; index++) defineWireValue(container, String(index), void 0);
5687
+ }
5688
+ for (const key of Reflect.ownKeys(input)) {
5689
+ if (array && key === "length") continue;
5690
+ visitTrustedOutput(budget, level + 1);
5691
+ if (typeof key !== "string") authorizationError("symbol selected output key");
5692
+ if (protectedValueKeys.has(key) || key === "toBSON" && (array || typeof hook === "function")) continue;
5693
+ if (array && !/^(0|[1-9]\d*)$/.test(key)) authorizationError("invalid selected array property");
5694
+ const child = array ? current : `${current}.${key}`;
5695
+ if (!array && !policy.keep(key, child)) continue;
5696
+ const slot = Object.getOwnPropertyDescriptor(input, key);
5697
+ if (!("value" in slot) || !slot.enumerable) authorizationError("accessor/non-enumerable selected value");
5698
+ defineWireValue(container, key, prepareWire(slot.value, child, level + 1, true, false, false, 0));
5699
+ }
5700
+ return container;
5701
+ } finally {
5702
+ if (!entered) active.delete(input);
5703
+ }
5704
+ };
5705
+ const prepared = prepareWire(value, path, depth, true, true);
5706
+ for (const key of wireKeys) {
5707
+ const slot = Object.getOwnPropertyDescriptor(Object.prototype, key);
5708
+ if (slot && !("value" in slot)) authorizationError("inherited accessor selected BSON output");
5709
+ }
5710
+ const wrapper = /* @__PURE__ */ Object.create(null);
5711
+ defineTrustedOutputValue(wrapper, "value", prepared);
5712
+ return mongo3.BSON.deserialize(mongo3.BSON.serialize(wrapper), { promoteValues: false, bsonRegExp: true }).value;
5713
+ }
5714
+ function materializeTrustedOutputValue(value, path, budget, policy, depth = 0) {
5715
+ const active = /* @__PURE__ */ new WeakSet();
5716
+ const visit = (input, current, level, slots = 1) => {
5717
+ visitTrustedOutput(budget, level, slots);
5718
+ if (typeof input === "function" || typeof input === "symbol") authorizationError("unsupported selected value");
5719
+ if (input === null || typeof input !== "object") return input;
5720
+ if (types6.isProxy(input)) authorizationError("unsupported selected proxy");
5721
+ if (active.has(input)) authorizationError("cyclic selected output");
5722
+ active.add(input);
5723
+ try {
5724
+ if (types6.isDate(input)) return new Date(input.getTime());
5725
+ if (Buffer.isBuffer(input)) return Buffer.from(input);
5726
+ if (types6.isRegExp(input)) {
5727
+ const output2 = new RegExp(input.source, input.flags);
5728
+ output2.lastIndex = input.lastIndex;
5729
+ return output2;
5730
+ }
5731
+ if (isBsonValue(input)) {
5732
+ try {
5733
+ return copyTrustedBsonValue(input, current, budget, policy, level, active);
5734
+ } catch (error2) {
5735
+ if (error2 instanceof ServiceAuthorizationError) throw error2;
5736
+ authorizationError("unsupported selected BSON value");
5737
+ }
5738
+ }
5739
+ if (types6.isMap(input)) {
5740
+ const output2 = {};
5741
+ for (const [key, entry] of Map.prototype.entries.call(input)) {
5742
+ visitTrustedOutput(budget, level + 1);
5743
+ if (typeof key !== "string") authorizationError("selected Map requires string keys");
5744
+ if (protectedValueKeys.has(key) || !policy.keep(key, `${current}.${key}`)) continue;
5745
+ defineTrustedOutputValue(output2, key, visit(entry, `${current}.${key}`, level + 1));
5746
+ }
5747
+ return output2;
5748
+ }
5749
+ const array = Array.isArray(input);
5750
+ const prototype = Object.getPrototypeOf(input);
5751
+ if (!array && prototype !== Object.prototype && prototype !== null)
5752
+ authorizationError("unsupported selected object");
5753
+ const output = array ? [] : {};
5754
+ if (array) {
5755
+ const length = Object.getOwnPropertyDescriptor(input, "length").value;
5756
+ visitTrustedOutput(budget, level + 1, length);
5757
+ output.length = length;
5758
+ }
5759
+ for (const key of Reflect.ownKeys(input)) {
5760
+ if (array && key === "length") continue;
5761
+ visitTrustedOutput(budget, level + 1);
5762
+ if (typeof key !== "string") authorizationError("symbol selected output key");
5763
+ if (protectedValueKeys.has(key)) continue;
5764
+ if (array && !/^(0|[1-9]\d*)$/.test(key)) authorizationError("invalid selected array property");
5765
+ const child = array ? current : `${current}.${key}`;
5766
+ if (!array && !policy.keep(key, child)) continue;
5767
+ const slot = Object.getOwnPropertyDescriptor(input, key);
5768
+ if (isGeneratedPermissionsAliasSlot(input, key, slot)) continue;
5769
+ if (!("value" in slot) || !slot.enumerable) authorizationError("accessor/non-enumerable selected value");
5770
+ defineTrustedOutputValue(output, key, visit(slot.value, child, level + 1, 0));
5771
+ }
5772
+ return output;
5773
+ } catch (error2) {
5774
+ if (error2 instanceof ServiceAuthorizationError) throw error2;
5775
+ authorizationError("unsupported selected value");
5776
+ } finally {
5777
+ active.delete(input);
5778
+ }
5779
+ };
5780
+ return visit(value, path, depth);
5781
+ }
5782
+ var unsafeKeys2, protectedValueKeys, budgets, bsonFamilies;
5783
+ var init_trusted_output_materialization = __esm({
5784
+ "src/acl/trusted-output-materialization.ts"() {
5785
+ init_authorization_snapshot();
5786
+ init_document();
5787
+ init_permissions_alias();
5788
+ unsafeKeys2 = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype", "_doc", "$__"]);
5789
+ protectedValueKeys = /* @__PURE__ */ new Set([...unsafeKeys2, "__v"]);
5790
+ budgets = /* @__PURE__ */ new WeakMap();
5791
+ bsonFamilies = new Map(
5792
+ Object.entries({
5793
+ ObjectId: mongo3.BSON.ObjectId,
5794
+ Code: mongo3.BSON.Code,
5795
+ DBRef: mongo3.BSON.DBRef,
5796
+ Timestamp: mongo3.BSON.Timestamp,
5797
+ Long: mongo3.BSON.Long,
5798
+ Decimal128: mongo3.BSON.Decimal128,
5799
+ Binary: mongo3.BSON.Binary,
5800
+ Double: mongo3.BSON.Double,
5801
+ Int32: mongo3.BSON.Int32,
5802
+ BSONRegExp: mongo3.BSON.BSONRegExp,
5803
+ BSONSymbol: mongo3.BSON.BSONSymbol,
5804
+ MinKey: mongo3.BSON.MinKey,
5805
+ MaxKey: mongo3.BSON.MaxKey
5806
+ }).map(([name, family]) => [family.prototype, name])
5807
+ );
5808
+ }
5809
+ });
5810
+
5811
+ // src/acl/document-authorization.ts
5812
+ import { types as types7 } from "util";
5813
+ import { Document as Document4 } from "mongoose";
5011
5814
  function bindOutputDocumentOwner(handle, knownOutput, owner, binding) {
5012
5815
  lookupDocumentOwner(handle);
5013
5816
  if (knownOutput || owner && unresolvedDocuments.has(owner)) unresolvedDocuments.add(handle);
@@ -5023,6 +5826,7 @@ function isUnresolvedOutputDocument(handle) {
5023
5826
  return unresolvedDocuments.has(handle);
5024
5827
  }
5025
5828
  function normalizeOutputAuthorizationOptions(input, options, purpose) {
5829
+ assertNoServerModelControls(options, authorizationError);
5026
5830
  const value = authorizationRecord(options, "output options");
5027
5831
  for (const key of Reflect.ownKeys(value)) {
5028
5832
  const descriptor = Object.getOwnPropertyDescriptor(value, key);
@@ -5054,6 +5858,7 @@ function normalizeOutputAuthorizationOptions(input, options, purpose) {
5054
5858
  kind: "policy",
5055
5859
  authorization: resolveServiceAuthorization({
5056
5860
  ...input,
5861
+ configuration: typeof input.configuration === "function" ? input.configuration() : input.configuration,
5057
5862
  binding: {
5058
5863
  ...input.binding,
5059
5864
  scopePath: copyAuthorizationValue(value.scopePath)
@@ -5074,6 +5879,10 @@ function lookupDocumentOwner(handle) {
5074
5879
  return record3;
5075
5880
  }
5076
5881
  function validateStageOwner(record3) {
5882
+ if (record3.sourceState === "trusted") {
5883
+ assertAuthorizationBinding(record3.call, record3.binding);
5884
+ return;
5885
+ }
5077
5886
  if (!record3.validateSnapshot) return;
5078
5887
  if (!matchesAuthorizationSnapshot(record3.input, record3.snapshot)) authorizationError("changed document snapshot");
5079
5888
  }
@@ -5087,43 +5896,164 @@ function validateDocumentOwner(handle) {
5087
5896
  function createDocumentAuthorizationStage(call, binding, projectedSnapshot) {
5088
5897
  assertAuthorizationBinding(call, binding);
5089
5898
  authorizationRecord(projectedSnapshot, "projected document snapshot");
5899
+ return createStage(
5900
+ call,
5901
+ binding,
5902
+ projectedSnapshot,
5903
+ readAuthorizationFastPath(call, binding)?.mode === "active" && isBorrowableAuthorizationRecord(projectedSnapshot) ? "trusted" : "copied"
5904
+ );
5905
+ }
5906
+ function createStage(call, binding, source, sourceState) {
5090
5907
  const stage = Object.freeze(/* @__PURE__ */ Object.create(null));
5091
5908
  const ownedBinding = Object.freeze({ ...binding, scopePath: Object.freeze([...binding.scopePath ?? []]) });
5092
- const snapshot = copyAuthorizationValue(projectedSnapshot, "document");
5093
- stages.set(stage, {
5909
+ const owner = {
5094
5910
  call,
5095
5911
  binding: ownedBinding,
5096
- input: projectedSnapshot,
5097
- snapshot,
5098
- validateSnapshot: requiresDocumentSnapshotChecks(call, binding)
5099
- });
5912
+ input: source,
5913
+ result: void 0,
5914
+ resolutionState: "unresolved"
5915
+ };
5916
+ stages.set(
5917
+ stage,
5918
+ sourceState === "trusted" ? { ...owner, sourceState, source } : {
5919
+ ...owner,
5920
+ sourceState,
5921
+ snapshot: copyAuthorizationValue(source, "document"),
5922
+ validateSnapshot: requiresDocumentSnapshotChecks(call, binding)
5923
+ }
5924
+ );
5100
5925
  return stage;
5101
5926
  }
5927
+ function prepareQueryDocumentAuthorization(call, binding, input) {
5928
+ const prepared = prepareQueryOutputSource(call, binding, input, "hook");
5929
+ if (!prepared) return;
5930
+ authorizationRecord(prepared.source, "projected document snapshot");
5931
+ return { ...prepared, stage: createStage(call, binding, prepared.source, prepared.sourceState) };
5932
+ }
5933
+ function getQueryOutputOriginal(input, call) {
5934
+ return input && typeof input === "object" && call && querySources.get(input)?.has(call) ? queryOriginals.get(input) ?? input : input;
5935
+ }
5936
+ function getQueryReferenceOriginal(input) {
5937
+ return referenceOriginals.get(input);
5938
+ }
5939
+ function captureNormalizedReferenceOrigins(original, normalized, paths, budget) {
5940
+ const storage2 = (value) => value instanceof Document4 ? value._doc : value;
5941
+ const walk = (raw, copy, parts, index, depth) => {
5942
+ visitTrustedOutput(budget, depth);
5943
+ if (!raw || !copy || typeof raw !== "object" || typeof copy !== "object" || types7.isProxy(raw) || types7.isProxy(copy))
5944
+ return;
5945
+ if (Array.isArray(raw) && Array.isArray(copy)) {
5946
+ visitTrustedOutput(budget, depth, copy.length);
5947
+ for (let slot = 0; slot < copy.length; slot++) {
5948
+ const source2 = Object.getOwnPropertyDescriptor(raw, String(slot)), target2 = Object.getOwnPropertyDescriptor(copy, String(slot));
5949
+ if (source2 && target2 && "value" in source2 && "value" in target2)
5950
+ walk(source2.value, target2.value, parts, index, depth + 1);
5951
+ }
5952
+ return;
5953
+ }
5954
+ if (index === parts.length) {
5955
+ if (raw !== copy && isBorrowableAuthorizationRecord(copy)) referenceOriginals.set(copy, raw);
5956
+ return;
5957
+ }
5958
+ const source = Object.getOwnPropertyDescriptor(storage2(raw), parts[index]), target = Object.getOwnPropertyDescriptor(copy, parts[index]);
5959
+ if (source && target && "value" in source && "value" in target)
5960
+ walk(source.value, target.value, parts, index + 1, depth + 1);
5961
+ };
5962
+ for (const path of paths) walk(original, normalized, path.split("."), 0, 0);
5963
+ }
5964
+ function prepareQueryOutputSource(call, binding, input, purpose) {
5965
+ if (readAuthorizationFastPath(call, binding)?.mode !== "active") return;
5966
+ const existing = input && typeof input === "object" ? querySources.get(input)?.get(call) : void 0;
5967
+ if (existing && (purpose !== "hook" || existing.sourceState === "copied" || isBorrowableAuthorizationRecord(input)))
5968
+ return { source: input, ...existing };
5969
+ const prepared = prepareTrustedAuthorizationSource(input);
5970
+ const budget = existing?.budget ?? (!binding.scopePath?.length ? createTrustedOutputBudget() : void 0);
5971
+ if (input && typeof input === "object" && prepared.source !== input) {
5972
+ queryOriginals.set(prepared.source, input);
5973
+ if (budget && prepared.kind === "trusted")
5974
+ captureNormalizedReferenceOrigins(
5975
+ input,
5976
+ prepared.source,
5977
+ readServiceOutputPolicy(call, binding).catalog.referencePaths ?? [],
5978
+ budget
5979
+ );
5980
+ }
5981
+ let captures2 = querySources.get(prepared.source);
5982
+ if (!captures2) querySources.set(prepared.source, captures2 = /* @__PURE__ */ new WeakMap());
5983
+ captures2.set(call, { sourceState: prepared.kind, budget });
5984
+ return { source: prepared.source, sourceState: prepared.kind, budget };
5985
+ }
5986
+ function isTrustedDocumentAuthorization(handle, binding) {
5987
+ const stage = lookupStageOwner(lookupDocumentOwner(handle).stage);
5988
+ if (stage.sourceState !== "trusted") return false;
5989
+ assertAuthorizationBinding(stage.call, binding);
5990
+ return true;
5991
+ }
5992
+ function isTrustedDocumentAuthorizationStage(stage, call, binding) {
5993
+ const record3 = lookupStageOwner(stage);
5994
+ assertAuthorizationBinding(record3.call, binding);
5995
+ if (record3.call !== call) authorizationError("document call/stage mismatch");
5996
+ return record3.sourceState === "trusted";
5997
+ }
5102
5998
  function assertDocumentAuthorizationStage(stage, call, binding, projectedSnapshot) {
5103
5999
  const record3 = lookupStageOwner(stage);
5104
6000
  validateStageOwner(record3);
5105
6001
  assertAuthorizationBinding(record3.call, binding);
5106
- if (record3.call !== call || record3.input !== projectedSnapshot || record3.validateSnapshot && !matchesAuthorizationSnapshot(projectedSnapshot, record3.snapshot)) {
6002
+ if (record3.call !== call || record3.input !== projectedSnapshot || record3.sourceState === "copied" && record3.validateSnapshot && !matchesAuthorizationSnapshot(projectedSnapshot, record3.snapshot)) {
5107
6003
  authorizationError("document call/stage/snapshot mismatch");
5108
6004
  }
5109
6005
  }
5110
6006
  function resolveDocumentAuthorization(stage, resolveGrants) {
5111
6007
  const record3 = lookupStageOwner(stage);
5112
6008
  validateStageOwner(record3);
6009
+ if (record3.sourceState === "trusted") {
6010
+ if (!record3.result) {
6011
+ record3.resolutionState = "pending";
6012
+ record3.result = (async () => {
6013
+ try {
6014
+ assertAuthorizationBinding(record3.call, record3.binding);
6015
+ const result2 = resolveGrants.call(
6016
+ record3.binding.request,
6017
+ record3.source,
6018
+ getAuthorizationPermissions(record3.call, record3.binding)
6019
+ );
6020
+ const grants = result2 && typeof result2.then === "function" ? await result2 : result2;
6021
+ assertAuthorizationBinding(record3.call, record3.binding);
6022
+ const grantState = isBorrowableAuthorizationRecord(grants) ? "borrowed" : "copied";
6023
+ const value = grantState === "borrowed" ? grants : copyAuthorizationValue(authorizationRecord(grants, "document grants"));
6024
+ const handle = Object.freeze(/* @__PURE__ */ Object.create(null));
6025
+ documents.set(handle, { stage, grants: value, grantState, decisions: /* @__PURE__ */ new Map() });
6026
+ record3.resolutionState = "fulfilled";
6027
+ return handle;
6028
+ } catch (error2) {
6029
+ record3.resolutionState = "rejected";
6030
+ throw error2;
6031
+ }
6032
+ })();
6033
+ }
6034
+ return record3.result;
6035
+ }
5113
6036
  if (!record3.result) {
6037
+ record3.resolutionState = "pending";
5114
6038
  record3.result = Promise.resolve().then(async () => {
5115
- validateStageOwner(record3);
5116
- const result2 = resolveGrants.call(
5117
- record3.binding.request,
5118
- copyAuthorizationValue(record3.snapshot, "document"),
5119
- getAuthorizationPermissions(record3.call, record3.binding)
5120
- );
5121
- const grants = result2 && typeof result2.then === "function" ? await result2 : result2;
5122
- validateStageOwner(record3);
5123
- const ownedGrants = copyAuthorizationValue(authorizationRecord(grants, "document grants"));
5124
- const handle = Object.freeze(/* @__PURE__ */ Object.create(null));
5125
- documents.set(handle, { stage, grants: ownedGrants, decisions: /* @__PURE__ */ new Map() });
5126
- return handle;
6039
+ try {
6040
+ validateStageOwner(record3);
6041
+ const result2 = resolveGrants.call(
6042
+ record3.binding.request,
6043
+ copyAuthorizationValue(record3.snapshot, "document"),
6044
+ getAuthorizationPermissions(record3.call, record3.binding)
6045
+ );
6046
+ const grants = result2 && typeof result2.then === "function" ? await result2 : result2;
6047
+ validateStageOwner(record3);
6048
+ const ownedGrants = copyAuthorizationValue(authorizationRecord(grants, "document grants"));
6049
+ const handle = Object.freeze(/* @__PURE__ */ Object.create(null));
6050
+ documents.set(handle, { stage, grants: ownedGrants, grantState: "copied", decisions: /* @__PURE__ */ new Map() });
6051
+ record3.resolutionState = "fulfilled";
6052
+ return handle;
6053
+ } catch (error2) {
6054
+ record3.resolutionState = "rejected";
6055
+ throw error2;
6056
+ }
5127
6057
  });
5128
6058
  }
5129
6059
  return record3.result;
@@ -5134,7 +6064,9 @@ function readDocumentAuthorization(handle, binding) {
5134
6064
  return Object.freeze({
5135
6065
  authorization: stage.call,
5136
6066
  stage: record3.stage,
5137
- grants: copyAuthorizationValue(record3.grants),
6067
+ grants: stage.sourceState === "trusted" ? record3.grants : copyAuthorizationValue(record3.grants),
6068
+ sourceState: stage.sourceState,
6069
+ grantState: record3.grantState,
5138
6070
  ...readServiceAuthorizationAccess(stage.call, binding)
5139
6071
  });
5140
6072
  }
@@ -5143,12 +6075,14 @@ function readDocumentAuthorizationAccess(handle, binding) {
5143
6075
  return Object.freeze({
5144
6076
  authorization: stage.call,
5145
6077
  stage: record3.stage,
6078
+ sourceState: stage.sourceState,
5146
6079
  ...readServiceAuthorizationAccess(stage.call, binding)
5147
6080
  });
5148
6081
  }
5149
6082
  function memoizeDocumentFieldDecision(handle, binding, field, evaluate) {
5150
6083
  const { document: record3, stage } = validateDocumentOwner(handle);
5151
6084
  assertAuthorizationBinding(stage.call, binding);
6085
+ if (stage.sourceState === "trusted") return memoizeTrustedFieldDecision(record3, stage, binding, field, evaluate);
5152
6086
  let decision = record3.decisions.get(field);
5153
6087
  if (decision) {
5154
6088
  return decision.promise.then((result2) => {
@@ -5159,6 +6093,7 @@ function memoizeDocumentFieldDecision(handle, binding, field, evaluate) {
5159
6093
  } else {
5160
6094
  const created = {
5161
6095
  state: "pending",
6096
+ value: void 0,
5162
6097
  promise: Promise.resolve().then(async () => {
5163
6098
  validateStageOwner(stage);
5164
6099
  assertAuthorizationBinding(stage.call, binding);
@@ -5187,8 +6122,52 @@ function memoizeDocumentFieldDecision(handle, binding, field, evaluate) {
5187
6122
  }
5188
6123
  return decision.promise;
5189
6124
  }
6125
+ function memoizeTrustedFieldDecision(record3, stage, binding, field, evaluate) {
6126
+ const previous = record3.decisions.get(field);
6127
+ if (previous) return previous.state === "fulfilled" ? previous.value : previous.promise;
6128
+ let fulfill, reject;
6129
+ const decision = {
6130
+ state: "pending",
6131
+ value: void 0,
6132
+ promise: new Promise((resolve, fail3) => {
6133
+ fulfill = resolve;
6134
+ reject = fail3;
6135
+ })
6136
+ };
6137
+ record3.decisions.set(field, decision);
6138
+ const settle = (value) => {
6139
+ assertAuthorizationBinding(stage.call, binding);
6140
+ assertAuthorizationBinding(stage.call, stage.binding);
6141
+ if (typeof value !== "boolean") authorizationError("field decision must be boolean");
6142
+ decision.value = value;
6143
+ decision.state = "fulfilled";
6144
+ fulfill(value);
6145
+ return value;
6146
+ };
6147
+ const fail2 = (error2) => {
6148
+ decision.state = "rejected";
6149
+ reject(error2);
6150
+ };
6151
+ try {
6152
+ const value = evaluate.call(stage.binding.request, getAuthorizationPermissions(stage.call, binding), record3.grants);
6153
+ if (value && typeof value.then === "function") {
6154
+ void (async () => {
6155
+ try {
6156
+ settle(await value);
6157
+ } catch (error2) {
6158
+ fail2(error2);
6159
+ }
6160
+ })();
6161
+ return decision.promise;
6162
+ }
6163
+ return settle(value);
6164
+ } catch (error2) {
6165
+ fail2(error2);
6166
+ return decision.promise;
6167
+ }
6168
+ }
5190
6169
  function ordinaryDecisionBinding(binding) {
5191
- if (types6.isProxy(binding) || Object.getPrototypeOf(binding) !== Object.prototype) return false;
6170
+ if (types7.isProxy(binding) || Object.getPrototypeOf(binding) !== Object.prototype) return false;
5192
6171
  for (const key of ["request", "runtime", "model", "modelName", "scopePath"]) {
5193
6172
  const slot = Object.getOwnPropertyDescriptor(binding, key);
5194
6173
  if (slot && !("value" in slot)) return false;
@@ -5314,6 +6293,7 @@ function tryStaticRequestFieldPaths(handle, binding, access) {
5314
6293
  return decisions && [...decisions].filter(([, allowed]) => allowed).map(([field]) => field);
5315
6294
  }
5316
6295
  function unchangedOutput(output, record3) {
6296
+ if (record3.snapshotState === "trusted") return outputs.get(output) === record3;
5317
6297
  if (record3.validateSnapshot && !matchesAuthorizationSnapshot(output, record3.snapshot)) return false;
5318
6298
  const identities = outputIdentities(output);
5319
6299
  return identities.length === record3.identities.length && identities.every((identity, i) => identity === record3.identities[i]);
@@ -5329,7 +6309,7 @@ function assertDocumentAuthorization(handle, use) {
5329
6309
  authorizationError("unknown, replaced or mutated authorized output");
5330
6310
  }
5331
6311
  }
5332
- function associateDocumentAuthorization(handle, binding, output) {
6312
+ function associateDocumentAuthorization(handle, binding, output, builder) {
5333
6313
  const { stage } = validateDocumentOwner(handle);
5334
6314
  assertAuthorizationBinding(stage.call, binding);
5335
6315
  if (!output || typeof output !== "object") authorizationError("output must be an object");
@@ -5339,12 +6319,17 @@ function associateDocumentAuthorization(handle, binding, output) {
5339
6319
  authorizationError("output already associated");
5340
6320
  return;
5341
6321
  }
6322
+ const members = builder ? finishTrustedOutputMembers(builder, handle, binding, output) : void 0;
6323
+ if (stage.sourceState === "trusted") {
6324
+ outputs.set(output, { handle, snapshotState: "trusted", members: members ?? /* @__PURE__ */ new Set([output]) });
6325
+ return;
6326
+ }
5342
6327
  if (skipsInitialOutputSnapshotCopy(stage.call) && ordinaryDecisionBinding(binding)) {
5343
6328
  if (requiresOutputSnapshotChecks(stage.call, binding))
5344
6329
  authorizationError("output snapshot copy requires skipped comparisons");
5345
6330
  const identities = tryOutputIdentitiesWithoutSnapshot(output);
5346
6331
  if (identities) {
5347
- outputs.set(output, { handle, snapshotState: "omitted", identities, validateSnapshot: false });
6332
+ outputs.set(output, { handle, snapshotState: "omitted", identities, validateSnapshot: false, members });
5348
6333
  return;
5349
6334
  }
5350
6335
  }
@@ -5353,7 +6338,8 @@ function associateDocumentAuthorization(handle, binding, output) {
5353
6338
  snapshotState: "copied",
5354
6339
  snapshot: copyAuthorizationValue(output, "document"),
5355
6340
  identities: outputIdentities(output),
5356
- validateSnapshot: requiresOutputSnapshotChecks(stage.call, binding)
6341
+ validateSnapshot: requiresOutputSnapshotChecks(stage.call, binding),
6342
+ members
5357
6343
  });
5358
6344
  }
5359
6345
  function transferDocumentAuthorization(handle, use, copy) {
@@ -5363,6 +6349,13 @@ function transferDocumentAuthorization(handle, use, copy) {
5363
6349
  function isKnownAuthorizationOutput(output) {
5364
6350
  return outputs.has(output);
5365
6351
  }
6352
+ function isTrustedAuthorizationOutput(output, call) {
6353
+ const record3 = outputs.get(output);
6354
+ if (record3?.snapshotState !== "trusted") return false;
6355
+ const { stage } = validateDocumentOwner(record3.handle);
6356
+ assertAuthorizationBinding(stage.call, stage.binding);
6357
+ return !call || getAuthorizationProvenance(stage.call) === getAuthorizationProvenance(call);
6358
+ }
5366
6359
  function getAssociatedDocumentAuthorization(output, call) {
5367
6360
  const record3 = outputs.get(output);
5368
6361
  if (!record3 || !unchangedOutput(output, record3)) return void 0;
@@ -5370,13 +6363,96 @@ function getAssociatedDocumentAuthorization(output, call) {
5370
6363
  if (call && getAuthorizationProvenance(stage.call) !== getAuthorizationProvenance(call)) return void 0;
5371
6364
  return record3.handle;
5372
6365
  }
6366
+ function createTrustedOutputMemberBuilder(call, binding, budget) {
6367
+ if (readAuthorizationFastPath(call, binding)?.mode !== "active") authorizationError("invalid trusted member origin");
6368
+ const builder = Object.freeze(/* @__PURE__ */ Object.create(null));
6369
+ memberBuilders.set(builder, { call, binding, budget, members: /* @__PURE__ */ new Set(), spines: /* @__PURE__ */ new WeakMap(), finished: false });
6370
+ return builder;
6371
+ }
6372
+ function retainTrustedOutputMember(builder, output) {
6373
+ const record3 = memberBuilders.get(builder);
6374
+ if (!record3 || record3.finished) authorizationError("invalid issued member builder");
6375
+ assertAuthorizationBinding(record3.call, record3.binding);
6376
+ const association = outputs.get(output);
6377
+ if (!association || !unchangedOutput(output, association)) authorizationError("unknown issued output member");
6378
+ const { stage } = validateDocumentOwner(association.handle);
6379
+ if (getAuthorizationProvenance(stage.call) !== getAuthorizationProvenance(record3.call))
6380
+ authorizationError("issued member call mismatch");
6381
+ visitTrustedOutput(record3.budget, 0);
6382
+ if (record3.members.has(output)) return;
6383
+ record3.members.add(output);
6384
+ const add = (member) => {
6385
+ visitTrustedOutput(record3.budget, 0);
6386
+ if (!record3.members.has(member)) {
6387
+ record3.members.add(member);
6388
+ }
6389
+ };
6390
+ for (const member of association.members ?? []) if (member !== output) add(member);
6391
+ }
6392
+ function retainTrustedOutputSpine(builder, source, copy) {
6393
+ const record3 = memberBuilders.get(builder);
6394
+ if (!record3 || record3.finished) authorizationError("invalid issued spine builder");
6395
+ assertAuthorizationBinding(record3.call, record3.binding);
6396
+ const association = outputs.get(source);
6397
+ if (!association) return;
6398
+ if (!unchangedOutput(source, association)) authorizationError("changed issued spine source");
6399
+ const { stage } = validateDocumentOwner(association.handle);
6400
+ if (getAuthorizationProvenance(stage.call) !== getAuthorizationProvenance(record3.call))
6401
+ authorizationError("issued spine call mismatch");
6402
+ const child = createTrustedOutputMemberBuilder(stage.call, stage.binding, record3.budget);
6403
+ const childRecord = memberBuilders.get(child);
6404
+ for (const member of association.members ?? []) {
6405
+ if (member === source) continue;
6406
+ visitTrustedOutput(record3.budget, 0);
6407
+ childRecord.members.add(member);
6408
+ const replacement = record3.spines.get(member);
6409
+ if (replacement) {
6410
+ visitTrustedOutput(record3.budget, 0);
6411
+ childRecord.members.add(replacement);
6412
+ }
6413
+ }
6414
+ associateDocumentAuthorization(association.handle, stage.binding, copy, child);
6415
+ record3.spines.set(source, copy);
6416
+ retainTrustedOutputMember(builder, copy);
6417
+ }
6418
+ function finishTrustedOutputMembers(builder, handle, binding, output) {
6419
+ const record3 = memberBuilders.get(builder);
6420
+ const { stage } = validateDocumentOwner(handle);
6421
+ if (!record3 || record3.finished || record3.call !== stage.call) authorizationError("invalid issued member publication");
6422
+ assertAuthorizationBinding(record3.call, binding);
6423
+ if (!record3.members.has(output)) {
6424
+ visitTrustedOutput(record3.budget, 0);
6425
+ record3.members.add(output);
6426
+ }
6427
+ record3.finished = true;
6428
+ return record3.members;
6429
+ }
6430
+ function getIssuedEmbeddedDocumentAuthorization(root, child, owner, binding) {
6431
+ const rootRecord = outputs.get(root);
6432
+ if (!rootRecord || rootRecord.handle !== owner || rootRecord.snapshotState !== "trusted" || !rootRecord.members.has(child))
6433
+ return;
6434
+ const childRecord = outputs.get(child);
6435
+ if (!childRecord) return;
6436
+ const owning = owningDocuments.get(childRecord.handle);
6437
+ if (owning?.handle !== owner) return;
6438
+ const { stage } = validateDocumentOwner(childRecord.handle);
6439
+ assertAuthorizationBinding(stage.call, binding);
6440
+ return childRecord.handle;
6441
+ }
6442
+ function isIssuedOutputMember(root, member) {
6443
+ const record3 = outputs.get(root);
6444
+ if (!record3 || record3.snapshotState !== "trusted" || !record3.members.has(member)) return false;
6445
+ const { stage } = validateDocumentOwner(record3.handle);
6446
+ assertAuthorizationBinding(stage.call, stage.binding);
6447
+ return outputs.has(member);
6448
+ }
5373
6449
  function transferDocumentAuthorizationGraph(source, copy, copyOrigins) {
5374
6450
  const seen = /* @__PURE__ */ new WeakSet();
5375
6451
  const visit = (source2, copy2) => {
5376
6452
  if (!copy2 || typeof copy2 !== "object" || seen.has(copy2)) return;
5377
6453
  seen.add(copy2);
5378
6454
  source2 = copyOrigins?.get(copy2) ?? source2;
5379
- if (source2 instanceof Document3) source2 = source2._doc;
6455
+ if (source2 instanceof Document4) source2 = source2._doc;
5380
6456
  const original = source2 && typeof source2 === "object" ? source2 : void 0;
5381
6457
  if (!original && !copyOrigins) return;
5382
6458
  const association = original && outputs.get(original);
@@ -5411,7 +6487,7 @@ function createServiceOutputContext(diagnostic, handle, use) {
5411
6487
  assertDocumentAuthorization(handle, use);
5412
6488
  const rootOutput = use.output;
5413
6489
  const root = outputs.get(rootOutput);
5414
- const graph = new Set(root.identities);
6490
+ const graph = root.snapshotState === "trusted" ? root.members : new Set(root.identities);
5415
6491
  const { stage } = validateDocumentOwner(handle);
5416
6492
  const call = stage.call;
5417
6493
  const context = { ...diagnostic };
@@ -5428,6 +6504,8 @@ function createServiceOutputContext(diagnostic, handle, use) {
5428
6504
  try {
5429
6505
  validateStageOwner(lookupStageOwner(lookupDocumentOwner(handle).stage));
5430
6506
  const { stage: child } = validateDocumentOwner(association.handle);
6507
+ assertAuthorizationBinding(call, use.binding);
6508
+ assertAuthorizationBinding(child.call, child.binding);
5431
6509
  if (getAuthorizationProvenance(child.call) !== getAuthorizationProvenance(call)) return void 0;
5432
6510
  return association.handle;
5433
6511
  } catch {
@@ -5438,25 +6516,40 @@ function createServiceOutputContext(diagnostic, handle, use) {
5438
6516
  });
5439
6517
  return context;
5440
6518
  }
5441
- var stages, documents, outputs, unresolvedDocuments, owningDocuments;
6519
+ var stages, documents, outputs, unresolvedDocuments, owningDocuments, querySources, queryOriginals, referenceOriginals, memberBuilders;
5442
6520
  var init_document_authorization = __esm({
5443
6521
  "src/acl/document-authorization.ts"() {
5444
6522
  init_service_authorization();
5445
6523
  init_authorization_snapshot();
5446
6524
  init_output_projection();
5447
6525
  init_output_field_policy();
6526
+ init_public_admission();
6527
+ init_trusted_output_materialization();
5448
6528
  stages = /* @__PURE__ */ new WeakMap();
5449
6529
  documents = /* @__PURE__ */ new WeakMap();
5450
6530
  outputs = /* @__PURE__ */ new WeakMap();
5451
6531
  unresolvedDocuments = /* @__PURE__ */ new WeakSet();
5452
6532
  owningDocuments = /* @__PURE__ */ new WeakMap();
6533
+ querySources = /* @__PURE__ */ new WeakMap();
6534
+ queryOriginals = /* @__PURE__ */ new WeakMap();
6535
+ referenceOriginals = /* @__PURE__ */ new WeakMap();
6536
+ memberBuilders = /* @__PURE__ */ new WeakMap();
5453
6537
  }
5454
6538
  });
5455
6539
 
5456
6540
  // src/output/include-output.ts
5457
6541
  import { set as set5 } from "@web-ts-toolkit/utils";
5458
- function prepareIncludeOutput(doc) {
6542
+ function prepareIncludeOutput(doc, call, binding) {
5459
6543
  if (stateFor(doc)) return doc;
6544
+ const prepared = call && binding ? prepareQueryOutputSource(call, binding, doc) : void 0;
6545
+ if (prepared) {
6546
+ const source2 = prepared.source;
6547
+ const budget = prepared.budget ?? createTrustedOutputBudget();
6548
+ const trusted = prepared.sourceState === "trusted" ? { call, binding, budget } : void 0;
6549
+ const working2 = trusted ? shallowTrustedOutput(source2, budget) : deepIsolateValue(source2);
6550
+ outputs2.set(working2, { original: getQueryOutputOriginal(doc, call), source: source2, attachments: [], trusted });
6551
+ return working2;
6552
+ }
5460
6553
  const source = isolateDocForOutput(doc);
5461
6554
  transferDocumentAuthorizationGraph(doc, source);
5462
6555
  const working = deepIsolateValue(source);
@@ -5467,13 +6560,59 @@ function attachIncludeOutput(doc, path, value) {
5467
6560
  const state = stateFor(doc);
5468
6561
  if (!state) throw new Error("Include attachment requires a prepared output row");
5469
6562
  state.attachments.push({ path, value });
5470
- set5(doc, path, deepIsolateValue(value));
6563
+ if (state.trusted) setTrustedOutputPath(doc, path, value, state.trusted.budget);
6564
+ else set5(doc, path, deepIsolateValue(value));
6565
+ }
6566
+ function restoreTrustedIncludeOutput(doc, output, materialization) {
6567
+ const state = stateFor(doc);
6568
+ if (!state?.attachments.length) return;
6569
+ for (const { path, value } of state.attachments) {
6570
+ const target = state.trusted ? readServiceAuthorization(state.trusted.call, state.trusted.binding).relatedTargets.find(
6571
+ (entry) => entry.path === path
6572
+ ) : void 0;
6573
+ const active = /* @__PURE__ */ new WeakSet();
6574
+ const retain = (input, depth) => {
6575
+ visitTrustedOutput(materialization.budget, depth);
6576
+ if (Array.isArray(input)) {
6577
+ if (active.has(input)) authorizationError("cyclic include output");
6578
+ active.add(input);
6579
+ try {
6580
+ return shallowTrustedOutputArray(input, materialization.budget, depth).map(
6581
+ (entry) => retain(entry, depth + 1)
6582
+ );
6583
+ } finally {
6584
+ active.delete(input);
6585
+ }
6586
+ }
6587
+ if (input && typeof input === "object") {
6588
+ const handle = target ? getAssociatedDocumentAuthorization(input, state.trusted.call) : void 0;
6589
+ if (!handle) authorizationError("unknown finalized include output");
6590
+ readDocumentAuthorizationAccess(handle, {
6591
+ ...state.trusted.binding,
6592
+ modelName: target.modelName,
6593
+ model: target.model,
6594
+ scopePath: []
6595
+ });
6596
+ retainTrustedOutputMember(materialization.members, input);
6597
+ return input;
6598
+ }
6599
+ return materializeTrustedOutputValue(input, path, materialization.budget, { keep: () => true }, depth);
6600
+ };
6601
+ setTrustedOutputPath(
6602
+ output,
6603
+ path,
6604
+ retain(value, materialization.depth + 1),
6605
+ materialization.budget,
6606
+ materialization.depth,
6607
+ (source, copy) => retainTrustedOutputSpine(materialization.members, source, copy)
6608
+ );
6609
+ }
5471
6610
  }
5472
6611
  function getIncludeSource(doc) {
5473
6612
  return stateFor(doc)?.source ?? doc;
5474
6613
  }
5475
- function getIncludeOriginal(doc) {
5476
- return stateFor(doc)?.original ?? doc;
6614
+ function getIncludeOriginal(doc, call) {
6615
+ return stateFor(doc)?.original ?? getQueryOutputOriginal(doc, call);
5477
6616
  }
5478
6617
  function restoreIncludeOutput(doc, output) {
5479
6618
  const attachments = stateFor(doc)?.attachments;
@@ -5490,6 +6629,10 @@ var outputs2, stateFor;
5490
6629
  var init_include_output = __esm({
5491
6630
  "src/output/include-output.ts"() {
5492
6631
  init_document_authorization();
6632
+ init_document_authorization();
6633
+ init_service_authorization();
6634
+ init_authorization_snapshot();
6635
+ init_trusted_output_materialization();
5493
6636
  init_document();
5494
6637
  outputs2 = /* @__PURE__ */ new WeakMap();
5495
6638
  stateFor = (doc) => doc !== null && typeof doc === "object" ? outputs2.get(doc) : void 0;
@@ -5535,48 +6678,47 @@ function captureModelAuthorizationConfiguration(runtime, modelName, options, pop
5535
6678
  const model = runtime.getModelInstance(modelName);
5536
6679
  if (!model) return authorizationError(`unknown receiving model: ${modelName}`);
5537
6680
  const virtuals = options.virtuals;
5538
- return copyAuthorizationValue(
5539
- {
5540
- catalog: captureAuthorizationFieldCatalog(model.schema, virtuals, options.documentPermissionField),
5541
- virtualPopulateSnapshot: captureVirtualPopulateSnapshot(
5542
- runtime,
5543
- modelName,
5544
- options,
5545
- populatePolicyDefaults
5546
- ),
5547
- populatePolicyDefaults,
5548
- ...resolvePopulatePolicy(options, populatePolicyDefaults),
5549
- permissionSchema: options.permissionSchema === void 0 ? runtime.getDefaultModelOption("permissionSchema") : options.permissionSchema,
5550
- virtuals,
5551
- alwaysSelectFields: options.alwaysSelectFields,
5552
- modelPermissionPrefix: options.modelPermissionPrefix,
5553
- requireExplicitSelect: options.requireExplicitSelect,
5554
- documentPermissionField: options.documentPermissionField,
5555
- docPermissions: options.docPermissions,
5556
- exposedDocPermissionKeys: options.exposedDocPermissionKeys,
5557
- stripPermissionsField: options.stripPermissionsField,
5558
- disableFieldPermissions: options.disableFieldPermissions,
5559
- unsafeSkipListDocumentSnapshotChecks: options.unsafeSkipListDocumentSnapshotChecks === true,
5560
- unsafeSkipReadDocumentSnapshotChecks: options.unsafeSkipReadDocumentSnapshotChecks === true,
5561
- unsafeSkipListOutputSnapshotChecks: options.unsafeSkipListOutputSnapshotChecks === true,
5562
- unsafeSkipReadOutputSnapshotChecks: options.unsafeSkipReadOutputSnapshotChecks === true,
5563
- unsafeSkipListNestedDocumentSnapshotChecks: options.unsafeSkipListNestedDocumentSnapshotChecks === true,
5564
- unsafeSkipReadNestedDocumentSnapshotChecks: options.unsafeSkipReadNestedDocumentSnapshotChecks === true,
5565
- unsafeSkipListInitialOutputSnapshotCopy: options.unsafeSkipListInitialOutputSnapshotCopy === true,
5566
- unsafeSkipReadInitialOutputSnapshotCopy: options.unsafeSkipReadInitialOutputSnapshotCopy === true,
5567
- overrideFilter: options.overrideFilter,
5568
- baseFilter: options.baseFilter,
5569
- idField: options.idField,
5570
- resolveIdFilter: options.resolveIdFilter,
5571
- operationAccess: options.operationAccess,
5572
- // A defined stored parent (including {}) wins over exact runtime defaults.
5573
- // Keep only operation fallback data; resolve each access without a live lookup.
5574
- operationAccessDefaults: options.operationAccess === void 0 ? runtime.getDefaultModelOption("operationAccess") : void 0,
5575
- hydration: options.hydration,
5576
- defaults: options.defaults
5577
- },
5578
- true
5579
- );
6681
+ return captureAuthorizationConfiguration({
6682
+ catalog: captureAuthorizationFieldCatalog(model.schema, virtuals, options.documentPermissionField),
6683
+ virtualPopulateSnapshot: captureVirtualPopulateSnapshot(
6684
+ runtime,
6685
+ modelName,
6686
+ options,
6687
+ populatePolicyDefaults
6688
+ ),
6689
+ populatePolicyDefaults,
6690
+ ...resolvePopulatePolicy(options, populatePolicyDefaults),
6691
+ permissionSchema: options.permissionSchema === void 0 ? runtime.getDefaultModelOption("permissionSchema") : options.permissionSchema,
6692
+ virtuals,
6693
+ alwaysSelectFields: options.alwaysSelectFields,
6694
+ modelPermissionPrefix: options.modelPermissionPrefix,
6695
+ requireExplicitSelect: options.requireExplicitSelect,
6696
+ documentPermissionField: options.documentPermissionField,
6697
+ docPermissions: options.docPermissions,
6698
+ exposedDocPermissionKeys: options.exposedDocPermissionKeys,
6699
+ stripPermissionsField: options.stripPermissionsField,
6700
+ disableFieldPermissions: options.disableFieldPermissions,
6701
+ unsafeSkipListDocumentSnapshotChecks: options.unsafeSkipListDocumentSnapshotChecks === true,
6702
+ unsafeSkipReadDocumentSnapshotChecks: options.unsafeSkipReadDocumentSnapshotChecks === true,
6703
+ unsafeSkipListOutputSnapshotChecks: options.unsafeSkipListOutputSnapshotChecks === true,
6704
+ unsafeSkipReadOutputSnapshotChecks: options.unsafeSkipReadOutputSnapshotChecks === true,
6705
+ unsafeSkipListNestedDocumentSnapshotChecks: options.unsafeSkipListNestedDocumentSnapshotChecks === true,
6706
+ unsafeSkipReadNestedDocumentSnapshotChecks: options.unsafeSkipReadNestedDocumentSnapshotChecks === true,
6707
+ unsafeSkipListInitialOutputSnapshotCopy: options.unsafeSkipListInitialOutputSnapshotCopy === true,
6708
+ unsafeSkipReadInitialOutputSnapshotCopy: options.unsafeSkipReadInitialOutputSnapshotCopy === true,
6709
+ unsafeUseListAuthorizationFastPath: options.unsafeUseListAuthorizationFastPath === true,
6710
+ unsafeUseReadAuthorizationFastPath: options.unsafeUseReadAuthorizationFastPath === true,
6711
+ overrideFilter: options.overrideFilter,
6712
+ baseFilter: options.baseFilter,
6713
+ idField: options.idField,
6714
+ resolveIdFilter: options.resolveIdFilter,
6715
+ operationAccess: options.operationAccess,
6716
+ // A defined stored parent (including {}) wins over exact runtime defaults.
6717
+ // Keep only operation fallback data; resolve each access without a live lookup.
6718
+ operationAccessDefaults: options.operationAccess === void 0 ? runtime.getDefaultModelOption("operationAccess") : void 0,
6719
+ hydration: options.hydration,
6720
+ defaults: options.defaults
6721
+ });
5580
6722
  }
5581
6723
  function planModelOutputForHelper(args) {
5582
6724
  const { request, runtime, modelName, access } = args;
@@ -5605,6 +6747,7 @@ var init_model_output_planning = __esm({
5605
6747
  init_manager();
5606
6748
  init_field_catalog();
5607
6749
  init_authorization_snapshot();
6750
+ init_captured_authorization_configuration();
5608
6751
  init_virtual_populate_dependencies();
5609
6752
  init_document_authorization();
5610
6753
  init_output_projection();
@@ -6180,7 +7323,7 @@ var init_filter_resolution = __esm({
6180
7323
  });
6181
7324
 
6182
7325
  // src/acl/virtual-populate-execution.ts
6183
- import { Document as Document4, mongo as mongo4 } from "mongoose";
7326
+ import { Document as Document5, mongo as mongo5 } from "mongoose";
6184
7327
  import { isDeepStrictEqual as isDeepStrictEqual3 } from "util";
6185
7328
  import { isPlainObject as isPlainObject21 } from "@web-ts-toolkit/utils";
6186
7329
  function projectVirtualPopulateView(source, selection, structurePaths = []) {
@@ -6206,10 +7349,10 @@ function projectVirtualPopulateView(source, selection, structurePaths = []) {
6206
7349
  }
6207
7350
  function equivalentVirtualPopulatePredicate(left, right) {
6208
7351
  if (Object.is(left, right)) return true;
6209
- if (left instanceof mongo4.BSON.BSONValue || right instanceof mongo4.BSON.BSONValue) {
6210
- if (!(left instanceof mongo4.BSON.BSONValue) || !(right instanceof mongo4.BSON.BSONValue)) return false;
6211
- return Buffer.from(mongo4.BSON.serialize({ value: left })).equals(
6212
- Buffer.from(mongo4.BSON.serialize({ value: right }))
7352
+ if (left instanceof mongo5.BSON.BSONValue || right instanceof mongo5.BSON.BSONValue) {
7353
+ if (!(left instanceof mongo5.BSON.BSONValue) || !(right instanceof mongo5.BSON.BSONValue)) return false;
7354
+ return Buffer.from(mongo5.BSON.serialize({ value: left })).equals(
7355
+ Buffer.from(mongo5.BSON.serialize({ value: right }))
6213
7356
  );
6214
7357
  }
6215
7358
  if (Array.isArray(left) || Array.isArray(right))
@@ -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 Document4 ? value._doc : isPlainObject21(value) ? value : void 0;
7764
+ storage = (value) => value instanceof Document5 ? value._doc : isPlainObject21(value) ? value : void 0;
6622
7765
  originalRef = (source, key) => {
6623
7766
  const record3 = storage(source);
6624
7767
  return {
@@ -6645,7 +7788,7 @@ var init_virtual_populate_execution = __esm({
6645
7788
  });
6646
7789
 
6647
7790
  // src/acl/output-field-filter.ts
6648
- import { types as types7 } from "util";
7791
+ import { types as types8 } from "util";
6649
7792
  import { isPlainObject as isPlainObject22 } from "@web-ts-toolkit/utils";
6650
7793
  function assertOwningOutputDocuments(handle) {
6651
7794
  const owner = readOutputDocumentOwner(handle);
@@ -6661,7 +7804,11 @@ function prepareOutputDocumentAuthorization(authorization, binding, configuratio
6661
7804
  const invariant = /^[A-Za-z0-9_-]+$/.test(access.docPermissionsAccess) && (docPermissions == null || isPlainObject22(docPermissions));
6662
7805
  const option = invariant ? getCapturedAuthorizationOption(configuration, key) : void 0;
6663
7806
  const hook = typeof option === "function" ? option : void 0;
6664
- const resolveHook = invariant ? () => hook : () => {
7807
+ const trusted = readAuthorizationFastPath(authorization, binding)?.mode === "active";
7808
+ const resolveHook = invariant ? () => hook : trusted ? () => {
7809
+ const option2 = getCapturedAuthorizationOption(configuration, key);
7810
+ return typeof option2 === "function" ? option2 : void 0;
7811
+ } : () => {
6665
7812
  const slice = { catalog: configuration.catalog, ...copyAuthorizationValue({ docPermissions }, true) };
6666
7813
  const option2 = getCapturedAuthorizationOption(slice, key);
6667
7814
  return typeof option2 === "function" ? option2 : void 0;
@@ -6708,6 +7855,32 @@ function evaluateRequestRule(handle, binding, entry, prefix, access) {
6708
7855
  if (owner && !entry.path.startsWith(`${(binding.scopePath ?? []).join(".")}.`)) {
6709
7856
  return evaluateRequestRule(owner.handle, owner.binding, entry, prefix, access);
6710
7857
  }
7858
+ if (isTrustedDocumentAuthorization(handle, binding))
7859
+ return memoizeDocumentFieldDecision(
7860
+ handle,
7861
+ binding,
7862
+ `request:${access}:${entry.path}`,
7863
+ function(permissions, grants) {
7864
+ const { authorization } = readDocumentAuthorizationAccess(handle, binding);
7865
+ const classification = requestRuleClassification(entry, authorization, permissions, prefix);
7866
+ const allowed = classification?.decision ?? evaluateScopedAccessRuleValue({
7867
+ req: this,
7868
+ rule: entry.rule,
7869
+ globalPermissions: permissions,
7870
+ docPermissions: grants,
7871
+ modelPermissionPrefix: prefix
7872
+ });
7873
+ if (typeof allowed !== "boolean")
7874
+ return (async () => {
7875
+ const result2 = await allowed;
7876
+ assertOwningOutputDocuments(handle);
7877
+ readDocumentAuthorizationAccess(handle, binding);
7878
+ return result2;
7879
+ })();
7880
+ assertOwningOutputDocuments(handle);
7881
+ return allowed;
7882
+ }
7883
+ );
6711
7884
  return memoizeDocumentFieldDecision(
6712
7885
  handle,
6713
7886
  binding,
@@ -6734,6 +7907,32 @@ function evaluateAuthorizedOutputField(handle, binding, field) {
6734
7907
  const { authorization } = readDocumentAuthorizationAccess(handle, binding);
6735
7908
  assertOwningOutputDocuments(handle);
6736
7909
  const path = [...binding.scopePath ?? [], field].join(".");
7910
+ const trusted = isTrustedDocumentAuthorization(handle, binding);
7911
+ if (trusted)
7912
+ return memoizeDocumentFieldDecision(handle, binding, `output:${path}`, function(permissions) {
7913
+ const policy = callFieldPolicy(authorization, binding);
7914
+ const { outputAccess } = readDocumentAuthorizationAccess(handle, binding);
7915
+ const prepared = prepareOutputPath(policy, authorization, binding, path, outputAccess);
7916
+ const unresolved = isUnresolvedOutputDocument(handle);
7917
+ const state = unresolved ? prepared.state ?? classifyEffectiveFieldAuthorization({
7918
+ path,
7919
+ rules: prepared.entries.map((entry) => entry.rule),
7920
+ modelPermissionPrefix: policy.prefix,
7921
+ outputFields: policy.outputFields,
7922
+ globalPermissions: permissions
7923
+ }) : void 0;
7924
+ if (unresolved && state !== "granted") return false;
7925
+ if (prepared.backendGrant) return true;
7926
+ const finish = () => {
7927
+ assertOwningOutputDocuments(handle);
7928
+ readDocumentAuthorizationAccess(handle, binding);
7929
+ };
7930
+ return orderedRequestRules(
7931
+ prepared.entries,
7932
+ (entry) => evaluateRequestRule(handle, binding, entry, policy.prefix, outputAccess),
7933
+ finish
7934
+ );
7935
+ });
6737
7936
  const decision = memoizeDocumentFieldDecision(handle, binding, `output:${path}`, async function(permissions) {
6738
7937
  const policy = callFieldPolicy(authorization, binding);
6739
7938
  const { outputAccess } = readDocumentAuthorizationAccess(handle, binding);
@@ -6766,10 +7965,38 @@ function evaluateAuthorizedOutputField(handle, binding, field) {
6766
7965
  return allowed;
6767
7966
  }) : decision;
6768
7967
  }
7968
+ function orderedRequestRules(entries, evaluate, check) {
7969
+ for (let index = 0; index < entries.length; index++) {
7970
+ const value = evaluate(entries[index]);
7971
+ if (typeof value !== "boolean")
7972
+ return (async () => {
7973
+ if (!await value) {
7974
+ check();
7975
+ return false;
7976
+ }
7977
+ check();
7978
+ for (let next = index + 1; next < entries.length; next++) {
7979
+ const result2 = evaluate(entries[next]);
7980
+ if (!(typeof result2 === "boolean" ? result2 : await result2)) {
7981
+ check();
7982
+ return false;
7983
+ }
7984
+ check();
7985
+ }
7986
+ return true;
7987
+ })();
7988
+ if (!value) {
7989
+ check();
7990
+ return false;
7991
+ }
7992
+ }
7993
+ check();
7994
+ return true;
7995
+ }
6769
7996
  async function requestOutputFieldPaths(handle, binding, access) {
6770
7997
  const staticFields = tryStaticRequestFieldPaths(handle, binding, access);
6771
7998
  if (staticFields) {
6772
- await Promise.resolve();
7999
+ if (!isTrustedDocumentAuthorization(handle, binding)) await Promise.resolve();
6773
8000
  readDocumentAuthorizationAccess(handle, binding);
6774
8001
  return staticFields;
6775
8002
  }
@@ -6781,7 +8008,8 @@ async function requestOutputFieldPaths(handle, binding, access) {
6781
8008
  const { entries } = prepareOutputPath(policy, authorization, binding, path, access);
6782
8009
  let allowed = true;
6783
8010
  for (const entry of entries) {
6784
- if (!await evaluateRequestRule(handle, binding, entry, policy.prefix, access)) {
8011
+ const decision = evaluateRequestRule(handle, binding, entry, policy.prefix, access);
8012
+ if (!(typeof decision === "boolean" ? decision : await decision)) {
6785
8013
  allowed = false;
6786
8014
  break;
6787
8015
  }
@@ -6797,6 +8025,33 @@ function authorizeEmbeddedOutputPlan(parent, child) {
6797
8025
  ...parent.authorizationBinding,
6798
8026
  scopePath: child.responseScopePath ?? child.scopePath.filter((p) => p !== "sub")
6799
8027
  };
8028
+ assertAuthorizationBinding(parent.authorization, parent.authorizationBinding);
8029
+ if (readAuthorizationFastPath(parent.authorization, parent.authorizationBinding)?.mode === "active") {
8030
+ if (!Object.values(parent.childPlans).includes(child)) authorizationError("unknown embedded output plan");
8031
+ let scopes = embeddedPlans.get(parent);
8032
+ if (!scopes) embeddedPlans.set(parent, scopes = /* @__PURE__ */ new WeakMap());
8033
+ const previous = scopes.get(child);
8034
+ if (previous) {
8035
+ assertAuthorizationBinding(previous.authorization, binding);
8036
+ return previous;
8037
+ }
8038
+ const view2 = readServiceAuthorization(parent.authorization, parent.authorizationBinding);
8039
+ const authorization2 = deriveTrustedQueryAuthorization({
8040
+ binding,
8041
+ ...view2,
8042
+ requestPermissions: getAuthorizationPermissions(parent.authorization, parent.authorizationBinding),
8043
+ parent: parent.authorization,
8044
+ snapshotDerivation: { kind: "embedded", parentBinding: parent.authorizationBinding }
8045
+ });
8046
+ if (!authorization2) authorizationError("invalid trusted embedded edge");
8047
+ const scoped = {
8048
+ ...child,
8049
+ authorization: authorization2,
8050
+ authorizationBinding: Object.freeze({ ...binding, scopePath: Object.freeze([...binding.scopePath ?? []]) })
8051
+ };
8052
+ scopes.set(child, scoped);
8053
+ return scoped;
8054
+ }
6800
8055
  const view = readServiceAuthorization(parent.authorization, parent.authorizationBinding);
6801
8056
  const authorization = resolveServiceAuthorization({
6802
8057
  binding,
@@ -6814,11 +8069,24 @@ function hasWholeOutputValueGrant(plan, field) {
6814
8069
  const { outputFields } = readServiceOutputPolicy(plan.authorization, binding);
6815
8070
  return hasExplicitFieldGrant(outputFields, [...binding.scopePath ?? [], field].join("."));
6816
8071
  }
6817
- function copyOutputValue(value, plan, path) {
8072
+ function copyOutputValue(value, plan, path, trusted) {
6818
8073
  const { catalog } = readServiceOutputPolicy(plan.authorization, plan.authorizationBinding);
6819
8074
  const virtualValue = catalog.virtualPaths?.some((p) => matchesCatalogPattern(p, path));
6820
8075
  const opaque = catalog.opaquePaths?.some((p) => matchesCatalogPattern(p, path));
6821
8076
  const excluded = plan.effectiveSelectNorm.filter((token) => token.startsWith("-")).map((token) => [...plan.authorizationBinding.scopePath ?? [], token.slice(1)].join("."));
8077
+ if (trusted)
8078
+ return materializeTrustedOutputValue(
8079
+ value,
8080
+ path,
8081
+ trusted.budget,
8082
+ {
8083
+ keep(key, child) {
8084
+ if (excluded.some((entry) => child === entry || child.startsWith(`${entry}.`))) return false;
8085
+ return (opaque || isSafeOutputPath(key)) && !catalog.protectedPaths?.some((p) => matchesCatalogPattern(p, child, true)) && (opaque || virtualValue || isCatalogOutputPath(catalog, child));
8086
+ }
8087
+ },
8088
+ trusted.depth
8089
+ );
6822
8090
  const visit = (input, current) => {
6823
8091
  if (Array.isArray(input)) return input.map((entry) => visit(entry, current));
6824
8092
  if (input instanceof Map) return visit(Object.fromEntries(input), current);
@@ -6836,7 +8104,45 @@ function copyOutputValue(value, plan, path) {
6836
8104
  };
6837
8105
  return visit(value, path);
6838
8106
  }
6839
- function copyAuthorizedReference(value, plan, path) {
8107
+ function copyAuthorizedReference(value, plan, path, trusted) {
8108
+ if (trusted) {
8109
+ const active = /* @__PURE__ */ new WeakSet();
8110
+ const { relatedTargets } = readServiceAuthorization(plan.authorization, plan.authorizationBinding);
8111
+ const target = relatedTargets.find((entry) => entry.path === path);
8112
+ const one = (input, depth) => {
8113
+ visitTrustedOutput(trusted.budget, depth);
8114
+ if (input && typeof input === "object" && types8.isProxy(input)) authorizationError("unsupported selected proxy");
8115
+ if (Array.isArray(input)) {
8116
+ if (active.has(input)) authorizationError("cyclic selected output");
8117
+ active.add(input);
8118
+ try {
8119
+ return shallowTrustedOutputArray(input, trusted.budget, depth).map((entry) => one(entry, depth + 1));
8120
+ } finally {
8121
+ active.delete(input);
8122
+ }
8123
+ }
8124
+ if (isPlainObject22(input)) {
8125
+ const handle2 = target && (!trusted.rootOutput || isIssuedOutputMember(trusted.rootOutput, input)) ? getAssociatedDocumentAuthorization(input, plan.authorization) : void 0;
8126
+ if (handle2) {
8127
+ const expected = {
8128
+ ...plan.authorizationBinding,
8129
+ model: target.model,
8130
+ modelName: target.modelName,
8131
+ scopePath: []
8132
+ };
8133
+ readDocumentAuthorizationAccess(handle2, expected);
8134
+ retainTrustedOutputMember(trusted.members, input);
8135
+ return input;
8136
+ }
8137
+ const id = Object.getOwnPropertyDescriptor(input, "_id");
8138
+ if (!id) return void 0;
8139
+ if (!("value" in id)) authorizationError("unsupported selected reference");
8140
+ return materializeTrustedOutputValue(id.value, path, trusted.budget, { keep: () => true }, depth + 1);
8141
+ }
8142
+ return materializeTrustedOutputValue(input, path, trusted.budget, { keep: () => true }, depth);
8143
+ };
8144
+ return one(value, trusted.depth);
8145
+ }
6840
8146
  if (Array.isArray(value)) return value.map((entry) => copyAuthorizedReference(entry, plan, path));
6841
8147
  if (!isPlainObject22(value)) return deepIsolateValue(value);
6842
8148
  const handle = getAssociatedDocumentAuthorization(value, plan.authorization);
@@ -6847,13 +8153,32 @@ function copyAuthorizedReference(value, plan, path) {
6847
8153
  }
6848
8154
  return Object.prototype.hasOwnProperty.call(value, "_id") ? deepIsolateValue(value._id) : void 0;
6849
8155
  }
6850
- function retainOutputMetadata(output, source, configuration, scope2) {
8156
+ function retainOutputMetadata(output, source, configuration, scope2, trusted) {
6851
8157
  if (scope2.length || configuration.stripPermissionsField) return;
6852
8158
  const parts = (configuration.documentPermissionField ?? "_permissions").split(".");
6853
8159
  let value = source;
6854
8160
  for (const part of parts) value = isPlainObject22(value) ? value[part] : void 0;
6855
8161
  if (!isPlainObject22(value)) return;
6856
8162
  const keys2 = configuration.exposedDocPermissionKeys;
8163
+ if (trusted) {
8164
+ const metadata2 = {};
8165
+ for (const key of Object.keys(value)) {
8166
+ visitTrustedOutput(trusted.budget, trusted.depth + 1);
8167
+ if (key === "_view" || key === "_edit" ? configuration.disableFieldPermissions : keys2 && !keys2.includes(key))
8168
+ continue;
8169
+ defineTrustedOutputValue(metadata2, key, value[key]);
8170
+ }
8171
+ setTrustedOutputPath(
8172
+ output,
8173
+ parts.join("."),
8174
+ metadata2,
8175
+ trusted.budget,
8176
+ trusted.depth,
8177
+ (source2, copy2) => retainTrustedOutputSpine(trusted.members, source2, copy2)
8178
+ );
8179
+ attachPermissionsAlias(output, parts.join("."));
8180
+ return;
8181
+ }
6857
8182
  const metadata = Object.fromEntries(
6858
8183
  Object.entries(value).filter(
6859
8184
  ([key]) => key === "_view" || key === "_edit" ? !configuration.disableFieldPermissions : !keys2 || keys2.includes(key)
@@ -6874,7 +8199,7 @@ function helperPlan(authorization, binding) {
6874
8199
  return planAuthorizedModelProjection({ authorization, binding, effectiveSelect: [] });
6875
8200
  }
6876
8201
  function primitiveHelperFields(source, plan) {
6877
- if (types7.isProxy(source)) return;
8202
+ if (types8.isProxy(source)) return;
6878
8203
  const canonical = readStaticOutputPlanFields(plan, plan.authorization);
6879
8204
  if (!canonical) return;
6880
8205
  const fields = [];
@@ -6889,15 +8214,25 @@ function primitiveHelperFields(source, plan) {
6889
8214
  }
6890
8215
  return fields;
6891
8216
  }
6892
- async function filterExistingOutput(source, plan, handle, associated) {
8217
+ async function filterExistingOutput(source, plan, handle, associated, parentBudget, depth = 0) {
6893
8218
  const binding = plan.authorizationBinding;
8219
+ const trustedStage = isTrustedDocumentAuthorization(handle, binding);
8220
+ const budget = readAuthorizationFastPath(plan.authorization, binding)?.mode === "active" ? parentBudget ?? createTrustedOutputBudget() : void 0;
8221
+ const members = budget ? createTrustedOutputMemberBuilder(plan.authorization, binding, budget) : void 0;
8222
+ const trusted = budget && trustedStage ? {
8223
+ budget,
8224
+ members,
8225
+ depth,
8226
+ rootOutput: associated ? source : void 0
8227
+ } : void 0;
8228
+ if (trusted) visitTrustedOutput(trusted.budget, depth);
6894
8229
  const { configuration } = readServiceAuthorization(plan.authorization, binding);
6895
8230
  const output = {};
6896
8231
  const fields = [];
6897
8232
  const primitiveFields = primitiveHelperFields(source, plan);
6898
8233
  const staticDecisions = primitiveFields && tryStaticOutputFieldDecisions(handle, binding, plan, primitiveFields);
6899
8234
  if (staticDecisions) {
6900
- await Promise.resolve();
8235
+ if (!trusted) await Promise.resolve();
6901
8236
  if (associated) assertDocumentAuthorization(handle, { binding, output: source, outputAccess: plan.outputAccess });
6902
8237
  else readDocumentAuthorizationAccess(handle, binding);
6903
8238
  if (!readStaticOutputPlanFields(plan, plan.authorization)) authorizationError("changed static output plan");
@@ -6908,14 +8243,22 @@ async function filterExistingOutput(source, plan, handle, associated) {
6908
8243
  if (childPlan && !hasWholeOutputValueGrant(plan, field)) {
6909
8244
  const scoped = authorizeEmbeddedOutputPlan(plan, childPlan);
6910
8245
  const childFields = /* @__PURE__ */ new Set();
6911
- const one = async (value2) => {
8246
+ const arrays = /* @__PURE__ */ new WeakSet();
8247
+ const one = async (value2, childDepth = depth + 1) => {
6912
8248
  if (Array.isArray(value2)) {
8249
+ if (trusted && arrays.has(value2)) authorizationError("cyclic selected document output");
8250
+ const entries = trusted ? shallowTrustedOutputArray(value2, trusted.budget, childDepth) : value2;
8251
+ arrays.add(value2);
6913
8252
  const values = [];
6914
- for (const entry of value2) values.push(await one(entry) ?? null);
8253
+ try {
8254
+ for (const entry of entries) values.push(await one(entry, childDepth + 1) ?? null);
8255
+ } finally {
8256
+ arrays.delete(value2);
8257
+ }
6915
8258
  return values;
6916
8259
  }
6917
8260
  if (!isPlainObject22(value2)) return value2 === null ? null : void 0;
6918
- const childHandle = associated ? getAssociatedDocumentAuthorization(value2) : void 0;
8261
+ const childHandle = associated ? trusted ? getIssuedEmbeddedDocumentAuthorization(source, value2, handle, scoped.authorizationBinding) : getAssociatedDocumentAuthorization(value2) : void 0;
6919
8262
  let child = scoped;
6920
8263
  if (childHandle) {
6921
8264
  const state = readDocumentAuthorizationAccess(childHandle, scoped.authorizationBinding);
@@ -6923,10 +8266,12 @@ async function filterExistingOutput(source, plan, handle, associated) {
6923
8266
  authorizationError("child call mismatch");
6924
8267
  child = helperPlan(state.authorization, scoped.authorizationBinding);
6925
8268
  }
8269
+ const prepared = !childHandle && trusted ? prepareQueryDocumentAuthorization(child.authorization, child.authorizationBinding, value2) : void 0;
6926
8270
  const resolved = childHandle ?? await resolveOutputDocumentAuthorization({
6927
8271
  authorization: child.authorization,
6928
8272
  binding: child.authorizationBinding,
6929
- snapshot: isolateDocForOutput(value2),
8273
+ snapshot: prepared?.source ?? isolateDocForOutput(value2),
8274
+ stage: prepared?.stage,
6930
8275
  context: {
6931
8276
  modelName: binding.modelName,
6932
8277
  mongooseModel: binding.model,
@@ -6935,27 +8280,48 @@ async function filterExistingOutput(source, plan, handle, associated) {
6935
8280
  owningDocument: handle,
6936
8281
  owningBinding: binding
6937
8282
  });
6938
- const result2 = await filterExistingOutput(value2, child, resolved, !!childHandle);
8283
+ const result2 = await filterExistingOutput(
8284
+ prepared?.source ?? value2,
8285
+ child,
8286
+ resolved,
8287
+ !!childHandle,
8288
+ budget,
8289
+ childDepth
8290
+ );
8291
+ if (members) retainTrustedOutputMember(members, result2.output);
6939
8292
  result2.fields.forEach((path) => childFields.add(`${field}.${path}`));
6940
8293
  return result2.output;
6941
8294
  };
6942
- const value = await one(source[field]);
6943
- if (value !== void 0) output[field] = value;
8295
+ const value = await one(
8296
+ trusted ? trustedMapOutputScope(source[field], childPlan.outputPersistedFields, trusted.budget, depth + 1) : source[field]
8297
+ );
8298
+ if (value !== void 0) {
8299
+ if (trusted) defineTrustedOutputValue(output, field, value);
8300
+ else output[field] = value;
8301
+ }
6944
8302
  fields.push(...childFields);
6945
8303
  } else if (staticDecisions ? staticDecisions.get(field) === true : await evaluateAuthorizedOutputField(handle, binding, field)) {
6946
8304
  const path = [...binding.scopePath ?? [], field].join(".");
6947
- output[field] = configuration.catalog.referencePaths?.some((p) => matchesCatalogPattern(p, path)) ? copyAuthorizedReference(source[field], plan, path) : copyOutputValue(source[field], plan, path);
6948
- if (associated) transferDocumentAuthorizationGraph(source[field], output[field]);
8305
+ const value = configuration.catalog.referencePaths?.some((p) => matchesCatalogPattern(p, path)) ? copyAuthorizedReference(source[field], plan, path, trusted) : copyOutputValue(source[field], plan, path, trusted);
8306
+ if (trusted) defineTrustedOutputValue(output, field, value);
8307
+ else output[field] = value;
8308
+ if (associated && !trusted) transferDocumentAuthorizationGraph(source[field], output[field]);
6949
8309
  if (output[field] !== void 0) fields.push(field);
6950
8310
  else delete output[field];
6951
8311
  }
6952
8312
  }
6953
8313
  if (plan.fetchIdRetained && Object.prototype.hasOwnProperty.call(source, "_id")) {
6954
- output._id = deepIsolateValue(source._id);
8314
+ const id = trusted ? materializeTrustedOutputValue(source._id, "_id", trusted.budget, { keep: () => true }, depth + 1) : deepIsolateValue(source._id);
8315
+ if (trusted) defineTrustedOutputValue(output, "_id", id);
8316
+ else output._id = id;
6955
8317
  fields.push("_id");
6956
8318
  }
6957
- retainOutputMetadata(output, source, configuration, binding.scopePath ?? []);
6958
- if (associated)
8319
+ retainOutputMetadata(output, source, configuration, binding.scopePath ?? [], trusted);
8320
+ if (trusted) associateDocumentAuthorization(handle, binding, output, trusted.members);
8321
+ else if (members) {
8322
+ if (associated) assertDocumentAuthorization(handle, { binding, output: source, outputAccess: plan.outputAccess });
8323
+ associateDocumentAuthorization(handle, binding, output, members);
8324
+ } else if (associated)
6959
8325
  transferDocumentAuthorization(
6960
8326
  handle,
6961
8327
  { binding, output: source, outputAccess: plan.outputAccess, authorization: plan.authorization },
@@ -6972,7 +8338,7 @@ async function filterModelOutputForHelper(args) {
6972
8338
  const normalized = normalizeOutputAuthorizationOptions(
6973
8339
  {
6974
8340
  binding: receiver,
6975
- configuration: captureModelAuthorizationConfiguration(runtime, modelName),
8341
+ configuration: () => captureModelAuthorizationConfiguration(runtime, modelName),
6976
8342
  requestPermissions: args.permissions,
6977
8343
  access: { operation: access, virtualAccess: access, outputAccess: access, docPermissionsAccess: access }
6978
8344
  },
@@ -7005,6 +8371,7 @@ async function filterModelOutputForHelper(args) {
7005
8371
  });
7006
8372
  return filterExistingOutput(source, plan, handle, false);
7007
8373
  }
8374
+ var embeddedPlans;
7008
8375
  var init_output_field_filter = __esm({
7009
8376
  "src/acl/output-field-filter.ts"() {
7010
8377
  init_permissions_alias();
@@ -7019,6 +8386,8 @@ var init_output_field_filter = __esm({
7019
8386
  init_field_catalog();
7020
8387
  init_output_projection();
7021
8388
  init_output_field_policy();
8389
+ init_trusted_output_materialization();
8390
+ embeddedPlans = /* @__PURE__ */ new WeakMap();
7022
8391
  }
7023
8392
  });
7024
8393
 
@@ -7102,19 +8471,31 @@ function prepareFinalizer(args, sharedContext = false) {
7102
8471
  const { authorization, authorizationBinding: binding } = args.plan;
7103
8472
  const policy = authorization && binding ? readServiceOutputPolicy(authorization, binding) : void 0;
7104
8473
  assertFinalizerCall(args, { authorization, policy });
8474
+ const trustedCall = !!authorization && readAuthorizationFastPath(authorization, binding)?.mode === "active";
8475
+ const reusable = trustedCall ? trustedFinalizerScopes.get(args.plan) : void 0;
8476
+ if (reusable) {
8477
+ if (reusable.authorization !== authorization) authorizationError("changed trusted finalizer scope");
8478
+ return { ...reusable, baseContext: { ...args.context }, sharedContext };
8479
+ }
7105
8480
  const configuration = authorization ? readServiceFinalizerConfiguration(authorization, binding) : void 0;
7106
8481
  const snapshot = configuration ? configuration : deepIsolateValue(args.snapshot);
7107
- return {
8482
+ const prepared = {
7108
8483
  authorization,
7109
8484
  policy,
7110
8485
  snapshot,
7111
- baseContext: deepIsolateValue(args.context ?? {}),
8486
+ baseContext: trustedCall ? { ...args.context } : deepIsolateValue(args.context ?? {}),
7112
8487
  sharedContext,
7113
8488
  scopeVirtualNames: getScopeVirtualNames(snapshot, args.scopePath),
7114
8489
  scopedSchema: configuration ? null : getScopedPermissionSchema2(snapshot.permissionSchema, args.scopePath),
7115
8490
  permissions: authorization ? getAuthorizationPermissions(authorization, binding) : void 0,
7116
- resolveDocument: authorization ? prepareOutputDocumentAuthorization(authorization, binding, configuration) : void 0
8491
+ resolveDocument: authorization ? prepareOutputDocumentAuthorization(authorization, binding, configuration) : void 0,
8492
+ trustedCall
7117
8493
  };
8494
+ if (trustedCall) {
8495
+ const { baseContext: _context, sharedContext: _shared, ...scope2 } = prepared;
8496
+ trustedFinalizerScopes.set(args.plan, scope2);
8497
+ }
8498
+ return prepared;
7118
8499
  }
7119
8500
  async function finalizeSingleDoc(args, input, prepared) {
7120
8501
  assertFinalizerCall(args, prepared);
@@ -7125,16 +8506,32 @@ async function finalizeSingleDoc(args, input, prepared) {
7125
8506
  const snapshot = prepared.snapshot;
7126
8507
  const limit = args.resolvedLimit;
7127
8508
  const gate = args.sharedGate;
7128
- const original = getIncludeOriginal(input);
8509
+ const original = getIncludeOriginal(input, prepared.authorization);
7129
8510
  const privateRow = args.virtualPopulateRow ?? (original && typeof original === "object" ? getVirtualPopulateRow(original) : void 0);
7130
8511
  const privateAddress = args.virtualPopulateAddress ?? [];
7131
- const isolated = isolateDocForOutput(input);
7132
- const output = isPlainObject23(isolated) ? isolated : {};
7133
- if (captured && isPlainObject23(input))
8512
+ const querySource = captured && !args.documentAuthorizationStage ? prepareQueryDocumentAuthorization(plan.authorization, binding, input) : void 0;
8513
+ const stage = args.documentAuthorizationStage ?? querySource?.stage;
8514
+ const source = querySource?.source ?? input;
8515
+ const trustedSource = !!stage && isTrustedDocumentAuthorizationStage(stage, plan.authorization, binding);
8516
+ const budget = prepared.trustedCall ? args.materialization?.budget ?? args.trustedOutputBudget ?? querySource?.budget ?? createTrustedOutputBudget() : void 0;
8517
+ const depth = args.materialization?.depth ?? 0;
8518
+ const lineage = args.materialization?.lineage ?? /* @__PURE__ */ new Set();
8519
+ if (budget) {
8520
+ visitTrustedOutput(budget, depth);
8521
+ if (source && typeof source === "object" && lineage.has(source))
8522
+ authorizationError("cyclic selected document output");
8523
+ }
8524
+ const nextLineage = new Set(lineage);
8525
+ if (source && typeof source === "object") nextLineage.add(source);
8526
+ const members = budget ? createTrustedOutputMemberBuilder(plan.authorization, binding, budget) : void 0;
8527
+ const trusted = trustedSource ? { budget, members, depth } : void 0;
8528
+ const isolated = trustedSource ? void 0 : isolateDocForOutput(source);
8529
+ let output = isPlainObject23(isolated) ? isolated : {};
8530
+ if (captured && !trustedSource && isPlainObject23(input))
7134
8531
  for (const key of Object.keys(output)) {
7135
8532
  transferDocumentAuthorizationGraph(input[key], output[key]);
7136
8533
  }
7137
- const baseContext = prepared.sharedContext ? deepIsolateValue(prepared.baseContext) : prepared.baseContext;
8534
+ const baseContext = prepared.trustedCall ? { ...prepared.baseContext } : prepared.sharedContext ? deepIsolateValue(prepared.baseContext) : prepared.baseContext;
7138
8535
  const operation = captured?.access.operation ?? baseContext.operation ?? args.operation ?? args.virtualAccess;
7139
8536
  const scopeContext = {
7140
8537
  ...baseContext,
@@ -7150,21 +8547,22 @@ async function finalizeSingleDoc(args, input, prepared) {
7150
8547
  let documentAuthorization;
7151
8548
  let metadataSource = output;
7152
8549
  if (captured) {
7153
- const projected = args.documentAuthorizationStage ? input : deepIsolateValue(output);
7154
- metadataSource = deepIsolateValue(output);
8550
+ const projected = stage ? source : deepIsolateValue(output);
8551
+ metadataSource = trustedSource ? source : deepIsolateValue(output);
7155
8552
  documentAuthorization = await prepared.resolveDocument({
7156
8553
  authorization: plan.authorization,
7157
8554
  binding,
7158
8555
  snapshot: projected,
7159
8556
  context: scopeContext,
7160
- stage: args.documentAuthorizationStage,
8557
+ stage,
7161
8558
  owningDocument: args.owningDocument,
7162
8559
  owningBinding: args.owningBinding,
7163
8560
  knownOutput: !args.documentAuthorizationStage && !!input && typeof input === "object" && isKnownAuthorizationOutput(input)
7164
8561
  });
7165
8562
  }
7166
8563
  const docGrants = documentAuthorization ? readDocumentAuthorization(documentAuthorization, binding).grants : await resolveDocPermissions(args, output, scopeContext);
7167
- scopeContext.docPermissions = deepIsolateValue(docGrants);
8564
+ if (trusted) output = shallowTrustedOutput(source, trusted.budget, depth);
8565
+ scopeContext.docPermissions = trusted ? docGrants : deepIsolateValue(docGrants);
7168
8566
  const globalPerms = prepared.permissions ?? resolveGlobalPermissions(args);
7169
8567
  const modelPermissionPrefix = captured ? "" : deepIsolateValue(snapshot.modelPermissionPrefix ?? "");
7170
8568
  const documentPermissionField = captured ? "_permissions" : deepIsolateValue(snapshot.documentPermissionField ?? "_permissions");
@@ -7172,21 +8570,26 @@ async function finalizeSingleDoc(args, input, prepared) {
7172
8570
  const childPlans = plan.childPlans ?? {};
7173
8571
  for (const [containerName, childPlan] of Object.entries(childPlans)) {
7174
8572
  if (!(containerName in output)) continue;
7175
- const rawContainer = output[containerName];
8573
+ let rawContainer = output[containerName];
7176
8574
  if (rawContainer === void 0 || rawContainer === null) continue;
7177
8575
  if (captured && hasWholeOutputValueGrant(plan, containerName)) {
7178
8576
  output[containerName] = copyOutputValue(
7179
8577
  rawContainer,
7180
8578
  plan,
7181
- [...binding.scopePath ?? [], containerName].join(".")
8579
+ [...binding.scopePath ?? [], containerName].join("."),
8580
+ trusted
7182
8581
  );
7183
8582
  continue;
7184
8583
  }
8584
+ if (trusted)
8585
+ rawContainer = trustedMapOutputScope(rawContainer, childPlan.outputPersistedFields, trusted.budget, depth + 1);
7185
8586
  if (captured && !isPlainObject23(rawContainer) && !Array.isArray(rawContainer)) {
8587
+ if (trusted && (typeof rawContainer === "object" || typeof rawContainer === "function" || typeof rawContainer === "symbol"))
8588
+ authorizationError("unsupported selected embedded value");
7186
8589
  delete output[containerName];
7187
8590
  continue;
7188
8591
  }
7189
- retainRawAssociation(output, containerName, rawContainer);
8592
+ if (!trusted) retainRawAssociation(output, containerName, rawContainer);
7190
8593
  const childBase = {
7191
8594
  ...args,
7192
8595
  scopePath: [...childPlan.scopePath ?? [...scopePath, containerName, "sub"]],
@@ -7199,16 +8602,34 @@ async function finalizeSingleDoc(args, input, prepared) {
7199
8602
  context: scopeContext,
7200
8603
  documentAuthorizationStage: void 0,
7201
8604
  onFinalized: void 0,
8605
+ completeTrustedOutput: void 0,
8606
+ trustedOutputBudget: void 0,
7202
8607
  owningDocument: documentAuthorization,
7203
8608
  owningBinding: binding,
7204
8609
  related: [],
7205
- virtualPopulateRow: privateRow
8610
+ virtualPopulateRow: privateRow,
8611
+ materialization: budget ? { budget, depth: depth + 1, lineage: nextLineage } : void 0
7206
8612
  };
7207
8613
  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 (!isPlainObject23(rawChild) && !Array.isArray(rawChild)) return captured ? null : deepIsolateValue(rawChild);
8614
+ const finalizeOneChild = async (rawChild, address, childDepth = depth + 1, childLineage = nextLineage) => {
8615
+ if (budget) visitTrustedOutput(budget, childDepth);
8616
+ if (captured && Array.isArray(rawChild)) {
8617
+ if (budget) {
8618
+ if (childLineage.has(rawChild)) authorizationError("cyclic selected document output");
8619
+ }
8620
+ const arrayLineage = new Set(childLineage);
8621
+ arrayLineage.add(rawChild);
8622
+ return mapWithConcurrencyLimit(
8623
+ budget ? shallowTrustedOutputArray(rawChild, budget, childDepth) : rawChild,
8624
+ limit,
8625
+ (entry, index) => finalizeOneChild(entry, [...address, index], childDepth + 1, arrayLineage)
8626
+ );
8627
+ }
8628
+ if (!isPlainObject23(rawChild) && !Array.isArray(rawChild)) {
8629
+ if (trusted && rawChild != null && (typeof rawChild === "object" || typeof rawChild === "function" || typeof rawChild === "symbol"))
8630
+ authorizationError("unsupported selected embedded value");
8631
+ return captured ? null : deepIsolateValue(rawChild);
8632
+ }
7212
8633
  if (args.traversal?.finalizeEmbeddedChildren) {
7213
8634
  return args.traversal.finalizeEmbeddedChildren({
7214
8635
  containerName,
@@ -7225,18 +8646,24 @@ async function finalizeSingleDoc(args, input, prepared) {
7225
8646
  } : { ...args, virtualPopulateRow: privateRow, virtualPopulateAddress: address }
7226
8647
  });
7227
8648
  }
7228
- return finalizeSingleDoc(
7229
- { ...childBase, virtualPopulateAddress: address },
8649
+ const finalized = await finalizeSingleDoc(
8650
+ {
8651
+ ...childBase,
8652
+ virtualPopulateAddress: address,
8653
+ materialization: budget ? { budget, depth: childDepth, lineage: childLineage } : void 0
8654
+ },
7230
8655
  rawChild,
7231
8656
  childPreparation ??= prepareFinalizer(
7232
8657
  childBase,
7233
8658
  Array.isArray(rawContainer) && (rawContainer.length > 1 || Array.isArray(rawContainer[0]))
7234
8659
  )
7235
8660
  );
8661
+ if (members) retainTrustedOutputMember(members, finalized);
8662
+ return finalized;
7236
8663
  };
7237
8664
  if (Array.isArray(rawContainer)) {
7238
8665
  const finalized = await mapWithConcurrencyLimit(
7239
- rawContainer,
8666
+ budget ? shallowTrustedOutputArray(rawContainer, budget, depth + 1) : rawContainer,
7240
8667
  limit,
7241
8668
  (entry, index) => finalizeOneChild(entry, [...privateAddress, containerName, index])
7242
8669
  );
@@ -7262,7 +8689,7 @@ async function finalizeSingleDoc(args, input, prepared) {
7262
8689
  if (typeof rawRelated === "string" || typeof rawRelated === "number" || typeof rawRelated === "bigint") continue;
7263
8690
  const bsontype = rawRelated?._bsontype;
7264
8691
  if (typeof bsontype === "string") continue;
7265
- retainRawAssociation(output, target.path, rawRelated);
8692
+ if (!trusted) retainRawAssociation(output, target.path, rawRelated);
7266
8693
  const relatedBase = {
7267
8694
  ...args,
7268
8695
  receivingModelName: target.plan.receivingModelName ?? args.receivingModelName,
@@ -7277,6 +8704,8 @@ async function finalizeSingleDoc(args, input, prepared) {
7277
8704
  docPermissions: void 0,
7278
8705
  documentAuthorizationStage: void 0,
7279
8706
  onFinalized: void 0,
8707
+ completeTrustedOutput: void 0,
8708
+ trustedOutputBudget: void 0,
7280
8709
  owningDocument: void 0,
7281
8710
  owningBinding: void 0,
7282
8711
  virtualPopulateRow: void 0,
@@ -7288,7 +8717,7 @@ async function finalizeSingleDoc(args, input, prepared) {
7288
8717
  const finalizeOneRelated = async (rawChild, originalChild = rawChild) => {
7289
8718
  if (!isPlainObject23(rawChild) && !Array.isArray(rawChild)) return rawChild;
7290
8719
  if (typeof rawChild?._bsontype === "string") return rawChild;
7291
- const childOriginal = getIncludeOriginal(originalChild);
8720
+ const childOriginal = getIncludeOriginal(originalChild, target.plan.authorization);
7292
8721
  const childRow = childOriginal && typeof childOriginal === "object" ? getVirtualPopulateRow(childOriginal) : void 0;
7293
8722
  if (args.traversal?.finalizeRelatedValue) {
7294
8723
  return args.traversal.finalizeRelatedValue({
@@ -7298,11 +8727,13 @@ async function finalizeSingleDoc(args, input, prepared) {
7298
8727
  parentArgs: { ...args, virtualPopulateRow: childRow, virtualPopulateAddress: [] }
7299
8728
  });
7300
8729
  }
7301
- return finalizeSingleDoc(
8730
+ const finalized2 = await finalizeSingleDoc(
7302
8731
  { ...relatedBase, virtualPopulateRow: childRow },
7303
8732
  rawChild,
7304
8733
  relatedPreparation ??= prepareFinalizer(relatedBase, Array.isArray(rawRelated) && rawRelated.length > 1)
7305
8734
  );
8735
+ if (members) retainTrustedOutputMember(members, finalized2);
8736
+ return finalized2;
7306
8737
  };
7307
8738
  let finalized;
7308
8739
  if (Array.isArray(rawRelated)) {
@@ -7317,7 +8748,16 @@ async function finalizeSingleDoc(args, input, prepared) {
7317
8748
  continue;
7318
8749
  }
7319
8750
  try {
7320
- if (target.path.includes(".")) set7(output, target.path, finalized);
8751
+ if (trusted)
8752
+ setTrustedOutputPath(
8753
+ output,
8754
+ target.path,
8755
+ finalized,
8756
+ trusted.budget,
8757
+ depth,
8758
+ (source2, copy) => retainTrustedOutputSpine(trusted.members, source2, copy)
8759
+ );
8760
+ else if (target.path.includes(".")) set7(output, target.path, finalized);
7321
8761
  else output[target.path] = finalized;
7322
8762
  } catch {
7323
8763
  }
@@ -7341,7 +8781,8 @@ async function finalizeSingleDoc(args, input, prepared) {
7341
8781
  for (const dep of dependsOn) {
7342
8782
  if (typeof dep !== "string" || isAbsentDependency(stableBase ?? output, dep)) return;
7343
8783
  }
7344
- const allowed = documentAuthorization ? await evaluateAuthorizedOutputField(documentAuthorization, binding, candidate.name) : await evaluateEffectiveFieldAuthorization({
8784
+ const candidateDecision = documentAuthorization ? evaluateAuthorizedOutputField(documentAuthorization, binding, candidate.name) : void 0;
8785
+ const allowed = documentAuthorization ? typeof candidateDecision === "boolean" ? candidateDecision : await candidateDecision : await evaluateEffectiveFieldAuthorization({
7345
8786
  req: args.request,
7346
8787
  path: candidate.name,
7347
8788
  rules: [extractScopedOutputRule(scopedSchema, candidate.name, args.outputAccess)],
@@ -7356,8 +8797,8 @@ async function finalizeSingleDoc(args, input, prepared) {
7356
8797
  if (!privateInputs.available) return;
7357
8798
  const isolatedView = deepIsolateValue(stableBase ??= deepIsolateValue(output));
7358
8799
  const virtualContext = {
7359
- ...deepIsolateValue(scopeContext),
7360
- docPermissions: deepIsolateValue(docGrants)
8800
+ ...trusted ? scopeContext : deepIsolateValue(scopeContext),
8801
+ docPermissions: trusted ? docGrants : deepIsolateValue(docGrants)
7361
8802
  };
7362
8803
  const outcome = await runVirtualGetter({
7363
8804
  req: args.request,
@@ -7378,7 +8819,15 @@ async function finalizeSingleDoc(args, input, prepared) {
7378
8819
  });
7379
8820
  if (!outcome.ok) return;
7380
8821
  if (outcome.value === void 0) return;
7381
- staged.set(candidate.name, deepIsolateValue(outcome.value));
8822
+ if (trusted) {
8823
+ try {
8824
+ staged.set(
8825
+ candidate.name,
8826
+ copyOutputValue(outcome.value, plan, [...binding.scopePath ?? [], candidate.name].join("."), trusted)
8827
+ );
8828
+ } catch {
8829
+ }
8830
+ } else staged.set(candidate.name, deepIsolateValue(outcome.value));
7382
8831
  };
7383
8832
  await mapWithConcurrencyLimit(
7384
8833
  candidates,
@@ -7389,7 +8838,8 @@ async function finalizeSingleDoc(args, input, prepared) {
7389
8838
  );
7390
8839
  for (const [name, stagedValue] of staged) {
7391
8840
  try {
7392
- setDocValue(output, name, stagedValue);
8841
+ if (trusted) defineTrustedOutputValue(output, name, stagedValue);
8842
+ else setDocValue(output, name, stagedValue);
7393
8843
  } catch {
7394
8844
  if (name in output) delete output[name];
7395
8845
  }
@@ -7398,7 +8848,7 @@ async function finalizeSingleDoc(args, input, prepared) {
7398
8848
  const eligibleVirtuals = new Set(plan.outputVirtualNames ?? []);
7399
8849
  const staticDecisions = documentAuthorization ? tryStaticOutputFieldDecisions(documentAuthorization, binding, plan, [...eligiblePersisted]) : void 0;
7400
8850
  if (staticDecisions) {
7401
- await Promise.resolve();
8851
+ if (!trusted) await Promise.resolve();
7402
8852
  assertFinalizerCall(args, prepared);
7403
8853
  readDocumentAuthorizationAccess(documentAuthorization, binding);
7404
8854
  if (!readStaticOutputPlanFields(plan, prepared.authorization)) authorizationError("changed static output plan");
@@ -7406,8 +8856,11 @@ async function finalizeSingleDoc(args, input, prepared) {
7406
8856
  const allowedPersisted = [];
7407
8857
  for (const field of eligiblePersisted) {
7408
8858
  if (documentAuthorization) {
7409
- if (plan.childPlans[field] || (staticDecisions ? staticDecisions.get(field) === true : await evaluateAuthorizedOutputField(documentAuthorization, binding, field)))
7410
- allowedPersisted.push(field);
8859
+ if (plan.childPlans[field]) allowedPersisted.push(field);
8860
+ else {
8861
+ const decision = staticDecisions ? staticDecisions.get(field) === true : evaluateAuthorizedOutputField(documentAuthorization, binding, field);
8862
+ if (typeof decision === "boolean" ? decision : await decision) allowedPersisted.push(field);
8863
+ }
7411
8864
  continue;
7412
8865
  }
7413
8866
  const rule = extractScopedOutputRule(scopedSchema, field, args.outputAccess);
@@ -7452,28 +8905,37 @@ async function finalizeSingleDoc(args, input, prepared) {
7452
8905
  }
7453
8906
  }
7454
8907
  if (!(key in output)) continue;
7455
- if (captured && !plan.childPlans[key]) {
8908
+ if (trusted && staged.has(key)) {
8909
+ defineTrustedOutputValue(trimmed, key, output[key]);
8910
+ } else if (captured && !plan.childPlans[key]) {
7456
8911
  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);
8912
+ const value = captured.catalog.referencePaths?.some((p) => matchesCatalogPattern(p, path)) ? copyAuthorizedReference(output[key], plan, path, trusted) : copyOutputValue(output[key], plan, path, trusted);
8913
+ if (trusted) defineTrustedOutputValue(trimmed, key, value);
8914
+ else trimmed[key] = value;
7458
8915
  if (trimmed[key] === void 0) delete trimmed[key];
7459
- } else trimmed[key] = output[key];
8916
+ } else if (trusted) defineTrustedOutputValue(trimmed, key, output[key]);
8917
+ else trimmed[key] = output[key];
7460
8918
  }
7461
8919
  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);
8920
+ if (trusted && args.completeTrustedOutput)
8921
+ await args.completeTrustedOutput(trimmed, documentAuthorization, trusted);
8922
+ else
8923
+ retainOutputMetadata(
8924
+ trimmed,
8925
+ metadataSource,
8926
+ trusted ? snapshot : copyAuthorizationValue(
8927
+ {
8928
+ documentPermissionField: snapshot.documentPermissionField,
8929
+ stripPermissionsField: snapshot.stripPermissionsField,
8930
+ exposedDocPermissionKeys: snapshot.exposedDocPermissionKeys,
8931
+ disableFieldPermissions: snapshot.disableFieldPermissions
8932
+ },
8933
+ true
8934
+ ),
8935
+ binding.scopePath ?? [],
8936
+ trusted
8937
+ );
8938
+ associateDocumentAuthorization(documentAuthorization, binding, trimmed, members);
7477
8939
  args.onFinalized?.(
7478
8940
  trimmed,
7479
8941
  createServiceOutputContext(scopeContext, documentAuthorization, {
@@ -7535,7 +8997,7 @@ async function finalizeModelOutputs(args) {
7535
8997
  );
7536
8998
  });
7537
8999
  }
7538
- var isVirtualContainerValue3, getScopeVirtualsObject2, getScopeVirtualNames, getScopedPermissionSchema2, resolveGlobalPermissions, resolveDocPermissions, isAbsentDependency, __finalizeInternals;
9000
+ var trustedFinalizerScopes, isVirtualContainerValue3, getScopeVirtualsObject2, getScopeVirtualNames, getScopedPermissionSchema2, resolveGlobalPermissions, resolveDocPermissions, isAbsentDependency, __finalizeInternals;
7539
9001
  var init_finalize_model_output = __esm({
7540
9002
  "src/output/finalize-model-output.ts"() {
7541
9003
  init_document();
@@ -7551,6 +9013,8 @@ var init_finalize_model_output = __esm({
7551
9013
  init_output_projection();
7552
9014
  init_virtual_populate_execution();
7553
9015
  init_include_output();
9016
+ init_trusted_output_materialization();
9017
+ trustedFinalizerScopes = /* @__PURE__ */ new WeakMap();
7554
9018
  isVirtualContainerValue3 = (value) => isPlainObject23(value) && "sub" in value;
7555
9019
  getScopeVirtualsObject2 = (rootVirtuals, scopePath) => {
7556
9020
  if (!rootVirtuals || !isPlainObject23(rootVirtuals)) return null;
@@ -7772,6 +9236,7 @@ init_document_authorization();
7772
9236
  // src/acl/field-helper-options.ts
7773
9237
  init_authorization_snapshot();
7774
9238
  init_field_catalog();
9239
+ init_public_admission();
7775
9240
  function assertFieldHelperCall(helper, count, maximum, options, family = "model") {
7776
9241
  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.";
7777
9242
  const removed = () => {
@@ -7781,12 +9246,14 @@ function assertFieldHelperCall(helper, count, maximum, options, family = "model"
7781
9246
  throw error2;
7782
9247
  };
7783
9248
  if (count > maximum || options === null || typeof options !== "object" || Array.isArray(options)) removed();
9249
+ assertNoServerModelControls(options, authorizationError);
7784
9250
  const value = authorizationRecord(options, `${helper} options`);
7785
9251
  for (const key of ["skipChecks", "subPaths", "baseFields"]) {
7786
9252
  if (key in value) removed();
7787
9253
  }
7788
9254
  }
7789
9255
  function requestFieldScope(options) {
9256
+ assertNoServerModelControls(options, authorizationError);
7790
9257
  const value = authorizationRecord(options, "request field options");
7791
9258
  for (const key of Reflect.ownKeys(value)) {
7792
9259
  const descriptor = Object.getOwnPropertyDescriptor(value, key);
@@ -8370,6 +9837,7 @@ import { AsyncLocalStorage as AsyncLocalStorage4 } from "async_hooks";
8370
9837
  var cores = /* @__PURE__ */ new WeakMap();
8371
9838
  var construction = new AsyncLocalStorage4();
8372
9839
  var dispatch = new AsyncLocalStorage4();
9840
+ var queryEntries = /* @__PURE__ */ new Set(["find", "findOne", "findById", "_list", "_read", "_readFilter"]);
8373
9841
  var operationGuard = new AsyncLocalStorage4();
8374
9842
  function withCapturedModelOperationGuard(core, modelName, access, guard2, permissions, run) {
8375
9843
  return operationGuard.run({ captured: { core, modelName, access, guard: guard2, permissions } }, run);
@@ -8413,7 +9881,7 @@ function bindModelOwnerMethods(receiver, runtime) {
8413
9881
  writable: true,
8414
9882
  value: (...args) => runWithRuntime(runtime, () => {
8415
9883
  const invoke = () => Reflect.apply(method, receiver, args);
8416
- return dispatch.getStore()?.receiver === receiver ? invoke() : dispatch.run({ receiver }, invoke);
9884
+ return dispatch.getStore()?.receiver === receiver && !queryEntries.has(key) ? invoke() : dispatch.run({ receiver }, invoke);
8417
9885
  })
8418
9886
  });
8419
9887
  }
@@ -8436,7 +9904,7 @@ init_request_work();
8436
9904
 
8437
9905
  // src/services/grouped-count.ts
8438
9906
  init_authorization_snapshot();
8439
- import { mongo as mongo3 } from "mongoose";
9907
+ import { mongo as mongo4 } from "mongoose";
8440
9908
  var MAX_GROUPS = 1e3;
8441
9909
  var MAX_KEYS = 1e4;
8442
9910
  var MAX_KEY_BYTES = 64 * 1024;
@@ -8482,10 +9950,10 @@ var KeyBudget = class {
8482
9950
  charge(8);
8483
9951
  } else if (Buffer.isBuffer(input)) {
8484
9952
  charge(input.length);
8485
- } else if (input instanceof mongo3.BSON.BSONValue) {
8486
- if (input instanceof mongo3.BSON.Code || input instanceof mongo3.BSON.DBRef || input instanceof mongo3.BSON.BSONRegExp)
9953
+ } else if (input instanceof mongo4.BSON.BSONValue) {
9954
+ if (input instanceof mongo4.BSON.Code || input instanceof mongo4.BSON.DBRef || input instanceof mongo4.BSON.BSONRegExp)
8487
9955
  invalid("unsupported equality key");
8488
- charge(mongo3.BSON.calculateObjectSize({ value: input }));
9956
+ charge(mongo4.BSON.calculateObjectSize({ value: input }));
8489
9957
  } else {
8490
9958
  const array = Array.isArray(input);
8491
9959
  if (array && input.length > MAX_KEYS) invalid(`key array exceeds ${MAX_KEYS} entries`);
@@ -8508,7 +9976,7 @@ var KeyBudget = class {
8508
9976
  }
8509
9977
  const alias = String(snapshot);
8510
9978
  const aliasBytes = Buffer.byteLength(alias);
8511
- const bsonBytes = mongo3.BSON.calculateObjectSize({ value: snapshot }, { ignoreUndefined: false });
9979
+ const bsonBytes = mongo4.BSON.calculateObjectSize({ value: snapshot }, { ignoreUndefined: false });
8512
9980
  if (Math.max(aliasBytes, bsonBytes) > MAX_KEY_BYTES) invalid(`key exceeds ${MAX_KEY_BYTES} bytes`);
8513
9981
  this.bytes += aliasBytes + bsonBytes;
8514
9982
  if (this.bytes > MAX_TOTAL_KEY_BYTES) invalid(`key payload exceeds ${MAX_TOTAL_KEY_BYTES} bytes`);
@@ -9093,7 +10561,8 @@ async function executePreparedGroupedCount(receiver, execution, query, foreignFi
9093
10561
  // src/services/base.ts
9094
10562
  var VIRT_ASSOCIATION_FIELD = /* @__PURE__ */ Symbol("accessRouter.virtAssociationField");
9095
10563
  var VIRT_ASSOCIATION_VALUES = /* @__PURE__ */ Symbol("accessRouter.virtAssociationValues");
9096
- var copyAuthorizedOutput = (value) => {
10564
+ var copyAuthorizedOutput = (value, call) => {
10565
+ if (value && typeof value === "object" && call && isTrustedAuthorizationOutput(value, call)) return value;
9097
10566
  const copy = deepIsolateValue(value);
9098
10567
  transferDocumentAuthorizationGraph(value, copy);
9099
10568
  return copy;
@@ -9723,7 +11192,9 @@ var Base = class {
9723
11192
  const includes = compact(castArray2(include));
9724
11193
  if (includes.length === 0) return docs;
9725
11194
  const isSingle = !isArray9(docs);
9726
- let docList = (isSingle ? [docs] : docs).map(prepareIncludeOutput);
11195
+ let docList = (isSingle ? [docs] : docs).map(
11196
+ (doc) => prepareIncludeOutput(doc, parentAuthorization, parentAuthorization ? this.relatedBinding() : void 0)
11197
+ );
9727
11198
  for (let x = 0; x < includes.length; x++) {
9728
11199
  const include2 = includes[x];
9729
11200
  if (isCorrelatedInclude(include2)) {
@@ -9819,7 +11290,9 @@ var Base = class {
9819
11290
  );
9820
11291
  if (!trustedResult.success && trustedResult.code === "bad_request" /* BadRequest */) throw new ClientRequestError(trustedResult);
9821
11292
  if (!trustedResult.success) return docs;
9822
- const finalizedRows = trustedResult.data.map((row) => copyAuthorizedOutput(row));
11293
+ const finalizedRows = trustedResult.data.map(
11294
+ (row) => copyAuthorizedOutput(row, parentAuthorization)
11295
+ );
9823
11296
  let index;
9824
11297
  const paired = trustedResult[VIRT_ASSOCIATION_VALUES];
9825
11298
  if (Array.isArray(paired) && paired.length === finalizedRows.length) {
@@ -9839,7 +11312,7 @@ var Base = class {
9839
11312
  for (let y = 0; y < docs.length; y++) {
9840
11313
  const doc = docs[y];
9841
11314
  const matches = this.getIndexedMatches(index, get8(doc, localField));
9842
- const isolated = matches.map((m) => copyAuthorizedOutput(m));
11315
+ const isolated = matches.map((m) => copyAuthorizedOutput(m, parentAuthorization));
9843
11316
  attachIncludeOutput(doc, path, op === "list" ? isolated : isolated[0]);
9844
11317
  }
9845
11318
  return docs;
@@ -9900,7 +11373,9 @@ var Base = class {
9900
11373
  );
9901
11374
  }
9902
11375
  const state = this.getCorrelatedExecState();
9903
- docs = docs.map(prepareIncludeOutput);
11376
+ docs = docs.map(
11377
+ (doc) => prepareIncludeOutput(doc, parentAuthorization, parentAuthorization ? this.relatedBinding() : void 0)
11378
+ );
9904
11379
  const resolvedSnapshots = snapshots2 ?? docs.map((doc) => cloneDeep3(toObject(getIncludeSource(doc))));
9905
11380
  for (const include of correlatedIncludes) {
9906
11381
  switch (include.op) {
@@ -10404,7 +11879,6 @@ init_document_authorization();
10404
11879
  init_output_field_filter();
10405
11880
  init_field_authorization();
10406
11881
  init_authorization_snapshot();
10407
- init_unsafe_snapshot_options();
10408
11882
  init_public_admission();
10409
11883
 
10410
11884
  // src/acl/subdocument-output.ts
@@ -10538,6 +12012,7 @@ init_core_shared();
10538
12012
  init_finalize_model_output();
10539
12013
  init_permissions_alias();
10540
12014
  init_include_output();
12015
+ init_trusted_output_materialization();
10541
12016
  init_populate_target();
10542
12017
  init_document();
10543
12018
  init_populate_target();
@@ -10582,7 +12057,7 @@ init_request_work();
10582
12057
  init_logger_helpers();
10583
12058
  init_request_complexity();
10584
12059
  import { get as get10, isPlainObject as isPlainObject25, set as set9 } from "@web-ts-toolkit/utils";
10585
- import { mongo as mongo5 } from "mongoose";
12060
+ import { mongo as mongo6 } from "mongoose";
10586
12061
 
10587
12062
  // src/acl/select-resolution.ts
10588
12063
  init_core_shared();
@@ -10704,7 +12179,7 @@ function inputValue(value) {
10704
12179
  authorizationError("input values must be persisted data, not functions or symbols");
10705
12180
  }
10706
12181
  if (isMongooseDocument(value)) return value.toObject({ virtuals: false, flattenMaps: true });
10707
- 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 mongo5.BSON.BSONValue))
12182
+ 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 mongo6.BSON.BSONValue))
10708
12183
  return Object.fromEntries(Object.entries(value));
10709
12184
  return value;
10710
12185
  }
@@ -11599,11 +13074,7 @@ var Service = class extends Base {
11599
13074
  ["args", args],
11600
13075
  ["options", options]
11601
13076
  ]) {
11602
- if (value !== null && (typeof value === "object" || typeof value === "function")) {
11603
- for (const key of unsafeSnapshotOptions) {
11604
- if (key in value) authorizationError(`${slot}.${key} is server model configuration only`);
11605
- }
11606
- }
13077
+ assertNoServerModelControls(value, authorizationError);
11607
13078
  if (value !== null && (typeof value === "object" || typeof value === "function") && "authorization" in value && (slot === "args" || !authorizationOptions)) {
11608
13079
  authorizationError(`${slot}.authorization is unsupported here; inputFields requires model mutation options`);
11609
13080
  }
@@ -11710,8 +13181,11 @@ var Service = class extends Base {
11710
13181
  const { authorization, authorizationBinding: binding } = plan;
11711
13182
  const access = readServiceAuthorizationAccess(authorization, binding);
11712
13183
  const configuration = readServiceOutputMetadata(authorization, binding);
11713
- const source = getIncludeSource(args.doc);
11714
- const snapshot = isolateDocForOutput(source);
13184
+ const source = args.copiedQuerySource?.source ?? getIncludeSource(args.doc);
13185
+ const prepared = prepareQueryOutputSource(authorization, binding, source, "hook");
13186
+ if (prepared?.sourceState === "trusted")
13187
+ return this.finalizeTrustedDirectOutput(args, prepared.source, prepared.budget);
13188
+ const snapshot = prepared?.source ?? isolateDocForOutput(source);
11715
13189
  for (const key of Object.keys(snapshot))
11716
13190
  transferDocumentAuthorizationGraph(getDocValue(source, key), snapshot[key]);
11717
13191
  if (args.privateAssociationField) unsetDocPath(snapshot, args.privateAssociationField);
@@ -11720,7 +13194,8 @@ var Service = class extends Base {
11720
13194
  authorization,
11721
13195
  binding,
11722
13196
  snapshot,
11723
- context
13197
+ context,
13198
+ stage: args.copiedQuerySource?.stage ?? (prepared ? prepareQueryDocumentAuthorization(authorization, binding, snapshot).stage : void 0)
11724
13199
  });
11725
13200
  const { stage, grants } = readDocumentAuthorization(handle, binding);
11726
13201
  context.docPermissions = deepIsolateValue(grants);
@@ -11737,7 +13212,7 @@ var Service = class extends Base {
11737
13212
  context,
11738
13213
  operation: access.operation,
11739
13214
  documentAuthorizationStage: stage,
11740
- virtualPopulateRow: getVirtualPopulateRow(getIncludeOriginal(args.doc)),
13215
+ virtualPopulateRow: getVirtualPopulateRow(getIncludeOriginal(args.doc, authorization)),
11741
13216
  sharedGate: gate,
11742
13217
  concurrencyLimit: this.getVirtualHookConcurrencyLimit(),
11743
13218
  onFinalized: (_output, outputContext) => {
@@ -11785,6 +13260,104 @@ var Service = class extends Base {
11785
13260
  })
11786
13261
  };
11787
13262
  }
13263
+ /** Same modern finalizer/evaluators; source/grants/attachments are borrowed only by authenticated trusted rows. */
13264
+ async finalizeTrustedDirectOutput(args, borrowedSource, sourceBudget) {
13265
+ const { plan, context } = args;
13266
+ const binding = plan.authorizationBinding, authorization = plan.authorization;
13267
+ const access = readServiceAuthorizationAccess(authorization, binding);
13268
+ const configuration = readServiceOutputMetadata(authorization, binding);
13269
+ const budget = sourceBudget ?? createTrustedOutputBudget();
13270
+ let source = borrowedSource;
13271
+ if (args.privateAssociationField) {
13272
+ source = shallowTrustedOutput(source, budget);
13273
+ unsetTrustedOutputPath(source, args.privateAssociationField, budget);
13274
+ }
13275
+ const prepared = prepareQueryDocumentAuthorization(authorization, binding, source);
13276
+ if (prepared.sourceState === "copied") return this.finalizeDirectOutput({ ...args, copiedQuerySource: prepared });
13277
+ let finalizedContext;
13278
+ const data = await finalizeModelOutput({
13279
+ receivingModelName: this.modelName,
13280
+ input: prepared.source,
13281
+ plan,
13282
+ snapshot: configuration,
13283
+ virtualAccess: access.virtualAccess,
13284
+ outputAccess: access.outputAccess,
13285
+ docPermissionsAccess: access.docPermissionsAccess,
13286
+ request: this.req,
13287
+ context,
13288
+ operation: access.operation,
13289
+ documentAuthorizationStage: prepared.stage,
13290
+ virtualPopulateRow: getVirtualPopulateRow(getIncludeOriginal(args.doc, authorization)),
13291
+ trustedOutputBudget: budget,
13292
+ completeTrustedOutput: async (output, handle, materialization) => {
13293
+ const { grants } = readDocumentAuthorization(handle, binding);
13294
+ context.docPermissions = grants;
13295
+ restoreTrustedIncludeOutput(args.doc, output, materialization);
13296
+ const field = configuration.documentPermissionField ?? "_permissions";
13297
+ if (configuration.stripPermissionsField)
13298
+ unsetTrustedOutputPath(
13299
+ output,
13300
+ field,
13301
+ budget,
13302
+ (source2, copy) => retainTrustedOutputSpine(materialization.members, source2, copy)
13303
+ );
13304
+ else {
13305
+ const exposed = configuration.exposedDocPermissionKeys;
13306
+ const metadata = {};
13307
+ if (args.includePermissions || args.includeFieldPermissions) {
13308
+ for (const key of Object.keys(grants)) {
13309
+ visitTrustedOutput(budget, 1);
13310
+ if (exposed && key !== "_view" && key !== "_edit" && !exposed.includes(key)) continue;
13311
+ defineTrustedOutputValue(metadata, key, grants[key]);
13312
+ }
13313
+ }
13314
+ if (args.includeFieldPermissions && !configuration.disableFieldPermissions) {
13315
+ const rowAccess = this.asServiceHookContext(context).fieldPermissionAccess ?? await this.getFieldPermissionAccess([source._id]);
13316
+ const id = String(source._id);
13317
+ const views = rowAccess.readIds?.has(id) ? await requestOutputFieldPaths(handle, binding, "read") : [];
13318
+ const edits = rowAccess.updateIds?.has(id) ? await requestOutputFieldPaths(handle, binding, "update") : [];
13319
+ const map2 = (paths) => {
13320
+ visitTrustedOutput(budget, 1, paths.length || 1);
13321
+ return paths.length ? Object.fromEntries(paths.map((path) => [path, true])) : { $: "_" };
13322
+ };
13323
+ defineTrustedOutputValue(metadata, "_view", map2(views));
13324
+ defineTrustedOutputValue(metadata, "_edit", map2(edits));
13325
+ } else if (!args.includePermissions) {
13326
+ defineTrustedOutputValue(metadata, "_view", { $: "_" });
13327
+ defineTrustedOutputValue(metadata, "_edit", { $: "_" });
13328
+ }
13329
+ setTrustedOutputPath(
13330
+ output,
13331
+ field,
13332
+ metadata,
13333
+ budget,
13334
+ 0,
13335
+ (source2, copy) => retainTrustedOutputSpine(materialization.members, source2, copy)
13336
+ );
13337
+ attachPermissionsAlias(output, field);
13338
+ }
13339
+ },
13340
+ onFinalized: (_output, outputContext) => {
13341
+ finalizedContext = outputContext;
13342
+ }
13343
+ });
13344
+ return { data, context: finalizedContext };
13345
+ }
13346
+ /** Actual correlated inputs only, not an unconditional whole-source diagnostic snapshot. */
13347
+ captureTrustedCorrelatedSource(doc, fields) {
13348
+ const output = {}, budget = createTrustedOutputBudget();
13349
+ for (const field of fields) {
13350
+ const value = get13(doc, field);
13351
+ if (value !== void 0)
13352
+ setTrustedOutputPath(
13353
+ output,
13354
+ field,
13355
+ materializeTrustedOutputValue(value, field, budget, { keep: () => true }),
13356
+ budget
13357
+ );
13358
+ }
13359
+ return output;
13360
+ }
11788
13361
  getEffectiveAllowedSortFields(allowedSortFields) {
11789
13362
  const extra = this.options?.sortableFields ?? [];
11790
13363
  const merged = extra.length > 0 ? [...allowedSortFields, ...extra] : allowedSortFields;
@@ -12133,7 +13706,7 @@ var Service = class extends Base {
12133
13706
  if (typeof record3._bsontype === "string") return true;
12134
13707
  return false;
12135
13708
  }
12136
- async finalizeSinglePopulateTarget(rawTarget, meta, parentOperation, parentContext, hookLimit, sharedGate, originalTarget = rawTarget) {
13709
+ async finalizeSinglePopulateTarget(rawTarget, meta, parentOperation, parentContext, hookLimit, sharedGate, originalTarget = rawTarget, trustedCacheOrigins = false) {
12137
13710
  if (rawTarget === null || rawTarget === void 0) return rawTarget;
12138
13711
  if (this.isScalarPopulateValue(rawTarget)) return rawTarget;
12139
13712
  const isDoc = (() => {
@@ -12154,10 +13727,12 @@ var Service = class extends Base {
12154
13727
  this.populateOutputCache.set(meta, cache);
12155
13728
  }
12156
13729
  const originalKey = originalTarget && typeof originalTarget === "object" ? originalTarget : rawTarget;
12157
- const cacheKey = getVirtualPopulatePublicIdentity(originalKey) ?? originalKey;
13730
+ const cacheKey = trustedCacheOrigins ? getVirtualPopulatePublicIdentity(rawTarget) ?? getQueryReferenceOriginal(rawTarget) ?? rawTarget : getVirtualPopulatePublicIdentity(originalKey) ?? originalKey;
12158
13731
  const existing = cache.get(cacheKey);
12159
13732
  if (existing) {
12160
13733
  const source = await existing;
13734
+ if (source && typeof source === "object" && isTrustedAuthorizationOutput(source, meta.plan.authorization))
13735
+ return source;
12161
13736
  const copy2 = deepIsolateValue(source);
12162
13737
  transferDocumentAuthorizationGraph(source, copy2);
12163
13738
  return copy2;
@@ -12195,11 +13770,13 @@ var Service = class extends Base {
12195
13770
  });
12196
13771
  cache.set(cacheKey, pending);
12197
13772
  const finalized = await pending;
13773
+ if (finalized && typeof finalized === "object" && isTrustedAuthorizationOutput(finalized, meta.plan.authorization))
13774
+ return finalized;
12198
13775
  const copy = deepIsolateValue(finalized);
12199
13776
  transferDocumentAuthorizationGraph(finalized, copy);
12200
13777
  return copy;
12201
13778
  }
12202
- async finalizePopulatePath(current, segments, segIdx, meta, parentOperation, parentContext, hookLimit, sharedGate, original = current) {
13779
+ async finalizePopulatePath(current, segments, segIdx, meta, parentOperation, parentContext, hookLimit, sharedGate, original = current, trustedCacheOrigins = false) {
12203
13780
  if (current === null || current === void 0) return;
12204
13781
  if (Array.isArray(current)) {
12205
13782
  for (const [index, el] of current.entries()) {
@@ -12212,7 +13789,8 @@ var Service = class extends Base {
12212
13789
  parentContext,
12213
13790
  hookLimit,
12214
13791
  sharedGate,
12215
- Array.isArray(original) ? original[index] : void 0
13792
+ Array.isArray(original) ? original[index] : void 0,
13793
+ trustedCacheOrigins
12216
13794
  );
12217
13795
  }
12218
13796
  return;
@@ -12254,7 +13832,8 @@ var Service = class extends Base {
12254
13832
  parentContext,
12255
13833
  hookLimit,
12256
13834
  sharedGate,
12257
- Array.isArray(originalChild) ? originalChild[index] : void 0
13835
+ Array.isArray(originalChild) ? originalChild[index] : void 0,
13836
+ trustedCacheOrigins
12258
13837
  )
12259
13838
  );
12260
13839
  }
@@ -12271,7 +13850,8 @@ var Service = class extends Base {
12271
13850
  parentContext,
12272
13851
  hookLimit,
12273
13852
  sharedGate,
12274
- originalChild
13853
+ originalChild,
13854
+ trustedCacheOrigins
12275
13855
  );
12276
13856
  try {
12277
13857
  setDocValue(current, key, finalized);
@@ -12288,11 +13868,12 @@ var Service = class extends Base {
12288
13868
  parentContext,
12289
13869
  hookLimit,
12290
13870
  sharedGate,
12291
- originalChild
13871
+ originalChild,
13872
+ trustedCacheOrigins
12292
13873
  );
12293
13874
  }
12294
13875
  }
12295
- async finalizePopulateForSingleDoc(doc, populateEntries, parentContext, parentOperation, hookLimit, sharedGate) {
13876
+ async finalizePopulateForSingleDoc(doc, populateEntries, parentContext, parentOperation, hookLimit, sharedGate, trustedCacheOrigins = false, parentAuthorization) {
12296
13877
  if (!doc || !Array.isArray(populateEntries) || populateEntries.length === 0) return;
12297
13878
  for (const entry of populateEntries) {
12298
13879
  if (!entry || typeof entry.path !== "string") continue;
@@ -12309,7 +13890,8 @@ var Service = class extends Base {
12309
13890
  parentContext,
12310
13891
  hookLimit,
12311
13892
  sharedGate,
12312
- getIncludeOriginal(doc)
13893
+ getIncludeOriginal(doc, parentAuthorization),
13894
+ trustedCacheOrigins
12313
13895
  );
12314
13896
  }
12315
13897
  }
@@ -12452,16 +14034,18 @@ var Service = class extends Base {
12452
14034
  void 0,
12453
14035
  findOneAssociationField ? [findOneAssociationField] : []
12454
14036
  );
14037
+ const trustedQuery = readAuthorizationFastPath(state.authorization, state.binding)?.mode === "active";
14038
+ if (trustedQuery) doc = prepareQueryOutputSource(state.authorization, state.binding, doc).source;
12455
14039
  const context = {
12456
14040
  mongooseModel: this.model.mongooseModel,
12457
14041
  modelName: this.modelName,
12458
14042
  // VIRT-00A D1: operation stays initiating (`read`), never the
12459
14043
  // fallback/effective visibility. Effective accesses carry `access`.
12460
14044
  operation: state.access.operation,
12461
- originalDocumentSnapshot: toObject(doc),
14045
+ originalDocumentSnapshot: trustedQuery ? doc : toObject(doc),
12462
14046
  resolvedQuery: query
12463
14047
  };
12464
- const correlatedSnapshots = [cloneDeep4(toObject(doc))];
14048
+ const correlatedSnapshots = trustedQuery ? correlatedIncludes.length ? [this.captureTrustedCorrelatedSource(doc, correlatedReferenceFields)] : [] : [cloneDeep4(toObject(doc))];
12465
14049
  try {
12466
14050
  doc = await this.includeDocs(doc, includes, state.authorization);
12467
14051
  if (correlatedIncludes.length > 0) {
@@ -12491,7 +14075,9 @@ var Service = class extends Base {
12491
14075
  context,
12492
14076
  "read",
12493
14077
  findOneHookLimit,
12494
- findOneGate
14078
+ findOneGate,
14079
+ trustedQuery && prepareQueryOutputSource(state.authorization, state.binding, getIncludeSource(doc)).sourceState === "trusted",
14080
+ state.authorization
12495
14081
  );
12496
14082
  } catch (error2) {
12497
14083
  const result2 = this.getClientRequestErrorResult(error2);
@@ -12702,8 +14288,12 @@ var Service = class extends Base {
12702
14288
  void 0,
12703
14289
  findAssociationField ? [findAssociationField] : []
12704
14290
  );
14291
+ const trustedQuery = readAuthorizationFastPath(state.authorization, state.binding)?.mode === "active";
14292
+ if (trustedQuery)
14293
+ docs = docs.map((doc) => prepareQueryOutputSource(state.authorization, state.binding, doc).source);
14294
+ const diagnosticSources = trustedQuery ? [...docs] : void 0;
12705
14295
  const capturedAssociation = findAssociationField ? this.captureAssociationValues(docs, findAssociationField) : void 0;
12706
- const correlatedSnapshots = docs.map((doc) => cloneDeep4(toObject(doc)));
14296
+ const correlatedSnapshots = trustedQuery ? correlatedIncludes.length ? docs.map((doc) => this.captureTrustedCorrelatedSource(doc, correlatedReferenceFields)) : [] : docs.map((doc) => cloneDeep4(toObject(doc)));
12707
14297
  try {
12708
14298
  docs = await this.includeDocs(docs, includes, state.authorization);
12709
14299
  if (correlatedIncludes.length > 0) {
@@ -12746,11 +14336,11 @@ var Service = class extends Base {
12746
14336
  } catch {
12747
14337
  }
12748
14338
  }
12749
- const contexts = correlatedSnapshots.map((doc) => ({
14339
+ const contexts = (diagnosticSources ?? correlatedSnapshots).map((doc) => ({
12750
14340
  mongooseModel: this.model.mongooseModel,
12751
14341
  modelName: this.modelName,
12752
14342
  operation: "list",
12753
- originalDocumentSnapshot: toObject(doc),
14343
+ originalDocumentSnapshot: trustedQuery ? doc : toObject(doc),
12754
14344
  resolvedQuery: query
12755
14345
  }));
12756
14346
  const outputContexts = [];
@@ -12766,7 +14356,9 @@ var Service = class extends Base {
12766
14356
  contexts[i],
12767
14357
  "list",
12768
14358
  hookLimit,
12769
- sharedGate
14359
+ sharedGate,
14360
+ trustedQuery && prepareQueryOutputSource(state.authorization, state.binding, getIncludeSource(doc)).sourceState === "trusted",
14361
+ state.authorization
12770
14362
  );
12771
14363
  }
12772
14364
  const output = await this.finalizeDirectOutput({