@memberjunction/ai-agents 6.2.1 → 6.2.2
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/dist/PayloadManager.d.ts +46 -0
- package/dist/PayloadManager.d.ts.map +1 -1
- package/dist/PayloadManager.js +298 -67
- package/dist/PayloadManager.js.map +1 -1
- package/dist/agent-types/base-agent-type.d.ts.map +1 -1
- package/dist/agent-types/base-agent-type.js +8 -1
- package/dist/agent-types/base-agent-type.js.map +1 -1
- package/dist/base-agent.d.ts +73 -10
- package/dist/base-agent.d.ts.map +1 -1
- package/dist/base-agent.js +197 -34
- package/dist/base-agent.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/native-tools/agent-tool-circuit-breaker.d.ts +44 -0
- package/dist/native-tools/agent-tool-circuit-breaker.d.ts.map +1 -0
- package/dist/native-tools/agent-tool-circuit-breaker.js +71 -0
- package/dist/native-tools/agent-tool-circuit-breaker.js.map +1 -0
- package/dist/native-tools/agent-tools.d.ts +7 -0
- package/dist/native-tools/agent-tools.d.ts.map +1 -1
- package/dist/native-tools/agent-tools.js.map +1 -1
- package/dist/payload-path-keys.d.ts +54 -0
- package/dist/payload-path-keys.d.ts.map +1 -0
- package/dist/payload-path-keys.js +126 -0
- package/dist/payload-path-keys.js.map +1 -0
- package/dist/unsafe-object-keys.d.ts +20 -0
- package/dist/unsafe-object-keys.d.ts.map +1 -0
- package/dist/unsafe-object-keys.js +42 -0
- package/dist/unsafe-object-keys.js.map +1 -0
- package/package.json +20 -20
package/dist/PayloadManager.js
CHANGED
|
@@ -36,6 +36,16 @@ import { DeepDiffer } from '@memberjunction/global';
|
|
|
36
36
|
import _ from 'lodash';
|
|
37
37
|
import { PayloadChangeAnalyzer } from './PayloadChangeAnalyzer.js';
|
|
38
38
|
import { ParsePathWithOperations, isOperationAllowed } from './types/payload-operations.js';
|
|
39
|
+
import { IsUnsafeObjectKey, StripUnsafeObjectKeys } from './unsafe-object-keys.js';
|
|
40
|
+
import { BuildNestedValue, FormatPayloadPath, IsPathKey, ParsePathKey, ResolvePayloadPath } from './payload-path-keys.js';
|
|
41
|
+
const CHANGE_BUCKETS = ['updateElements', 'newElements', 'removeElements', 'replaceElements'];
|
|
42
|
+
/** The operation each bucket performs, used when a path key in it is refused. */
|
|
43
|
+
const BUCKET_OPERATION = {
|
|
44
|
+
updateElements: 'update',
|
|
45
|
+
newElements: 'add',
|
|
46
|
+
removeElements: 'delete',
|
|
47
|
+
replaceElements: 'update'
|
|
48
|
+
};
|
|
39
49
|
/**
|
|
40
50
|
* Manages payload access control for agent hierarchies.
|
|
41
51
|
*
|
|
@@ -715,26 +725,23 @@ export class PayloadManager {
|
|
|
715
725
|
if (compiled) {
|
|
716
726
|
return compiled;
|
|
717
727
|
}
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
+
// Paths are checked in dot form (`items.0.price`), so `items[*]` / `items[0]` become `items.*` / `items.0`.
|
|
729
|
+
const pattern = pathPattern.replace(/\[(\*|\d+)\]/g, '.$1');
|
|
730
|
+
const toSegmentRegex = (part) => part
|
|
731
|
+
.replace(/\\/g, '\\\\')
|
|
732
|
+
.replace(/\./g, '\\.')
|
|
733
|
+
.replace(/\*/g, '[^.]+');
|
|
734
|
+
if (pattern.includes('**')) {
|
|
735
|
+
// `**` spans any number of segments; it is split out first so the single-`*` rule can't rewrite it
|
|
736
|
+
compiled = new RegExp(`^${pattern.split('**').map(toSegmentRegex).join('.*')}$`);
|
|
737
|
+
}
|
|
738
|
+
else if (pattern.endsWith('.*')) {
|
|
739
|
+
const basePath = pattern.slice(0, -2);
|
|
728
740
|
const escapedBase = basePath.replace(/\\/g, '\\\\').replace(/\./g, '\\.');
|
|
729
741
|
compiled = new RegExp(`^${escapedBase}(\\..*)?$`);
|
|
730
742
|
}
|
|
731
743
|
else {
|
|
732
|
-
|
|
733
|
-
.replace(/\\/g, '\\\\')
|
|
734
|
-
.replace(/\./g, '\\.')
|
|
735
|
-
.replace(/\*/g, '[^.]+')
|
|
736
|
-
.replace(/\[(\*|\d+)\]/g, '\\[(\\*|\\d+)\\]');
|
|
737
|
-
compiled = new RegExp(`^${regexStr}$`);
|
|
744
|
+
compiled = new RegExp(`^${toSegmentRegex(pattern)}$`);
|
|
738
745
|
}
|
|
739
746
|
this._pathPatternRegexCache.set(pathPattern, compiled);
|
|
740
747
|
return compiled;
|
|
@@ -870,6 +877,8 @@ export class PayloadManager {
|
|
|
870
877
|
const srcObj = source;
|
|
871
878
|
const result = {};
|
|
872
879
|
for (const key of Object.keys(destObj)) {
|
|
880
|
+
if (IsUnsafeObjectKey(key))
|
|
881
|
+
continue;
|
|
873
882
|
if (!Object.prototype.hasOwnProperty.call(srcObj, key)) {
|
|
874
883
|
result[key] = this.fastCloneDeep(destObj[key]);
|
|
875
884
|
}
|
|
@@ -878,6 +887,8 @@ export class PayloadManager {
|
|
|
878
887
|
}
|
|
879
888
|
}
|
|
880
889
|
for (const key of Object.keys(srcObj)) {
|
|
890
|
+
if (IsUnsafeObjectKey(key))
|
|
891
|
+
continue;
|
|
881
892
|
const srcVal = srcObj[key];
|
|
882
893
|
const destVal = destObj[key];
|
|
883
894
|
// Only plain objects merge key by key. A Date or class instance has no own keys to merge,
|
|
@@ -926,6 +937,9 @@ export class PayloadManager {
|
|
|
926
937
|
const keys = Object.keys(value);
|
|
927
938
|
for (let i = 0; i < keys.length; i++) {
|
|
928
939
|
const k = keys[i];
|
|
940
|
+
// Assigning `__proto__` on the copy would replace its prototype instead of copying data.
|
|
941
|
+
if (IsUnsafeObjectKey(k))
|
|
942
|
+
continue;
|
|
929
943
|
const val = value[k];
|
|
930
944
|
copy[k] = (val !== null && typeof val === 'object') ? this.fastCloneDeep(val) : val;
|
|
931
945
|
}
|
|
@@ -957,6 +971,154 @@ export class PayloadManager {
|
|
|
957
971
|
}
|
|
958
972
|
return false;
|
|
959
973
|
}
|
|
974
|
+
/**
|
|
975
|
+
* Resolves path keys at the top of each bucket (`"meta.title"`, `"dependencies[2].code"`), so a
|
|
976
|
+
* change can name one nested field without restating the objects and arrays around it.
|
|
977
|
+
*
|
|
978
|
+
* - A key the payload already holds as a literal property name is left as it is.
|
|
979
|
+
* - Path keys in updateElements, newElements and removeElements become the nested form the merge
|
|
980
|
+
* already handles. A newElements path that already holds a value is treated as an update.
|
|
981
|
+
* - Path keys in replaceElements are set at their exact location after the rest of the change,
|
|
982
|
+
* because the nested form would replace the whole top-level property.
|
|
983
|
+
* - A path that can't be written (index out of range, a step through a string) is refused as a
|
|
984
|
+
* blocked operation with a warning. It is never written as a literal key.
|
|
985
|
+
*/
|
|
986
|
+
normalizePathKeys(changeRequest, originalPayload, warnings, blockedOperations) {
|
|
987
|
+
const root = this.isPlainObject(originalPayload) ? originalPayload : {};
|
|
988
|
+
const replacements = [];
|
|
989
|
+
if (!CHANGE_BUCKETS.some(bucket => this.bucketHasPathKeys(changeRequest[bucket], root))) {
|
|
990
|
+
return { Request: changeRequest, Replacements: replacements };
|
|
991
|
+
}
|
|
992
|
+
const request = { ...changeRequest };
|
|
993
|
+
const expansions = [];
|
|
994
|
+
for (const bucket of CHANGE_BUCKETS) {
|
|
995
|
+
const source = changeRequest[bucket];
|
|
996
|
+
if (!this.isPlainObject(source) || !this.bucketHasPathKeys(source, root))
|
|
997
|
+
continue;
|
|
998
|
+
const kept = {};
|
|
999
|
+
for (const [key, value] of Object.entries(source)) {
|
|
1000
|
+
if (IsPathKey(key) && !(key in root)) {
|
|
1001
|
+
this.routePathKey({ Bucket: bucket, Key: key, Value: value, Root: root, Expansions: expansions, Replacements: replacements, Warnings: warnings, BlockedOperations: blockedOperations });
|
|
1002
|
+
}
|
|
1003
|
+
else {
|
|
1004
|
+
kept[key] = value;
|
|
1005
|
+
}
|
|
1006
|
+
}
|
|
1007
|
+
request[bucket] = kept;
|
|
1008
|
+
}
|
|
1009
|
+
for (const expansion of expansions) {
|
|
1010
|
+
this.mergePathExpansion(request, expansion);
|
|
1011
|
+
}
|
|
1012
|
+
return { Request: request, Replacements: replacements };
|
|
1013
|
+
}
|
|
1014
|
+
/** True when a bucket has a top-level path key that is not a literal property of the payload. */
|
|
1015
|
+
bucketHasPathKeys(bucket, root) {
|
|
1016
|
+
if (!this.isPlainObject(bucket))
|
|
1017
|
+
return false;
|
|
1018
|
+
return Object.keys(bucket).some(key => IsPathKey(key) && !(key in root));
|
|
1019
|
+
}
|
|
1020
|
+
/** Checks one path key against the payload and sends it to the bucket that will apply it. */
|
|
1021
|
+
routePathKey(route) {
|
|
1022
|
+
const segments = ParsePathKey(route.Key);
|
|
1023
|
+
// A path segment named like a prototype key would walk into Object.prototype when the
|
|
1024
|
+
// change is applied, the same hole StripUnsafeObjectKeys closes for whole keys.
|
|
1025
|
+
const unsafe = segments?.find(segment => typeof segment === 'string' && IsUnsafeObjectKey(segment));
|
|
1026
|
+
if (unsafe !== undefined) {
|
|
1027
|
+
this.refusePathKey(route, `Cannot apply '${route.Key}' in ${route.Bucket}: '${unsafe}' is not a data key`);
|
|
1028
|
+
return;
|
|
1029
|
+
}
|
|
1030
|
+
const resolved = segments ? ResolvePayloadPath(route.Root, segments) : null;
|
|
1031
|
+
if (!resolved || resolved.Error) {
|
|
1032
|
+
const reason = resolved?.Error ?? 'the path is malformed';
|
|
1033
|
+
this.refusePathKey(route, `Cannot apply '${route.Key}' in ${route.Bucket}: ${reason}`);
|
|
1034
|
+
return;
|
|
1035
|
+
}
|
|
1036
|
+
switch (route.Bucket) {
|
|
1037
|
+
case 'replaceElements':
|
|
1038
|
+
route.Replacements.push({ Key: route.Key, Segments: resolved.Segments, Value: route.Value });
|
|
1039
|
+
return;
|
|
1040
|
+
case 'removeElements':
|
|
1041
|
+
if (!resolved.Exists) {
|
|
1042
|
+
route.Warnings.push(`Nothing to remove at '${route.Key}': the payload has no value there`);
|
|
1043
|
+
return;
|
|
1044
|
+
}
|
|
1045
|
+
break;
|
|
1046
|
+
case 'newElements':
|
|
1047
|
+
if (resolved.Exists) {
|
|
1048
|
+
route.Warnings.push(`Auto-corrected: '${route.Key}' was in newElements but already exists (treated as update)`);
|
|
1049
|
+
route.Expansions.push({ Bucket: 'updateElements', Segments: resolved.Segments, Value: route.Value });
|
|
1050
|
+
return;
|
|
1051
|
+
}
|
|
1052
|
+
break;
|
|
1053
|
+
}
|
|
1054
|
+
route.Expansions.push({ Bucket: route.Bucket, Segments: resolved.Segments, Value: route.Value });
|
|
1055
|
+
}
|
|
1056
|
+
/** Records a path key that can't be applied, so the caller sees a refusal, not a silent no-op. */
|
|
1057
|
+
refusePathKey(route, message) {
|
|
1058
|
+
route.Warnings.push(message);
|
|
1059
|
+
route.BlockedOperations.push({
|
|
1060
|
+
path: route.Key,
|
|
1061
|
+
operation: BUCKET_OPERATION[route.Bucket],
|
|
1062
|
+
to: route.Value,
|
|
1063
|
+
reason: message,
|
|
1064
|
+
timestamp: new Date().toISOString()
|
|
1065
|
+
});
|
|
1066
|
+
}
|
|
1067
|
+
/**
|
|
1068
|
+
* Merges one resolved path into its bucket as nested objects and sparse arrays. A top-level
|
|
1069
|
+
* property the bucket already had is copied before the merge, so the caller's request is not
|
|
1070
|
+
* changed.
|
|
1071
|
+
*/
|
|
1072
|
+
mergePathExpansion(request, expansion) {
|
|
1073
|
+
const existing = request[expansion.Bucket];
|
|
1074
|
+
const bucket = this.isPlainObject(existing) ? existing : {};
|
|
1075
|
+
const rootKey = String(expansion.Segments[0]);
|
|
1076
|
+
if (rootKey in bucket) {
|
|
1077
|
+
bucket[rootKey] = this.fastCloneDeep(bucket[rootKey]);
|
|
1078
|
+
}
|
|
1079
|
+
_.merge(bucket, BuildNestedValue(expansion.Segments, expansion.Value));
|
|
1080
|
+
request[expansion.Bucket] = bucket;
|
|
1081
|
+
}
|
|
1082
|
+
/**
|
|
1083
|
+
* Sets each replaceElements path key at its exact location in `result`, after the rest of the
|
|
1084
|
+
* change is applied. Missing parent objects are created. Each write is checked against
|
|
1085
|
+
* `allowedPaths` as an add (nothing there yet) or an update.
|
|
1086
|
+
*/
|
|
1087
|
+
applyPathReplacements(result, replacements, counts, warnings, allowedPaths, blockedOperations) {
|
|
1088
|
+
for (const replacement of replacements) {
|
|
1089
|
+
const resolved = ResolvePayloadPath(result, replacement.Segments);
|
|
1090
|
+
if (resolved.Error) {
|
|
1091
|
+
const message = `Cannot apply '${replacement.Key}' in replaceElements: ${resolved.Error}`;
|
|
1092
|
+
warnings.push(message);
|
|
1093
|
+
blockedOperations.push({ path: replacement.Key, operation: 'update', to: replacement.Value, reason: message, timestamp: new Date().toISOString() });
|
|
1094
|
+
continue;
|
|
1095
|
+
}
|
|
1096
|
+
const operation = resolved.Exists ? 'update' : 'add';
|
|
1097
|
+
const permissionPath = replacement.Segments.join('.');
|
|
1098
|
+
if (allowedPaths && !this.isOperationAllowedForPath(permissionPath, operation, allowedPaths)) {
|
|
1099
|
+
const message = `Operation denied: Cannot replace '${FormatPayloadPath(replacement.Segments)}' - operation '${operation}' not allowed`;
|
|
1100
|
+
warnings.push(message);
|
|
1101
|
+
blockedOperations.push({ path: permissionPath, operation, to: replacement.Value, reason: `operation '${operation}' not allowed`, timestamp: new Date().toISOString() });
|
|
1102
|
+
continue;
|
|
1103
|
+
}
|
|
1104
|
+
this.setAtPath(result, replacement.Segments, replacement.Value);
|
|
1105
|
+
if (resolved.Exists)
|
|
1106
|
+
counts.deletions++;
|
|
1107
|
+
counts.additions++;
|
|
1108
|
+
}
|
|
1109
|
+
}
|
|
1110
|
+
/** Writes `value` at `segments`, creating missing parent objects. The path must already resolve. */
|
|
1111
|
+
setAtPath(root, segments, value) {
|
|
1112
|
+
let node = root;
|
|
1113
|
+
for (let i = 0; i < segments.length - 1; i++) {
|
|
1114
|
+
const segment = segments[i];
|
|
1115
|
+
if (node[segment] === undefined) {
|
|
1116
|
+
node[segment] = {};
|
|
1117
|
+
}
|
|
1118
|
+
node = node[segment];
|
|
1119
|
+
}
|
|
1120
|
+
node[segments[segments.length - 1]] = value;
|
|
1121
|
+
}
|
|
960
1122
|
/**
|
|
961
1123
|
* Applies an AgentPayloadChangeRequest to a payload
|
|
962
1124
|
*
|
|
@@ -968,6 +1130,11 @@ export class PayloadManager {
|
|
|
968
1130
|
ApplyAgentChangeRequest(originalPayload, changeRequest, options) {
|
|
969
1131
|
const warnings = [];
|
|
970
1132
|
const blockedOperations = [];
|
|
1133
|
+
// The change request is model-written JSON. A `__proto__` key in it would lead the key walk
|
|
1134
|
+
// below into Object.prototype and write there, so those keys are dropped before anything runs.
|
|
1135
|
+
for (const removedPath of StripUnsafeObjectKeys(changeRequest)) {
|
|
1136
|
+
warnings.push(`Ignored unsafe key '${removedPath}' in payloadChangeRequest`);
|
|
1137
|
+
}
|
|
971
1138
|
// Auto-correct stray keys in the changeRequest unless ignoreStrayKeys is true.
|
|
972
1139
|
// LLMs sometimes place payload properties (e.g. changeRequest, dataRequirements) as
|
|
973
1140
|
// siblings of updateElements/newElements instead of inside them. This detects those
|
|
@@ -975,14 +1142,18 @@ export class PayloadManager {
|
|
|
975
1142
|
if (!options?.ignoreStrayKeys) {
|
|
976
1143
|
this.autoCorrectStrayKeys(changeRequest, originalPayload, warnings, options?.agentName, options?.allowedPaths);
|
|
977
1144
|
}
|
|
1145
|
+
// Resolve path keys ("meta.title", "dependencies[2].code") into nested form. The caller's
|
|
1146
|
+
// request is left as it was; `request` is a copy whenever anything had to change.
|
|
1147
|
+
const { Request: request, Replacements: replacements } = this.normalizePathKeys(changeRequest, originalPayload, warnings, blockedOperations);
|
|
978
1148
|
const result = this.fastCloneDeep(originalPayload) || {};
|
|
979
1149
|
const counts = { additions: 0, updates: 0, deletions: 0 };
|
|
980
|
-
const requestHasDottedKeys = this.hasDottedKeys(
|
|
981
|
-
this.hasDottedKeys(
|
|
982
|
-
this.hasDottedKeys(
|
|
983
|
-
this.hasDottedKeys(
|
|
1150
|
+
const requestHasDottedKeys = this.hasDottedKeys(request.newElements) ||
|
|
1151
|
+
this.hasDottedKeys(request.updateElements) ||
|
|
1152
|
+
this.hasDottedKeys(request.removeElements) ||
|
|
1153
|
+
this.hasDottedKeys(request.replaceElements);
|
|
984
1154
|
// Process all changes recursively
|
|
985
|
-
this.processChangeRequest(result, originalPayload,
|
|
1155
|
+
this.processChangeRequest(result, originalPayload, request, [], counts, warnings, options?.allowedPaths, blockedOperations, requestHasDottedKeys);
|
|
1156
|
+
this.applyPathReplacements(result, replacements, counts, warnings, options?.allowedPaths, blockedOperations);
|
|
986
1157
|
// Log if requested and in verbose mode
|
|
987
1158
|
if (options?.logChanges && options?.verbose) {
|
|
988
1159
|
this.logChangesSummary(counts, changeRequest.reasoning, options.agentName);
|
|
@@ -990,7 +1161,7 @@ export class PayloadManager {
|
|
|
990
1161
|
// Analyze changes if requested
|
|
991
1162
|
let analysis;
|
|
992
1163
|
if (options?.analyzeChanges !== false) { // Default to true
|
|
993
|
-
analysis = this._defaultAnalyzer.AnalyzeChangeRequest(originalPayload,
|
|
1164
|
+
analysis = this._defaultAnalyzer.AnalyzeChangeRequest(originalPayload, request, result);
|
|
994
1165
|
// Add analysis warnings to the main warnings array
|
|
995
1166
|
if (analysis.warnings.length > 0) {
|
|
996
1167
|
warnings.push(...analysis.warnings.map(w => `[${w.severity}] ${w.message}`));
|
|
@@ -1019,12 +1190,12 @@ export class PayloadManager {
|
|
|
1019
1190
|
/**
|
|
1020
1191
|
* Process a change request recursively through the payload structure
|
|
1021
1192
|
*/
|
|
1022
|
-
processChangeRequest(target, original, changeRequest, path, counts, warnings, allowedPaths, blockedOperations, requestHasDottedKeys = false) {
|
|
1193
|
+
processChangeRequest(target, original, changeRequest, path, counts, warnings, allowedPaths, blockedOperations, requestHasDottedKeys = false, basePath = []) {
|
|
1023
1194
|
if (Array.isArray(target)) {
|
|
1024
|
-
this.processArrayChanges(target, original, changeRequest, path, counts, warnings, allowedPaths, blockedOperations, requestHasDottedKeys);
|
|
1195
|
+
this.processArrayChanges(target, original, changeRequest, path, counts, warnings, allowedPaths, blockedOperations, requestHasDottedKeys, basePath);
|
|
1025
1196
|
}
|
|
1026
1197
|
else if (typeof target === 'object' && target !== null) {
|
|
1027
|
-
this.processObjectChanges(target, original, changeRequest, path, counts, warnings, allowedPaths, blockedOperations, requestHasDottedKeys);
|
|
1198
|
+
this.processObjectChanges(target, original, changeRequest, path, counts, warnings, allowedPaths, blockedOperations, requestHasDottedKeys, basePath);
|
|
1028
1199
|
}
|
|
1029
1200
|
}
|
|
1030
1201
|
/**
|
|
@@ -1125,7 +1296,7 @@ export class PayloadManager {
|
|
|
1125
1296
|
*
|
|
1126
1297
|
* Arrays of primitives still use replacement behavior for backwards compatibility.
|
|
1127
1298
|
*/
|
|
1128
|
-
processArrayChanges(target, original, changeRequest, path, counts, warnings, allowedPaths, blockedOperations, requestHasDottedKeys = false) {
|
|
1299
|
+
processArrayChanges(target, original, changeRequest, path, counts, warnings, allowedPaths, blockedOperations, requestHasDottedKeys = false, basePath = []) {
|
|
1129
1300
|
const pathStr = path.join('.');
|
|
1130
1301
|
// Get change arrays for this path
|
|
1131
1302
|
const removeArray = pathStr ? _.get(changeRequest.removeElements, pathStr) : changeRequest.removeElements;
|
|
@@ -1134,16 +1305,21 @@ export class PayloadManager {
|
|
|
1134
1305
|
const replaceArray = pathStr ? _.get(changeRequest.replaceElements, pathStr) : changeRequest.replaceElements;
|
|
1135
1306
|
// Build a new array with all changes applied
|
|
1136
1307
|
const newTargetArray = [];
|
|
1308
|
+
const arrayPath = [...basePath, ...path].join('.');
|
|
1309
|
+
const blocked = { warnings, blockedOperations };
|
|
1137
1310
|
// Process existing elements
|
|
1138
1311
|
for (let i = 0; i < target.length; i++) {
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1312
|
+
// __DELETE__ may come from removeElements or, forgivingly, from updateElements
|
|
1313
|
+
const deleteRequested = (removeArray && removeArray[i] === '__DELETE__') ||
|
|
1314
|
+
(updateArray && updateArray[i] === '__DELETE__');
|
|
1315
|
+
if (deleteRequested) {
|
|
1316
|
+
if (this.isArrayElementOperationAllowed(arrayPath, i, 'delete', allowedPaths)) {
|
|
1317
|
+
counts.deletions++;
|
|
1318
|
+
continue; // Skip deleted items
|
|
1319
|
+
}
|
|
1320
|
+
this.recordBlockedOperation(blocked, `${arrayPath}.${i}`, 'delete', target[i], undefined);
|
|
1321
|
+
newTargetArray.push(target[i]); // A refused delete keeps the element unchanged
|
|
1322
|
+
continue;
|
|
1147
1323
|
}
|
|
1148
1324
|
// Use updated value if provided, otherwise keep original
|
|
1149
1325
|
let elementToAdd = target[i];
|
|
@@ -1158,13 +1334,17 @@ export class PayloadManager {
|
|
|
1158
1334
|
updateElements: updateArray[i]
|
|
1159
1335
|
};
|
|
1160
1336
|
this.processChangeRequest(elementToAdd, original ? original[i] : undefined, elementChangeRequest, [], // Empty path since updateArray[i] is already at the element level
|
|
1161
|
-
counts, warnings, allowedPaths, blockedOperations, requestHasDottedKeys)
|
|
1337
|
+
counts, warnings, allowedPaths, blockedOperations, requestHasDottedKeys, [...basePath, ...path, i.toString()] // ...so permissions see the element's full path
|
|
1338
|
+
);
|
|
1162
1339
|
}
|
|
1163
|
-
else {
|
|
1340
|
+
else if (this.isArrayElementOperationAllowed(arrayPath, i, 'update', allowedPaths)) {
|
|
1164
1341
|
// For primitives or arrays, replace entirely (existing behavior)
|
|
1165
1342
|
elementToAdd = updateArray[i];
|
|
1166
1343
|
counts.updates++;
|
|
1167
1344
|
}
|
|
1345
|
+
else {
|
|
1346
|
+
this.recordBlockedOperation(blocked, `${arrayPath}.${i}`, 'update', elementToAdd, updateArray[i]);
|
|
1347
|
+
}
|
|
1168
1348
|
}
|
|
1169
1349
|
else if (typeof elementToAdd === 'object' &&
|
|
1170
1350
|
elementToAdd !== null &&
|
|
@@ -1179,7 +1359,7 @@ export class PayloadManager {
|
|
|
1179
1359
|
reasoning: changeRequest.reasoning
|
|
1180
1360
|
// Intentionally omit newElements
|
|
1181
1361
|
};
|
|
1182
|
-
this.processChangeRequest(elementToAdd, original ? original[i] : undefined, changeRequestWithoutNew, [...path, i.toString()], counts, warnings, allowedPaths, blockedOperations, requestHasDottedKeys);
|
|
1362
|
+
this.processChangeRequest(elementToAdd, original ? original[i] : undefined, changeRequestWithoutNew, [...path, i.toString()], counts, warnings, allowedPaths, blockedOperations, requestHasDottedKeys, basePath);
|
|
1183
1363
|
}
|
|
1184
1364
|
newTargetArray.push(elementToAdd);
|
|
1185
1365
|
}
|
|
@@ -1187,13 +1367,18 @@ export class PayloadManager {
|
|
|
1187
1367
|
// These should be treated as additions (AI put new items in updateElements)
|
|
1188
1368
|
if (updateArray && Array.isArray(updateArray)) {
|
|
1189
1369
|
for (let i = target.length; i < updateArray.length; i++) {
|
|
1190
|
-
if (this.isSignificantValue(updateArray[i]))
|
|
1370
|
+
if (!this.isSignificantValue(updateArray[i]))
|
|
1371
|
+
continue;
|
|
1372
|
+
if (this.isArrayElementOperationAllowed(arrayPath, i, 'add', allowedPaths)) {
|
|
1191
1373
|
newTargetArray.push(updateArray[i]);
|
|
1192
1374
|
counts.additions++;
|
|
1193
1375
|
}
|
|
1376
|
+
else {
|
|
1377
|
+
this.recordBlockedOperation(blocked, `${arrayPath}.${i}`, 'add', undefined, updateArray[i]);
|
|
1378
|
+
}
|
|
1194
1379
|
}
|
|
1195
1380
|
}
|
|
1196
|
-
// Add new elements
|
|
1381
|
+
// Add new elements. Appends are not checked against allowedPaths (they never have been).
|
|
1197
1382
|
if (newArray && Array.isArray(newArray)) {
|
|
1198
1383
|
for (const item of newArray) {
|
|
1199
1384
|
if (this.isSignificantValue(item)) {
|
|
@@ -1206,15 +1391,50 @@ export class PayloadManager {
|
|
|
1206
1391
|
target.length = 0;
|
|
1207
1392
|
target.push(...newTargetArray);
|
|
1208
1393
|
}
|
|
1394
|
+
/**
|
|
1395
|
+
* Whether an operation on one array element is allowed. Element operations used to be gated only
|
|
1396
|
+
* by 'update' on the array itself, so that permission still allows them. A pattern naming the
|
|
1397
|
+
* element path (for example `dependencies.*`) allows them too.
|
|
1398
|
+
*/
|
|
1399
|
+
isArrayElementOperationAllowed(arrayPath, index, operation, allowedPaths) {
|
|
1400
|
+
if (!allowedPaths)
|
|
1401
|
+
return true;
|
|
1402
|
+
return this.isOperationAllowedForPath(arrayPath, 'update', allowedPaths) ||
|
|
1403
|
+
this.isOperationAllowedForPath(`${arrayPath}.${index}`, operation, allowedPaths);
|
|
1404
|
+
}
|
|
1405
|
+
/**
|
|
1406
|
+
* Whether a `"__DELETE__"` value in updateElements may delete `key`. It needs 'delete' or 'update'
|
|
1407
|
+
* on the key itself, or 'update' on the object that holds it (the gate it used to pass through).
|
|
1408
|
+
*/
|
|
1409
|
+
isUpdateDeleteAllowed(containerPath, key, allowedPaths) {
|
|
1410
|
+
if (!allowedPaths)
|
|
1411
|
+
return true;
|
|
1412
|
+
const keyPath = [...containerPath, key].join('.');
|
|
1413
|
+
return this.isOperationAllowedForPath(keyPath, 'delete', allowedPaths) ||
|
|
1414
|
+
this.isOperationAllowedForPath(keyPath, 'update', allowedPaths) ||
|
|
1415
|
+
(containerPath.length > 0 && this.isOperationAllowedForPath(containerPath.join('.'), 'update', allowedPaths));
|
|
1416
|
+
}
|
|
1417
|
+
/** Adds a warning and a blocked-operation record for an operation `allowedPaths` refused. */
|
|
1418
|
+
recordBlockedOperation(sink, path, operation, from, to) {
|
|
1419
|
+
sink.warnings.push(`Operation denied: Cannot ${operation} '${path}' - operation '${operation}' not allowed`);
|
|
1420
|
+
sink.blockedOperations?.push({
|
|
1421
|
+
path,
|
|
1422
|
+
operation,
|
|
1423
|
+
from,
|
|
1424
|
+
to,
|
|
1425
|
+
reason: `operation '${operation}' not allowed`,
|
|
1426
|
+
timestamp: new Date().toISOString()
|
|
1427
|
+
});
|
|
1428
|
+
}
|
|
1209
1429
|
/**
|
|
1210
1430
|
* Process changes for object properties
|
|
1211
1431
|
*/
|
|
1212
|
-
processObjectChanges(target, original, changeRequest, path, counts, warnings, allowedPaths, blockedOperations, requestHasDottedKeys = false) {
|
|
1432
|
+
processObjectChanges(target, original, changeRequest, path, counts, warnings, allowedPaths, blockedOperations, requestHasDottedKeys = false, basePath = []) {
|
|
1213
1433
|
// Get all unique keys from change request
|
|
1214
1434
|
const changeKeys = this.getChangeKeys(changeRequest, path);
|
|
1215
1435
|
// Process changes for each key
|
|
1216
1436
|
for (const key of changeKeys) {
|
|
1217
|
-
this.processKeyChange(target, original, changeRequest, [...path, key], key, counts, warnings, allowedPaths, blockedOperations, requestHasDottedKeys);
|
|
1437
|
+
this.processKeyChange(target, original, changeRequest, [...path, key], key, counts, warnings, allowedPaths, blockedOperations, requestHasDottedKeys, basePath);
|
|
1218
1438
|
}
|
|
1219
1439
|
// After processing all changes, check for "_DELETE_" values in updateElements
|
|
1220
1440
|
// This allows deletion within update operations at any depth
|
|
@@ -1224,7 +1444,12 @@ export class PayloadManager {
|
|
|
1224
1444
|
const keysToDelete = [];
|
|
1225
1445
|
for (const [key, value] of Object.entries(updateObj)) {
|
|
1226
1446
|
if (value === '__DELETE__' && key in target) {
|
|
1227
|
-
|
|
1447
|
+
if (this.isUpdateDeleteAllowed([...basePath, ...path], key, allowedPaths)) {
|
|
1448
|
+
keysToDelete.push(key);
|
|
1449
|
+
}
|
|
1450
|
+
else {
|
|
1451
|
+
this.recordBlockedOperation({ warnings, blockedOperations }, [...basePath, ...path, key].join('.'), 'delete', target[key], undefined);
|
|
1452
|
+
}
|
|
1228
1453
|
}
|
|
1229
1454
|
}
|
|
1230
1455
|
// Delete the keys after iteration to avoid modification during iteration
|
|
@@ -1237,7 +1462,7 @@ export class PayloadManager {
|
|
|
1237
1462
|
if (requestHasDottedKeys) {
|
|
1238
1463
|
for (const key of Object.keys(target)) {
|
|
1239
1464
|
if (!changeKeys.has(key) && typeof target[key] === 'object' && target[key] !== null) {
|
|
1240
|
-
this.processChangeRequest(target[key], original ? original[key] : undefined, changeRequest, [...path, key], counts, warnings, allowedPaths, blockedOperations, requestHasDottedKeys);
|
|
1465
|
+
this.processChangeRequest(target[key], original ? original[key] : undefined, changeRequest, [...path, key], counts, warnings, allowedPaths, blockedOperations, requestHasDottedKeys, basePath);
|
|
1241
1466
|
}
|
|
1242
1467
|
}
|
|
1243
1468
|
}
|
|
@@ -1245,19 +1470,22 @@ export class PayloadManager {
|
|
|
1245
1470
|
/**
|
|
1246
1471
|
* Process a single key change (add, update, or delete)
|
|
1247
1472
|
*/
|
|
1248
|
-
processKeyChange(target, original, changeRequest, keyPath, key, counts, warnings, allowedPaths, blockedOperations, requestHasDottedKeys = false) {
|
|
1473
|
+
processKeyChange(target, original, changeRequest, keyPath, key, counts, warnings, allowedPaths, blockedOperations, requestHasDottedKeys = false, basePath = []) {
|
|
1249
1474
|
const pathStr = keyPath.join('.');
|
|
1475
|
+
// The path checked against allowedPaths and reported when blocked. It differs from pathStr
|
|
1476
|
+
// inside an array element merge, where keyPath is relative to the element.
|
|
1477
|
+
const permissionPath = [...basePath, ...keyPath].join('.');
|
|
1250
1478
|
// Check for replacement first (complete replacement - remove then add)
|
|
1251
1479
|
const replaceValue = _.get(changeRequest.replaceElements, pathStr);
|
|
1252
1480
|
if (replaceValue !== undefined) {
|
|
1253
1481
|
// Check if appropriate operation is allowed (delete if exists, add if not)
|
|
1254
1482
|
const operation = key in target ? 'update' : 'add';
|
|
1255
|
-
if (allowedPaths && !this.isOperationAllowedForPath(
|
|
1256
|
-
const warning = `Operation denied: Cannot replace '${
|
|
1483
|
+
if (allowedPaths && !this.isOperationAllowedForPath(permissionPath, operation, allowedPaths)) {
|
|
1484
|
+
const warning = `Operation denied: Cannot replace '${permissionPath}' - operation '${operation}' not allowed`;
|
|
1257
1485
|
warnings.push(warning);
|
|
1258
1486
|
if (blockedOperations) {
|
|
1259
1487
|
blockedOperations.push({
|
|
1260
|
-
path:
|
|
1488
|
+
path: permissionPath,
|
|
1261
1489
|
operation: operation,
|
|
1262
1490
|
from: target[key],
|
|
1263
1491
|
to: replaceValue,
|
|
@@ -1283,12 +1511,12 @@ export class PayloadManager {
|
|
|
1283
1511
|
const removeValue = _.get(changeRequest.removeElements, pathStr);
|
|
1284
1512
|
if (removeValue === '__DELETE__') {
|
|
1285
1513
|
// Check if delete operation is allowed
|
|
1286
|
-
if (allowedPaths && !this.isOperationAllowedForPath(
|
|
1287
|
-
const warning = `Operation denied: Cannot delete '${
|
|
1514
|
+
if (allowedPaths && !this.isOperationAllowedForPath(permissionPath, 'delete', allowedPaths)) {
|
|
1515
|
+
const warning = `Operation denied: Cannot delete '${permissionPath}' - operation 'delete' not allowed`;
|
|
1288
1516
|
warnings.push(warning);
|
|
1289
1517
|
if (blockedOperations) {
|
|
1290
1518
|
blockedOperations.push({
|
|
1291
|
-
path:
|
|
1519
|
+
path: permissionPath,
|
|
1292
1520
|
operation: 'delete',
|
|
1293
1521
|
from: target[key],
|
|
1294
1522
|
to: undefined,
|
|
@@ -1307,12 +1535,12 @@ export class PayloadManager {
|
|
|
1307
1535
|
const newValue = _.get(changeRequest.newElements, pathStr);
|
|
1308
1536
|
if (newValue !== undefined && !(key in target)) {
|
|
1309
1537
|
// Check if add operation is allowed
|
|
1310
|
-
if (allowedPaths && !this.isOperationAllowedForPath(
|
|
1311
|
-
const warning = `Operation denied: Cannot add '${
|
|
1538
|
+
if (allowedPaths && !this.isOperationAllowedForPath(permissionPath, 'add', allowedPaths)) {
|
|
1539
|
+
const warning = `Operation denied: Cannot add '${permissionPath}' - operation 'add' not allowed`;
|
|
1312
1540
|
warnings.push(warning);
|
|
1313
1541
|
if (blockedOperations) {
|
|
1314
1542
|
blockedOperations.push({
|
|
1315
|
-
path:
|
|
1543
|
+
path: permissionPath,
|
|
1316
1544
|
operation: 'add',
|
|
1317
1545
|
from: undefined,
|
|
1318
1546
|
to: newValue,
|
|
@@ -1346,13 +1574,17 @@ export class PayloadManager {
|
|
|
1346
1574
|
shouldTreatNewAsUpdate ? newValue :
|
|
1347
1575
|
undefined;
|
|
1348
1576
|
if (effectiveUpdateValue !== undefined && key in target) {
|
|
1349
|
-
//
|
|
1350
|
-
|
|
1351
|
-
|
|
1577
|
+
// When the update merges into an existing object or array, permission is checked on each
|
|
1578
|
+
// value it writes inside, not on the container: allowing `dependencies.*.code` must let a
|
|
1579
|
+
// change write that code without also allowing every other update to `dependencies`.
|
|
1580
|
+
const mergesIntoContainer = typeof effectiveUpdateValue === 'object' && effectiveUpdateValue !== null &&
|
|
1581
|
+
typeof target[key] === 'object' && target[key] !== null;
|
|
1582
|
+
if (!mergesIntoContainer && allowedPaths && !this.isOperationAllowedForPath(permissionPath, 'update', allowedPaths)) {
|
|
1583
|
+
const warning = `Operation denied: Cannot update '${permissionPath}' - operation 'update' not allowed`;
|
|
1352
1584
|
warnings.push(warning);
|
|
1353
1585
|
if (blockedOperations) {
|
|
1354
1586
|
blockedOperations.push({
|
|
1355
|
-
path:
|
|
1587
|
+
path: permissionPath,
|
|
1356
1588
|
operation: 'update',
|
|
1357
1589
|
from: target[key],
|
|
1358
1590
|
to: effectiveUpdateValue,
|
|
@@ -1363,10 +1595,9 @@ export class PayloadManager {
|
|
|
1363
1595
|
return;
|
|
1364
1596
|
}
|
|
1365
1597
|
// If both values are objects or arrays, we need to recursively process the update
|
|
1366
|
-
if (
|
|
1367
|
-
typeof target[key] === 'object' && target[key] !== null) {
|
|
1598
|
+
if (mergesIntoContainer) {
|
|
1368
1599
|
// Recursively process nested updates for both objects and arrays
|
|
1369
|
-
this.processChangeRequest(target[key], original ? original[key] : undefined, changeRequest, keyPath, counts, warnings, allowedPaths, blockedOperations, requestHasDottedKeys);
|
|
1600
|
+
this.processChangeRequest(target[key], original ? original[key] : undefined, changeRequest, keyPath, counts, warnings, allowedPaths, blockedOperations, requestHasDottedKeys, basePath);
|
|
1370
1601
|
}
|
|
1371
1602
|
else {
|
|
1372
1603
|
// For primitives or type mismatches, replace the value
|
|
@@ -1381,12 +1612,12 @@ export class PayloadManager {
|
|
|
1381
1612
|
else if (updateValue !== undefined && !(key in target)) {
|
|
1382
1613
|
// Be forgiving: if AI put an addition in updateElements by mistake, treat it as an addition
|
|
1383
1614
|
// Check if add operation is allowed
|
|
1384
|
-
if (allowedPaths && !this.isOperationAllowedForPath(
|
|
1385
|
-
const warning = `Operation denied: Cannot add '${
|
|
1615
|
+
if (allowedPaths && !this.isOperationAllowedForPath(permissionPath, 'add', allowedPaths)) {
|
|
1616
|
+
const warning = `Operation denied: Cannot add '${permissionPath}' - operation 'add' not allowed`;
|
|
1386
1617
|
warnings.push(warning);
|
|
1387
1618
|
if (blockedOperations) {
|
|
1388
1619
|
blockedOperations.push({
|
|
1389
|
-
path:
|
|
1620
|
+
path: permissionPath,
|
|
1390
1621
|
operation: 'add',
|
|
1391
1622
|
from: undefined,
|
|
1392
1623
|
to: updateValue,
|
|
@@ -1405,17 +1636,17 @@ export class PayloadManager {
|
|
|
1405
1636
|
// Handle case where removeValue exists but isn't a direct deletion
|
|
1406
1637
|
// This happens with arrays where removeValue is like [{}, '_DELETE_', {}]
|
|
1407
1638
|
// We need to recurse to process the array removals
|
|
1408
|
-
this.processChangeRequest(target[key], original ? original[key] : undefined, changeRequest, keyPath, counts, warnings, allowedPaths, blockedOperations, requestHasDottedKeys);
|
|
1639
|
+
this.processChangeRequest(target[key], original ? original[key] : undefined, changeRequest, keyPath, counts, warnings, allowedPaths, blockedOperations, requestHasDottedKeys, basePath);
|
|
1409
1640
|
}
|
|
1410
1641
|
else if (newValue !== undefined && Array.isArray(newValue) && Array.isArray(target[key])) {
|
|
1411
1642
|
// Handle array append: newElements has an array for an existing array key
|
|
1412
1643
|
// Recurse to let processArrayChanges handle the append
|
|
1413
|
-
this.processChangeRequest(target[key], original ? original[key] : undefined, changeRequest, keyPath, counts, warnings, allowedPaths, blockedOperations, requestHasDottedKeys);
|
|
1644
|
+
this.processChangeRequest(target[key], original ? original[key] : undefined, changeRequest, keyPath, counts, warnings, allowedPaths, blockedOperations, requestHasDottedKeys, basePath);
|
|
1414
1645
|
}
|
|
1415
1646
|
else if (bothAreObjects) {
|
|
1416
1647
|
// Handle object in newElements for existing object key
|
|
1417
1648
|
// Recurse to find nested arrays that need append semantics
|
|
1418
|
-
this.processChangeRequest(target[key], original ? original[key] : undefined, changeRequest, keyPath, counts, warnings, allowedPaths, blockedOperations, requestHasDottedKeys);
|
|
1649
|
+
this.processChangeRequest(target[key], original ? original[key] : undefined, changeRequest, keyPath, counts, warnings, allowedPaths, blockedOperations, requestHasDottedKeys, basePath);
|
|
1419
1650
|
}
|
|
1420
1651
|
}
|
|
1421
1652
|
/**
|
|
@@ -1426,7 +1657,7 @@ export class PayloadManager {
|
|
|
1426
1657
|
const pathStr = path.join('.');
|
|
1427
1658
|
const addKeysFromObject = (obj) => {
|
|
1428
1659
|
if (obj && typeof obj === 'object' && !Array.isArray(obj)) {
|
|
1429
|
-
Object.keys(obj).forEach(k => keys.add(k));
|
|
1660
|
+
Object.keys(obj).filter(k => !IsUnsafeObjectKey(k)).forEach(k => keys.add(k));
|
|
1430
1661
|
}
|
|
1431
1662
|
};
|
|
1432
1663
|
const removeObj = pathStr ? _.get(changeRequest.removeElements, pathStr) : changeRequest.removeElements;
|