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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -85,7 +85,7 @@ function assertAuthorizationModeOptions(value, model) {
85
85
  normalizeAuthorizationMode(slot.value);
86
86
  }
87
87
  }
88
- var import_node_util, retiredAuthorizationOptions, authorizationModeKeys, serverAuthorizationControls;
88
+ var import_node_util, retiredAuthorizationOptions, authorizationModeKeys, authorizationModeOperations, serverAuthorizationControls;
89
89
  var init_authorization_modes = __esm({
90
90
  "src/acl/authorization-modes.ts"() {
91
91
  import_node_util = require("util");
@@ -101,7 +101,18 @@ var init_authorization_modes = __esm({
101
101
  "unsafeUseListAuthorizationFastPath",
102
102
  "unsafeUseReadAuthorizationFastPath"
103
103
  ];
104
- authorizationModeKeys = ["readAuthorizationMode", "listAuthorizationMode"];
104
+ authorizationModeKeys = [
105
+ "readAuthorizationMode",
106
+ "listAuthorizationMode",
107
+ "createAuthorizationMode",
108
+ "updateAuthorizationMode"
109
+ ];
110
+ authorizationModeOperations = {
111
+ readAuthorizationMode: "read",
112
+ listAuthorizationMode: "list",
113
+ createAuthorizationMode: "create",
114
+ updateAuthorizationMode: "update"
115
+ };
105
116
  serverAuthorizationControls = [...retiredAuthorizationOptions, ...authorizationModeKeys];
106
117
  }
107
118
  });
@@ -3076,6 +3087,158 @@ var init_data_manager = __esm({
3076
3087
  }
3077
3088
  });
3078
3089
 
3090
+ // src/operation-access.ts
3091
+ function isOperationAccessMemberPath(access) {
3092
+ const keys2 = access.split(".");
3093
+ if (operations.has(keys2[0]) && members.has(keys2[1])) return true;
3094
+ return keys2[0] === "subs" && keys2[1] !== "" && subOperations.has(keys2[2]) && members.has(keys2[3]);
3095
+ }
3096
+ function readOwnOption(root, key) {
3097
+ let value = root;
3098
+ for (const part of key.split(".")) {
3099
+ if (value === null || typeof value !== "object") return void 0;
3100
+ const slot = Object.getOwnPropertyDescriptor(value, part);
3101
+ if (!slot || !("value" in slot)) return void 0;
3102
+ value = slot.value;
3103
+ }
3104
+ return value;
3105
+ }
3106
+ function createOperationAccessReaders(options, defaults2) {
3107
+ return {
3108
+ readOption: (key) => readOwnOption(options, key),
3109
+ readDefaultOption: defaults2 === void 0 ? void 0 : (key) => readOwnOption(defaults2, key)
3110
+ };
3111
+ }
3112
+ function operationDefault(value) {
3113
+ if (!isRecord(value)) return scalarGuard(value);
3114
+ if (Reflect.ownKeys(value).some((key) => typeof key !== "string" || !members.has(key))) return false;
3115
+ return scalarGuard(readOwnOption(value, "default"));
3116
+ }
3117
+ function selectOperationAccessGuard({
3118
+ baseAccess,
3119
+ context,
3120
+ readOption,
3121
+ readDefaultOption,
3122
+ subdocuments = false
3123
+ }) {
3124
+ const keys2 = baseAccess.split(".");
3125
+ if (isRemovedOperationAccess(baseAccess) || isOperationAccessMemberPath(baseAccess) || keys2[0] === "subs" && isRemovedOperationAccess(keys2[2]))
3126
+ return false;
3127
+ if (context !== void 0 && !["basic", "advanced", "root"].includes(context)) return false;
3128
+ const exact = (key) => {
3129
+ const value = readOption(key);
3130
+ return value === void 0 ? readDefaultOption?.(key) : value;
3131
+ };
3132
+ const contextGuard = (key, supported) => context === void 0 || !supported ? void 0 : scalarGuard(exact(`${key}.${context}`));
3133
+ let access = baseAccess;
3134
+ if (subdocuments && keys2[0] === "subs") {
3135
+ if (keys2.length < 3 || keys2[1] === "") return false;
3136
+ const fieldKey = `operationAccess.subs.${keys2[1]}`;
3137
+ const operationKey2 = `operationAccess.${baseAccess}`;
3138
+ const selected2 = contextGuard(operationKey2, keys2.length === 3 && subOperations.has(keys2[2]));
3139
+ if (selected2 !== void 0) return selected2;
3140
+ const operation2 = exact(operationKey2);
3141
+ if (operation2 !== void 0) {
3142
+ const guard2 = keys2.length === 3 && subOperations.has(keys2[2]) ? operationDefault(operation2) : scalarGuard(operation2);
3143
+ if (guard2 !== void 0) return guard2;
3144
+ }
3145
+ const field = exact(fieldKey);
3146
+ if (field !== void 0) return scalarGuard(field);
3147
+ access = keys2[2];
3148
+ }
3149
+ const operationKey = `operationAccess.${access}`;
3150
+ const selected = contextGuard(operationKey, operations.has(access));
3151
+ if (selected !== void 0) return selected;
3152
+ const operation = readOption(operationKey);
3153
+ if (operation !== void 0) {
3154
+ const guard2 = operations.has(access) ? operationDefault(operation) : scalarGuard(operation);
3155
+ if (guard2 !== void 0) return guard2;
3156
+ }
3157
+ const outerDefault = readOption("operationAccess.default");
3158
+ if (outerDefault !== void 0) return scalarGuard(outerDefault);
3159
+ const outer = readOption("operationAccess");
3160
+ if (outer !== void 0) return scalarGuard(outer);
3161
+ const inherited = readDefaultOption?.(operationKey);
3162
+ return operations.has(access) ? operationDefault(inherited) : scalarGuard(inherited);
3163
+ }
3164
+ async function resolveRouteOperationAccess({
3165
+ canActivate,
3166
+ ...selection
3167
+ }) {
3168
+ const guard2 = selectOperationAccessGuard(selection);
3169
+ return guard2 === void 0 ? false : canActivate(guard2);
3170
+ }
3171
+ function rejectRemovedKey(key, prefix) {
3172
+ const context = key.startsWith("basic") ? "basic" : "advanced";
3173
+ const operation = key.slice(context.length);
3174
+ const replacement = `${operation[0].toLowerCase()}${operation.slice(1)}.${context}`;
3175
+ throw new TypeError(
3176
+ `Removed operation-access key "${prefix}${key}"; use "${prefix}${replacement}" instead. Move the operation's former scalar guard to its "default" member when using an object.`
3177
+ );
3178
+ }
3179
+ function assertOperationNode(node, prefix) {
3180
+ if (!node || typeof node !== "object" || Array.isArray(node)) return;
3181
+ for (const key of removedAccesses) if (key in node) rejectRemovedKey(key, prefix);
3182
+ for (const key of Object.getOwnPropertyNames(node)) {
3183
+ const [operation] = key.split(".");
3184
+ if (isRemovedOperationAccess(operation)) rejectRemovedKey(operation, prefix);
3185
+ }
3186
+ }
3187
+ function assertOperationAccessOptions(options) {
3188
+ if (!options || typeof options !== "object") return;
3189
+ for (const key of Object.getOwnPropertyNames(options)) {
3190
+ if (key === "operationAccess" || key.startsWith("operationAccess.")) {
3191
+ assertOperationAccessUpdate(key, options[key]);
3192
+ }
3193
+ }
3194
+ }
3195
+ function assertOperationAccessUpdate(key, value) {
3196
+ const path = key.split(".");
3197
+ if (path[0] !== "operationAccess") return;
3198
+ if (isRemovedOperationAccess(path[1])) rejectRemovedKey(path[1], "operationAccess.");
3199
+ if (path[1] === "subs" && path.length >= 4 && isRemovedOperationAccess(path[3]))
3200
+ rejectRemovedKey(path[3], `operationAccess.subs.${path[2]}.`);
3201
+ if (path.length === 1) {
3202
+ assertOperationNode(value, "operationAccess.");
3203
+ if (value && typeof value === "object" && !Array.isArray(value)) {
3204
+ for (const property of Object.getOwnPropertyNames(value)) {
3205
+ if (property === "subs" || property.startsWith("subs."))
3206
+ assertOperationAccessUpdate(`operationAccess.${property}`, value[property]);
3207
+ }
3208
+ }
3209
+ } else if (path.length === 2 && path[1] === "subs") {
3210
+ if (value && typeof value === "object" && !Array.isArray(value)) {
3211
+ for (const field of Object.getOwnPropertyNames(value))
3212
+ assertOperationAccessUpdate(`operationAccess.subs.${field}`, value[field]);
3213
+ }
3214
+ } else if (path.length === 3 && path[1] === "subs") {
3215
+ assertOperationNode(value, `${key}.`);
3216
+ }
3217
+ }
3218
+ var operations, subOperations, members, removedAccesses, isRemovedOperationAccess, isRecord, scalarGuard;
3219
+ var init_operation_access = __esm({
3220
+ "src/operation-access.ts"() {
3221
+ operations = /* @__PURE__ */ new Set(["new", "list", "read", "create", "update", "upsert", "delete", "count", "distinct"]);
3222
+ subOperations = /* @__PURE__ */ new Set(["list", "read", "create", "update", "delete"]);
3223
+ members = /* @__PURE__ */ new Set(["default", "basic", "advanced", "root"]);
3224
+ removedAccesses = new Set(
3225
+ ["List", "Read", "Create", "Update", "Upsert", "Count", "Distinct"].flatMap((operation) => [
3226
+ `basic${operation}`,
3227
+ `advanced${operation}`
3228
+ ])
3229
+ );
3230
+ isRemovedOperationAccess = (access) => typeof access === "string" && removedAccesses.has(access);
3231
+ isRecord = (value) => value !== null && typeof value === "object" && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
3232
+ scalarGuard = (value) => {
3233
+ if (value === void 0) return void 0;
3234
+ if (typeof value === "boolean" || typeof value === "string" || typeof value === "function")
3235
+ return value;
3236
+ if (Array.isArray(value) && value.every((entry) => typeof entry === "string")) return value;
3237
+ return false;
3238
+ };
3239
+ }
3240
+ });
3241
+
3079
3242
  // src/request-complexity.ts
