@zvenigora/ng-eval-core 0.9.0 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -928,6 +928,261 @@ var RecursiveVisitorResultType;
928
928
  RecursiveVisitorResultType[RecursiveVisitorResultType["Registry"] = 1] = "Registry";
929
929
  })(RecursiveVisitorResultType || (RecursiveVisitorResultType = {}));
930
930
 
931
+ /**
932
+ * Prototype Pollution Prevention Utilities
933
+ *
934
+ * This module provides safeguards against prototype pollution attacks
935
+ * by controlling access to dangerous property names and ensuring safe
936
+ * object operations.
937
+ */
938
+ /**
939
+ * Set of property names that are dangerous for prototype pollution attacks
940
+ */
941
+ const DANGEROUS_PROPERTY_NAMES = new Set([
942
+ '__proto__',
943
+ 'constructor',
944
+ 'prototype',
945
+ '__defineGetter__',
946
+ '__defineSetter__',
947
+ '__lookupGetter__',
948
+ '__lookupSetter__',
949
+ 'hasOwnProperty',
950
+ 'isPrototypeOf',
951
+ 'propertyIsEnumerable',
952
+ 'toString',
953
+ 'valueOf',
954
+ 'toLocaleString'
955
+ ]);
956
+ /**
957
+ * The subset of DANGEROUS_PROPERTY_NAMES refused on a string, number or
958
+ * boolean receiver: the names that reach a global constructor, a built-in
959
+ * prototype or an accessor definer. The other six - `toString`, `valueOf`,
960
+ * `toLocaleString`, `hasOwnProperty`, `isPrototypeOf`,
961
+ * `propertyIsEnumerable` - are ordinary reads on a primitive and stay
962
+ * readable.
963
+ *
964
+ * Matched by exact key, under `caseInsensitive` too: a primitive receiver is
965
+ * never case-corrected, so a variant such as `s.CONSTRUCTOR` is a missing
966
+ * property, not a route to `String`.
967
+ */
968
+ const DANGEROUS_PRIMITIVE_PROPERTY_NAMES = new Set([
969
+ '__proto__',
970
+ 'constructor',
971
+ 'prototype',
972
+ '__defineGetter__',
973
+ '__defineSetter__',
974
+ '__lookupGetter__',
975
+ '__lookupSetter__'
976
+ ]);
977
+ /**
978
+ * DANGEROUS_PROPERTY_NAMES lower-cased, for {@link mayMatchDangerousProperty}.
979
+ */
980
+ const LOWERED_DANGEROUS_PROPERTY_NAMES = new Set(Array.from(DANGEROUS_PROPERTY_NAMES, (name) => name.toLowerCase()));
981
+ /**
982
+ * Any UTF-16 code unit outside ASCII, for {@link mayMatchDangerousProperty}.
983
+ */
984
+ const NON_ASCII = /[\u0080-￿]/;
985
+ /**
986
+ * Set of constructor names that should be blocked from modification
987
+ */
988
+ const DANGEROUS_CONSTRUCTORS$1 = new Set([
989
+ 'Object',
990
+ 'Function',
991
+ 'Array',
992
+ 'String',
993
+ 'Number',
994
+ 'Boolean',
995
+ 'Date',
996
+ 'RegExp',
997
+ 'Error',
998
+ 'Promise'
999
+ ]);
1000
+ /**
1001
+ * Checks if a property name is dangerous for prototype pollution
1002
+ * @param key The property name to check
1003
+ * @returns true if the property is dangerous, false otherwise
1004
+ */
1005
+ const isDangerousProperty = (key) => {
1006
+ if (typeof key === 'string') {
1007
+ return DANGEROUS_PROPERTY_NAMES.has(key);
1008
+ }
1009
+ return false;
1010
+ };
1011
+ /**
1012
+ * Checks if a property name is dangerous on a primitive receiver
1013
+ * @param key The property name to check
1014
+ * @returns true if the property is in the primitive subset, false otherwise
1015
+ */
1016
+ const isDangerousPrimitiveProperty = (key) => {
1017
+ if (typeof key === 'string') {
1018
+ return DANGEROUS_PRIMITIVE_PROPERTY_NAMES.has(key);
1019
+ }
1020
+ return false;
1021
+ };
1022
+ /**
1023
+ * Whether a name, matched against a context under `caseInsensitive`, could
1024
+ * match a key in DANGEROUS_PROPERTY_NAMES: the cheap filter ahead of
1025
+ * `EvalContext.getKey`, which says which key it did match. False means it
1026
+ * cannot, so an identifier pays for `getKey` only when it is near a dangerous
1027
+ * name.
1028
+ *
1029
+ * A context matches another spelling in two ways. A case-insensitive
1030
+ * `Registry`, and an `eval-signals` source, compare `toLowerCase()` forms, so
1031
+ * a name can match a dangerous key only if its own lower-case form is one. A
1032
+ * prior scope's namespace is compared by `localeCompare` at base sensitivity,
1033
+ * which ignores accents as well as case: on ASCII identifier characters that
1034
+ * is the same comparison, but a name with any other character may match a
1035
+ * dangerous key - `cönstructor` matches `constructor` - so such a name always
1036
+ * answers true.
1037
+ * @param name The name as written
1038
+ * @returns false if the name cannot match a dangerous key, true otherwise
1039
+ */
1040
+ const mayMatchDangerousProperty = (name) => NON_ASCII.test(name) || LOWERED_DANGEROUS_PROPERTY_NAMES.has(name.toLowerCase());
1041
+ /**
1042
+ * Checks if an object is a dangerous constructor that shouldn't be modified
1043
+ * @param obj The object to check
1044
+ * @returns true if the object is a dangerous constructor, false otherwise
1045
+ */
1046
+ const isDangerousConstructor = (obj) => {
1047
+ if (typeof obj === 'function' && obj.name) {
1048
+ return DANGEROUS_CONSTRUCTORS$1.has(obj.name);
1049
+ }
1050
+ return false;
1051
+ };
1052
+ /**
1053
+ * Safely sets a property on an object with prototype pollution protection.
1054
+ * Refuses a dangerous target or key, then assigns - so a setter runs, and a
1055
+ * write the object refuses throws, prefixed "Failed to set property".
1056
+ * @param target The target object
1057
+ * @param key The property key
1058
+ * @param value The property value
1059
+ * @throws Error if the operation would cause prototype pollution, or if the
1060
+ * object refuses the write
1061
+ */
1062
+ const safeSetProperty = (target, key, value) => {
1063
+ if (!target || (typeof target !== 'object' && typeof target !== 'function')) {
1064
+ throw new Error(`Cannot set property on non-object: ${typeof target}`);
1065
+ }
1066
+ if (isDangerousProperty(key)) {
1067
+ throw new Error(`Access to dangerous property "${String(key)}" is blocked for security reasons`);
1068
+ }
1069
+ // Additional protection: don't allow setting properties on built-in prototypes
1070
+ if (isDangerousConstructor(target)) {
1071
+ throw new Error(`Modification of built-in constructor "${target.name}" is blocked for security reasons`);
1072
+ }
1073
+ // Check if we're trying to modify prototype chain
1074
+ if (target === Object.prototype ||
1075
+ target === Function.prototype ||
1076
+ target === Array.prototype ||
1077
+ target === String.prototype ||
1078
+ target === Number.prototype ||
1079
+ target === Boolean.prototype) {
1080
+ throw new Error(`Modification of built-in prototype is blocked for security reasons`);
1081
+ }
1082
+ // Convert key to PropertyKey for safe operations
1083
+ let propertyKey;
1084
+ if (typeof key === 'string' || typeof key === 'number' || typeof key === 'symbol') {
1085
+ propertyKey = key;
1086
+ }
1087
+ else {
1088
+ // For other types, try to convert to string
1089
+ propertyKey = String(key);
1090
+ }
1091
+ // An assignment, after every refusal above - not a definition. Up to 0.9.x
1092
+ // this was `Object.defineProperty` with a writable, enumerable, configurable
1093
+ // descriptor (`docs/backlog-retired.md` A23), which a write in JavaScript is
1094
+ // not: it replaced an own accessor and hid an inherited one, so no setter
1095
+ // ever ran; it made a non-enumerable property enumerable; and it refused
1096
+ // every non-configurable property, `lastIndex` and an array's `length`
1097
+ // included. Reads already ran the caller's getters, so running its setters
1098
+ // here is the one behaviour this adds. This module is strict, so a write the
1099
+ // object refuses - frozen, non-writable, an accessor with no setter - throws
1100
+ // rather than failing silently, and is reported below.
1101
+ try {
1102
+ target[propertyKey] = value;
1103
+ }
1104
+ catch (error) {
1105
+ throw new Error(`Failed to set property "${String(key)}": ${error instanceof Error ? error.message : String(error)}`);
1106
+ }
1107
+ };
1108
+ /**
1109
+ * Safely gets a property from an object with prototype pollution protection
1110
+ * @param target The target object
1111
+ * @param key The property key
1112
+ * @returns The property value or undefined
1113
+ */
1114
+ const safeGetProperty = (target, key) => {
1115
+ if (!target || (typeof target !== 'object' && typeof target !== 'function')) {
1116
+ return undefined;
1117
+ }
1118
+ if (isDangerousProperty(key)) {
1119
+ throw new Error(`Access to dangerous property "${String(key)}" is blocked for security reasons`);
1120
+ }
1121
+ // Convert key to PropertyKey for safe operations
1122
+ let propertyKey;
1123
+ if (typeof key === 'string' || typeof key === 'number' || typeof key === 'symbol') {
1124
+ propertyKey = key;
1125
+ }
1126
+ else {
1127
+ // For other types, try to convert to string
1128
+ propertyKey = String(key);
1129
+ }
1130
+ // Direct property access using bracket notation (safer than complex prototype walking)
1131
+ try {
1132
+ return target[propertyKey];
1133
+ }
1134
+ catch {
1135
+ // If property access fails, return undefined
1136
+ return undefined;
1137
+ }
1138
+ };
1139
+ /**
1140
+ * Creates a safe object without dangerous prototype pollution vectors
1141
+ * @param entries Key-value pairs to populate the object
1142
+ * @returns A new safe object
1143
+ */
1144
+ const createSafeObject = (entries = []) => {
1145
+ // Create object with normal prototype for compatibility, but validate contents
1146
+ const obj = {};
1147
+ for (const [key, value] of entries) {
1148
+ if (isDangerousProperty(key)) {
1149
+ throw new Error(`Cannot create object with dangerous property "${String(key)}"`);
1150
+ }
1151
+ // Safely set the property
1152
+ if (typeof key === 'string' || typeof key === 'number') {
1153
+ obj[key] = value;
1154
+ }
1155
+ else if (typeof key === 'symbol') {
1156
+ obj[key] = value;
1157
+ }
1158
+ }
1159
+ return obj;
1160
+ };
1161
+ /**
1162
+ * Validates that an object is safe from prototype pollution
1163
+ * @param obj The object to validate
1164
+ * @throws Error if the object contains dangerous properties
1165
+ */
1166
+ const validateSafeObject = (obj) => {
1167
+ if (!obj || typeof obj !== 'object') {
1168
+ return;
1169
+ }
1170
+ const keys = Object.getOwnPropertyNames(obj);
1171
+ for (const key of keys) {
1172
+ if (isDangerousProperty(key)) {
1173
+ throw new Error(`Object contains dangerous property "${key}" that could lead to prototype pollution`);
1174
+ }
1175
+ }
1176
+ // Also check symbol properties
1177
+ const symbols = Object.getOwnPropertySymbols(obj);
1178
+ for (const symbol of symbols) {
1179
+ const description = symbol.description;
1180
+ if (description && isDangerousProperty(description)) {
1181
+ throw new Error(`Object contains dangerous symbol property "${description}" that could lead to prototype pollution`);
1182
+ }
1183
+ }
1184
+ };
1185
+
931
1186
  const literals = Registry.fromObject({
932
1187
  'undefined': undefined,
933
1188
  'null': null,
@@ -974,11 +1229,50 @@ const emitRead = (node, st, value) => {
974
1229
  ...(scoped ? { scoped: true } : {})
975
1230
  });
976
1231
  };