3080
3243
  function validateRequestComplexity(value, options, scope2 = "request") {
3081
3244
  const limits = resolveRequestComplexity(options);
@@ -3479,8 +3642,8 @@ function captureVirtualPopulateDependencies(runtime, modelName, options, populat
3479
3642
  if (!model || !schema || unsupportedScope)
3480
3643
  return fail(label, "requires a static embedded, non-discriminator source scope");
3481
3644
  const type = schema.path(join(schemaPrefix, path));
3482
- const isArray14 = type?.instance === "Array";
3483
- const scalar = type && (isArray14 ? elementType(type) : type);
3645
+ const isArray13 = type?.instance === "Array";
3646
+ const scalar = type && (isArray13 ? elementType(type) : type);
3484
3647
  const ref = type?.options?.ref ?? scalar?.options?.ref;
3485
3648
  if (!scalar || scalar.instance !== "ObjectId" || typeof ref !== "string" || !ref || type?.options?.refPath !== void 0 || scalar.options?.refPath !== void 0)
3486
3649
  return fail(label, `path "${path}" requires a static string ref on an ObjectId scalar or 1D array`);
@@ -3512,7 +3675,12 @@ function captureVirtualPopulateDependencies(runtime, modelName, options, populat
3512
3675
  populatePolicyDefaults,
3513
3676
  ...resolvePopulatePolicy(targetOptions, populatePolicyDefaults),
3514
3677
  permissionSchema: targetOptions.permissionSchema,
3515
- operationAccess: { read: readOption("operationAccess.read") },
3678
+ operationAccess: {
3679
+ read: selectOperationAccessGuard({
3680
+ ...createOperationAccessReaders(targetOptions, defaults2),
3681
+ baseAccess: "read"
3682
+ })
3683
+ },
3516
3684
  baseFilter: { read: readOption("baseFilter.read") },
3517
3685
  overrideFilter: { read: readOption("overrideFilter.read") },
3518
3686
  hydration: targetOptions.hydration
@@ -3535,7 +3703,7 @@ function captureVirtualPopulateDependencies(runtime, modelName, options, populat
3535
3703
  return Object.freeze({
3536
3704
  path,
3537
3705
  sourcePath: join(sourcePrefix, path),
3538
- cardinality: isArray14 ? "array" : "scalar",
3706
+ cardinality: isArray13 ? "array" : "scalar",
3539
3707
  target: captured.target,
3540
3708
  ...normalizeSelection(dependency.select, captured.catalog, label)
3541
3709
  });
@@ -3622,6 +3790,7 @@ var init_virtual_populate_dependencies = __esm({
3622
3790
  import_utils16 = require("@web-ts-toolkit/utils");
3623
3791
  init_query();
3624
3792
  init_manager();
3793
+ init_operation_access();
3625
3794
  init_authorization_snapshot();
3626
3795
  init_field_catalog();
3627
3796
  init_virtual_descriptor();
@@ -3640,6 +3809,102 @@ var init_virtual_populate_dependencies = __esm({
3640
3809
  }
3641
3810
  });
3642
3811
 
3812
+ // src/acl/persisted-dependencies.ts
3813
+ function collectPersistedTopLevel(schema) {
3814
+ return /* @__PURE__ */ new Set([
3815
+ ...Object.keys(schema?.paths ?? {}).map((path) => path.split(".")[0]),
3816
+ ...Object.keys(schema?.obj ?? {})
3817
+ ]);
3818
+ }
3819
+ function capturePersistedDependencies(value, label, storedFields, virtualNames = /* @__PURE__ */ new Set()) {
3820
+ if (value === void 0) return Object.freeze([]);
3821
+ if (!Array.isArray(value) || import_node_util9.types.isProxy(value) || Object.getPrototypeOf(value) !== Array.prototype)
3822
+ throw new TypeError(`${label}: dependsOn must be an array of top-level persisted field names`);
3823
+ const length = Object.getOwnPropertyDescriptor(value, "length").value;
3824
+ if (length > 2e4 || Reflect.ownKeys(value).length !== length + 1)
3825
+ throw new TypeError(`${label}: dependsOn must be a dense array of persisted field names`);
3826
+ const result2 = [];
3827
+ for (let index = 0; index < length; index++) {
3828
+ const slot = Object.getOwnPropertyDescriptor(value, String(index));
3829
+ if (!slot || !("value" in slot) || typeof slot.value !== "string" || !slot.value)
3830
+ throw new TypeError(`${label}: dependsOn entries must be non-empty strings`);
3831
+ const dep = slot.value;
3832
+ if (dep.includes("."))
3833
+ throw new TypeError(`${label}: dependsOn "${dep}" must be a top-level persisted name (dotted paths rejected)`);
3834
+ if (!isSafeOutputPath(dep)) throw new TypeError(`${label}: unsafe dependsOn field "${dep}"`);
3835
+ if (virtualNames.has(dep)) throw new TypeError(`${label}: dependsOn "${dep}" must not reference another virtual`);
3836
+ if (storedFields && !storedFields.has(dep))
3837
+ throw new TypeError(`${label}: dependsOn "${dep}" is not a persisted field in its scope`);
3838
+ result2.push(dep);
3839
+ }
3840
+ return Object.freeze([...new Set(result2)]);
3841
+ }
3842
+ var import_node_util9;
3843
+ var init_persisted_dependencies = __esm({
3844
+ "src/acl/persisted-dependencies.ts"() {
3845
+ import_node_util9 = require("util");
3846
+ init_field_catalog();
3847
+ }
3848
+ });
3849
+
3850
+ // src/acl/document-permissions-definition.ts
3851
+ function dataRecord(value, label) {
3852
+ if (!value || typeof value !== "object" || import_node_util10.types.isProxy(value))
3853
+ throw new TypeError(`${label}: expected a function, { get, dependsOn? }, or per-access record`);
3854
+ const prototype = Object.getPrototypeOf(value);
3855
+ if (prototype !== Object.prototype && prototype !== null)
3856
+ throw new TypeError(`${label}: definition must be a plain object`);
3857
+ const result2 = /* @__PURE__ */ Object.create(null);
3858
+ const keys2 = Reflect.ownKeys(value);
3859
+ if (keys2.length > 2e4) throw new TypeError(`${label}: too many definition entries`);
3860
+ for (const key of keys2) {
3861
+ if (typeof key !== "string" || ["__proto__", "constructor", "prototype"].includes(key))
3862
+ throw new TypeError(`${label}: unsafe definition key`);
3863
+ const slot = Object.getOwnPropertyDescriptor(value, key);
3864
+ if (!slot.enumerable || !("value" in slot))
3865
+ throw new TypeError(`${label}: definition entries must be enumerable data properties`);
3866
+ Object.defineProperty(result2, key, { value: slot.value, enumerable: true });
3867
+ }
3868
+ return result2;
3869
+ }
3870
+ function captureLeaf(value, label, scope2) {
3871
+ if (typeof value === "function") return value;
3872
+ const record3 = dataRecord(value, label);
3873
+ if (typeof record3.get !== "function") throw new TypeError(`${label}: descriptor.get must be callable`);
3874
+ if (Object.keys(record3).some((key) => key !== "get" && key !== "dependsOn"))
3875
+ throw new TypeError(`${label}: descriptor accepts only get/dependsOn; cannot mix per-access keys`);
3876
+ return Object.freeze({
3877
+ get: record3.get,
3878
+ dependsOn: capturePersistedDependencies(record3.dependsOn, label, scope2.storedFields, scope2.virtualNames)
3879
+ });
3880
+ }
3881
+ function captureDocumentPermissionsDefinition(value, scope2 = {}) {
3882
+ if (value === void 0) return void 0;
3883
+ if (typeof value === "function") return value;
3884
+ const record3 = dataRecord(value, "docPermissions");
3885
+ if (Object.hasOwn(record3, "get") || Object.hasOwn(record3, "dependsOn"))
3886
+ return captureLeaf(record3, "docPermissions", scope2);
3887
+ const entries = Object.entries(record3).map(([access, leaf]) => {
3888
+ if (!/^[A-Za-z_][A-Za-z0-9_$]*$/.test(access))
3889
+ throw new TypeError(`docPermissions: unsafe or dotted access "${access}"`);
3890
+ return [access, leaf === void 0 ? void 0 : captureLeaf(leaf, `docPermissions.${access}`, scope2)];
3891
+ });
3892
+ return Object.freeze(Object.fromEntries(entries));
3893
+ }
3894
+ function resolveDocumentPermissionsDefinition(value, access) {
3895
+ const captured = captureDocumentPermissionsDefinition(value);
3896
+ const leaf = typeof captured === "function" || captured && Object.hasOwn(captured, "get") ? captured : Object.getOwnPropertyDescriptor(captured ?? {}, access)?.value ?? Object.getOwnPropertyDescriptor(captured ?? {}, "default")?.value;
3897
+ if (leaf === void 0) return void 0;
3898
+ return typeof leaf === "function" ? Object.freeze({ get: leaf, dependsOn: Object.freeze([]) }) : Object.freeze({ get: leaf.get, dependsOn: leaf.dependsOn ?? Object.freeze([]) });
3899
+ }
3900
+ var import_node_util10;
3901
+ var init_document_permissions_definition = __esm({
3902
+ "src/acl/document-permissions-definition.ts"() {
3903
+ import_node_util10 = require("util");
3904
+ init_persisted_dependencies();
3905
+ }
3906
+ });
3907
+
3643
3908
  // src/runtime.ts
3644
3909
  var import_mongoose5, import_mongoose_schema_jsonschema, import_utils17, mongooseJsonSchemaInitialized, ensureMongooseJsonSchemaInitialized, pluralize, FIELD_ACCESS_KEYS, defaultModelOptions, modelOverrides, defaultDataOptions, normalizeBasePath, hasModelPermission, classifyPermissionSchema, refreshPermissionMetadata, VIRTUAL_SUPPORTED_ACCESSES, VIRTUAL_UNSUPPORTED_ACCESSES, VIRTUAL_RESERVED_NAMES, VIRTUAL_DANGEROUS_SEGMENTS, VIRTUAL_NAME_PATTERN, isVirtualContainerValue2, virtualFullPath, virtualPathsOverlap, collectStoredTopLevel, getChildSchemaForField, getNestedChildFields, cloneModelOptionForUpdate, validateVirtualDependsOn, validateVirtualLeafValue, validateVirtualsScope, validateVirtualsTree, AccessRuntime, defaultRuntime;
3645
3910
  var init_runtime = __esm({
@@ -3655,10 +3920,13 @@ var init_runtime = __esm({
3655
3920
  init_logger_default();
3656
3921
  init_manager();
3657
3922
  init_data_manager();
3923
+ init_operation_access();
3658
3924
  init_data_values();
3659
3925
  init_request_complexity();
3660
3926
  init_virtual_descriptor();
3661
3927
  init_virtual_populate_dependencies();
3928
+ init_document_permissions_definition();
3929
+ init_persisted_dependencies();
3662
3930
  init_authorization_modes();
3663
3931
  mongooseJsonSchemaInitialized = false;
3664
3932
  ensureMongooseJsonSchemaInitialized = () => {
@@ -3669,8 +3937,7 @@ var init_runtime = __esm({
3669
3937
  pluralize = import_mongoose5.default.pluralize();
3670
3938
  FIELD_ACCESS_KEYS = ["list", "create", "read", "update"];
3671
3939
  defaultModelOptions = {
3672
- basePath: null,
3673
- alwaysSelectFields: []
3940
+ basePath: null
3674
3941
  };
3675
3942
  modelOverrides = (options) => {
3676
3943
  const result2 = Object.fromEntries(
@@ -3768,22 +4035,7 @@ var init_runtime = __esm({
3768
4035
  }
3769
4036
  return false;
3770
4037
  };
3771
- collectStoredTopLevel = (schema) => {
3772
- const fields = /* @__PURE__ */ new Set();
3773
- if (!schema) return fields;
3774
- const paths = schema.paths;
3775
- if (paths) {
3776
- for (const p of Object.keys(paths)) {
3777
- const top = p.split(".")[0];
3778
- if (top) fields.add(top);
3779
- }
3780
- }
3781
- const obj = schema.obj;
3782
- if (obj) {
3783
- for (const k of Object.keys(obj)) fields.add(k);
3784
- }
3785
- return fields;
3786
- };
4038
+ collectStoredTopLevel = collectPersistedTopLevel;
3787
4039
  getChildSchemaForField = (parentSchema, fieldName) => {
3788
4040
  if (!parentSchema) return null;
3789
4041
  try {
@@ -3822,32 +4074,7 @@ var init_runtime = __esm({
3822
4074
  );
3823
4075
  };
3824
4076
  validateVirtualDependsOn = (dependsOn, entryLabel, storedFields, siblingVirtualNames) => {
3825
- if (dependsOn === void 0) return [];
3826
- if (!(0, import_utils17.isArray)(dependsOn)) {
3827
- throw new Error(`Virtual ${entryLabel}: dependsOn must be an array of top-level persisted field names`);
3828
- }
3829
- const list = dependsOn;
3830
- for (const dep of list) {
3831
- if (!(0, import_utils17.isString)(dep) || dep.length === 0) {
3832
- throw new Error(`Virtual ${entryLabel}: dependsOn entries must be non-empty strings`);
3833
- }
3834
- if (dep.includes(".")) {
3835
- throw new Error(
3836
- `Virtual ${entryLabel}: dependsOn "${dep}" must be a top-level persisted name relative to its scope (dotted paths rejected)`
3837
- );
3838
- }
3839
- if (siblingVirtualNames.has(dep)) {
3840
- throw new Error(
3841
- `Virtual ${entryLabel}: dependsOn "${dep}" must not reference another virtual (virtual-to-virtual rejected)`
3842
- );
3843
- }
3844
- if (!storedFields.has(dep)) {
3845
- throw new Error(
3846
- `Virtual ${entryLabel}: dependsOn "${dep}" is not a persisted field in its scope (validated against the receiving Mongoose schema/child scope)`
3847
- );
3848
- }
3849
- }
3850
- return list;
4077
+ return [...capturePersistedDependencies(dependsOn, `Virtual ${entryLabel}`, storedFields, siblingVirtualNames)];
3851
4078
  };
3852
4079
  validateVirtualLeafValue = (value, entryLabel, storedFields, siblingVirtualNames, sharedDependsOn) => {
3853
4080
  if ((0, import_utils17.isFunction)(value)) return;
@@ -4022,6 +4249,7 @@ var init_runtime = __esm({
4022
4249
  this.defaultModelOptions = new OptionsManager({
4023
4250
  listHardLimit: DEFAULT_LIST_HARD_LIMIT,
4024
4251
  documentPermissionField: "_permissions",
4252
+ disableFieldPermissions: true,
4025
4253
  idParam: "id",
4026
4254
  idField: "_id",
4027
4255
  parentPath: "/",
@@ -4032,7 +4260,9 @@ var init_runtime = __esm({
4032
4260
  requireOperationAccessForPopulateDependencies: true,
4033
4261
  modelPermissionPrefix: "",
4034
4262
  readAuthorizationMode: "isolated",
4035
- listAuthorizationMode: "isolated"
4263
+ listAuthorizationMode: "isolated",
4264
+ createAuthorizationMode: "isolated",
4265
+ updateAuthorizationMode: "isolated"
4036
4266
  }).build();
4037
4267
  this.modelOptions = {};
4038
4268
  this.modelOptionOverrides = {};
@@ -4173,15 +4403,18 @@ var init_runtime = __esm({
4173
4403
  assertAuthorizationModeOptions(snapshot.globalOptions, false);
4174
4404
  assertNoServerModelControls(snapshot.globalOptions, reject);
4175
4405
  assertAuthorizationModeOptions(snapshot.defaultModelOptions, true);
4406
+ assertOperationAccessOptions(snapshot.defaultModelOptions);
4176
4407
  assertNoServerModelControls(snapshot.defaultModelOptions, reject, "model-options");
4177
4408
  assertPublicDefaults(snapshot.defaultModelOptions.defaults);
4178
4409
  for (const options of [...Object.values(snapshot.modelOptions), ...Object.values(snapshot.modelOptionOverrides)]) {
4179
4410
  assertAuthorizationModeOptions(options, true);
4411
+ assertOperationAccessOptions(options);
4180
4412
  assertNoServerModelControls(options, reject, "model-options");
4181
4413
  assertPublicDefaults(options.defaults);
4182
4414
  }
4183
4415
  for (const options of Object.values(snapshot.dataOptions)) {
4184
4416
  assertAuthorizationModeOptions(options, false);
4417
+ assertOperationAccessOptions(options);
4185
4418
  assertNoServerModelControls(options, reject, "data-options");
4186
4419
  }
4187
4420
  this.globalOptions.restore(snapshot.globalOptions);
@@ -4269,6 +4502,7 @@ var init_runtime = __esm({
4269
4502
  /** Update inherited model defaults shallowly. Explicit model values and captured calls are unchanged. */
4270
4503
  setDefaultModelOptions(options) {
4271
4504
  assertAuthorizationModeOptions(options, true);
4505
+ assertOperationAccessOptions(options);
4272
4506
  assertNoServerModelControls(
4273
4507
  options,
4274
4508
  (detail) => {
@@ -4290,6 +4524,7 @@ var init_runtime = __esm({
4290
4524
  setDefaultModelOption(key, value) {
4291
4525
  assertAuthorizationModeKey(key, true);
4292
4526
  const keyStr = key;
4527
+ assertOperationAccessUpdate(keyStr, value);
4293
4528
  if (authorizationModeKeys.includes(keyStr)) {
4294
4529
  this.setDefaultModelOptions({ [keyStr]: value });
4295
4530
  return;
@@ -4343,15 +4578,20 @@ var init_runtime = __esm({
4343
4578
  return cloneOptionsSnapshot(effective);
4344
4579
  }
4345
4580
  validateModelOptions(modelName, options, proposed) {
4346
- validateVirtualsTree(
4347
- this.getModelInstance(modelName),
4348
- options.virtuals,
4349
- options.documentPermissionField ?? "_permissions",
4350
- modelName
4351
- );
4581
+ assertOperationAccessOptions(options);
4582
+ const model = this.getModelInstance(modelName);
4583
+ validateVirtualsTree(model, options.virtuals, options.documentPermissionField ?? "_permissions", modelName);
4584
+ captureDocumentPermissionsDefinition(options.docPermissions, {
4585
+ storedFields: collectPersistedTopLevel(model?.schema),
4586
+ virtualNames: /* @__PURE__ */ new Set([
4587
+ ...Object.keys(model?.schema.virtuals ?? {}),
4588
+ ...Object.entries(options.virtuals ?? {}).filter(([, value]) => value !== void 0 && !isVirtualContainerValue2(value)).map(([name]) => name)
4589
+ ])
4590
+ });
4352
4591
  captureVirtualPopulateDependencies(this, modelName, options, void 0, proposed);
4353
4592
  }
4354
4593
  publishDefaultModelOptions(options) {
4594
+ assertOperationAccessOptions(options);
4355
4595
  const next = { ...options };
4356
4596
  const defaults2 = cloneOptionsSnapshot(next);
4357
4597
  const models = new Map(
@@ -4384,10 +4624,10 @@ var init_runtime = __esm({
4384
4624
  if (options[key] !== "trusted" || before.get(modelName)?.[key] === "trusted") continue;
4385
4625
  try {
4386
4626
  this.getGlobalOption("logger")?.warn?.(
4387
- "Trusted authorization source mode enabled; projected source/document-hook input may be borrowed. Actor, policy, facts, getter views and selected output bounds remain owned.",
4627
+ "Trusted authorization output source mode enabled; admitted source/document-hook input may be borrowed. Write input is unchanged. Actor, policy, facts, getter views and selected output bounds remain owned.",
4388
4628
  {
4389
4629
  modelName,
4390
- access: key === "readAuthorizationMode" ? "read" : "list",
4630
+ access: authorizationModeOperations[key],
4391
4631
  category: "trustedAuthorizationSource"
4392
4632
  }
4393
4633
  );
@@ -4439,6 +4679,7 @@ var init_runtime = __esm({
4439
4679
  */
4440
4680
  setModelOptions(modelName, options) {
4441
4681
  assertAuthorizationModeOptions(options, true);
4682
+ assertOperationAccessOptions(options);
4442
4683
  assertNoServerModelControls(
4443
4684
  options,
4444
4685
  (detail) => {
@@ -4447,6 +4688,12 @@ var init_runtime = __esm({
4447
4688
  "model-options"
4448
4689
  );
4449
4690
  assertPublicDefaults(options.defaults);
4691
+ if ("docPermissions" in options) {
4692
+ const slot = Object.getOwnPropertyDescriptor(options, "docPermissions");
4693
+ if (!slot || !("value" in slot) || !slot.enumerable)
4694
+ throw new TypeError("docPermissions must be an enumerable data property");
4695
+ options = { ...options, docPermissions: captureDocumentPermissionsDefinition(slot.value) };
4696
+ }
4450
4697
  options = normalizePopulatePolicyOptions(options);
4451
4698
  if ("hydration" in options) options = { ...options, hydration: normalizeHydration(options.hydration) };
4452
4699
  const overrides = modelOverrides({ ...this.modelOptionOverrides[modelName], ...options });
@@ -4462,6 +4709,17 @@ var init_runtime = __esm({
4462
4709
  setModelOption(modelName, key, value) {
4463
4710
  assertAuthorizationModeKey(key, true);
4464
4711
  const keyStr = key;
4712
+ assertOperationAccessUpdate(keyStr, value);
4713
+ if (keyStr === "docPermissions") {
4714
+ value = captureDocumentPermissionsDefinition(value);
4715
+ } else if (keyStr.startsWith("docPermissions.")) {
4716
+ const path2 = keyStr.slice("docPermissions.".length);
4717
+ if (path2.includes(".") || path2 === "get" || path2 === "dependsOn")
4718
+ throw new TypeError(
4719
+ "docPermissions dotted setters replace an access definition; set { get, dependsOn? } together"
4720
+ );
4721
+ captureDocumentPermissionsDefinition({ [path2]: value });
4722
+ }
4465
4723
  if (keyStr === "hydration" || keyStr.startsWith("hydration.")) {
4466
4724
  const hydration = normalizeHydrationUpdate(this.resolveModelOptions(modelName).hydration, keyStr, value);
4467
4725
  this.setModelOptions(modelName, { hydration });
@@ -4494,7 +4752,10 @@ var init_runtime = __esm({
4494
4752
  return;
4495
4753
  }
4496
4754
  const current = this.resolveModelOptions(modelName);
4497
- const nested = cloneModelOptionForUpdate((0, import_utils17.isPlainObject)(current[root]) ? current[root] : {});
4755
+ const directDocumentPermissions = root === "docPermissions" && current[root] && typeof current[root] === "object" && Object.hasOwn(current[root], "get");
4756
+ const nested = cloneModelOptionForUpdate(
4757
+ (0, import_utils17.isPlainObject)(current[root]) && !directDocumentPermissions ? current[root] : {}
4758
+ );
4498
4759
  if (root === "virtuals" && value === void 0) {
4499
4760
  const parent = path.length === 1 ? nested : (0, import_utils17.get)(nested, path.slice(0, -1));
4500
4761
  if ((0, import_utils17.isPlainObject)(parent)) delete parent[path[path.length - 1]];
@@ -4509,8 +4770,9 @@ var init_runtime = __esm({
4509
4770
  /**
4510
4771
  * Generic stored exact → parent.default → parent lookup; only undefined falls through.
4511
4772
  * The exact runtime-model-default path is the final fallback if the stored parent is
4512
- * absent. This is not the route-specific variant-to-base resolver; use
4513
- * getExactModelOption to inspect a variant including its exact model-default fallback.
4773
+ * absent. This raw generic lookup is not the final nested operation-entry resolver;
4774
+ * it may return an operation object. getExactModelOption inspects a member including
4775
+ * its same-owner exact model-default fallback, without resolving entry policy.
4514
4776
  */
4515
4777
  getModelOption(modelName, key, defaultValue) {
4516
4778
  const manager = this.getOrCreateModelOptions(modelName);
@@ -4520,7 +4782,7 @@ var init_runtime = __esm({
4520
4782
  );
4521
4783
  return getNestedOption(manager, key, defaultModelValue);
4522
4784
  }
4523
- /** Exact stored path, then the same runtime-model-default path; no parent/default or variant-to-base lookup. */
4785
+ /** Exact stored path, then the same runtime-model-default path; no parent/default or final entry resolution. */
4524
4786
  getExactModelOption(modelName, key) {
4525
4787
  const manager = this.getOrCreateModelOptions(modelName);
4526
4788
  const defaultModelValue = this.getDefaultModelOption(key);
@@ -4603,6 +4865,7 @@ var init_runtime = __esm({
4603
4865
  }
4604
4866
  setDataOptions(dataName, options) {
4605
4867
  assertAuthorizationModeOptions(options, false);
4868
+ assertOperationAccessOptions(options);
4606
4869
  assertNoServerModelControls(
4607
4870
  options,
4608
4871
  (detail) => {
@@ -4615,6 +4878,7 @@ var init_runtime = __esm({
4615
4878
  }
4616
4879
  setDataOption(dataName, key, value) {
4617
4880
  assertAuthorizationModeKey(key, false);
4881
+ assertOperationAccessUpdate(key, value);
4618
4882
  const proposed = {};
4619
4883
  (0, import_utils17.set)(proposed, key, value);
4620
4884
  assertNoServerModelControls(
@@ -4709,7 +4973,7 @@ var init_global_options = __esm({
4709
4973
  });
4710
4974
 
4711
4975
  // src/options/model-options.ts
4712
- var getRuntime3, setModelOptions, setModelOption, getModelOptions, getModelOption, getExactModelOption, getModelNames, getModelJsonSchema, registerModelInstance, hasModelInstance, getModelInstance;
4976
+ var getRuntime3, setModelOptions, setModelOption, getModelOptions, getModelOption, getModelNames, getModelJsonSchema, registerModelInstance, hasModelInstance, getModelInstance;
4713
4977
  var init_model_options = __esm({
4714
4978
  "src/options/model-options.ts"() {
4715
4979
  init_runtime();
@@ -4727,9 +4991,6 @@ var init_model_options = __esm({
4727
4991
  getModelOption = (modelName, key, defaultValue) => {
4728
4992
  return getRuntime3().getModelOption(modelName, key, defaultValue);
4729
4993
  };
4730
- getExactModelOption = (modelName, key) => {
4731
- return getRuntime3().getExactModelOption(modelName, key);
4732
- };
4733
4994
  getModelNames = () => {
4734
4995
  return (getActiveRuntime() ?? defaultRuntime).getModelNames();
4735
4996
  };
@@ -4771,7 +5032,7 @@ var init_default_model_options = __esm({
4771
5032
  });
4772
5033
 
4773
5034
  // src/options/data-options.ts
4774
- var getRuntime5, getDataOptions, getDataOption, getExactDataOption;
5035
+ var getRuntime5, getDataOptions, getDataOption;
4775
5036
  var init_data_options = __esm({
4776
5037
  "src/options/data-options.ts"() {
4777
5038
  init_runtime();
@@ -4783,9 +5044,6 @@ var init_data_options = __esm({
4783
5044
  getDataOption = (dataName, key, defaultValue) => {
4784
5045
  return getRuntime5().getDataOption(dataName, key, defaultValue);
4785
5046
  };
4786
- getExactDataOption = (dataName, key) => {
4787
- return getRuntime5().getExactDataOption(dataName, key);
4788
- };
4789
5047
  }
4790
5048
  });
4791
5049
 
@@ -5129,7 +5387,7 @@ init_document();
5129
5387
  var import_utils19 = require("@web-ts-toolkit/utils");
5130
5388
 
5131
5389
  // src/acl/document-stage.ts
5132
- var import_node_util10 = require("util");
5390
+ var import_node_util12 = require("util");
5133
5391
  var import_mongoose6 = require("mongoose");
5134
5392
 
5135
5393
  // src/acl/service-authorization.ts
@@ -5168,6 +5426,22 @@ function serviceAuthorizationInput(policy, targets) {
5168
5426
  }
5169
5427
  var calls = /* @__PURE__ */ new WeakMap();
5170
5428
  var capturedActors = /* @__PURE__ */ new WeakSet();
5429
+ function storeCallRecord(call, record3) {
5430
+ calls.set(
5431
+ call,
5432
+ Object.assign(
5433
+ /* @__PURE__ */ Object.create(null),
5434
+ {
5435
+ queryOrigin: void 0,
5436
+ writeOrigin: void 0,
5437
+ writeOutputBranch: void 0,
5438
+ fieldPolicyOwner: void 0,
5439
+ view: void 0
5440
+ },
5441
+ record3
5442
+ )
5443
+ );
5444
+ }
5171
5445
  function clearOutputHelperAuthorization(call) {
5172
5446
  if (callRecord(call).factOrigin !== "output-helper") authorizationError("not output-helper preparation");
5173
5447
  calls.delete(call);
@@ -5374,8 +5648,37 @@ function assertAuthorizationBinding(call, binding) {
5374
5648
  authorizationError("request/runtime/model/scope binding mismatch");
5375
5649
  }
5376
5650
  }
5651
+ function targetOutputAccess(access) {
5652
+ return (access.rowAccess === "read" || access.rowAccess === "list") && access.outputAccess === access.rowAccess && access.virtualAccess === access.rowAccess && access.docPermissionsAccess === access.rowAccess;
5653
+ }
5377
5654
  function queryOutputAccess(access) {
5378
- return (access.operation === "read" || access.operation === "list") && (access.rowAccess === "read" || access.rowAccess === "list") && access.outputAccess === access.rowAccess && access.virtualAccess === access.rowAccess && access.docPermissionsAccess === access.rowAccess;
5655
+ return (access.operation === "read" || access.operation === "list") && targetOutputAccess(access);
5656
+ }
5657
+ function writeBranchAccess(access, operation, branch) {
5658
+ return access.operation === operation && access.rowAccess === (branch === "update" ? "update" : void 0) && access.virtualAccess === branch && access.outputAccess === "read" && access.docPermissionsAccess === branch;
5659
+ }
5660
+ function resolveWriteServiceAuthorization(input, origin) {
5661
+ if (!["create", "update", "upsert"].includes(origin) || input.parent || scope(input.binding).length || (origin === "create" ? input.applicability !== "create" : origin === "update" ? input.applicability !== "mutation" : input.applicability !== "mutation" && input.applicability !== "service") || !writeBranchAccess(input.access, origin, origin === "create" ? "create" : "update"))
5662
+ authorizationError("invalid write entry origin");
5663
+ const call = resolveServiceAuthorization(input);
5664
+ storeCallRecord(call, { ...callRecord(call), writeOrigin: origin });
5665
+ return call;
5666
+ }
5667
+ function deriveWriteOutputAuthorization(parent, binding, branch) {
5668
+ assertAuthorizationBinding(parent, binding);
5669
+ const record3 = callRecord(parent);
5670
+ if (!record3.writeOrigin || record3.writeOutputBranch || scope(binding).length || record3.writeOrigin !== "upsert" && record3.writeOrigin !== branch || !writeBranchAccess(record3.access, record3.writeOrigin, branch))
5671
+ authorizationError("invalid write output origin/branch");
5672
+ const call = Object.freeze(/* @__PURE__ */ Object.create(null));
5673
+ storeCallRecord(call, {
5674
+ ...record3,
5675
+ writeOrigin: void 0,
5676
+ writeOutputBranch: branch,
5677
+ sourceMode: record3.configuration[branch === "create" ? "createAuthorizationMode" : "updateAuthorizationMode"] ?? "isolated",
5678
+ fieldPolicyOwner: void 0,
5679
+ view: void 0
5680
+ });
5681
+ return call;
5379
5682
  }
5380
5683
  function deriveQueryAuthorization(input) {
5381
5684
  if (!input.parent || !input.snapshotDerivation) return;
@@ -5406,9 +5709,9 @@ function deriveQueryAuthorization(input) {
5406
5709
  const configuration = target?.configuration ?? parent.configuration;
5407
5710
  const relatedTargets = target ? target.relatedTargets ?? [] : parent.relatedTargets;
5408
5711
  const policy = target ? parent.policy.related[target.path] ?? copyAuthorizationValue(normalizePolicy(void 0, "service", configuration, relatedTargets)) : parent.policy;
5409
- const queryOrigin = edge.kind === "related" ? parent.queryOrigin && queryOutputAccess(access) ? access.rowAccess : void 0 : parent.queryOrigin;
5712
+ const queryOrigin = edge.kind === "related" ? parent.queryOrigin && queryOutputAccess(access) || parent.writeOutputBranch && targetOutputAccess(access) ? access.rowAccess : void 0 : parent.queryOrigin;
5410
5713
  const call = Object.freeze(/* @__PURE__ */ Object.create(null));
5411
- calls.set(call, {
5714
+ storeCallRecord(call, {
5412
5715
  binding: Object.freeze({ ...input.binding, scopePath: Object.freeze([...scope(input.binding)]) }),
5413
5716
  access,
5414
5717
  configuration,
@@ -5422,6 +5725,7 @@ function deriveQueryAuthorization(input) {
5422
5725
  permissions: parent.permissions,
5423
5726
  provenance: parent.provenance,
5424
5727
  queryOrigin,
5728
+ writeOutputBranch: parent.writeOutputBranch,
5425
5729
  sourceMode: edge.kind === "related" ? modeFor(configuration, queryOrigin) : parent.sourceMode,
5426
5730
  factOrigin: edge.kind === "embedded" ? parent.factOrigin : "document",
5427
5731
  fieldPolicyOwner: target ? call : parent.fieldPolicyOwner ?? input.parent,
@@ -5434,8 +5738,8 @@ function modeFor(configuration, origin) {
5434
5738
  }
5435
5739
  function resolveServiceAuthorization(input) {
5436
5740
  if (input.parent) {
5437
- const parent = callRecord(input.parent).binding;
5438
- if (parent.request !== input.binding.request || parent.runtime !== input.binding.runtime)
5741
+ const parent2 = callRecord(input.parent).binding;
5742
+ if (parent2.request !== input.binding.request || parent2.runtime !== input.binding.runtime)
5439
5743
  authorizationError("derived call request/runtime mismatch");
5440
5744
  }
5441
5745
  const permissions = input.parent ? callRecord(input.parent).permissions : captureAuthorizationPermissions(input.requestPermissions, input.applicability === "output");
@@ -5460,13 +5764,16 @@ function resolveServiceAuthorization(input) {
5460
5764
  if (part.includes(".")) authorizationError("scopePath requires response segments");
5461
5765
  }
5462
5766
  if (input.parent) {
5463
- const parent = callRecord(input.parent).binding;
5464
- if (parent.request !== input.binding.request || parent.runtime !== input.binding.runtime) {
5767
+ const parent2 = callRecord(input.parent).binding;
5768
+ if (parent2.request !== input.binding.request || parent2.runtime !== input.binding.runtime) {
5465
5769
  authorizationError("derived call request/runtime mismatch");
5466
5770
  }
5467
5771
  }
5772
+ const parent = input.parent ? callRecord(input.parent) : void 0;
5773
+ const writeOrigin = parent?.writeOrigin === "upsert" && !parent.writeOutputBranch && input.snapshotDerivation?.kind === "retry" && input.applicability === "create" && !scope(input.binding).length && writeBranchAccess(parent.access, "upsert", "update") && writeBranchAccess(access, "upsert", "create") ? "upsert" : void 0;
5774
+ if (writeOrigin) assertAuthorizationBinding(input.parent, input.binding);
5468
5775
  const call = Object.freeze(/* @__PURE__ */ Object.create(null));
5469
- calls.set(call, {
5776
+ storeCallRecord(call, {
5470
5777
  binding: Object.freeze({ ...input.binding, scopePath: Object.freeze(scopePath) }),
5471
5778
  access,
5472
5779
  configuration,
@@ -5477,6 +5784,7 @@ function resolveServiceAuthorization(input) {
5477
5784
  permissions,
5478
5785
  provenance: input.parent ? callRecord(input.parent).provenance : call,
5479
5786
  queryOrigin,
5787
+ writeOrigin,
5480
5788
  sourceMode,
5481
5789
  factOrigin: !input.parent && input.applicability === "output" ? "output-helper" : "document",
5482
5790
  fieldPolicyOwner: void 0,
@@ -5507,6 +5815,10 @@ function readServiceAuthorizationMode(call, binding) {
5507
5815
  assertAuthorizationBinding(call, binding);
5508
5816
  return callRecord(call).sourceMode;
5509
5817
  }
5818
+ function isWriteOutputAuthorization(call, binding) {
5819
+ assertAuthorizationBinding(call, binding);
5820
+ return callRecord(call).writeOutputBranch !== void 0;
5821
+ }
5510
5822
  function isOutputHelperAuthorization(call, binding) {
5511
5823
  assertAuthorizationBinding(call, binding);
5512
5824
  return callRecord(call).factOrigin === "output-helper";
@@ -5575,7 +5887,7 @@ function getAuthorizationProvenance(call) {
5575
5887
  init_authorization_snapshot();
5576
5888
 
5577
5889
  // src/acl/document-grants.ts
5578
- var import_node_util9 = require("util");
5890
+ var import_node_util11 = require("util");
5579
5891
  init_logger_helpers();
5580
5892
  init_authorization_snapshot();
5581
5893
  init_output_work_ledger();
@@ -5596,7 +5908,7 @@ owned.add(EMPTY_DOCUMENT_GRANTS);
5596
5908
  function normalizeDocumentGrants(value, metadataField = "_permissions") {
5597
5909
  debitOutputWork();
5598
5910
  if (typeof metadataField !== "string") authorizationError("invalid document permission field");
5599
- if (value === null || typeof value !== "object" || import_node_util9.types.isProxy(value))
5911
+ if (value === null || typeof value !== "object" || import_node_util11.types.isProxy(value))
5600
5912
  authorizationError("document grants must be a plain boolean record");
5601
5913
  if (owned.has(value)) {
5602
5914
  if (Object.hasOwn(value, metadataField)) authorizationError("protected document grant key");
@@ -5623,7 +5935,7 @@ function normalizeDocumentGrants(value, metadataField = "_permissions") {
5623
5935
  return facts;
5624
5936
  }
5625
5937
  function documentGrantsFromMetadata(value, metadataField) {
5626
- if (value === null || typeof value !== "object" || import_node_util9.types.isProxy(value))
5938
+ if (value === null || typeof value !== "object" || import_node_util11.types.isProxy(value))
5627
5939
  return normalizeDocumentGrants(value, metadataField);
5628
5940
  const slots = Object.getOwnPropertyDescriptors(value);
5629
5941
  delete slots._view;
@@ -5636,7 +5948,7 @@ async function invokeDocumentPermissions(args) {
5636
5948
  try {
5637
5949
  box = await args.gate.run(() => {
5638
5950
  const value = args.invoke();
5639
- return import_node_util9.types.isPromise(value) ? Promise.prototype.then.call(value, (result2) => ({ value: result2 })) : { value };
5951
+ return import_node_util11.types.isPromise(value) ? Promise.prototype.then.call(value, (result2) => ({ value: result2 })) : { value };
5640
5952
  });
5641
5953
  } catch (error2) {
5642
5954
  if (args.preserveControlledErrors && error2 instanceof ServiceAuthorizationError) throw error2;
@@ -5821,7 +6133,7 @@ function admitDocumentStage(call, binding, input, owning, inheritedSource = fals
5821
6133
  let prepared;
5822
6134
  if (owning && inheritedSource) {
5823
6135
  const parent = stageRecord(owning.stage);
5824
- if (!input || typeof input !== "object" || import_node_util10.types.isProxy(input) || Object.getPrototypeOf(input) !== Object.prototype && Object.getPrototypeOf(input) !== null)
6136
+ if (!input || typeof input !== "object" || import_node_util12.types.isProxy(input) || Object.getPrototypeOf(input) !== Object.prototype && Object.getPrototypeOf(input) !== null)
5825
6137
  authorizationError("embedded source must be an ordinary projected document");
5826
6138
  if (parent.borrowed && !isBorrowableAuthorizationRecord(input))
5827
6139
  authorizationError("unsupported borrowed embedded source");
@@ -5936,7 +6248,7 @@ function resolveDocumentStage(stage, resolve, exposeSource = true) {
5936
6248
  source,
5937
6249
  getAuthorizationPermissions(record3.call, record3.binding)
5938
6250
  );
5939
- if (import_node_util10.types.isPromise(value)) {
6251
+ if (import_node_util12.types.isPromise(value)) {
5940
6252
  void value.then((facts) => {
5941
6253
  try {
5942
6254
  commit(facts);
@@ -6020,7 +6332,7 @@ function memoizeStageFieldDecision(stage, binding, key, evaluate) {
6020
6332
  };
6021
6333
  try {
6022
6334
  const value = evaluate.call(record3.binding.request, getAuthorizationPermissions(authorization, binding), grants);
6023
- if (import_node_util10.types.isPromise(value)) {
6335
+ if (import_node_util12.types.isPromise(value)) {
6024
6336
  const promise = pendingFieldDecision(decision);
6025
6337
  track(promise);
6026
6338
  void value.then((result2) => {
@@ -6062,19 +6374,44 @@ function copyDocumentView(value, budget = createTrustedOutputBudget()) {
6062
6374
  return materializeTrustedOutputValue(value, "", budget, { keep: () => true });
6063
6375
  }
6064
6376
  var sources = /* @__PURE__ */ new WeakMap();
6065
- var originals = /* @__PURE__ */ new WeakMap();
6066
6377
  var referenceOriginals = /* @__PURE__ */ new WeakMap();
6067
6378
  function getQueryOutputOriginal(input, call) {
6068
- return input && typeof input === "object" && call && sources.get(input)?.has(call) ? originals.get(input) ?? input : input;
6069
- }
6070
- function getQueryReferenceOriginal(input) {
6071
- return referenceOriginals.get(input);
6379
+ return input && typeof input === "object" && call ? sources.get(input)?.get(call)?.original ?? input : input;
6380
+ }
6381
+ function getQueryReferenceOriginal(input, publication) {
6382
+ const origins = referenceOriginals.get(input);
6383
+ const originals = publication ? origins?.owners.get(publication) : origins?.originals;
6384
+ return originals?.size === 1 ? originals.keys().next().value : void 0;
6385
+ }
6386
+ function retainReferenceOrigin(input, original, publication) {
6387
+ let origins = referenceOriginals.get(input);
6388
+ if (!origins) {
6389
+ origins = { owners: /* @__PURE__ */ new WeakMap(), originals: /* @__PURE__ */ new Map() };
6390
+ referenceOriginals.set(input, origins);
6391
+ }
6392
+ let owned2 = origins.owners.get(publication);
6393
+ if (!owned2) origins.owners.set(publication, owned2 = /* @__PURE__ */ new Map());
6394
+ owned2.set(original, (owned2.get(original) ?? 0) + 1);
6395
+ origins.originals.set(original, (origins.originals.get(original) ?? 0) + 1);
6396
+ }
6397
+ function releaseReferenceOrigin(input, original, publication) {
6398
+ const origins = referenceOriginals.get(input);
6399
+ const owned2 = origins.owners.get(publication);
6400
+ const release = (counts) => {
6401
+ const count = counts.get(original);
6402
+ if (count === 1) counts.delete(original);
6403
+ else counts.set(original, count - 1);
6404
+ };
6405
+ release(owned2);
6406
+ if (!owned2.size) origins.owners.delete(publication);
6407
+ release(origins.originals);
6408
+ if (!origins.originals.size) referenceOriginals.delete(input);
6072
6409
  }
6073
- function captureReferenceOrigins(original, normalized, paths, budget) {
6410
+ function captureReferenceOrigins(original, normalized, paths, budget, retain) {
6074
6411
  const storage2 = (value) => value instanceof import_mongoose6.Document ? value._doc : value;
6075
6412
  const walk = (raw, copy, parts, index, depth) => {
6076
6413
  visitTrustedOutput(budget, depth);
6077
- if (!raw || !copy || typeof raw !== "object" || typeof copy !== "object" || import_node_util10.types.isProxy(raw) || import_node_util10.types.isProxy(copy))
6414
+ if (!raw || !copy || typeof raw !== "object" || typeof copy !== "object" || import_node_util12.types.isProxy(raw) || import_node_util12.types.isProxy(copy))
6078
6415
  return;
6079
6416
  if (Array.isArray(raw) && Array.isArray(copy)) {
6080
6417
  visitTrustedOutput(budget, depth, copy.length);
@@ -6085,7 +6422,7 @@ function captureReferenceOrigins(original, normalized, paths, budget) {
6085
6422
  return;
6086
6423
  }
6087
6424
  if (index === parts.length) {
6088
- if (raw !== copy && isBorrowableAuthorizationRecord(copy)) referenceOriginals.set(copy, raw);
6425
+ if (raw !== copy && isBorrowableAuthorizationRecord(copy)) retain(copy, raw);
6089
6426
  return;
6090
6427
  }
6091
6428
  const a = Object.getOwnPropertyDescriptor(storage2(raw), parts[index]), b = Object.getOwnPropertyDescriptor(copy, parts[index]);
@@ -6097,40 +6434,49 @@ function prepareQueryOutputSource(call, binding, input) {
6097
6434
  assertAuthorizationBinding(call, binding);
6098
6435
  assertOutputPublication(outputPublicationFor(call));
6099
6436
  const existing = input && typeof input === "object" ? sources.get(input)?.get(call) : void 0;
6100
- if (existing) return existing;
6101
- if (!input || typeof input !== "object" || import_node_util10.types.isProxy(input)) authorizationError("unsupported output source");
6437
+ if (existing) return existing.prepared;
6438
+ if (!input || typeof input !== "object" || import_node_util12.types.isProxy(input)) authorizationError("unsupported output source");
6439
+ const writeOutput = isWriteOutputAuthorization(call, binding);
6440
+ const publication = outputPublicationFor(call);
6102
6441
  let raw = input;
6103
6442
  if (input instanceof import_mongoose6.Document) {
6104
6443
  try {
6105
6444
  raw = outsideOutputWorkLedger(() => input.toObject({ virtuals: false, flattenMaps: true }));
6106
6445
  } catch {
6446
+ if (writeOutput) {
6447
+ const error2 = new ServiceAuthorizationError("write output conversion failed");
6448
+ failOutputPublication(publication, error2);
6449
+ throw error2;
6450
+ }
6107
6451
  raw = input._doc;
6108
6452
  }
6109
6453
  }
6110
- const borrowed = readServiceAuthorizationMode(call, binding) === "trusted" && isBorrowableAuthorizationRecord(raw);
6111
- const publication = outputPublicationFor(call);
6112
- const source = borrowed ? raw : copyDocumentView(raw, createPublicationRowBudget(publication));
6454
+ const borrowed = readServiceAuthorizationMode(call, binding) === "trusted" && (writeOutput || isBorrowableAuthorizationRecord(raw));
6455
+ const source = writeOutput || !borrowed ? copyDocumentView(raw, createPublicationRowBudget(publication)) : raw;
6113
6456
  assertOutputPublication(outputPublicationFor(call));
6114
- if (!borrowed && (!source || typeof source !== "object" || Object.getPrototypeOf(source) !== Object.prototype && Object.getPrototypeOf(source) !== null))
6457
+ if ((writeOutput || !borrowed) && (!source || typeof source !== "object" || Object.getPrototypeOf(source) !== Object.prototype && Object.getPrototypeOf(source) !== null))
6115
6458
  authorizationError("output source must be an ordinary projected document");
6116
6459
  const prepared = { source, borrowed };
6117
6460
  let captures2 = sources.get(source);
6118
6461
  if (!captures2) sources.set(source, captures2 = /* @__PURE__ */ new WeakMap());
6119
- captures2.set(call, prepared);
6120
- if (publicationOutputLedger(publication))
6121
- retainPublicationResource(publication, () => {
6122
- captures2.delete(call);
6123
- originals.delete(source);
6124
- referenceOriginals.delete(source);
6125
- });
6462
+ captures2.set(call, { prepared, original: input });
6463
+ const references = [];
6464
+ retainPublicationResource(publication, () => {
6465
+ captures2.delete(call);
6466
+ for (const [key, original] of references) releaseReferenceOrigin(key, original, publication);
6467
+ references.length = 0;
6468
+ });
6126
6469
  if (source !== input) {
6127
- originals.set(source, input);
6128
6470
  if (!isOutputHelperAuthorization(call, binding))
6129
6471
  captureReferenceOrigins(
6130
6472
  input,
6131
6473
  source,
6132
6474
  readServiceOutputPolicy(call, binding).catalog.referencePaths ?? [],
6133
- createTrustedOutputBudget()
6475
+ createTrustedOutputBudget(),
6476
+ (key, original) => {
6477
+ retainReferenceOrigin(key, original, publication);
6478
+ references.push([key, original]);
6479
+ }
6134
6480
  );
6135
6481
  }
6136
6482
  return prepared;
@@ -6195,53 +6541,7 @@ init_concurrency();
6195
6541
 
6196
6542
  // src/acl/populate-access.ts
6197
6543
  var import_express_json_router4 = __toESM(require("@web-ts-toolkit/express-json-router"));
6198
-
6199
- // src/operation-access.ts
6200
- var OPERATION_ACCESS_VARIANTS = {
6201
- list: { basic: "basicList", advanced: "advancedList" },
6202
- read: { basic: "basicRead", advanced: "advancedRead" },
6203
- create: { basic: "basicCreate", advanced: "advancedCreate" },
6204
- update: { basic: "basicUpdate", advanced: "advancedUpdate" },
6205
- upsert: { basic: "basicUpsert", advanced: "advancedUpsert" },
6206
- count: { basic: "basicCount", advanced: "advancedCount" },
6207
- distinct: { basic: "basicDistinct", advanced: "advancedDistinct" }
6208
- };
6209
- var reservedVariantAccesses = new Set(
6210
- Object.values(OPERATION_ACCESS_VARIANTS).flatMap(({ basic, advanced }) => [basic, advanced])
6211
- );
6212
- var isRouteVariantAccess = (access) => typeof access === "string" && reservedVariantAccesses.has(access);
6213
- var isPairedRouteAccess = (access) => Object.hasOwn(OPERATION_ACCESS_VARIANTS, access);
6214
- async function resolveRouteOperationAccess({
6215
- baseAccess,
6216
- variant,
6217
- getExactOption,
6218
- isAllowedBase,
6219
- canActivate,
6220
- subdocuments = false
6221
- }) {
6222
- let access = baseAccess;
6223
- if (subdocuments) {
6224
- const keys2 = access.split(".");
6225
- const operation = keys2[2];
6226
- if (keys2.length === 3 && keys2[0] === "subs" && keys2[1] !== "" && (operation === "list" || operation === "read")) {
6227
- const field = keys2[1];
6228
- const fieldKey = `operationAccess.subs.${field}`;
6229
- const variantGuard2 = getExactOption(`${fieldKey}.${OPERATION_ACCESS_VARIANTS[operation][variant]}`);
6230
- if (variantGuard2 !== void 0) return canActivate(variantGuard2);
6231
- const baseGuard = getExactOption(`${fieldKey}.${operation}`);
6232
- if (baseGuard !== void 0) return canActivate(baseGuard);
6233
- const fieldGuard = getExactOption(fieldKey);
6234
- if (fieldGuard !== void 0) return canActivate(fieldGuard);
6235
- access = operation;
6236
- }
6237
- }
6238
- if (!isPairedRouteAccess(access)) return isAllowedBase(access);
6239
- const variantGuard = getExactOption(`operationAccess.${OPERATION_ACCESS_VARIANTS[access][variant]}`);
6240
- if (variantGuard !== void 0) return canActivate(variantGuard);
6241
- return isAllowedBase(access);
6242
- }
6243
-
6244
- // src/acl/populate-access.ts
6544
+ init_operation_access();
6245
6545
  var PopulateAccessError = class extends import_express_json_router4.default.clientErrors.BadRequestError {
6246
6546
  constructor(access) {
6247
6547
  const errors = [{ detail: `Route-only access ${access} cannot be used for populate` }];
@@ -6250,7 +6550,10 @@ var PopulateAccessError = class extends import_express_json_router4.default.clie
6250
6550
  }
6251
6551
  };
6252
6552
  function assertPopulateAccess(access) {
6253
- if (isRouteVariantAccess(access)) throw new PopulateAccessError(access);
6553
+ if (typeof access !== "string") return;
6554
+ const keys2 = access.split(".");
6555
+ if (isRemovedOperationAccess(access) || isOperationAccessMemberPath(access) || keys2[0] === "subs" && isRemovedOperationAccess(keys2[2]))
6556
+ throw new PopulateAccessError(access);
6254
6557
  }
6255
6558
 
6256
6559
  // src/services/base.ts
@@ -6260,7 +6563,7 @@ init_trusted_output_materialization();
6260
6563
  init_authorization_snapshot();
6261
6564
 
6262
6565
  // src/acl/document-guard.ts
6263
- var import_node_util11 = require("util");
6566
+ var import_node_util13 = require("util");
6264
6567
  init_authorization_snapshot();
6265
6568
  init_trusted_output_materialization();
6266
6569
  init_helpers();
@@ -6278,7 +6581,7 @@ function captureCondition(input) {
6278
6581
  const copy = (value, depth) => {
6279
6582
  visitTrustedOutput(budget, depth);
6280
6583
  if (typeof value === "string") return value;
6281
- if (!value || typeof value !== "object" || import_node_util11.types.isProxy(value) || !Array.isArray(value))
6584
+ if (!value || typeof value !== "object" || import_node_util13.types.isProxy(value) || !Array.isArray(value))
6282
6585
  authorizationError("document condition must contain only strings and arrays");
6283
6586
  if (Object.getPrototypeOf(value) !== Array.prototype || active.has(value))
6284
6587
  authorizationError("unsupported document condition array");
@@ -6333,11 +6636,47 @@ function getServiceExecutors(receiver) {
6333
6636
  return registered;
6334
6637
  }
6335
6638
  function createServiceExecution(receiver, access, authorization, applicability = "service", relatedTargets = [], parent, configuration, requestPermissions, hydration = access.operation === "list" ? "find" : "findOne", snapshotDerivation) {
6639
+ return prepareServiceExecution(
6640
+ receiver,
6641
+ access,
6642
+ authorization,
6643
+ applicability,
6644
+ relatedTargets,
6645
+ parent,
6646
+ configuration,
6647
+ requestPermissions,
6648
+ hydration,
6649
+ snapshotDerivation
6650
+ );
6651
+ }
6652
+ function createWriteServiceExecution(receiver, operation, authorization, applicability = operation === "create" ? "create" : "mutation", relatedTargets = []) {
6653
+ const branch = operation === "create" ? "create" : "update";
6654
+ return prepareServiceExecution(
6655
+ receiver,
6656
+ {
6657
+ operation,
6658
+ ...branch === "update" ? { rowAccess: "update" } : {},
6659
+ virtualAccess: branch,
6660
+ outputAccess: "read",
6661
+ docPermissionsAccess: branch
6662
+ },
6663
+ authorization,
6664
+ applicability,
6665
+ relatedTargets,
6666
+ void 0,
6667
+ void 0,
6668
+ void 0,
6669
+ "findOne",
6670
+ void 0,
6671
+ operation
6672
+ );
6673
+ }
6674
+ function prepareServiceExecution(receiver, access, authorization, applicability, relatedTargets, parent, configuration, requestPermissions, hydration, snapshotDerivation, writeOrigin) {
6336
6675
  const registered = getServiceExecutors(receiver);
6337
6676
  const receiving = registered.binding();
6338
6677
  const binding = Object.freeze({ ...receiving, scopePath: Object.freeze([...receiving.scopePath ?? []]) });
6339
6678
  const permissions = requestPermissions ?? registered.permissions();
6340
- const call = resolveServiceAuthorization({
6679
+ const input = {
6341
6680
  binding,
6342
6681
  access,
6343
6682
  authorization,
@@ -6349,7 +6688,8 @@ function createServiceExecution(receiver, access, authorization, applicability =
6349
6688
  listResponse: access.operation === "list" && parent === void 0,
6350
6689
  readResponse: access.operation === "read" && parent === void 0,
6351
6690
  snapshotDerivation
6352
- });
6691
+ };
6692
+ const call = writeOrigin ? resolveWriteServiceAuthorization(input, writeOrigin) : resolveServiceAuthorization(input);
6353
6693
  const execution = Object.freeze(/* @__PURE__ */ Object.create(null));
6354
6694
  const publication = parent && snapshotDerivation?.kind === "related" ? outputPublicationFor(parent) : createOutputPublication();
6355
6695
  bindOutputPublication(call, publication);
@@ -6364,11 +6704,26 @@ function createServiceExecution(receiver, access, authorization, applicability =
6364
6704
  access: readServiceAuthorizationAccess(call, binding),
6365
6705
  family: execution,
6366
6706
  purpose: Object.freeze({ kind: "dto" }),
6707
+ writeOrigin,
6367
6708
  hydration: resolveHydration(readServiceAuthorizationHydration(call, binding), hydration)
6368
6709
  })
6369
6710
  );
6370
6711
  return execution;
6371
6712
  }
6713
+ function deriveWriteOutputExecution(receiver, parent, branch) {
6714
+ const record3 = readServiceExecution(receiver, parent);
6715
+ if (!record3.writeOrigin || record3.purpose.kind !== "dto" || outputPublicationFor(record3.authorization) !== record3.publication)
6716
+ authorizationError("invalid write output purpose/publication");
6717
+ assertOutputPublication(record3.publication);
6718
+ const call = deriveWriteOutputAuthorization(record3.authorization, record3.binding, branch);
6719
+ bindOutputPublication(call, record3.publication);
6720
+ const execution = Object.freeze(/* @__PURE__ */ Object.create(null));
6721
+ executions.set(
6722
+ execution,
6723
+ Object.freeze({ ...record3, authorization: call, ownsPublication: false, writeOrigin: void 0 })
6724
+ );
6725
+ return execution;
6726
+ }
6372
6727
  function withExecutionDocumentCondition(receiver, parent, condition) {
6373
6728
  assertDocumentConditionReceiver(receiver);
6374
6729
  const record3 = readServiceExecution(receiver, parent);
@@ -7051,7 +7406,7 @@ init_runtime();
7051
7406
  init_runtime_context();
7052
7407
  init_populate_policy2();
7053
7408
  init_authorization_snapshot();
7054
- var import_node_util12 = require("util");
7409
+ var import_node_util14 = require("util");
7055
7410
  var cores = /* @__PURE__ */ new WeakMap();
7056
7411
  var outputHelperServices = /* @__PURE__ */ new WeakMap();
7057
7412
  function ownValue(receiver, key) {
@@ -7059,9 +7414,9 @@ function ownValue(receiver, key) {
7059
7414
  return slot && "value" in slot ? slot.value : void 0;
7060
7415
  }
7061
7416
  function assertOutputHelperCoreOwner(receiver) {
7062
- if (!receiver || import_node_util12.types.isProxy(receiver)) authorizationError("invalid output-helper Core receiver");
7417
+ if (!receiver || import_node_util14.types.isProxy(receiver)) authorizationError("invalid output-helper Core receiver");
7063
7418
  const owner = cores.get(receiver);
7064
- if (!owner || ownValue(receiver, "req") !== owner.request || ownValue(receiver, "requestRuntime") !== owner.runtime || import_node_util12.types.isProxy(owner.request) || ownValue(owner.request, "macl") !== receiver)
7419
+ if (!owner || ownValue(receiver, "req") !== owner.request || ownValue(receiver, "requestRuntime") !== owner.runtime || import_node_util14.types.isProxy(owner.request) || ownValue(owner.request, "macl") !== receiver)
7065
7420
  authorizationError("output-helper receiving request/Core/runtime mismatch");
7066
7421
  return owner;
7067
7422
  }
@@ -7069,7 +7424,7 @@ function registerOutputHelperServiceOwner(receiver, owner, modelName) {
7069
7424
  outputHelperServices.set(receiver, { ...owner, modelName, model: owner.runtime.getModelInstance(modelName) });
7070
7425
  }
7071
7426
  function assertOutputHelperServiceOwner(receiver) {
7072
- if (!receiver || import_node_util12.types.isProxy(receiver)) authorizationError("invalid output-helper service receiver");
7427
+ if (!receiver || import_node_util14.types.isProxy(receiver)) authorizationError("invalid output-helper service receiver");
7073
7428
  const owner = outputHelperServices.get(receiver);
7074
7429
  if (!owner || ownValue(receiver, "req") !== owner.request || ownValue(receiver, "requestCore") !== owner.core || ownValue(receiver, "requestRuntime") !== owner.runtime || ownValue(receiver, "modelName") !== owner.modelName)
7075
7430
  authorizationError("output-helper receiving service mismatch");
@@ -7324,10 +7679,13 @@ function castCountGroups(input, values) {
7324
7679
  init_public_admission();
7325
7680
 
7326
7681
  // src/acl/model-output-planning.ts
7682
+ init_operation_access();
7327
7683
  init_manager();
7328
7684
  init_field_catalog();
7329
7685
  init_authorization_snapshot();
7330
7686
  init_authorization_modes();
7687
+ init_document_permissions_definition();
7688
+ init_persisted_dependencies();
7331
7689
  init_virtual_populate_dependencies();
7332
7690
 
7333
7691
  // src/acl/output-helper-options.ts
@@ -7362,7 +7720,7 @@ function normalizeOutputAuthorizationOptions(input, options, purpose) {
7362
7720
  }
7363
7721
 
7364
7722
  // src/acl/output-projection.ts
7365
- var import_node_util13 = require("util");
7723
+ var import_node_util15 = require("util");
7366
7724
  init_authorization_snapshot();
7367
7725
  init_field_catalog();
7368
7726
 
@@ -7640,9 +7998,11 @@ function prepareExistingOutputShape(authorization, binding, source) {
7640
7998
 
7641
7999
  // src/acl/output-projection.ts
7642
8000
  init_virtual_populate_dependencies();
8001
+ init_document_permissions_definition();
7643
8002
 
7644
8003
  // src/acl/virtual-projection.ts
7645
8004
  var import_utils22 = require("@web-ts-toolkit/utils");
8005
+ init_document_permissions_definition();
7646
8006
  init_query();
7647
8007
  init_virtual_descriptor();
7648
8008
  init_virtual_populate_dependencies();
@@ -7652,19 +8012,6 @@ var getScopedPermissionSchema = (root, scopePath) => {
7652
8012
  const scoped = (0, import_utils22.get)(root, scopePath.join("."));
7653
8013
  return (0, import_utils22.isPlainObject)(scoped) ? scoped : null;
7654
8014
  };
7655
- var resolveAlwaysSelectForAccess = (raw, access) => {
7656
- if (!raw) return [];
7657
- if ((0, import_utils22.isArray)(raw)) return [...raw];
7658
- if ((0, import_utils22.isPlainObject)(raw)) {
7659
- const record3 = raw;
7660
- const exact = record3[access];
7661
- if ((0, import_utils22.isArray)(exact)) return [...exact];
7662
- const def = record3.default;
7663
- if ((0, import_utils22.isArray)(def)) return [...def];
7664
- return [];
7665
- }
7666
- return [];
7667
- };
7668
8015
  var stripVirtualsFromNormalizedSelect = (normalized, virtualNames) => normalized.filter((token) => {
7669
8016
  const base = token.startsWith("-") ? token.slice(1) : token;
7670
8017
  if (base.includes(".sub.")) return false;
@@ -7710,11 +8057,10 @@ function planVirtualProjection(args) {
7710
8057
  scopePath
7711
8058
  );
7712
8059
  const modelPermissionPrefix = snapshot.modelPermissionPrefix ?? "";
7713
- const rawAlways = scopePath.length > 0 ? [] : resolveAlwaysSelectForAccess(snapshot.alwaysSelectFields, outputAccess);
7714
- const alwaysStripped = stripVirtualsFromNormalizedSelect(
7715
- normalizeSelect(rawAlways),
7716
- dbVirtualPaths
7717
- ).filter((t) => !t.startsWith("-") && !t.includes(".sub."));
8060
+ const hookInputs = scopePath.length > 0 ? [] : resolveDocumentPermissionsDefinition(snapshot.docPermissions, docPermissionsAccess)?.dependsOn ?? [];
8061
+ const hookInputsStripped = stripVirtualsFromNormalizedSelect([...hookInputs], dbVirtualPaths).filter(
8062
+ (t) => !t.startsWith("-") && !t.includes(".sub.")
8063
+ );
7718
8064
  const persistedDefined = scopedPermissionSchema ? Object.keys(scopedPermissionSchema).filter((k) => !registrySet.has(k) && k !== "sub") : [];
7719
8065
  let outputPersisted;
7720
8066
  if (selectionMode === "all") {
@@ -7785,7 +8131,7 @@ function planVirtualProjection(args) {
7785
8131
  if (isPersistedFetchable(f)) fetchSet.add(f);
7786
8132
  }
7787
8133
  for (const d of depRelative) fetchSet.add(d);
7788
- for (const f of alwaysStripped) fetchSet.add(f);
8134
+ for (const f of hookInputsStripped) fetchSet.add(f);
7789
8135
  for (const f of joinFields.filter((t) => !t.startsWith("-"))) fetchSet.add(stripLeadingDash(f));
7790
8136
  for (const f of [...baseFields, ...identityFields]) {
7791
8137
  const leaf = stripLeadingDash(f);
@@ -7800,7 +8146,7 @@ function planVirtualProjection(args) {
7800
8146
  );
7801
8147
  const internalOnly = /* @__PURE__ */ new Set([
7802
8148
  ...virtualOnlyDeps,
7803
- ...alwaysStripped.filter((f) => !outputPersistedSet.has(f)),
8149
+ ...hookInputsStripped.filter((f) => !outputPersistedSet.has(f)),
7804
8150
  ...joinFields.filter((f) => !outputPersistedSet.has(stripLeadingDash(f)))
7805
8151
  ]);
7806
8152
  if (outputIdExcluded) internalOnly.add("_id");
@@ -8009,14 +8355,9 @@ function expandCatalogProjection(args, selection, safeDefinitions) {
8009
8355
  const internal = args.internalFetch ?? {};
8010
8356
  const { fetchIdRetained, outputIdExcluded } = shape;
8011
8357
  const identity = fetchIdRetained ? ["_id"] : [];
8012
- const always = scope2.length ? [] : [
8013
- .../* @__PURE__ */ new Set([
8014
- ...resolveAlwaysSelectForAccess(snapshot.alwaysSelectFields, outputAccess),
8015
- ...resolveAlwaysSelectForAccess(snapshot.alwaysSelectFields, docPermissionsAccess)
8016
- ])
8017
- ];
8358
+ const hookInputs = scope2.length ? [] : resolveDocumentPermissionsDefinition(snapshot.docPermissions, docPermissionsAccess)?.dependsOn ?? [];
8018
8359
  const joins = [...internal.joinFields ?? [], ...internal.extraPersistedFields ?? []];
8019
- const forced = [...always, ...joins, ...internal.baseFields ?? identity, ...internal.identityFields ?? []];
8360
+ const forced = [...hookInputs, ...joins, ...internal.baseFields ?? identity, ...internal.identityFields ?? []];
8020
8361
  const fetchSafe = (path) => isSafeOutputPath(path) && !virtual(full(path));
8021
8362
  const dependencies = Object.keys(depProvenance).filter(fetchSafe);
8022
8363
  const childFetch = Object.entries(children).flatMap(([name, child]) => {
@@ -8097,21 +8438,39 @@ function readCapturedAuthorizationOption(root, path, fallback) {
8097
8438
  return value === void 0 ? fallback : value;
8098
8439
  }
8099
8440
  function getCapturedAuthorizationOption(configuration, key) {
8100
- const defaultValue = key.startsWith("operationAccess.") ? readCapturedAuthorizationOption(configuration.operationAccessDefaults, key.slice("operationAccess.".length)) : void 0;
8441
+ const defaultValue = configuration.operationAccess === void 0 && key.startsWith("operationAccess.") ? readCapturedAuthorizationOption(configuration.operationAccessDefaults, key.slice("operationAccess.".length)) : void 0;
8101
8442
  return resolveNestedOption(
8102
8443
  (path, fallback) => readCapturedAuthorizationOption(configuration, path, fallback),
8103
8444
  key,
8104
8445
  defaultValue
8105
8446
  );
8106
8447
  }
8448
+ function selectCapturedOperationAccessGuard(configuration, access) {
8449
+ return selectOperationAccessGuard({
8450
+ ...createOperationAccessReaders(configuration, { operationAccess: configuration.operationAccessDefaults }),
8451
+ baseAccess: access,
8452
+ subdocuments: true
8453
+ });
8454
+ }
8107
8455
  function captureModelAuthorizationConfiguration(runtime, modelName, options, populatePolicyDefaults = capturePopulatePolicyDefaults(runtime)) {
8108
8456
  options ??= runtime.getModelOptions(modelName);
8109
8457
  assertAuthorizationModeOptions(options, true);
8110
8458
  const readAuthorizationMode = options.readAuthorizationMode ?? "isolated";
8111
8459
  const listAuthorizationMode = options.listAuthorizationMode ?? "isolated";
8460
+ const createAuthorizationMode = options.createAuthorizationMode ?? "isolated";
8461
+ const updateAuthorizationMode = options.updateAuthorizationMode ?? "isolated";
8112
8462
  const model = runtime.getModelInstance(modelName);
8113
8463
  if (!model) return authorizationError(`unknown receiving model: ${modelName}`);
8114
8464
  const virtuals = options.virtuals;
8465
+ const docPermissions = captureDocumentPermissionsDefinition(options.docPermissions, {
8466
+ storedFields: collectPersistedTopLevel(model.schema),
8467
+ virtualNames: /* @__PURE__ */ new Set([
8468
+ ...Object.keys(model.schema.virtuals ?? {}),
8469
+ ...Object.entries(virtuals ?? {}).filter(
8470
+ ([, value]) => value !== void 0 && !(value && typeof value === "object" && Object.hasOwn(value, "sub"))
8471
+ ).map(([name]) => name)
8472
+ ])
8473
+ });
8115
8474
  return captureAuthorizationConfiguration({
8116
8475
  catalog: captureAuthorizationFieldCatalog(model.schema, virtuals, options.documentPermissionField),
8117
8476
  virtualPopulateSnapshot: captureVirtualPopulateSnapshot(
@@ -8124,24 +8483,25 @@ function captureModelAuthorizationConfiguration(runtime, modelName, options, pop
8124
8483
  ...resolvePopulatePolicy(options, populatePolicyDefaults),
8125
8484
  permissionSchema: options.permissionSchema === void 0 ? runtime.getDefaultModelOption("permissionSchema") : options.permissionSchema,
8126
8485
  virtuals,
8127
- alwaysSelectFields: options.alwaysSelectFields,
8128
8486
  modelPermissionPrefix: options.modelPermissionPrefix,
8129
8487
  requireExplicitSelect: options.requireExplicitSelect,
8130
8488
  documentPermissionField: options.documentPermissionField,
8131
- docPermissions: options.docPermissions,
8489
+ docPermissions,
8132
8490
  exposedDocPermissionKeys: options.exposedDocPermissionKeys,
8133
8491
  stripPermissionsField: options.stripPermissionsField,
8134
- disableFieldPermissions: options.disableFieldPermissions,
8492
+ disableFieldPermissions: options.disableFieldPermissions ?? true,
8135
8493
  readAuthorizationMode,
8136
8494
  listAuthorizationMode,
8495
+ createAuthorizationMode,
8496
+ updateAuthorizationMode,
8137
8497
  overrideFilter: options.overrideFilter,
8138
8498
  baseFilter: options.baseFilter,
8139
8499
  idField: options.idField,
8140
8500
  resolveIdFilter: options.resolveIdFilter,
8141
8501
  operationAccess: options.operationAccess,
8142
- // A defined stored parent (including {}) wins over exact runtime defaults.
8143
- // Keep only operation fallback data; resolve each access without a live lookup.
8144
- operationAccessDefaults: options.operationAccess === void 0 ? runtime.getDefaultModelOption("operationAccess") : void 0,
8502
+ // Keep same-owner raw defaults separately for exact field specificity. The shared
8503
+ // selector decides which paths apply; a defined operation object is never deep-merged.
8504
+ operationAccessDefaults: runtime.getDefaultModelOption("operationAccess"),
8145
8505
  hydration: options.hydration,
8146
8506
  defaults: options.defaults
8147
8507
  });
@@ -8153,7 +8513,7 @@ function captureOutputHelperConfiguration(runtime, modelName) {
8153
8513
  const modelPermissionPrefix = runtime.getExactModelOption(modelName, "modelPermissionPrefix");
8154
8514
  const exposedDocPermissionKeys = runtime.getExactModelOption(modelName, "exposedDocPermissionKeys");
8155
8515
  const stripPermissionsField = runtime.getExactModelOption(modelName, "stripPermissionsField");
8156
- const disableFieldPermissions = runtime.getExactModelOption(modelName, "disableFieldPermissions");
8516
+ const disableFieldPermissions = runtime.getExactModelOption(modelName, "disableFieldPermissions") ?? true;
8157
8517
  const permissionSchema = runtime.getExactModelOption(modelName, "permissionSchema");
8158
8518
  const virtuals = runtime.getExactModelOption(modelName, "virtuals");
8159
8519
  return captureAuthorizationConfiguration({
@@ -8446,7 +8806,7 @@ function captureRelatedTargets(runtime, modelName, args = {}, depth = 0, populat
8446
8806
  kind: entry.op === "count" ? "count" : "output",
8447
8807
  configuration,
8448
8808
  queryIntent,
8449
- operationGuard: getCapturedAuthorizationOption(configuration, `operationAccess.${entry.op}`),
8809
+ operationGuard: selectCapturedOperationAccessGuard(configuration, entry.op),
8450
8810
  relatedTargets: captureRelatedTargets(
8451
8811
  runtime,
8452
8812
  entry.model,
@@ -8489,7 +8849,7 @@ function createRelatedExecution(receiver, access, parent, binding, path) {
8489
8849
 
8490
8850
  // src/core-shared.ts
8491
8851
  var import_utils23 = require("@web-ts-toolkit/utils");
8492
- var import_node_util14 = require("util");
8852
+ var import_node_util16 = require("util");
8493
8853
  init_helpers();
8494
8854
  init_options();
8495
8855
  init_runtime_context();
@@ -8548,7 +8908,7 @@ function optimizeAndFilter(clausesInput) {
8548
8908
  }
8549
8909
  let canMerge = true;
8550
8910
  for (const [key, value] of Object.entries(clause)) {
8551
- if ((0, import_utils23.hasOwn)(mergedClause, key) && !(0, import_node_util14.isDeepStrictEqual)(mergedClause[key], value)) {
8911
+ if ((0, import_utils23.hasOwn)(mergedClause, key) && !(0, import_node_util16.isDeepStrictEqual)(mergedClause[key], value)) {
8552
8912
  canMerge = false;
8553
8913
  break;
8554
8914
  }
@@ -9149,7 +9509,7 @@ var Base = class {
9149
9509
  * Fresh output-only planner: selection stays independent of additive server authority.
9150
9510
  * Returns persisted fetch inputs including private identity/dependencies, not an output
9151
9511
  * allowlist. Document-dependent rules are deferred; no permission functions/getters run.
9152
- * Configure extra projected hook inputs with alwaysSelectFields. Omitted/undefined
9512
+ * Declare private hook inputs on docPermissions descriptors' dependsOn. Omitted/undefined
9153
9513
  * options equal {} (request-mode output); positional skipChecks/subPaths are removed.
9154
9514
  */
9155
9515
  async genSelect(access, targetFields, options = {}) {
@@ -10124,7 +10484,7 @@ var Base = class {
10124
10484
 
10125
10485
  // src/services/service.ts
10126
10486
  var import_mongoose10 = require("mongoose");
10127
- var import_node_util20 = require("util");
10487
+ var import_node_util22 = require("util");
10128
10488
  var import_utils34 = require("@web-ts-toolkit/utils");
10129
10489
  var import_just_diff = require("just-diff");
10130
10490
 
@@ -10240,10 +10600,11 @@ init_helpers();
10240
10600
  init_sort_policy();
10241
10601
  init_sort_policy();
10242
10602
  init_concurrency();
10603
+ init_document_permissions_definition();
10243
10604
 
10244
10605
  // src/acl/virtual-populate-execution.ts
10245
10606
  var import_mongoose8 = require("mongoose");
10246
- var import_node_util15 = require("util");
10607
+ var import_node_util17 = require("util");
10247
10608
  var import_utils26 = require("@web-ts-toolkit/utils");
10248
10609
 
10249
10610
  // src/cache.ts
@@ -10420,11 +10781,12 @@ function equivalentVirtualPopulatePredicate(left, right) {
10420
10781
  )
10421
10782
  );
10422
10783
  }
10423
- return (0, import_node_util15.isDeepStrictEqual)(left, right);
10784
+ return (0, import_node_util17.isDeepStrictEqual)(left, right);
10424
10785
  }
10425
10786
  var readPolicy = (configuration, access) => ["operationAccess", "baseFilter", "overrideFilter"].map((key) => {
10787
+ if (key === "operationAccess") return selectCapturedOperationAccessGuard(configuration, access);
10426
10788
  const option = getCapturedAuthorizationOption(configuration, `${key}.${access}`);
10427
- return key === "operationAccess" || typeof option === "function" ? option : void 0;
10789
+ return typeof option === "function" ? option : void 0;
10428
10790
  });
10429
10791
  var compatible = (a, b) => a.binding.runtime === b.binding.runtime && a.binding.model === b.binding.model && a.binding.schema === b.binding.schema && a.access === b.access && a.requestRead === b.requestRead && a.binding.configuration.requireOperationAccessForPopulateDependencies === b.binding.configuration.requireOperationAccessForPopulateDependencies && // Different captures may share only an equivalent terminal persisted binding/policy.
10430
10792
  equivalentVirtualPopulatePredicate(
@@ -10571,7 +10933,7 @@ function targetReadAllowed(state, target) {
10571
10933
  () => evaluateRouteGuard(
10572
10934
  owner.request,
10573
10935
  owner.permissions,
10574
- getCapturedAuthorizationOption(target.configuration, "operationAccess.read")
10936
+ selectCapturedOperationAccessGuard(target.configuration, "read") ?? false
10575
10937
  )
10576
10938
  ).then(
10577
10939
  (allowed) => !!allowed,
@@ -10811,13 +11173,14 @@ async function loadVirtualPopulateOutputRows(owner, inputs, plan, publicPopulate
10811
11173
  }
10812
11174
 
10813
11175
  // src/acl/output-field-filter.ts
10814
- var import_node_util18 = require("util");
11176
+ var import_node_util20 = require("util");
10815
11177
  var import_utils28 = require("@web-ts-toolkit/utils");
10816
11178
  init_authorization_snapshot();
11179
+ init_document_permissions_definition();
10817
11180
  init_field_catalog();
10818
11181
 
10819
11182
  // src/acl/output-field-policy.ts
10820
- var import_node_util16 = require("util");
11183
+ var import_node_util18 = require("util");
10821
11184
  var import_utils27 = require("@web-ts-toolkit/utils");
10822
11185
  init_output_work_ledger();
10823
11186
  var fieldPolicies = /* @__PURE__ */ new WeakMap();
@@ -10964,7 +11327,7 @@ init_permissions_alias();
10964
11327
  init_concurrency();
10965
11328
 
10966
11329
  // src/acl/output-helper-many-admission.ts
10967
- var import_node_util17 = require("util");
11330
+ var import_node_util19 = require("util");
10968
11331
  init_authorization_snapshot();
10969
11332
  init_field_catalog();
10970
11333
  init_output_work_ledger();
@@ -10983,7 +11346,7 @@ var intrinsicObjectKeys = /* @__PURE__ */ new Set([
10983
11346
  "toLocaleString"
10984
11347
  ]);
10985
11348
  function exactRecord(value, keys2, label) {
10986
- if (!value || typeof value !== "object" || import_node_util17.types.isProxy(value)) authorizationError(`invalid ${label}`);
11349
+ if (!value || typeof value !== "object" || import_node_util19.types.isProxy(value)) authorizationError(`invalid ${label}`);
10987
11350
  const prototype = Object.getPrototypeOf(value);
10988
11351
  if (prototype !== Object.prototype && prototype !== null) authorizationError(`invalid ${label} prototype`);
10989
11352
  for (const key of keys2)
@@ -11024,7 +11387,7 @@ function exactRecord(value, keys2, label) {
11024
11387
  return value;
11025
11388
  }
11026
11389
  function denseArray(value, maximum, label) {
11027
- if (!value || typeof value !== "object" || import_node_util17.types.isProxy(value)) authorizationError(`invalid ${label}`);
11390
+ if (!value || typeof value !== "object" || import_node_util19.types.isProxy(value)) authorizationError(`invalid ${label}`);
11028
11391
  if (!Array.isArray(value) || Object.getPrototypeOf(value) !== Array.prototype)
11029
11392
  authorizationError(`${label} must be an ordinary dense Array`);
11030
11393
  const length = Object.getOwnPropertyDescriptor(value, "length").value;
@@ -11073,8 +11436,7 @@ function admitOutputHelperRows(rows2) {
11073
11436
  init_output_work_ledger();
11074
11437
  function prepareOutputDocumentStage(authorization, binding, configuration) {
11075
11438
  const access = readServiceAuthorizationAccess(authorization, binding);
11076
- const option = getCapturedAuthorizationOption(configuration, `docPermissions.${access.docPermissionsAccess}`);
11077
- const hook = typeof option === "function" ? option : void 0;
11439
+ const hook = resolveDocumentPermissionsDefinition(configuration.docPermissions, access.docPermissionsAccess)?.get;
11078
11440
  return async (args) => {
11079
11441
  if (args.authorization !== authorization) authorizationError("document resolver call mismatch");
11080
11442
  assertAuthorizationBinding(authorization, args.binding);
@@ -11254,7 +11616,7 @@ function prepareOutputValueCopy(plan) {
11254
11616
  };
11255
11617
  }
11256
11618
  function copyAuthorizedReference(value, path, construction2, prepaid = false) {
11257
- if (value && typeof value === "object" && import_node_util18.types.isProxy(value))
11619
+ if (value && typeof value === "object" && import_node_util20.types.isProxy(value))
11258
11620
  failTrustedOutputBudget(construction2.budget, new ServiceAuthorizationError("unsupported selected proxy"));
11259
11621
  if (Array.isArray(value)) {
11260
11622
  const entries = shallowTrustedOutputArray(value, construction2.budget, construction2.depth, prepaid);
@@ -11323,7 +11685,7 @@ function continueExistingOutput(value, stage, binding, owner, accept) {
11323
11685
  readDocumentStage(stage, binding);
11324
11686
  return accept(result2);
11325
11687
  };
11326
- if (!import_node_util18.types.isPromise(value)) return checked(value);
11688
+ if (!import_node_util20.types.isPromise(value)) return checked(value);
11327
11689
  readDocumentStage(stage, binding);
11328
11690
  return trackPublicationWork(
11329
11691
  owner,
@@ -11378,7 +11740,7 @@ function filterExistingOutput(source, plan, stage, construction2, owner, prepaid
11378
11740
  const one = (value2, depth) => {
11379
11741
  readDocumentStage(stage, binding);
11380
11742
  visitTrustedOutput(construction2.budget, depth, 0);
11381
- if (value2 && typeof value2 === "object" && import_node_util18.types.isProxy(value2))
11743
+ if (value2 && typeof value2 === "object" && import_node_util20.types.isProxy(value2))
11382
11744
  failTrustedOutputBudget(construction2.budget, new ServiceAuthorizationError("unsupported selected proxy"));
11383
11745
  if (Array.isArray(value2)) {
11384
11746
  const entries = shallowTrustedOutputArray(value2, construction2.budget, depth, true);
@@ -11386,7 +11748,7 @@ function filterExistingOutput(source, plan, stage, construction2, owner, prepaid
11386
11748
  const append = (start) => {
11387
11749
  for (let index = start; index < entries.length; index++) {
11388
11750
  const value3 = one(entries[index], depth + 1);
11389
- if (import_node_util18.types.isPromise(value3))
11751
+ if (import_node_util20.types.isPromise(value3))
11390
11752
  return resume(value3, (result3) => {
11391
11753
  values.push(result3 ?? null);
11392
11754
  return append(index + 1);
@@ -11481,7 +11843,7 @@ function filterExistingOutput(source, plan, stage, construction2, owner, prepaid
11481
11843
  const walk = (start) => {
11482
11844
  for (let index = start; index < selected.length; index++) {
11483
11845
  const value = fieldValue(selected[index]);
11484
- if (import_node_util18.types.isPromise(value)) return resume(value, () => walk(index + 1));
11846
+ if (import_node_util20.types.isPromise(value)) return resume(value, () => walk(index + 1));
11485
11847
  }
11486
11848
  return finish();
11487
11849
  };
@@ -11638,7 +12000,7 @@ init_public_admission();
11638
12000
  init_document();
11639
12001
 
11640
12002
  // src/output/finalize-model-output.ts
11641
- var import_node_util19 = require("util");
12003
+ var import_node_util21 = require("util");
11642
12004
  var import_utils29 = require("@web-ts-toolkit/utils");
11643
12005
  init_trusted_output_materialization();
11644
12006
  init_authorization_snapshot();
@@ -11808,7 +12170,7 @@ async function finalizeSingleDoc(args, prepared) {
11808
12170
  const one = async (value2, childDepth, childAddress, ancestors) => {
11809
12171
  assertOutputPublication(owner);
11810
12172
  visitTrustedOutput(budget, childDepth, 0);
11811
- if (value2 && typeof value2 === "object" && import_node_util19.types.isProxy(value2))
12173
+ if (value2 && typeof value2 === "object" && import_node_util21.types.isProxy(value2))
11812
12174
  failTrustedOutputBudget(budget, new ServiceAuthorizationError("unsupported selected proxy"));
11813
12175
  if (Array.isArray(value2)) {
11814
12176
  if (ancestors.has(value2))
@@ -12247,14 +12609,12 @@ async function resolveSelectForRequest({
12247
12609
  hasPermission,
12248
12610
  functionArgs = [],
12249
12611
  mode,
12250
- alwaysSelectFields = [],
12251
12612
  virtualNames = []
12252
12613
  }) {
12253
12614
  const virtualSet = virtualNames instanceof Set ? virtualNames : new Set(virtualNames ?? []);
12254
- const strippedAlways = stripVirtuals(alwaysSelectFields ?? [], virtualSet);
12255
12615
  let normalizedSelect = stripVirtuals(normalizeSelect(targetFields), virtualSet);
12256
12616
  const persistedSchema = stripVirtualKeysFromPermissionSchema(permissionSchema, virtualSet);
12257
- if (!persistedSchema) return strippedAlways;
12617
+ if (!persistedSchema) return [];
12258
12618
  let fields = await collectSchemaFields({
12259
12619
  req,
12260
12620
  permissionSchema: persistedSchema,
@@ -12274,7 +12634,7 @@ async function resolveSelectForRequest({
12274
12634
  fields = (0, import_utils31.intersection)(normalizedSelect, fields.concat(excludeid ? "-_id" : "_id"));
12275
12635
  }
12276
12636
  }
12277
- return fields.concat(strippedAlways);
12637
+ return fields;
12278
12638
  }
12279
12639
  return (0, import_utils31.intersection)(normalizedSelect, fields);
12280
12640
  }
@@ -12302,6 +12662,7 @@ function stripVirtualKeysFromPermissionSchema(permissionSchema, virtualNames) {
12302
12662
 
12303
12663
  // src/acl/model-input-admission.ts
12304
12664
  init_authorization_snapshot();
12665
+ init_document_permissions_definition();
12305
12666
  init_field_catalog();
12306
12667
  var own = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
12307
12668
  var inside = (path, root) => path === root || path.startsWith(`${root}.`);
@@ -12525,7 +12886,7 @@ async function requestInputFields(args) {
12525
12886
  }
12526
12887
  async function resolveInputDocumentGrants(args) {
12527
12888
  const { configuration } = readServiceAuthorization(args.authorization, args.binding);
12528
- const hook = getCapturedAuthorizationOption(configuration, "docPermissions.update");
12889
+ const hook = resolveDocumentPermissionsDefinition(configuration.docPermissions, "update")?.get;
12529
12890
  const access = readServiceAuthorizationAccess(args.authorization, args.binding);
12530
12891
  const context = createModelOutputContext({
12531
12892
  modelName: args.binding.modelName,
@@ -12555,10 +12916,12 @@ async function resolveInputDocumentGrants(args) {
12555
12916
  closeDocumentStage(stage, void 0, true);
12556
12917
  }
12557
12918
  }
12558
- function inputFetchPaths(catalog) {
12919
+ function inputFetchPaths(catalog, privateDependencies = []) {
12559
12920
  return [
12560
12921
  ...new Set(
12561
- (catalog.persistedPaths ?? catalog.paths).filter((p) => !p.includes("$*") && isCatalogInputPath(catalog, p))
12922
+ (catalog.persistedPaths ?? catalog.paths).filter(
12923
+ (p) => !p.includes("$*") && (isCatalogInputPath(catalog, p) || isSafeOutputPath(p) && privateDependencies.some((dep) => p === dep || p.startsWith(`${dep}.`)))
12924
+ )
12562
12925
  )
12563
12926
  ];
12564
12927
  }
@@ -12757,13 +13120,8 @@ async function subdocumentGateAllowed(service, gate) {
12757
13120
  const state = readServiceExecution(service, gate.execution);
12758
13121
  const { configuration } = readServiceAuthorization(state.authorization, state.binding);
12759
13122
  const access = state.access.rowAccess;
12760
- let guard2;
12761
- if (access.startsWith("subs.")) {
12762
- const [, sub, op] = access.split(".");
12763
- guard2 = readCapturedAuthorizationOption(configuration, `operationAccess.${access}`);
12764
- if (guard2 === void 0) guard2 = readCapturedAuthorizationOption(configuration, `operationAccess.subs.${sub}`);
12765
- if (guard2 === void 0) guard2 = getCapturedAuthorizationOption(configuration, `operationAccess.${op}`);
12766
- } else guard2 = getCapturedAuthorizationOption(configuration, `operationAccess.${access}`);
13123
+ const guard2 = selectCapturedOperationAccessGuard(configuration, access);
13124
+ if (guard2 === void 0) return false;
12767
13125
  return evaluateRouteGuard(
12768
13126
  state.binding.request,
12769
13127
  getAuthorizationPermissions(state.authorization, state.binding),
@@ -12803,6 +13161,7 @@ function subdocumentInputPolicy(service, call) {
12803
13161
  }
12804
13162
 
12805
13163
  // src/services/model-subdocument-service.ts
13164
+ init_document_permissions_definition();
12806
13165
  var denied2 = (code = "forbidden" /* Forbidden */) => ({ success: false, kind: "error", code });
12807
13166
  var invalid2 = (detail) => ({ ...denied2("bad_request" /* BadRequest */), errors: [{ detail }] });
12808
13167
  async function result(run) {
@@ -12821,16 +13180,18 @@ async function initialDenial(service, call) {
12821
13180
  if (isExecutionRowDenied(service, call.child.execution)) return denied2();
12822
13181
  if (!await initialGates(service, call)) return denied2();
12823
13182
  }
12824
- function parentSelection(service, call) {
12825
- const input = inputFetchPaths(subdocumentInputPolicy(service, call).configuration.catalog);
12826
- return [.../* @__PURE__ */ new Set(["_id", `${call.sub}._id`, ...input])].map((path) => `+${path}`).join(" ");
13183
+ function parentSelection(service, call, docPermissionsAccess) {
13184
+ const { configuration } = subdocumentInputPolicy(service, call);
13185
+ const dependencies = docPermissionsAccess ? resolveDocumentPermissionsDefinition(configuration.docPermissions, docPermissionsAccess)?.dependsOn ?? [] : [];
13186
+ const input = inputFetchPaths(configuration.catalog, dependencies);
13187
+ return [.../* @__PURE__ */ new Set(["_id", `${call.sub}._id`, ...input, ...dependencies])].map((path) => `+${path}`).join(" ");
12827
13188
  }
12828
13189
  async function mutationParent(service, id, call) {
12829
13190
  const filter2 = await subdocumentParentFilter(service, call.parent, id);
12830
13191
  if (filter2 === false) return { error: denied2("not_found" /* NotFound */) };
12831
13192
  const parent = await service.findRawParentDoc({
12832
13193
  filter: filter2,
12833
- select: parentSelection(service, call),
13194
+ select: parentSelection(service, call, ["update", "bulkUpdate"].includes(call.method) ? "update" : void 0),
12834
13195
  populate: []
12835
13196
  });
12836
13197
  return parent ? { parent } : { error: denied2("not_found" /* NotFound */) };
@@ -12882,7 +13243,7 @@ async function visibleMutationRows(service, call, parentId, rows2) {
12882
13243
  if (filter2 === false) return [];
12883
13244
  const parent = await getServiceExecutors(service).subdocumentVisibility({
12884
13245
  filter: filter2,
12885
- select: parentSelection(service, call),
13246
+ select: parentSelection(service, call, "read"),
12886
13247
  populate: []
12887
13248
  });
12888
13249
  if (!parent) return [];
@@ -12912,7 +13273,7 @@ async function listSub(service, id, sub, options) {
12912
13273
  if (childFilter === false) return denied2();
12913
13274
  const parent = await service.findRawParentDoc({
12914
13275
  filter: filter2,
12915
- select: parentSelection(service, call),
13276
+ select: parentSelection(service, call, "read"),
12916
13277
  populate: []
12917
13278
  });
12918
13279
  if (!parent) return denied2("not_found" /* NotFound */);
@@ -12935,7 +13296,7 @@ async function readSub(service, id, sub, subId, options) {
12935
13296
  const capture = subdocumentRequiresPopulateCapture(call.output, entries);
12936
13297
  const parent = await service.findRawParentDoc({
12937
13298
  filter: filter2,
12938
- select: parentSelection(service, call),
13299
+ select: parentSelection(service, call, "read"),
12939
13300
  populate: capture ? [] : entries
12940
13301
  });
12941
13302
  if (!parent) return denied2("not_found" /* NotFound */);
@@ -12989,12 +13350,12 @@ async function bulkUpdateSub(service, persist, id, sub, data, options) {
12989
13350
  const filter2 = await subdocumentRows(service, call.child, selected, selected, sub);
12990
13351
  if (filter2 === false) return denied2();
12991
13352
  const rows2 = filterCollection((0, import_utils33.get)(parent, sub), filter2);
12992
- const originals2 = rows2.map((row) => isolateDocForOutput(row));
13353
+ const originals = rows2.map((row) => isolateDocForOutput(row));
12993
13354
  const admit = await inputAdmission(service, call, parent);
12994
13355
  for (const [index, row] of rows2.entries()) {
12995
13356
  const input = findElementById(data, row._id);
12996
13357
  if (input) {
12997
- const { allowedData, allowedFields } = admit(input, originals2[index]);
13358
+ const { allowedData, allowedFields } = admit(input, originals[index]);
12998
13359
  applyUpdate(row, allowedData, allowedFields);
12999
13360
  }
13000
13361
  }
@@ -13236,7 +13597,7 @@ var Service = class extends Base {
13236
13597
  getPermissionsPosture() {
13237
13598
  return {
13238
13599
  stripPermissionsField: this.options.stripPermissionsField ?? false,
13239
- disableFieldPermissions: this.options.disableFieldPermissions ?? false
13600
+ disableFieldPermissions: this.options.disableFieldPermissions ?? true
13240
13601
  };
13241
13602
  }
13242
13603
  asServiceHookContext(context) {
@@ -13427,7 +13788,7 @@ var Service = class extends Base {
13427
13788
  };
13428
13789
  defineTrustedOutputValue(metadata, "_view", await map2("read", rowAccess.readIds?.has(id) ?? false));
13429
13790
  defineTrustedOutputValue(metadata, "_edit", await map2("update", rowAccess.updateIds?.has(id) ?? false));
13430
- } else if (!args.includePermissions) {
13791
+ } else if (!args.includePermissions && !configuration.disableFieldPermissions) {
13431
13792
  visitTrustedOutput(args.budget, metadataDepth + 1, 2);
13432
13793
  visitTrustedOutput(args.budget, metadataDepth + 2, 2);
13433
13794
  defineTrustedOutputValue(metadata, "_view", { $: "_" });
@@ -13492,13 +13853,13 @@ var Service = class extends Base {
13492
13853
  {
13493
13854
  permissionSchema: o.permissionSchema ?? null,
13494
13855
  virtuals: o.virtuals ?? null,
13495
- alwaysSelectFields: o.alwaysSelectFields ?? null,
13856
+ docPermissions: captureDocumentPermissionsDefinition(o.docPermissions),
13496
13857
  modelPermissionPrefix: o.modelPermissionPrefix ?? "",
13497
13858
  requireExplicitSelect: o.requireExplicitSelect ?? false,
13498
13859
  documentPermissionField: o.documentPermissionField ?? "_permissions",
13499
13860
  exposedDocPermissionKeys: o.exposedDocPermissionKeys,
13500
13861
  stripPermissionsField: o.stripPermissionsField ?? false,
13501
- disableFieldPermissions: o.disableFieldPermissions ?? false
13862
+ disableFieldPermissions: o.disableFieldPermissions ?? true
13502
13863
  },
13503
13864
  true
13504
13865
  );
@@ -13688,7 +14049,7 @@ var Service = class extends Base {
13688
14049
  () => evaluateRouteGuard(
13689
14050
  this.req,
13690
14051
  getAuthorizationPermissions(childState.authorization, childState.binding),
13691
- getCapturedAuthorizationOption(targetConfiguration, `operationAccess.${targetAccess}`)
14052
+ selectCapturedOperationAccessGuard(targetConfiguration, targetAccess) ?? false
13692
14053
  )
13693
14054
  ))
13694
14055
  continue;
@@ -13727,10 +14088,10 @@ var Service = class extends Base {
13727
14088
  if (value === null || value === void 0) return true;
13728
14089
  if (typeof value === "string" || typeof value === "number" || typeof value === "bigint" || typeof value === "boolean")
13729
14090
  return true;
13730
- if (import_node_util20.types.isProxy(value)) return false;
14091
+ if (import_node_util22.types.isProxy(value)) return false;
13731
14092
  let record3 = value;
13732
14093
  for (let hops = 0; record3 && hops <= 100; hops++) {
13733
- if (import_node_util20.types.isProxy(record3)) return false;
14094
+ if (import_node_util22.types.isProxy(record3)) return false;
13734
14095
  if (record3 === import_mongoose10.mongo.BSON.BSONValue.prototype) return true;
13735
14096
  const slot = Object.getOwnPropertyDescriptor(record3, "_bsontype");
13736
14097
  if (slot && "value" in slot) return typeof slot.value === "string";
@@ -13739,14 +14100,14 @@ var Service = class extends Base {
13739
14100
  return false;
13740
14101
  }
13741
14102
  /** Compose exact private source/public-fetch provenance; never IDs or DTO authority. */
13742
- populateTargetIdentity(value) {
13743
- const original = getQueryReferenceOriginal(value) ?? value;
14103
+ populateTargetIdentity(value, publication) {
14104
+ const original = getQueryReferenceOriginal(value, publication) ?? value;
13744
14105
  return getVirtualPopulatePublicIdentity(value) ?? getVirtualPopulatePublicIdentity(original) ?? original;
13745
14106
  }
13746
14107
  async finalizeSinglePopulateTarget(rawTarget, meta, parentOperation, parentContext, hookLimit, sharedGate, originalTarget = rawTarget, budget, publication, parentAuthorization, outputDepth = 1) {
13747
14108
  if (rawTarget === null || rawTarget === void 0) return rawTarget;
13748
14109
  if (this.isScalarPopulateValue(rawTarget)) return rawTarget;
13749
- const isDoc = !import_node_util20.types.isProxy(rawTarget) && ((0, import_utils34.isPlainObject)(rawTarget) || rawTarget instanceof import_mongoose10.Document);
14110
+ const isDoc = !import_node_util22.types.isProxy(rawTarget) && ((0, import_utils34.isPlainObject)(rawTarget) || rawTarget instanceof import_mongoose10.Document);
13750
14111
  if (!isDoc) failTrustedOutputBudget(budget, new ServiceAuthorizationError("unsupported populated target"));
13751
14112
  let cache = this.populateOutputCache.get(meta);
13752
14113
  if (!cache) {
@@ -13761,7 +14122,8 @@ var Service = class extends Base {
13761
14122
  });
13762
14123
  }
13763
14124
  const originalKey = originalTarget && typeof originalTarget === "object" ? originalTarget : rawTarget;
13764
- const cacheKey = this.populateTargetIdentity(rawTarget);
14125
+ const owner = publication ?? outputPublicationFor(meta.plan.authorization);
14126
+ const cacheKey = this.populateTargetIdentity(rawTarget, owner);
13765
14127
  const recipients = this.populateBudgetRecipients.get(meta)?.get(cacheKey);
13766
14128
  if (!recipients?.some((edge) => edge.budget === budget && edge.depth === outputDepth))
13767
14129
  authorizationError("populate target requires preregistered receiving occurrences");
@@ -13784,12 +14146,11 @@ var Service = class extends Base {
13784
14146
  docPermissionsAccess: meta.docPermissionsAccess,
13785
14147
  resolvedQuery: parentContext.resolvedQuery
13786
14148
  });
13787
- const owner = publication ?? outputPublicationFor(meta.plan.authorization);
13788
14149
  bindOutputPublication(meta.plan.authorization, owner);
13789
14150
  const selectedBudget = createReceivingOutputBudget(recipients);
13790
14151
  const pending = finalizeModelOutput({
13791
14152
  receivingModelName: meta.targetModelName,
13792
- input: parentAuthorization && readServiceAuthorizationMode(parentAuthorization, getServiceExecutors(this).binding()) === "isolated" && readServiceAuthorizationMode(meta.plan.authorization, meta.plan.authorizationBinding) === "trusted" ? copyDocumentView(rawTarget) : rawTarget,
14153
+ input: parentAuthorization && readServiceAuthorizationMode(parentAuthorization, getServiceExecutors(this).binding()) === "isolated" && readServiceAuthorizationMode(meta.plan.authorization, meta.plan.authorizationBinding) === "trusted" && !isWriteOutputAuthorization(meta.plan.authorization, meta.plan.authorizationBinding) ? copyDocumentView(rawTarget) : rawTarget,
13793
14154
  virtualAccess: meta.virtualAccess,
13794
14155
  outputAccess: meta.outputAccess,
13795
14156
  docPermissionsAccess: meta.docPermissionsAccess,
@@ -13801,7 +14162,7 @@ var Service = class extends Base {
13801
14162
  operation: parentContext.operation ?? parentOperation,
13802
14163
  publication: owner,
13803
14164
  outputBudget: selectedBudget,
13804
- virtualPopulateRow: getVirtualPopulateRow(originalKey) ?? getVirtualPopulateRow(getQueryReferenceOriginal(rawTarget) ?? rawTarget)
14165
+ virtualPopulateRow: getVirtualPopulateRow(originalKey) ?? getVirtualPopulateRow(getQueryReferenceOriginal(rawTarget, owner) ?? rawTarget)
13805
14166
  });
13806
14167
  cache.set(cacheKey, pending);
13807
14168
  const finalized = await pending;
@@ -13828,7 +14189,7 @@ var Service = class extends Base {
13828
14189
  for (const row of rows2) {
13829
14190
  const walk = (value, index, depth) => {
13830
14191
  visitTrustedOutput(row.budget, depth, 0);
13831
- if (value && typeof value === "object" && import_node_util20.types.isProxy(value))
14192
+ if (value && typeof value === "object" && import_node_util22.types.isProxy(value))
13832
14193
  failTrustedOutputBudget(row.budget, new ServiceAuthorizationError("unsupported selected proxy"));
13833
14194
  if (Array.isArray(value)) {
13834
14195
  const entries2 = shallowTrustedOutputArray(value, row.budget, depth);
@@ -13839,7 +14200,7 @@ var Service = class extends Base {
13839
14200
  if (!value || typeof value !== "object") return;
13840
14201
  if (index === parts.length) {
13841
14202
  if (this.isScalarPopulateValue(value)) return;
13842
- const key = this.populateTargetIdentity(value);
14203
+ const key = this.populateTargetIdentity(value, row.publication);
13843
14204
  const receivers = targets.get(key) ?? [];
13844
14205
  receivers.push({ budget: row.budget, depth });
13845
14206
  targets.set(key, receivers);
@@ -13893,7 +14254,7 @@ var Service = class extends Base {
13893
14254
  const slots = this.populateInputSlots.get(meta)?.get(current);
13894
14255
  if (!slots?.has(key)) authorizationError("unregistered populate source slot");
13895
14256
  child = slots.get(key);
13896
- originalChild = child && typeof child === "object" ? getQueryReferenceOriginal(child) ?? child : child;
14257
+ originalChild = child && typeof child === "object" ? getQueryReferenceOriginal(child, publication ?? outputPublicationFor(meta.plan.authorization)) ?? child : child;
13897
14258
  if (child === void 0 || child === null) {
13898
14259
  return;
13899
14260
  }
@@ -14495,10 +14856,7 @@ var Service = class extends Base {
14495
14856
  const normalizedRequested = normalizeSelect(_select).map((t) => t.startsWith("-") ? t.slice(1) : t);
14496
14857
  const overlapsAssociation = (path) => path === findAssociationField || path.startsWith(`${findAssociationField}.`) || findAssociationField.startsWith(`${path}.`);
14497
14858
  const isDep = Object.keys(virtualPlan.depProvenance).some(overlapsAssociation);
14498
- const isHookInput = [
14499
- ...resolveAlwaysSelectForAccess(virtualSnapshot.alwaysSelectFields, virtualPlan.outputAccess),
14500
- ...resolveAlwaysSelectForAccess(virtualSnapshot.alwaysSelectFields, virtualPlan.docPermissionsAccess)
14501
- ].some(overlapsAssociation);
14859
+ const isHookInput = (resolveDocumentPermissionsDefinition(virtualSnapshot.docPermissions, virtualPlan.docPermissionsAccess)?.dependsOn ?? []).some(overlapsAssociation);
14502
14860
  const isSelected = normalizedRequested.includes(findAssociationField);
14503
14861
  if (!isDep && !isHookInput && !isSelected) {
14504
14862
  privateAssociationField = findAssociationField;
@@ -14589,13 +14947,7 @@ var Service = class extends Base {
14589
14947
  const intent = captureModelServiceIntent(this, "create", args, options);
14590
14948
  const execution = withExecutionQueryIntent(
14591
14949
  this,
14592
- createServiceExecution(
14593
- this,
14594
- { operation: "create", virtualAccess: "create", outputAccess: "read", docPermissionsAccess: "create" },
14595
- options?.authorization,
14596
- "create",
14597
- this.captureRelated(intent.args)
14598
- ),
14950
+ createWriteServiceExecution(this, "create", options?.authorization, "create", this.captureRelated(intent.args)),
14599
14951
  intent
14600
14952
  );
14601
14953
  return await executeCreate(this, execution, data, args, options, decorate);
@@ -14613,7 +14965,9 @@ var Service = class extends Base {
14613
14965
  const { populate, select } = intent.args;
14614
14966
  const { includePermissions, includeFieldPermissions, populateAccess } = intent.options;
14615
14967
  const initiatingOperation = state.access.operation;
14616
- const createPlan = this.executionOutputPlan(execution, select);
14968
+ const outputExecution = deriveWriteOutputExecution(this, execution, "create");
14969
+ const outputState = readServiceExecution(this, outputExecution);
14970
+ const createPlan = this.executionOutputPlan(outputExecution, select);
14617
14971
  const isArr = Array.isArray(data);
14618
14972
  let dataArr = isArr ? data : [data];
14619
14973
  const { maxBulkItems, maxBulkConcurrency } = this.getRequestComplexity();
@@ -14659,7 +15013,7 @@ var Service = class extends Base {
14659
15013
  }
14660
15014
  let resolvedPopulate;
14661
15015
  try {
14662
- resolvedPopulate = populate ? await this.genExecutionPopulate(execution, populateAccess, populate) : [];
15016
+ resolvedPopulate = populate ? await this.genExecutionPopulate(outputExecution, populateAccess, populate) : [];
14663
15017
  } catch (error2) {
14664
15018
  const result2 = this.getClientRequestErrorResult(error2);
14665
15019
  if (result2) return result2;
@@ -14737,8 +15091,8 @@ var Service = class extends Base {
14737
15091
  contexts[index].finalDocumentSnapshot = doc.toObject({ virtuals: false });
14738
15092
  return doc;
14739
15093
  });
14740
- const detached = await this.prepareDetachedOutputRows(execution, persistedDocs, createPlan, resolvedPopulate);
14741
- const outputRows2 = this.admitOutputRows(execution, detached);
15094
+ const detached = await this.prepareDetachedOutputRows(outputExecution, persistedDocs, createPlan, resolvedPopulate);
15095
+ const outputRows2 = this.admitOutputRows(outputExecution, detached);
14742
15096
  this.registerPopulateRecipients(outputRows2, resolvedPopulate);
14743
15097
  const docs = await mapWithConcurrencyLimit(
14744
15098
  outputRows2,
@@ -14753,7 +15107,7 @@ var Service = class extends Base {
14753
15107
  initiatingOperation,
14754
15108
  hookLimit,
14755
15109
  createGate,
14756
- state.authorization,
15110
+ outputState.authorization,
14757
15111
  row.references,
14758
15112
  row.budget,
14759
15113
  row.publication
@@ -14871,15 +15225,9 @@ var Service = class extends Base {
14871
15225
  const intent = captureModelServiceIntent(this, "updateOne", args, options);
14872
15226
  const execution = withExecutionQueryIntent(
14873
15227
  this,
14874
- createServiceExecution(
15228
+ createWriteServiceExecution(
14875
15229
  this,
14876
- {
14877
- operation: "update",
14878
- rowAccess: "update",
14879
- virtualAccess: "update",
14880
- outputAccess: "read",
14881
- docPermissionsAccess: "update"
14882
- },
15230
+ "update",
14883
15231
  options?.authorization,
14884
15232
  "mutation",
14885
15233
  this.captureRelated(intent.args)
@@ -14903,11 +15251,13 @@ var Service = class extends Base {
14903
15251
  const { populate, select } = intent.args;
14904
15252
  const { includePermissions, includeFieldPermissions, populateAccess } = intent.options;
14905
15253
  const initiatingOperation = state.access.operation;
14906
- const updatePlan = this.executionOutputPlan(execution, select);
15254
+ const outputExecution = deriveWriteOutputExecution(this, execution, "update");
15255
+ const outputState = readServiceExecution(this, outputExecution);
15256
+ const updatePlan = this.executionOutputPlan(outputExecution, select);
14907
15257
  const _filter = filter2;
14908
15258
  let _populate;
14909
15259
  try {
14910
- _populate = await this.genExecutionPopulate(execution, populateAccess, populate);
15260
+ _populate = await this.genExecutionPopulate(outputExecution, populateAccess, populate);
14911
15261
  } catch (error2) {
14912
15262
  const result2 = this.getClientRequestErrorResult(error2);
14913
15263
  if (result2) return result2;
@@ -14921,11 +15271,13 @@ var Service = class extends Base {
14921
15271
  this.completeOp("updateOne", startedAt, "forbidden" /* Forbidden */, _filter);
14922
15272
  return { success: false, kind: "error", code: "forbidden" /* Forbidden */, query };
14923
15273
  }
15274
+ const hookInputs = resolveDocumentPermissionsDefinition(captured.configuration.docPermissions, updatePlan.docPermissionsAccess)?.dependsOn ?? [];
14924
15275
  let doc = await this.model.findOne({
14925
15276
  filter: _filter,
14926
- select: (0, import_utils34.uniq)([...updatePlan.persistedFetchSelection, ...inputFetchPaths(captured.configuration.catalog)]).map(
14927
- (path) => `+${path}`
14928
- )
15277
+ select: (0, import_utils34.uniq)([
15278
+ ...updatePlan.persistedFetchSelection,
15279
+ ...inputFetchPaths(captured.configuration.catalog, hookInputs)
15280
+ ]).map((path) => `+${path}`)
14929
15281
  });
14930
15282
  if (!doc) {
14931
15283
  this.completeOp("updateOne", startedAt, "not_found" /* NotFound */, _filter);
@@ -14997,8 +15349,8 @@ var Service = class extends Base {
14997
15349
  context.finalDocumentSnapshot = doc.toObject({ virtuals: false });
14998
15350
  this.asServiceHookContext(context).diff(doc);
14999
15351
  await this.changes(doc.toObject({ virtuals: false }), context);
15000
- const [detached] = await this.prepareDetachedOutputRows(execution, [doc], updatePlan, _populate);
15001
- const [row] = this.admitOutputRows(execution, [detached]);
15352
+ const [detached] = await this.prepareDetachedOutputRows(outputExecution, [doc], updatePlan, _populate);
15353
+ const [row] = this.admitOutputRows(outputExecution, [detached]);
15002
15354
  this.registerPopulateRecipients([row], _populate);
15003
15355
  if (_populate) {
15004
15356
  const updateHookLimit = this.getVirtualHookConcurrencyLimit();
@@ -15010,7 +15362,7 @@ var Service = class extends Base {
15010
15362
  initiatingOperation,
15011
15363
  updateHookLimit,
15012
15364
  updateGate,
15013
- state.authorization,
15365
+ outputState.authorization,
15014
15366
  row.references,
15015
15367
  row.budget,
15016
15368
  row.publication
@@ -15046,15 +15398,9 @@ var Service = class extends Base {
15046
15398
  const { skim, includePermissions, includeFieldPermissions, populateAccess } = intent.options;
15047
15399
  const execution = withExecutionQueryIntent(
15048
15400
  this,
15049
- createServiceExecution(
15401
+ createWriteServiceExecution(
15050
15402
  this,
15051
- {
15052
- operation: "update",
15053
- rowAccess: "update",
15054
- virtualAccess: "update",
15055
- outputAccess: "read",
15056
- docPermissionsAccess: "update"
15057
- },
15403
+ "update",
15058
15404
  options?.authorization,
15059
15405
  "mutation",
15060
15406
  this.captureRelated(intent.args)
@@ -15094,19 +15440,7 @@ var Service = class extends Base {
15094
15440
  );
15095
15441
  const execution = withExecutionQueryIntent(
15096
15442
  this,
15097
- createServiceExecution(
15098
- this,
15099
- {
15100
- operation: "upsert",
15101
- rowAccess: "update",
15102
- virtualAccess: "update",
15103
- outputAccess: "read",
15104
- docPermissionsAccess: "update"
15105
- },
15106
- options?.authorization,
15107
- "mutation",
15108
- related
15109
- ),
15443
+ createWriteServiceExecution(this, "upsert", options?.authorization, "mutation", related),
15110
15444
  updateIntent
15111
15445
  );
15112
15446
  const { populate, select } = updateIntent.args;
@@ -16006,15 +16340,9 @@ var PublicService = class extends Service {
16006
16340
  const intent = upsertId ? captureModelServiceIntent(this, "updateOne", { ...updateArgs, select: effectiveSelect }, updateOptions) : captureModelServiceIntent(this, "create", createArgs, createOptions);
16007
16341
  const execution = withExecutionQueryIntent(
16008
16342
  this,
16009
- createServiceExecution(
16343
+ createWriteServiceExecution(
16010
16344
  this,
16011
- {
16012
- operation: "upsert",
16013
- rowAccess: "update",
16014
- virtualAccess: "update",
16015
- outputAccess: "read",
16016
- docPermissionsAccess: "update"
16017
- },
16345
+ "upsert",
16018
16346
  requestOnlyServiceOptions({}).authorization,
16019
16347
  "service",
16020
16348
  this.captureRelated(intent.args)
@@ -16104,7 +16432,7 @@ var PublicService = class extends Service {
16104
16432
  captureListFallbackAdmission(execution) {
16105
16433
  const { authorization, binding } = readServiceExecution(this, execution);
16106
16434
  const { configuration } = readServiceAuthorization(authorization, binding);
16107
- const guard2 = getCapturedAuthorizationOption(configuration, "operationAccess.list");
16435
+ const guard2 = selectCapturedOperationAccessGuard(configuration, "list");
16108
16436
  const permissions = getAuthorizationPermissions(authorization, binding);
16109
16437
  return () => getRequestWorkState(this.req, this.requestRuntime).hookGate.run(
16110
16438
  () => withCapturedModelOperationGuard(
@@ -16449,11 +16777,11 @@ function resolveLeafParents(obj, src) {
16449
16777
  });
16450
16778
  return pairs;
16451
16779
  }
16452
- var copyAndDepopulate = (docObject, operations, options = { mutable: true, idField: "_id" }) => {
16780
+ var copyAndDepopulate = (docObject, operations2, options = { mutable: true, idField: "_id" }) => {
16453
16781
  const mutable = options.mutable !== false;
16454
16782
  const idField = options.idField ?? "_id";
16455
16783
  const obj = mutable ? docObject : cloneProcessorValue(docObject);
16456
- (0, import_utils37.forEach)(Array.isArray(operations) ? operations : [], (op) => {
16784
+ (0, import_utils37.forEach)(Array.isArray(operations2) ? operations2 : [], (op) => {
16457
16785
  if (!op || typeof op.src !== "string" || typeof op.dest !== "string") return;
16458
16786
  const src = op.src;
16459
16787
  const dest = op.dest;
@@ -16512,10 +16840,10 @@ var copyAndDepopulate = (docObject, operations, options = { mutable: true, idFie
16512
16840
  });
16513
16841
  return obj;
16514
16842
  };
16515
- var copyPaths = (docObject, operations, options = { mutable: true }) => {
16843
+ var copyPaths = (docObject, operations2, options = { mutable: true }) => {
16516
16844
  const mutable = options.mutable !== false;
16517
16845
  const obj = mutable ? docObject : cloneProcessorValue(docObject);
16518
- (0, import_utils37.forEach)(Array.isArray(operations) ? operations : [], (op) => {
16846
+ (0, import_utils37.forEach)(Array.isArray(operations2) ? operations2 : [], (op) => {
16519
16847
  if (!op || typeof op.src !== "string" || typeof op.dest !== "string") return;
16520
16848
  const src = op.src;
16521
16849
  const dest = op.dest;
@@ -16530,10 +16858,10 @@ var copyPaths = (docObject, operations, options = { mutable: true }) => {
16530
16858
  });
16531
16859
  return obj;
16532
16860
  };
16533
- var movePaths = (docObject, operations, options = { mutable: true }) => {
16861
+ var movePaths = (docObject, operations2, options = { mutable: true }) => {
16534
16862
  const mutable = options.mutable !== false;
16535
16863
  const obj = mutable ? docObject : cloneProcessorValue(docObject);
16536
- (0, import_utils37.forEach)(Array.isArray(operations) ? operations : [], (op) => {
16864
+ (0, import_utils37.forEach)(Array.isArray(operations2) ? operations2 : [], (op) => {
16537
16865
  if (!op || typeof op.src !== "string" || typeof op.dest !== "string") return;
16538
16866
  const src = op.src;
16539
16867
  const dest = op.dest;
@@ -16551,12 +16879,12 @@ var movePaths = (docObject, operations, options = { mutable: true }) => {
16551
16879
  });
16552
16880
  return obj;
16553
16881
  };
16554
- var sliceArrays = (docObject, operations, options = { mutable: true, maxSlice: DEFAULT_MAX_SLICE }) => {
16882
+ var sliceArrays = (docObject, operations2, options = { mutable: true, maxSlice: DEFAULT_MAX_SLICE }) => {
16555
16883
  const mutable = options.mutable !== false;
16556
16884
  const maxSlice = options.maxSlice ?? DEFAULT_MAX_SLICE;
16557
16885
  assertNonNegativeSafeInteger(maxSlice, "maxSlice", "sliceArrays");
16558
16886
  const obj = mutable ? docObject : cloneProcessorValue(docObject);
16559
- (0, import_utils37.forEach)(Array.isArray(operations) ? operations : [], (op) => {
16887
+ (0, import_utils37.forEach)(Array.isArray(operations2) ? operations2 : [], (op) => {
16560
16888
  if (!op || typeof op.src !== "string") return;
16561
16889
  const src = op.src;
16562
16890
  if (src.length === 0) return;
@@ -16587,10 +16915,10 @@ var sliceArrays = (docObject, operations, options = { mutable: true, maxSlice: D
16587
16915
  });
16588
16916
  return obj;
16589
16917
  };
16590
- var countPaths = (docObject, operations, options = { mutable: true }) => {
16918
+ var countPaths = (docObject, operations2, options = { mutable: true }) => {
16591
16919
  const mutable = options.mutable !== false;
16592
16920
  const obj = mutable ? docObject : cloneProcessorValue(docObject);
16593
- (0, import_utils37.forEach)(Array.isArray(operations) ? operations : [], (op) => {
16921
+ (0, import_utils37.forEach)(Array.isArray(operations2) ? operations2 : [], (op) => {
16594
16922
  if (!op || typeof op.src !== "string" || typeof op.dest !== "string") return;
16595
16923
  const src = op.src;
16596
16924
  const dest = op.dest;
@@ -16615,10 +16943,10 @@ var countPaths = (docObject, operations, options = { mutable: true }) => {
16615
16943
  });
16616
16944
  return obj;
16617
16945
  };
16618
- var maskPaths = (docObject, operations, options = { mutable: true }) => {
16946
+ var maskPaths = (docObject, operations2, options = { mutable: true }) => {
16619
16947
  const mutable = options.mutable !== false;
16620
16948
  const obj = mutable ? docObject : cloneProcessorValue(docObject);
16621
- (0, import_utils37.forEach)(Array.isArray(operations) ? operations : [], (op) => {
16949
+ (0, import_utils37.forEach)(Array.isArray(operations2) ? operations2 : [], (op) => {
16622
16950
  if (!op || typeof op.src !== "string") return;
16623
16951
  const src = op.src;
16624
16952
  if (src.length === 0) return;
@@ -16670,6 +16998,8 @@ async function initializeAclRequest({
16670
16998
  // src/core.ts
16671
16999
  init_runtime();
16672
17000
  init_runtime_context();
17001
+ init_operation_access();
17002
+ init_document_permissions_definition();
16673
17003
  init_authorization_snapshot();
16674
17004
  init_document();
16675
17005
  var emptyPermissionLeaf = () => ({ $: "_" });
@@ -16884,7 +17214,7 @@ var Core = class {
16884
17214
  this,
16885
17215
  refModelName,
16886
17216
  populateAccess,
16887
- getCapturedAuthorizationOption(targetConfiguration, `operationAccess.${populateAccess}`),
17217
+ selectCapturedOperationAccessGuard(targetConfiguration, populateAccess),
16888
17218
  permissions,
16889
17219
  () => this.isAllowed(refModelName, populateAccess)
16890
17220
  )) {
@@ -16896,13 +17226,10 @@ var Core = class {
16896
17226
  populateAccess,
16897
17227
  ret.select
16898
17228
  );
16899
- const hookInputs = resolveAlwaysSelectForAccess(
16900
- targetConfiguration.alwaysSelectFields,
16901
- populateAccess
16902
- );
17229
+ const hookInputs = resolveDocumentPermissionsDefinition(targetConfiguration.docPermissions, populateAccess)?.dependsOn ?? [];
16903
17230
  ret.select = (0, import_utils38.uniq)([
16904
17231
  ...ret.select,
16905
- ...stripVirtuals(hookInputs, [...targetConfiguration.catalog.virtualPaths ?? []])
17232
+ ...stripVirtuals([...hookInputs], [...targetConfiguration.catalog.virtualPaths ?? []])
16906
17233
  ]);
16907
17234
  const match = (0, import_utils38.isString)(p) ? {} : p.match ?? {};
16908
17235
  const filter2 = await resolveAccessFilterForRequest({
@@ -17019,7 +17346,7 @@ var Core = class {
17019
17346
  /** Explicit fresh hook-to-boolean-facts utility, not document/output/row authority. */
17020
17347
  async genDocPermissions(modelName, doc, access, context) {
17021
17348
  const configuration = captureModelAuthorizationConfiguration(this.requestRuntime, modelName);
17022
- const hook = getCapturedAuthorizationOption(configuration, `docPermissions.${access}`);
17349
+ const hook = resolveDocumentPermissionsDefinition(configuration.docPermissions, access)?.get;
17023
17350
  const permissions = this.getGlobalPermissions();
17024
17351
  const diagnostic = createModelOutputContext({
17025
17352
  modelName,
@@ -17215,33 +17542,21 @@ var Core = class {
17215
17542
  async isAllowed(modelName, access) {
17216
17543
  const captured = consumeCapturedModelOperationGuard(this, modelName, access);
17217
17544
  if (captured) return evaluateRouteGuard(this.req, captured.permissions, captured.guard);
17218
- if (access.startsWith("subs")) {
17219
- const keys2 = access.split(".");
17220
- if (keys2.length < 3) {
17221
- return false;
17222
- }
17223
- const [, field, op] = keys2;
17224
- const subOption = getExactModelOption(modelName, `operationAccess.${access}`);
17225
- if ((0, import_utils38.isUndefined)(subOption)) {
17226
- const subFieldOption = getExactModelOption(modelName, `operationAccess.subs.${field}`);
17227
- if ((0, import_utils38.isUndefined)(subFieldOption)) {
17228
- const opOption = getModelOption(modelName, `operationAccess.${op}`);
17229
- return this.canActivate(opOption);
17230
- }
17231
- return this.canActivate(subFieldOption);
17232
- }
17233
- return this.canActivate(subOption);
17234
- }
17235
- const operationAccess = getModelOption(modelName, `operationAccess.${access}`);
17236
- return this.canActivate(operationAccess);
17545
+ return this.resolveOperationAccess(modelName, access);
17237
17546
  }
17238
- /** Authorize route entry using explicit server-owned basic/advanced metadata. */
17239
- async isAllowedRoute(modelName, baseAccess, variant) {
17547
+ /** Authorize entry using explicit server-owned basic/advanced/root metadata. */
17548
+ async isAllowedRoute(modelName, baseAccess, context) {
17549
+ return this.resolveOperationAccess(modelName, baseAccess, context);
17550
+ }
17551
+ /** Fresh live reads; omitted context is a base check, never an ambient entry context. */
17552
+ async resolveOperationAccess(modelName, baseAccess, context) {
17240
17553
  return resolveRouteOperationAccess({
17241
17554
  baseAccess,
17242
- variant,
17243
- getExactOption: (key) => getExactModelOption(modelName, key),
17244
- isAllowedBase: (access) => this.isAllowed(modelName, access),
17555
+ context,
17556
+ ...createOperationAccessReaders(
17557
+ this.requestRuntime.getModelOptions(modelName),
17558
+ this.requestRuntime.getDefaultModelOptions()
17559
+ ),
17245
17560
  canActivate: (guard2) => this.canActivate(guard2),
17246
17561
  subdocuments: true
17247
17562
  });
@@ -17334,6 +17649,7 @@ var import_express2 = __toESM(require("express"));
17334
17649
  // src/routers/model-router.ts
17335
17650
  var import_express_json_router8 = __toESM(require("@web-ts-toolkit/express-json-router"));
17336
17651
  var import_utils43 = require("@web-ts-toolkit/utils");
17652
+ init_operation_access();
17337
17653
  init_logger_helpers();
17338
17654
  init_runtime();
17339
17655
  init_runtime_context();
@@ -18821,7 +19137,7 @@ function setModelCollectionRoutes(context) {
18821
19137
  body: defineOpenApiSchemaResolver(getAdvancedCreateOpenApiBody)
18822
19138
  });
18823
19139
  router.get("/new", async (req) => {
18824
- await context.assertAllowed(req, "new");
19140
+ await context.assertAllowed(req, "new", "basic");
18825
19141
  const svc = context.getPublicService(req);
18826
19142
  const result2 = await svc._new({}, { includePermissions: false, includeFieldPermissions: false });
18827
19143
  handleResultError(result2);
@@ -19155,7 +19471,7 @@ function setModelDocumentRoutes(context) {
19155
19471
  body: defineOpenApiSchemaResolver(getAdvancedUpsertOpenApiBody)
19156
19472
  });
19157
19473
  router.delete(`/:${options.idParam}`, async (req) => {
19158
- await context.assertAllowed(req, "delete");
19474
+ await context.assertAllowed(req, "delete", "basic");
19159
19475
  const id = parsePathParam(req.params[options.idParam], options.idParam);
19160
19476
  const svc = context.getPublicService(req);
19161
19477
  const result2 = await svc._delete(id);
@@ -19252,7 +19568,7 @@ function setModelSubDocumentRoutes(context) {
19252
19568
  body: defineOpenApiSchemaResolver(() => context.getRequestSchema("requestSchemas.subList") ?? subListBodySchema)
19253
19569
  });
19254
19570
  context.router.patch(`/:${context.options.idParam}/${sub}`, async (req) => {
19255
- await context.assertAllowed(req, `subs.${sub}.update`);
19571
+ await context.assertAllowed(req, `subs.${sub}.update`, "basic");
19256
19572
  const id = parsePathParam(req.params[context.options.idParam], context.options.idParam);
19257
19573
  const data = await parseBodyWithSchema(
19258
19574
  subMutationBodySchema,
@@ -19316,7 +19632,7 @@ function setModelSubDocumentRoutes(context) {
19316
19632
  body: defineOpenApiSchemaResolver(() => context.getRequestSchema("requestSchemas.subRead") ?? subReadBodySchema)
19317
19633
  });
19318
19634
  context.router.patch(`/:${context.options.idParam}/${sub}/:subId`, async (req) => {
19319
- await context.assertAllowed(req, `subs.${sub}.update`);
19635
+ await context.assertAllowed(req, `subs.${sub}.update`, "basic");
19320
19636
  const id = parsePathParam(req.params[context.options.idParam], context.options.idParam);
19321
19637
  const subId = parsePathParam(req.params.subId, "subId");
19322
19638
  const data = await parseBodyWithSchema(
@@ -19339,7 +19655,7 @@ function setModelSubDocumentRoutes(context) {
19339
19655
  )
19340
19656
  });
19341
19657
  context.router.post(`/:${context.options.idParam}/${sub}`, async (req) => {
19342
- await context.assertAllowed(req, `subs.${sub}.create`);
19658
+ await context.assertAllowed(req, `subs.${sub}.create`, "basic");
19343
19659
  const id = parsePathParam(req.params[context.options.idParam], context.options.idParam);
19344
19660
  const data = await parseBodyWithSchema(
19345
19661
  subMutationBodySchema,
@@ -19361,7 +19677,7 @@ function setModelSubDocumentRoutes(context) {
19361
19677
  )
19362
19678
  });
19363
19679
  context.router.delete(`/:${context.options.idParam}/${sub}/:subId`, async (req) => {
19364
- await context.assertAllowed(req, `subs.${sub}.delete`);
19680
+ await context.assertAllowed(req, `subs.${sub}.delete`, "basic");
19365
19681
  const id = parsePathParam(req.params[context.options.idParam], context.options.idParam);
19366
19682
  const subId = parsePathParam(req.params.subId, "subId");
19367
19683
  const svc = context.getPublicService(req);
@@ -19478,22 +19794,39 @@ var ModelRouter = class _ModelRouter {
19478
19794
  */
19479
19795
  this.documentPermissionField = setOption.bind(this, "documentPermissionField");
19480
19796
  /**
19481
- * The model fields always selected for ACL and response shaping.
19482
- */
19483
- this.alwaysSelectFields = setOption.bind(this, "alwaysSelectFields");
19484
- /**
19485
- * The function called in the process of generating document permissions.
19797
+ * Configure a callable/descriptor directly, or replace one exact/default/custom
19798
+ * access definition. Descriptor dependsOn adds private persisted inputs, not output grants.
19799
+ * An undefined access restores default fallback; pass undefined alone to clear the option.
19486
19800
  */
19487
- this.docPermissions = setOption.bind(this, "docPermissions");
19801
+ this.docPermissions = (...args) => {
19802
+ const key = args.length === 2 ? `docPermissions.${args[0]}` : "docPermissions";
19803
+ const value = args.length === 2 ? args[1] : args[0];
19804
+ assertMutableRouterOption("model", key);
19805
+ this.runtime.setModelOption(
19806
+ this.modelName,
19807
+ key,
19808
+ value
19809
+ );
19810
+ return this;
19811
+ };
19488
19812
  /**
19489
- * Configure live base and basic/advanced route guards. Only undefined inherits;
19813
+ * Configure live scalar/default and independent basic/advanced/root entry guards. Only undefined inherits;
19490
19814
  * selected false denies with HTTP 401 without removing routes or OpenAPI entries.
19491
- * `operationAccess('basicRead', false)` updates one key, and
19492
- * `operationAccess('subs.comments.basicRead', false)` updates a field-specific key.
19815
+ * `operationAccess('read.basic', false)` updates one member, and
19816
+ * `operationAccess('subs.comments.read.basic', false)` updates a field-specific member.
19493
19817
  * `operationAccess({ list: true, read: true })` replaces the whole rule object,
19494
- * not a deep merge. Use setOption with undefined to restore variant inheritance.
19818
+ * not a deep merge. Two-argument member setters accept undefined to restore fallback.
19819
+ * Updating beneath a scalar starts an object; retain the old guard in operation.default.
19495
19820
  */
19496
- this.operationAccess = setOption.bind(this, "operationAccess");
19821
+ this.operationAccess = (...args) => {
19822
+ const key = args.length === 2 ? `operationAccess.${args[0]}` : "operationAccess";
19823
+ this.runtime.setModelOption(
19824
+ this.modelName,
19825
+ key,
19826
+ args.length === 2 ? args[1] : args[0]
19827
+ );
19828
+ return this;
19829
+ };
19497
19830
  /**
19498
19831
  * The base filter definitions applied in every query transaction.
19499
19832
  * @operation `list`, `read`, `update`, `delete`
@@ -19605,6 +19938,7 @@ var ModelRouter = class _ModelRouter {
19605
19938
  }
19606
19939
  static fromModel(model, initialOptions, runtime = defaultRuntime) {
19607
19940
  assertAuthorizationModeOptions(initialOptions, true);
19941
+ assertOperationAccessOptions(initialOptions);
19608
19942
  assertNoServerModelControls(
19609
19943
  initialOptions,
19610
19944
  (detail) => {
@@ -19640,7 +19974,7 @@ var ModelRouter = class _ModelRouter {
19640
19974
  const operation = baseAccess.split(".").at(-1);
19641
19975
  const businessBody = variant !== "advanced" && ["create", "update", "upsert"].includes(operation);
19642
19976
  assertPublicAdmission(req.body, businessBody ? "data" : "envelope");
19643
- const allowed = variant === void 0 ? await req.macl.isAllowed(this.modelName, baseAccess) : await req.macl.isAllowedRoute(this.modelName, baseAccess, variant);
19977
+ const allowed = await req.macl.isAllowedRoute(this.modelName, baseAccess, variant);
19644
19978
  if (!allowed) throw new clientErrors2.UnauthorizedError();
19645
19979
  }
19646
19980
  registerOpenApiRoute(route) {
@@ -19717,7 +20051,7 @@ var ModelRouter = class _ModelRouter {
19717
20051
  }
19718
20052
  return this;
19719
20053
  }
19720
- /** Set one live option/path; `setOption('operationAccess.basicRead', undefined)` restores inheritance. */
20054
+ /** Set one live option/path; `setOption('operationAccess.read.basic', undefined)` restores fallback. */
19721
20055
  setOption(key, option) {
19722
20056
  assertMutableRouterOption("model", key);
19723
20057
  this.runtime.setModelOption(this.modelName, key, option);
@@ -19742,6 +20076,7 @@ var import_utils44 = require("@web-ts-toolkit/utils");
19742
20076
  init_options();
19743
20077
  init_runtime();
19744
20078
  init_runtime_context();
20079
+ init_operation_access();
19745
20080
  var DataCore = class {
19746
20081
  constructor(req) {
19747
20082
  this.requestRuntime = getActiveRuntime() ?? defaultRuntime;
@@ -19869,16 +20204,18 @@ var DataCore = class {
19869
20204
  return evaluateRouteGuard(this.req, this.getGlobalPermissions(), routeGuard);
19870
20205
  }
19871
20206
  async isAllowed(dataName, access) {
19872
- const operationAccess = getDataOption(dataName, `operationAccess.${access}`);
19873
- return this.canActivate(operationAccess);
20207
+ return this.resolveOperationAccess(dataName, access);
19874
20208
  }
19875
- /** Authorize route entry using explicit server-owned basic/advanced metadata. */
19876
- async isAllowedRoute(dataName, baseAccess, variant) {
20209
+ /** Authorize entry using explicit server-owned basic/advanced/root metadata. */
20210
+ async isAllowedRoute(dataName, baseAccess, context) {
20211
+ return this.resolveOperationAccess(dataName, baseAccess, context);
20212
+ }
20213
+ /** Data policy has no model-default reader; base calls never select entry members. */
20214
+ async resolveOperationAccess(dataName, baseAccess, context) {
19877
20215
  return resolveRouteOperationAccess({
19878
20216
  baseAccess,
19879
- variant,
19880
- getExactOption: (key) => getExactDataOption(dataName, key),
19881
- isAllowedBase: (access) => this.isAllowed(dataName, access),
20217
+ context,
20218
+ ...createOperationAccessReaders(this.requestRuntime.getDataOptions(dataName)),
19882
20219
  canActivate: (guard2) => this.canActivate(guard2)
19883
20220
  });
19884
20221
  }
@@ -20065,22 +20402,22 @@ var RootRouter = class {
20065
20402
  }
20066
20403
  async isAllowed(req, item) {
20067
20404
  if (item.target === "data") {
20068
- return req.dacl.isAllowed(item.name, item.op);
20405
+ return req.dacl.isAllowedRoute(item.name, item.op, "root");
20069
20406
  }
20070
20407
  switch (item.op) {
20071
20408
  case "subList":
20072
- return req.macl.isAllowed(item.name, `subs.${item.sub}.list`);
20409
+ return req.macl.isAllowedRoute(item.name, `subs.${item.sub}.list`, "root");
20073
20410
  case "subRead":
20074
- return req.macl.isAllowed(item.name, `subs.${item.sub}.read`);
20411
+ return req.macl.isAllowedRoute(item.name, `subs.${item.sub}.read`, "root");
20075
20412
  case "subCreate":
20076
- return req.macl.isAllowed(item.name, `subs.${item.sub}.create`);
20413
+ return req.macl.isAllowedRoute(item.name, `subs.${item.sub}.create`, "root");
20077
20414
  case "subUpdate":
20078
20415
  case "subBulkUpdate":
20079
- return req.macl.isAllowed(item.name, `subs.${item.sub}.update`);
20416
+ return req.macl.isAllowedRoute(item.name, `subs.${item.sub}.update`, "root");
20080
20417
  case "subDelete":
20081
- return req.macl.isAllowed(item.name, `subs.${item.sub}.delete`);
20418
+ return req.macl.isAllowedRoute(item.name, `subs.${item.sub}.delete`, "root");
20082
20419
  default:
20083
- return req.macl.isAllowed(item.name, item.op);
20420
+ return req.macl.isAllowedRoute(item.name, item.op, "root");
20084
20421
  }
20085
20422
  }
20086
20423
  async processOp(req, item, index) {
@@ -20268,13 +20605,22 @@ var DataRouter = class {
20268
20605
  /** Base-operation field grants; basic/advanced route guards belong to operationAccess. */
20269
20606
  this.permissionSchema = setOption2.bind(this, "permissionSchema");
20270
20607
  /**
20271
- * Live list/read guards plus basicList/advancedList/basicRead/advancedRead.
20272
- * `operationAccess('basicRead', false)` updates one key and denies GET /:id
20273
- * (and HEAD) with HTTP 401; registered POST reads still inherit `read`.
20608
+ * Live scalar/default and independent basic/advanced/root list/read entry guards.
20609
+ * `operationAccess('read.basic', false)` updates one member and denies GET /:id
20610
+ * (and HEAD) with HTTP 401; registered POST reads use read.advanced then read.default.
20274
20611
  * `operationAccess({ list: true, read: true })` replaces the whole rule object,
20275
- * not a deep merge. Use setOption with undefined to restore variant inheritance.
20612
+ * not a deep merge. Two-argument member setters accept undefined to restore fallback.
20613
+ * Data never inherits model defaults; updating beneath a scalar starts an object.
20276
20614
  */
20277
- this.operationAccess = setOption2.bind(this, "operationAccess");
20615
+ this.operationAccess = (...args) => {
20616
+ const key = args.length === 2 ? `operationAccess.${args[0]}` : "operationAccess";
20617
+ this.runtime.setDataOption(
20618
+ this.dataName,
20619
+ key,
20620
+ args.length === 2 ? args[1] : args[0]
20621
+ );
20622
+ return this;
20623
+ };
20278
20624
  this.baseFilter = setOption2.bind(
20279
20625
  this,
20280
20626
  "baseFilter"
@@ -20471,7 +20817,7 @@ var DataRouter = class {
20471
20817
  }
20472
20818
  return this;
20473
20819
  }
20474
- /** Set one live option/path; `setOption('operationAccess.basicRead', undefined)` restores inheritance. */
20820
+ /** Set one live option/path; `setOption('operationAccess.read.basic', undefined)` restores fallback. */
20475
20821
  setOption(key, option) {
20476
20822
  assertMutableRouterOption("data", key);
20477
20823
  this.runtime.setDataOption(this.dataName, key, option);