1232
+ /**
1233
+ * Refuses an identifier whose name is on the prototype-pollution blocklist,
1234
+ * before any lookup, with the member visitor's error.
1235
+ *
1236
+ * An identifier is resolved against the context, and `EvalContext.get` reads a
1237
+ * plain object there - the original, or a scope - with a bare property access.
1238
+ * So up to 0.10.0 a name on the blocklist resolved to what the context inherits
1239
+ * from `Object.prototype` (`docs/backlog-retired.md` B6): the blocklist guarded
1240
+ * member access to the objects an expression holds, and the context is not one
1241
+ * of them. Every kind of context is refused alike, including those - a
1242
+ * `Registry`, a signal context's source - that hold such a name only as a key
1243
+ * of their own.
1244
+ */
1245
+ const refuseDangerousName = (node) => {
1246
+ if (isDangerousProperty(node.name)) {
1247
+ throw new Error(`Access to dangerous property "${node.name}" is blocked for security reasons`);
1248
+ }
1249
+ };
1250
+ /**
1251
+ * Under `caseInsensitive`, refuses an identifier whose lookup matched a key on
1252
+ * the blocklist - `CONSTRUCTOR` over a context holding `constructor` - as the
1253
+ * member visitor re-checks `foundKey` for another object.
1254
+ *
1255
+ * The matched key is asked of `getKey`, which answers the key `get` resolves,
1256
+ * and only for a name `mayMatchDangerousProperty` lets through. Any other name
1257
+ * cannot match a blocklisted key, and an identifier must not pay a second
1258
+ * resolution for nothing: the performance spec's read-emission guard asserts
1259
+ * that, with no read hook, `getKey` is not called per identifier.
1260
+ */
1261
+ const refuseDangerousMatch = (node, st) => {
1262
+ if (!st.context || !mayMatchDangerousProperty(node.name)) {
1263
+ return;
1264
+ }
1265
+ const matched = st.context.getKey(node.name);
1266
+ if (isDangerousProperty(matched)) {
1267
+ throw new Error(`Access to dangerous property "${String(matched)}" is blocked for security reasons`);
1268
+ }
1269
+ };
977
1270
  const identifierVisitor = (node, st) => {
978
1271
  if (st.options?.caseInsensitive) {
979
1272
  return identifierVisitorCaseInsensitive(node, st);
980
1273
  }
981
1274
  beforeVisitor(node, st);
1275
+ refuseDangerousName(node);
982
1276
  const context = st.context;
983
1277
  const isThis = node.name === 'this';
984
1278
  const value = isThis
@@ -995,8 +1289,12 @@ const identifierVisitor = (node, st) => {
995
1289
  };
996
1290
  const identifierVisitorCaseInsensitive = (node, st) => {
997
1291
  beforeVisitor(node, st);
1292
+ refuseDangerousName(node);
998
1293
  const context = st.context;
999
1294
  const isThis = !!equalIgnoreCase(node.name, 'this');
1295
+ if (!isThis) {
1296
+ refuseDangerousMatch(node, st);
1297
+ }
1000
1298
  const value = isThis
1001
1299
  ? st.context
1002
1300
  : context?.get(node.name) ?? literals.get(node.name);
@@ -1009,7 +1307,20 @@ const identifierVisitorCaseInsensitive = (node, st) => {
1009
1307
 
1010
1308
  const literalVisitor = (node, st) => {
1011
1309
  beforeVisitor(node, st);
1012
- const value = node.value;
1310
+ // A regex literal is a new `RegExp` on every evaluation, as it is in
1311
+ // JavaScript. Acorn builds `node.value` once, at parse time, and every walk of
1312
+ // the parsed tree used to push that one object - a cached `simpleEval` string
1313
+ // and each recompute of a compiled expression alike - so `lastIndex` carried
1314
+ // from one evaluation into the next, and `/a/g.test("a")` answered true, then
1315
+ // false. A copy starts at `lastIndex` 0, and being new it is recorded under a
1316
+ // member-write policy, as a literal is - `EvalContext.checkMemberWrite`. When
1317
+ // acorn could not build the regex in this environment, `value` is null and is
1318
+ // pushed as before.
1319
+ let value = node.value;
1320
+ if (value instanceof RegExp) {
1321
+ value = new RegExp(value);
1322
+ st.createdObjects?.add(value);
1323
+ }
1013
1324
  pushVisitorResult(node, st, value);
1014
1325
  afterVisitor(node, st);
1015
1326
  };
@@ -1179,228 +1490,6 @@ const binaryExpressionVisitor = (node, st, callback) => {
1179
1490
  afterVisitor(node, st);
1180
1491
  };
1181
1492
 
1182
- /**
1183
- * Prototype Pollution Prevention Utilities
1184
- *
1185
- * This module provides safeguards against prototype pollution attacks
1186
- * by controlling access to dangerous property names and ensuring safe
1187
- * object operations.
1188
- */
1189
- /**
1190
- * Set of property names that are dangerous for prototype pollution attacks
1191
- */
1192
- const DANGEROUS_PROPERTY_NAMES = new Set([
1193
- '__proto__',
1194
- 'constructor',
1195
- 'prototype',
1196
- '__defineGetter__',
1197
- '__defineSetter__',
1198
- '__lookupGetter__',
1199
- '__lookupSetter__',
1200
- 'hasOwnProperty',
1201
- 'isPrototypeOf',
1202
- 'propertyIsEnumerable',
1203
- 'toString',
1204
- 'valueOf',
1205
- 'toLocaleString'
1206
- ]);
1207
- /**
1208
- * The subset of DANGEROUS_PROPERTY_NAMES refused on a string, number or
1209
- * boolean receiver: the names that reach a global constructor, a built-in
1210
- * prototype or an accessor definer. The other six - `toString`, `valueOf`,
1211
- * `toLocaleString`, `hasOwnProperty`, `isPrototypeOf`,
1212
- * `propertyIsEnumerable` - are ordinary reads on a primitive and stay
1213
- * readable.
1214
- *
1215
- * Matched by exact key, under `caseInsensitive` too: a primitive receiver is
1216
- * never case-corrected, so a variant such as `s.CONSTRUCTOR` is a missing
1217
- * property, not a route to `String`.
1218
- */
1219
- const DANGEROUS_PRIMITIVE_PROPERTY_NAMES = new Set([
1220
- '__proto__',
1221
- 'constructor',
1222
- 'prototype',
1223
- '__defineGetter__',
1224
- '__defineSetter__',
1225
- '__lookupGetter__',
1226
- '__lookupSetter__'
1227
- ]);
1228
- /**
1229
- * Set of constructor names that should be blocked from modification
1230
- */
1231
- const DANGEROUS_CONSTRUCTORS$1 = new Set([
1232
- 'Object',
1233
- 'Function',
1234
- 'Array',
1235
- 'String',
1236
- 'Number',
1237
- 'Boolean',
1238
- 'Date',
1239
- 'RegExp',
1240
- 'Error',
1241
- 'Promise'
1242
- ]);
1243
- /**
1244
- * Checks if a property name is dangerous for prototype pollution
1245
- * @param key The property name to check
1246
- * @returns true if the property is dangerous, false otherwise
1247
- */
1248
- const isDangerousProperty = (key) => {
1249
- if (typeof key === 'string') {
1250
- return DANGEROUS_PROPERTY_NAMES.has(key);
1251
- }
1252
- return false;
1253
- };
1254
- /**
1255
- * Checks if a property name is dangerous on a primitive receiver
1256
- * @param key The property name to check
1257
- * @returns true if the property is in the primitive subset, false otherwise
1258
- */
1259
- const isDangerousPrimitiveProperty = (key) => {
1260
- if (typeof key === 'string') {
1261
- return DANGEROUS_PRIMITIVE_PROPERTY_NAMES.has(key);
1262
- }
1263
- return false;
1264
- };
1265
- /**
1266
- * Checks if an object is a dangerous constructor that shouldn't be modified
1267
- * @param obj The object to check
1268
- * @returns true if the object is a dangerous constructor, false otherwise
1269
- */
1270
- const isDangerousConstructor = (obj) => {
1271
- if (typeof obj === 'function' && obj.name) {
1272
- return DANGEROUS_CONSTRUCTORS$1.has(obj.name);
1273
- }
1274
- return false;
1275
- };
1276
- /**
1277
- * Safely sets a property on an object with prototype pollution protection
1278
- * @param target The target object
1279
- * @param key The property key
1280
- * @param value The property value
1281
- * @throws Error if the operation would cause prototype pollution
1282
- */
1283
- const safeSetProperty = (target, key, value) => {
1284
- if (!target || (typeof target !== 'object' && typeof target !== 'function')) {
1285
- throw new Error(`Cannot set property on non-object: ${typeof target}`);
1286
- }
1287
- if (isDangerousProperty(key)) {
1288
- throw new Error(`Access to dangerous property "${String(key)}" is blocked for security reasons`);
1289
- }
1290
- // Additional protection: don't allow setting properties on built-in prototypes
1291
- if (isDangerousConstructor(target)) {
1292
- throw new Error(`Modification of built-in constructor "${target.name}" is blocked for security reasons`);
1293
- }
1294
- // Check if we're trying to modify prototype chain
1295
- if (target === Object.prototype ||
1296
- target === Function.prototype ||
1297
- target === Array.prototype ||
1298
- target === String.prototype ||
1299
- target === Number.prototype ||
1300
- target === Boolean.prototype) {
1301
- throw new Error(`Modification of built-in prototype is blocked for security reasons`);
1302
- }
1303
- // Convert key to PropertyKey for safe operations
1304
- let propertyKey;
1305
- if (typeof key === 'string' || typeof key === 'number' || typeof key === 'symbol') {
1306
- propertyKey = key;
1307
- }
1308
- else {
1309
- // For other types, try to convert to string
1310
- propertyKey = String(key);
1311
- }
1312
- // Use Object.defineProperty for safer assignment
1313
- const descriptor = {
1314
- value,
1315
- writable: true,
1316
- enumerable: true,
1317
- configurable: true
1318
- };
1319
- try {
1320
- Object.defineProperty(target, propertyKey, descriptor);
1321
- }
1322
- catch (error) {
1323
- throw new Error(`Failed to set property "${String(key)}": ${error instanceof Error ? error.message : String(error)}`);
1324
- }
1325
- };
1326
- /**
1327
- * Safely gets a property from an object with prototype pollution protection
1328
- * @param target The target object
1329
- * @param key The property key
1330
- * @returns The property value or undefined
1331
- */
1332
- const safeGetProperty = (target, key) => {
1333
- if (!target || (typeof target !== 'object' && typeof target !== 'function')) {
1334
- return undefined;
1335
- }
1336
- if (isDangerousProperty(key)) {
1337
- throw new Error(`Access to dangerous property "${String(key)}" is blocked for security reasons`);
1338
- }
1339
- // Convert key to PropertyKey for safe operations
1340
- let propertyKey;
1341
- if (typeof key === 'string' || typeof key === 'number' || typeof key === 'symbol') {
1342
- propertyKey = key;
1343
- }
1344
- else {
1345
- // For other types, try to convert to string
1346
- propertyKey = String(key);
1347
- }
1348
- // Direct property access using bracket notation (safer than complex prototype walking)
1349
- try {
1350
- return target[propertyKey];
1351
- }
1352
- catch {
1353
- // If property access fails, return undefined
1354
- return undefined;
1355
- }
1356
- };
1357
- /**
1358
- * Creates a safe object without dangerous prototype pollution vectors
1359
- * @param entries Key-value pairs to populate the object
1360
- * @returns A new safe object
1361
- */
1362
- const createSafeObject = (entries = []) => {
1363
- // Create object with normal prototype for compatibility, but validate contents
1364
- const obj = {};
1365
- for (const [key, value] of entries) {
1366
- if (isDangerousProperty(key)) {
1367
- throw new Error(`Cannot create object with dangerous property "${String(key)}"`);
1368
- }
1369
- // Safely set the property
1370
- if (typeof key === 'string' || typeof key === 'number') {
1371
- obj[key] = value;
1372
- }
1373
- else if (typeof key === 'symbol') {
1374
- obj[key] = value;
1375
- }
1376
- }
1377
- return obj;
1378
- };
1379
- /**
1380
- * Validates that an object is safe from prototype pollution
1381
- * @param obj The object to validate
1382
- * @throws Error if the object contains dangerous properties
1383
- */
1384
- const validateSafeObject = (obj) => {
1385
- if (!obj || typeof obj !== 'object') {
1386
- return;
1387
- }
1388
- const keys = Object.getOwnPropertyNames(obj);
1389
- for (const key of keys) {
1390
- if (isDangerousProperty(key)) {
1391
- throw new Error(`Object contains dangerous property "${key}" that could lead to prototype pollution`);
1392
- }
1393
- }
1394
- // Also check symbol properties
1395
- const symbols = Object.getOwnPropertySymbols(obj);
1396
- for (const symbol of symbols) {
1397
- const description = symbol.description;
1398
- if (description && isDangerousProperty(description)) {
1399
- throw new Error(`Object contains dangerous symbol property "${description}" that could lead to prototype pollution`);
1400
- }
1401
- }
1402
- };
1403
-
1404
1493
  /**
1405
1494
  * Property Lookup Cache
1406
1495
  *
@@ -1614,10 +1703,22 @@ const evaluateMember = (node, st, callback) => {
1614
1703
  }
1615
1704
  // Get the value with context-aware or prototype pollution protection
1616
1705
  if (object === st.context) {
1706
+ // `this.k` resolves `k` against the context, as an identifier does, so it
1707
+ // is refused as one is (`identifier.ts`, `docs/backlog-retired.md` B6): a
1708
+ // blocklisted key before the lookup, and under `caseInsensitive` a
1709
+ // blocklisted key the lookup matched. Up to 0.10.0 neither was checked,
1710
+ // and `this.constructor` over a plain object was `Object`.
1711
+ if (isDangerousProperty(key)) {
1712
+ throw new Error(`Access to dangerous property "${String(key)}" is blocked for security reasons`);
1713
+ }
1617
1714
  // For context objects, preserve case-insensitive behavior
1618
- const contextKey = st.options?.caseInsensitive && typeof key === 'string'
1619
- ? st.context.getKey(key)
1620
- : key;
1715
+ let contextKey = key;
1716
+ if (st.options?.caseInsensitive && typeof key === 'string') {
1717
+ contextKey = st.context.getKey(key);
1718
+ if (isDangerousProperty(contextKey)) {
1719
+ throw new Error(`Access to dangerous property "${String(contextKey)}" is blocked for security reasons`);
1720
+ }
1721
+ }
1621
1722
  const value = st.context.get(contextKey);
1622
1723
  const thisValue = st.context.getThis(contextKey);
1623
1724
  if (st.hasHooks && st.hooks.hasReadHooks) {
@@ -1634,6 +1735,11 @@ const evaluateMember = (node, st, callback) => {
1634
1735
  return [thisValue ?? object, contextKey, value];
1635
1736
  }
1636
1737
  else if (object instanceof EvalScope) {
1738
+ // A global scope reads its object as the context does, with a bare
1739
+ // property access, so a blocklisted key is refused here as it is above.
1740
+ if (isDangerousProperty(key)) {
1741
+ throw new Error(`Access to dangerous property "${String(key)}" is blocked for security reasons`);
1742
+ }
1637
1743
  // For scope objects, preserve original behavior (no getKey method)
1638
1744
  const value = object.get(key);
1639
1745
  const thisValue = object;
@@ -1755,6 +1861,10 @@ const evaluateMember = (node, st, callback) => {
1755
1861
  const arrayExpressionVisitor = (node, st, callback) => {
1756
1862
  beforeVisitor(node, st);
1757
1863
  const elements = evaluateArray(node, node.elements, st, callback);
1864
+ // Recorded only under a member-write policy - `EvalContext.checkMemberWrite`.
1865
+ // Here and not in `evaluateArray`, which also builds call and `new` argument
1866
+ // lists: those are not literals the expression can hold.
1867
+ st.createdObjects?.add(elements);
1758
1868
  pushVisitorResult(node, st, elements);
1759
1869
  afterVisitor(node, st);
1760
1870
  };
@@ -2267,6 +2377,8 @@ const objectExpressionVisitor = (node, st, callback) => {
2267
2377
  // Create safe object with prototype pollution protection
2268
2378
  try {
2269
2379
  const obj = createSafeObject(entries);
2380
+ // Recorded only under a member-write policy - `EvalContext.checkMemberWrite`.
2381
+ st.createdObjects?.add(obj);
2270
2382
  pushVisitorResult(node, st, obj);
2271
2383
  }
2272
2384
  catch (error) {
@@ -2341,6 +2453,51 @@ const getDefaultVisitors = () => {
2341
2453
  return visitors;
2342
2454
  };
2343
2455
 
2456
+ /**
2457
+ * Whether `value` can be held in a `WeakSet` - an object or a function.
2458
+ */
2459
+ const isObjectLike = (value) => (typeof value === 'object' && value !== null) || typeof value === 'function';
2460
+ /**
2461
+ * Records `value` as created by the walk, unless it is a primitive.
2462
+ *
2463
+ * For the one recording site whose value may be a primitive: an array or
2464
+ * parameter rest is `args.slice(i)`, which is a string when the destructured
2465
+ * source is one (`let [h, ...t] = "abc"`), and `WeakSet.add` throws on a
2466
+ * primitive. The literal, object-rest and arrow-function sites always create
2467
+ * an object and add directly.
2468
+ *
2469
+ * @param created - `st.createdObjects`, already read and found set by the caller.
2470
+ * @param value - The value the walk created.
2471
+ */
2472
+ const recordCreated = (created, value) => {
2473
+ if (isObjectLike(value)) {
2474
+ created.add(value);
2475
+ }
2476
+ };
2477
+ /**
2478
+ * Asks the context whether a member write may happen, through
2479
+ * `EvalContext.checkMemberWrite`. A refusal is a throw, and it propagates from
2480
+ * here unchanged: nothing has been written yet.
2481
+ *
2482
+ * Called by the member branches of `assignment-expression.ts` and
2483
+ * `update-expression.ts`, immediately before `safeSetProperty`, and only after
2484
+ * the caller has read `st.createdObjects` and found it set. That read is the
2485
+ * whole of the default path's cost: a state whose context has no policy holds
2486
+ * no set, so neither visitor reaches this call.
2487
+ *
2488
+ * @param st - The state of the walk making the write.
2489
+ * @param created - `st.createdObjects`, already read by the caller.
2490
+ * @param target - The object about to receive the write.
2491
+ * @param key - The property about to be written.
2492
+ */
2493
+ const consultMemberWrite = (st, created, target, key) => {
2494
+ st.context?.checkMemberWrite?.({
2495
+ target,
2496
+ key,
2497
+ createdByEvaluation: isObjectLike(target) && created.has(target),
2498
+ });
2499
+ };
2500
+
2344
2501
  // based on evalArrowContext
2345
2502
  // https://github.com/6utt3rfly/jse-eval/blob/main/index.ts
2346
2503
  /**
@@ -2365,6 +2522,13 @@ const unsupportedBindingTarget = (type) => {
2365
2522
  const evaluatePatterns = (patterns, st, callback, args) => {
2366
2523
  let context = {};
2367
2524
  patterns.map((pattern, i) => {
2525
+ // A hole - the elision in `[, b]` - binds nothing, and is skipped *here*
2526
+ // so that every pattern after it keeps its own index into `args`, the
2527
+ // rest's `args.slice(i)` included. Only an array pattern can hold one: a
2528
+ // parameter list with a hole does not parse.
2529
+ if (pattern === null) {
2530
+ return;
2531
+ }
2368
2532
  switch (pattern.type) {
2369
2533
  case 'Identifier':
2370
2534
  {
@@ -2392,7 +2556,15 @@ const evaluatePatterns = (patterns, st, callback, args) => {
2392
2556
  break;
2393
2557
  case 'RestElement':
2394
2558
  {
2395
- const object = evaluateRestElement(pattern, st, callback, args.slice(i));
2559
+ // An array rest and a parameter rest are both this slice: a new
2560
+ // array the expression then holds. Recorded only under a member-write
2561
+ // policy - `EvalContext.checkMemberWrite`.
2562
+ const rest = args.slice(i);
2563
+ const created = st.createdObjects;
2564
+ if (created) {
2565
+ recordCreated(created, rest);
2566
+ }
2567
+ const object = evaluateRestElement(pattern, st, callback, rest);
2396
2568
  context = { ...context, ...object };
2397
2569
  }
2398
2570
  break;
@@ -2559,7 +2731,11 @@ const evaluateObjectPattern = (pattern, st, callback, arg) => {
2559
2731
  // element last in an object pattern, so `taken` is complete here.
2560
2732
  // Binding the whole argument left an already-destructured key on the
2561
2733
  // rest record - `docs/backlog.md` A13.
2562
- const object = evaluateRestElement(pattern, st, callback, restOf(arg, taken));
2734
+ // A new object, so recorded under a member-write policy exactly as
2735
+ // a literal is - `EvalContext.checkMemberWrite`.
2736
+ const rest = restOf(arg, taken);
2737
+ st.createdObjects?.add(rest);
2738
+ const object = evaluateRestElement(pattern, st, callback, rest);
2563
2739
  context = { ...context, ...object };
2564
2740
  }
2565
2741
  break;
@@ -2567,9 +2743,11 @@ const evaluateObjectPattern = (pattern, st, callback, arg) => {
2567
2743
  });
2568
2744
  return context;
2569
2745
  };
2746
+ // The elements go through with their holes in place. Filtering them out first
2747
+ // - which this did up to 0.9.0 - renumbered every element after a hole, so
2748
+ // `let [, b] = [1, 2]` bound `b` to 1.
2570
2749
  const evaluateArrayPattern = (pattern, st, callback, args) => {
2571
- const patterns = pattern.elements.filter(s => !!s);
2572
- const object = evaluatePatterns(patterns, st, callback, args);
2750
+ const object = evaluatePatterns(pattern.elements, st, callback, args);
2573
2751
  return object;
2574
2752
  };
2575
2753
  const evaluateRestElement = (pattern, st, callback, args) => {
@@ -2630,11 +2808,12 @@ const bindingScope = (st) => {
2630
2808
  * `pattern.ts` rather than of this module's contract with it.
2631
2809
  *
2632
2810
  * The write itself dispatches through `setContextValue`, not through
2633
- * `safeSetProperty`. `safeSetProperty` finishes with `Object.defineProperty`,
2634
- * which suits the plain records `pattern.ts` builds and **not** a scope: a
2635
- * `caseInsensitive` scope is a Map-backed `Registry`, and defining a property
2636
- * on the instance inserts nothing into its map. The binding would be written
2637
- * and then not found, silently, for that option only.
2811
+ * `safeSetProperty`. `safeSetProperty` writes a property onto the object it is
2812
+ * given - by assignment since 0.10.0, by `Object.defineProperty` before - which
2813
+ * suits the plain records `pattern.ts` builds and **not** a scope: a
2814
+ * `caseInsensitive` scope is a Map-backed `Registry`, and setting a property on
2815
+ * the instance, either way, inserts nothing into its map. The binding would be
2816
+ * written and then not found, silently, for that option only.
2638
2817
  */
2639
2818
  const bindDeclarator = (declarator, value, kind, scope, st, callback) => {
2640
2819
  const bindings = evaluatePattern(declarator.id, st, callback, value);
@@ -2808,6 +2987,12 @@ const assignmentExpressionVisitor = (node, st, callback) => {
2808
2987
  else if (target.type === 'MemberExpression') {
2809
2988
  const [object, key,] = evaluateMember(target, st, callback);
2810
2989
  const value = func(left, right);
2990
+ // A member write never reaches `EvalContext.set`, so a context policing
2991
+ // writes is asked here instead - `EvalContext.checkMemberWrite`.
2992
+ const created = st.createdObjects;
2993
+ if (created) {
2994
+ consultMemberWrite(st, created, object, key);
2995
+ }
2811
2996
  // Use safe property assignment to prevent prototype pollution
2812
2997
  safeSetProperty(object, key, value);
2813
2998
  pushVisitorResult(node, st, value);
@@ -2842,6 +3027,11 @@ const updateExpressionVisitor = (node, st, callback) => {
2842
3027
  else if (target.type === 'MemberExpression') {
2843
3028
  const [object, property, value] = evaluateMember(target, st, callback);
2844
3029
  const newValue = updateOperators[node.operator](value);
3030
+ // The same consultation as `assignment-expression.ts`'s member branch.
3031
+ const created = st.createdObjects;
3032
+ if (created) {
3033
+ consultMemberWrite(st, created, object, property);
3034
+ }
2845
3035
  // Use safe property assignment to prevent prototype pollution
2846
3036
  safeSetProperty(object, property, newValue);
2847
3037
  pushVisitorResult(node, st, node.prefix ? newValue : value);
@@ -3199,6 +3389,9 @@ const arrowFunctionExpressionVisitor = (node, st, callback) => {
3199
3389
  st.context?.pop();
3200
3390
  }
3201
3391
  };
3392
+ // A new function per evaluation of this node, so recorded under a
3393
+ // member-write policy - `EvalContext.checkMemberWrite`.
3394
+ st.createdObjects?.add(fn);
3202
3395
  pushVisitorResult(node, st, fn);
3203
3396
  afterVisitor(node, st);
3204
3397
  };
@@ -4053,8 +4246,10 @@ class EvalContext {
4053
4246
  * The write dispatches through `setContextValue` rather than through the
4054
4247
  * prototype-pollution guard's `safeSetProperty`, and the difference is not
4055
4248
  * cosmetic: {@link push} normalises a plain record into a `Registry` when
4056
- * `caseInsensitive` is set, and `Object.defineProperty` on a `Registry` would
4057
- * define a property on the instance while inserting nothing into its map. No
4249
+ * `caseInsensitive` is set, and `safeSetProperty` writes a property onto the
4250
+ * object it is given - by assignment since 0.10.0, by `Object.defineProperty`
4251
+ * before - which on a `Registry` sets a property on the instance while
4252
+ * inserting nothing into its map. No
4058
4253
  * guard is lost - this method only ever writes a key some scope already
4059
4254
  * *binds*, and a binding can only have been created through the guarded
4060
4255
  * declaration path, which rejects every blocklisted name.
@@ -5273,6 +5468,28 @@ class EvalState {
5273
5468
  isConstBinding(scope, key) {
5274
5469
  return !!this._constBindings?.get(scope)?.has(key);
5275
5470
  }
5471
+ /**
5472
+ * The objects this state's walk created for the expression to hold -
5473
+ * object, array and regex literals, rest values, arrow functions - or
5474
+ * undefined when its context does not police member writes. See
5475
+ * `EvalContext.checkMemberWrite`, whose presence is the opt-in, and
5476
+ * `EvalMemberWrite.createdByEvaluation` for what is deliberately left out.
5477
+ *
5478
+ * **Undefined is the default path, and the reason this is a field.** It is
5479
+ * decided once, in the constructor, so each recording site and the two
5480
+ * member-write branches pay one read of it and nothing else when no policy
5481
+ * is in force: no set is allocated and no object is recorded.
5482
+ *
5483
+ * Per state rather than per `evaluate` call, deliberately: an arrow-function
5484
+ * body re-enters the walk on this same state, possibly after the outer walk
5485
+ * has returned, and an object its enclosing expression created is still that
5486
+ * expression's own. A `WeakSet`, so recording an object never keeps it alive.
5487
+ *
5488
+ * @internal Not part of the published API.
5489
+ */
5490
+ get createdObjects() {
5491
+ return this._createdObjects;
5492
+ }
5276
5493
  /**
5277
5494
  * Drops every per-run record this state holds: the collected hook errors, the
5278
5495
  * open-node stack, the accumulated timings, and the walk bases bounding
@@ -5316,6 +5533,9 @@ class EvalState {
5316
5533
  this._options = options;
5317
5534
  this._isAsync = isAsync;
5318
5535
  this._hooks = adoptHooks(options);
5536
+ this._createdObjects = typeof context?.checkMemberWrite === 'function'
5537
+ ? new WeakSet()
5538
+ : undefined;
5319
5539
  // Options configure the registry this state owns, never an adopted one -
5320
5540
  // the same rule `onHookError` follows, and for the same reason: an adopted
5321
5541
  // `EvalHooks` belongs to the caller, and installing into it would leave a