@zvenigora/ng-eval-core 0.15.0 → 0.16.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.
@@ -750,10 +750,11 @@ const afterVisitor = (node, st) => {
750
750
  */
751
751
  // Direct, not through the `classes/eval` barrel. `instanceof` needs the class
752
752
  // itself and not its type, and this module is imported by most visitors, so
753
- // the narrowest edge is the right one. Nothing here reads the binding at
754
- // module scope - only inside {@link safeSetProperty} - so the import cycle
755
- // the barrels already carry (`eval-scope.ts` imports the visitors barrel) is
756
- // not deepened into an initialisation order.
753
+ // the narrowest edge is the right one. Nothing here reads either binding at
754
+ // module scope - only inside {@link refuseContextWrite} and
755
+ // {@link safeSetProperty} - so the import cycle the barrels already carry
756
+ // (`eval-scope.ts` imports the visitors barrel) is not deepened into an
757
+ // initialisation order.
757
758
  /**
758
759
  * Set of property names that are dangerous for prototype pollution attacks
759
760
  */
@@ -958,6 +959,18 @@ const safeSetProperty = (target, key, value) => {
958
959
  throw new Error(`Cannot set property on non-object: ${typeof target}`);
959
960
  }
960
961
  refuseContextWrite(target);
962
+ // A scope a host placed in the context as a value is read only through its
963
+ // `get`, so a property written on the instance is never read back, and it
964
+ // could replace the scope's own fields (`docs/backlog-retired.md` A51). By
965
+ // class, so a subclass is refused too. Refused here, after the right side
966
+ // and after a write policy has been asked, as JavaScript refuses a write the
967
+ // object does not accept: a refusal earlier would run ahead of a policy such
968
+ // as a signal context's, whose own error bypasses `onError`
969
+ // (`docs/a48/plan.md`, P-1). The object a namespaced scope holds, `ns.n`, is
970
+ // not a scope, and is written as any object is.
971
+ if (target instanceof EvalScope) {
972
+ throw new Error(`Write to an evaluation scope is blocked`);
973
+ }
961
974
  if (isDangerousProperty(key)) {
962
975
  throw new Error(`Access to dangerous property "${String(key)}" is blocked for security reasons`);
963
976
  }
@@ -1001,10 +1014,11 @@ const safeSetProperty = (target, key, value) => {
1001
1014
  }
1002
1015
  };
1003
1016
  /**
1004
- * Safely gets a property from an object with prototype pollution protection
1017
+ * Safely gets a property from an object with prototype pollution protection.
1018
+ * A getter's or a proxy trap's throw propagates, as in JavaScript.
1005
1019
  * @param target The target object
1006
1020
  * @param key The property key
1007
- * @returns The property value or undefined
1021
+ * @returns The property value, or undefined for a target that is not an object
1008
1022
  */
1009
1023
  const safeGetProperty = (target, key) => {
1010
1024
  if (!target || (typeof target !== 'object' && typeof target !== 'function')) {
@@ -1022,14 +1036,9 @@ const safeGetProperty = (target, key) => {
1022
1036
  // For other types, try to convert to string
1023
1037
  propertyKey = String(key);
1024
1038
  }
1025
- // Direct property access using bracket notation (safer than complex prototype walking)
1026
- try {
1027
- return target[propertyKey];
1028
- }
1029
- catch {
1030
- // If property access fails, return undefined
1031
- return undefined;
1032
- }
1039
+ // A getter's or a proxy trap's throw propagates, as it does in JavaScript
1040
+ // (`docs/backlog-retired.md` A55).
1041
+ return target[propertyKey];
1033
1042
  };
1034
1043
  /**
1035
1044
  * Creates a safe object without dangerous prototype pollution vectors
@@ -1174,10 +1183,10 @@ let entriesCreated = 0;
1174
1183
  *
1175
1184
  * A key found before is still the answer while it is still an own key of the
1176
1185
  * object, which is checked without a scan. One deleted or renamed since is
1177
- * scanned for again. A miss stays a miss while the object's own-key count is
1178
- * unchanged; a key added since changes the count, and the object's answers
1179
- * are made afresh. Not caught: a key added in the same interval as another is
1180
- * deleted, which leaves the count as it was, so a cached miss can outlive it.
1186
+ * scanned for again. A miss stays a miss while the object's own names are the
1187
+ * ones it was made from, in order; any difference, a key added in the same
1188
+ * interval as another is deleted included, and the object's answers are made
1189
+ * afresh (`docs/backlog-retired.md` A33).
1181
1190
  */
1182
1191
  function getCachedCaseInsensitiveProperty(obj, searchKey, equalIgnoreCase) {
1183
1192
  if (!obj || typeof obj !== 'object') {
@@ -1190,8 +1199,8 @@ function getCachedCaseInsensitiveProperty(obj, searchKey, equalIgnoreCase) {
1190
1199
  return cached;
1191
1200
  }
1192
1201
  const ownKeys = Object.getOwnPropertyNames(obj);
1193
- if (!entry || entry.keyCount !== ownKeys.length) {
1194
- entry = { keyCount: ownKeys.length, found: new Map() };
1202
+ if (!entry || !sameNames(entry.keys, ownKeys)) {
1203
+ entry = { keys: ownKeys, found: new Map() };
1195
1204
  propertyLookupCache.set(obj, entry);
1196
1205
  entriesCreated++;
1197
1206
  }
@@ -1202,6 +1211,17 @@ function getCachedCaseInsensitiveProperty(obj, searchKey, equalIgnoreCase) {
1202
1211
  entry.found.set(lowered, foundKey);
1203
1212
  return foundKey;
1204
1213
  }
1214
+ const sameNames = (a, b) => {
1215
+ if (a.length !== b.length) {
1216
+ return false;
1217
+ }
1218
+ for (let i = 0; i < a.length; i++) {
1219
+ if (a[i] !== b[i]) {
1220
+ return false;
1221
+ }
1222
+ }
1223
+ return true;
1224
+ };
1205
1225
  /**
1206
1226
  * Clears the property lookup cache (for testing or memory management)
1207
1227
  */
@@ -1210,8 +1230,9 @@ function clearPropertyLookupCache() {
1210
1230
  entriesCreated = 0;
1211
1231
  }
1212
1232
  /**
1213
- * Gets current property lookup cache statistics: the number of objects given
1214
- * an entry since the last clear, live or collected.
1233
+ * Gets current property lookup cache statistics: the number of entries made
1234
+ * since the last clear, live or collected; an object gets a new one when a
1235
+ * lookup that is not a cached hit finds its own names changed.
1215
1236
  */
1216
1237
  function getPropertyLookupCacheStats() {
1217
1238
  return {
@@ -1462,10 +1483,15 @@ const evaluateMember = (node, st, callback) => {
1462
1483
  }
1463
1484
  // If cache miss or not found in own properties, check if the original key exists (including prototype methods)
1464
1485
  if (cachedFoundKey === undefined || !foundKey) {
1486
+ // The `catch` swallows a throw from a trap JavaScript's `x.k` does
1487
+ // not call, a `has` on the chain or the prototype's `ownKeys`, and
1488
+ // leaves the key as spelled, as `resolveMemberTarget`'s does; the
1489
+ // read below is the one JavaScript makes, and its throw propagates
1490
+ // (`docs/a48/plan.md` § 8 q1).
1465
1491
  try {
1466
- // Test if property exists in prototype chain (this includes native methods like array.find)
1467
- const testValue = obj[key];
1468
- if (testValue !== undefined) {
1492
+ // The key as spelled, anywhere on the chain, tested with `in` as the
1493
+ // `=` resolver tests it, so no getter runs here (`docs/backlog-retired.md` A48)
1494
+ if (key in obj) {
1469
1495
  foundKey = key;
1470
1496
  }
1471
1497
  else {
@@ -1541,15 +1567,23 @@ const evaluateMember = (node, st, callback) => {
1541
1567
  * `null` and `undefined` included, the full blocklist.
1542
1568
  *
1543
1569
  * Under `caseInsensitive` a string key on an object is matched as the read
1544
- * matches it, the own-key cache and then the prototype's own names, but tested
1545
- * with `in` where the read tests `obj[key]`, so no getter is called
1546
- * (`docs/backlog.md` A44). The match is checked against the blocklist, as the
1570
+ * matches it, the own-key cache, then the key tested with `in`, then the
1571
+ * prototype's own names, so no getter is called (`docs/backlog.md` A44;
1572
+ * the read's test, `docs/backlog-retired.md` A48). The match is checked against the blocklist, as the
1547
1573
  * read's `foundKey` is. Any other object takes the key as spelled, as on the
1548
1574
  * read path.
1549
1575
  *
1550
- * The context branch still calls `getThis`, which reads the value it tests
1551
- * (`docs/backlog.md` A49), and under `caseInsensitive` answers the `Registry`
1552
- * copy (A50). An `EvalScope` is written as an object (A51).
1576
+ * The context branch still calls `getThis`, which reads the value it tests,
1577
+ * so a getter there runs where JavaScript reads nothing; how many times is not
1578
+ * part of the contract (`docs/backlog-retired.md` A49). When it answers the
1579
+ * context's original and that is a `Registry`, the `caseInsensitive` copy or a
1580
+ * host's, {@link writeMemberTarget} writes it through its map
1581
+ * (`docs/backlog-retired.md` A50). An `EvalScope` is refused, by
1582
+ * `safeSetProperty` (`docs/backlog-retired.md` A51).
1583
+ *
1584
+ * The third slot is the receiver's origin, as `evaluateMember`'s fourth is:
1585
+ * true when the context branch chose it, so that a `Registry` the host holds
1586
+ * in its own data, even the original itself, is written as any object is.
1553
1587
  */
1554
1588
  const resolveMemberTarget = (node, st, callback) => {
1555
1589
  markThisPositional(node.object, !!st.options?.caseInsensitive);
@@ -1579,13 +1613,13 @@ const resolveMemberTarget = (node, st, callback) => {
1579
1613
  throw new Error(`Access to dangerous property "${String(contextKey)}" is blocked for security reasons`);
1580
1614
  }
1581
1615
  }
1582
- return [st.context.getThis(contextKey) ?? object, contextKey];
1616
+ return [st.context.getThis(contextKey) ?? object, contextKey, true];
1583
1617
  }
1584
1618
  else if (object instanceof EvalScope) {
1585
1619
  if (isDangerousProperty(key)) {
1586
1620
  throw new Error(`Access to dangerous property "${String(key)}" is blocked for security reasons`);
1587
1621
  }
1588
- return [object, key];
1622
+ return [object, key, false];
1589
1623
  }
1590
1624
  const isPrimitive = (typeof object === 'string' || typeof object === 'number' || typeof object === 'boolean');
1591
1625
  if (isPrimitive ? isDangerousPrimitiveProperty(key) : isDangerousProperty(key)) {
@@ -1595,9 +1629,9 @@ const resolveMemberTarget = (node, st, callback) => {
1595
1629
  const target = object;
1596
1630
  let foundKey = getCachedCaseInsensitiveProperty(target, key, (a, b) => equalIgnoreCase(a, b) === true);
1597
1631
  if (!foundKey) {
1598
- // As the read path's `obj[key]` test, a lookup that throws leaves the
1599
- // key as spelled. A proxy's `has` trap is called here, which
1600
- // JavaScript's `=` does not call.
1632
+ // As the read path's `in` test, a lookup that throws leaves the key as
1633
+ // spelled. A proxy's `has` trap is called here, which JavaScript's `=`
1634
+ // does not call.
1601
1635
  try {
1602
1636
  if (key in target) {
1603
1637
  foundKey = key;
@@ -1616,9 +1650,37 @@ const resolveMemberTarget = (node, st, callback) => {
1616
1650
  if (foundKey && isDangerousProperty(foundKey)) {
1617
1651
  throw new Error(`Access to dangerous property "${foundKey}" is blocked for security reasons`);
1618
1652
  }
1619
- return [object, foundKey || key];
1653
+ return [object, foundKey || key, false];
1620
1654
  }
1621
- return [object, key];
1655
+ return [object, key, false];
1656
+ };
1657
+ /**
1658
+ * Writes `value` to `key` of a member target. The context's original, when it
1659
+ * is a `Registry` - a host's, or the `caseInsensitive` copy of a plain
1660
+ * context - and the context branch chose it (`fromContext`), is written through
1661
+ * its map, as `k = v` writes it: that path reads it through `get`, so a property
1662
+ * on the instance is never read back (`docs/backlog-retired.md` A50). Anything
1663
+ * else is `safeSetProperty`'s, a `Registry` reached as a value included, even
1664
+ * the original, which the host may hold in its own data: that path reads it as
1665
+ * an object, so it is written as one, consistent with itself as before.
1666
+ *
1667
+ * That branch bypasses `safeSetProperty`, so it refuses a blocked name itself,
1668
+ * with the same message. It stands behind the callers' own refusals: for `=`
1669
+ * and the compound and logical operators `resolveMemberTarget` refuses a
1670
+ * blocked key, and its `caseInsensitive` resolution, before the right side
1671
+ * runs, and for an update the read in `evaluateMember` refuses it.
1672
+ */
1673
+ const writeMemberTarget = (st, object, key, value, fromContext) => {
1674
+ // The origin and the identity first: `instanceof` calls a proxy's
1675
+ // `getPrototypeOf` trap.
1676
+ if (fromContext && object === st.context?.original && object instanceof Registry) {
1677
+ if (isDangerousProperty(key)) {
1678
+ throw new Error(`Access to dangerous property "${String(key)}" is blocked for security reasons`);
1679
+ }
1680
+ object.set(key, value);
1681
+ return;
1682
+ }
1683
+ safeSetProperty(object, key, value);
1622
1684
  };
1623
1685
 
1624
1686
  const arrayExpressionVisitor = (node, st, callback) => {
@@ -1913,7 +1975,7 @@ const recordCreated = (created, value) => {
1913
1975
  * here unchanged: nothing has been written yet.
1914
1976
  *
1915
1977
  * Called by the member branches of `assignment-expression.ts` and
1916
- * `update-expression.ts`, immediately before `safeSetProperty`, and only after
1978
+ * `update-expression.ts`, immediately before `writeMemberTarget`, and only after
1917
1979
  * the caller has read `st.createdObjects` and found it set. That read is the
1918
1980
  * whole of the default path's cost: a state whose context has no policy holds
1919
1981
  * no set, so neither visitor reaches this call.
@@ -2023,9 +2085,10 @@ const WRITE_SITES = (() => {
2023
2085
  * the other half of `refuseContextWrite` (`docs/a35/plan.md` Revision 16,
2024
2086
  * item 2's enumeration).
2025
2087
  *
2026
- * `safeSetProperty` covers every write an expression makes through the
2027
- * evaluator: dotted and computed member assignment, compound assignment and
2028
- * the update expressions. It does not cover a write made by **native code**
2088
+ * `writeMemberTarget`, and the `safeSetProperty` it falls to, cover every
2089
+ * write an expression makes through the evaluator: dotted and computed member
2090
+ * assignment, compound assignment and the update expressions. They do not
2091
+ * cover a write made by **native code**
2029
2092
  * the expression merely calls - `Object.assign(c, { push: f })`,
2030
2093
  * `Object.defineProperty`, `Reflect.set`, `Object.setPrototypeOf`,
2031
2094
  * `Object.freeze`, and each of them reached through `call`, `apply` or
@@ -2464,7 +2527,7 @@ const callMember = (st, [object, propertyName, fn, contextResolved], args, optio
2464
2527
  // not the caller's to write (`member-write-policy.ts`). After the
2465
2528
  // consultation and not before, so a policy still sees the write it would
2466
2529
  // have seen and its own refusal is still the one that surfaces - the same
2467
- // order the member-write path has, where `safeSetProperty` refuses after
2530
+ // order the member-write path has, where `writeMemberTarget` refuses after
2468
2531
  // `consultMemberWrite` has been asked.
2469
2532
  refuseContextMethodWrite(fn, receiver, args);
2470
2533
  // A receiver the evaluator resolved out of the context's own chain is
@@ -4308,6 +4371,7 @@ const assignmentExpressionVisitor = (node, st, callback) => {
4308
4371
  let left;
4309
4372
  let targetObject;
4310
4373
  let targetKey;
4374
+ let targetFromContext = false;
4311
4375
  if (target.type === 'Identifier') {
4312
4376
  if (plain) {
4313
4377
  refuseIdentifierTarget(target, st);
@@ -4317,12 +4381,13 @@ const assignmentExpressionVisitor = (node, st, callback) => {
4317
4381
  }
4318
4382
  }
4319
4383
  else if (plain) {
4320
- [targetObject, targetKey] = resolveMemberTarget(target, st, callback);
4384
+ [targetObject, targetKey, targetFromContext] = resolveMemberTarget(target, st, callback);
4321
4385
  }
4322
4386
  else {
4323
- const [object, , value, , key] = evaluateMember(target, st, callback);
4387
+ const [object, , value, fromContext, key] = evaluateMember(target, st, callback);
4324
4388
  targetObject = object;
4325
4389
  targetKey = key;
4390
+ targetFromContext = fromContext === true;
4326
4391
  left = value;
4327
4392
  }
4328
4393
  if (!plain) {
@@ -4375,8 +4440,10 @@ const assignmentExpressionVisitor = (node, st, callback) => {
4375
4440
  if (created) {
4376
4441
  consultMemberWrite(st, created, object, key);
4377
4442
  }
4378
- // Use safe property assignment to prevent prototype pollution
4379
- safeSetProperty(object, key, value);
4443
+ // A `Registry` that is the context's original, reached through the
4444
+ // context, through its map; anything else through `safeSetProperty`; each
4445
+ // refusing a blocked name.
4446
+ writeMemberTarget(st, object, key, value, targetFromContext);
4380
4447
  pushVisitorResult(node, st, value);
4381
4448
  }
4382
4449
  afterVisitor(node, st);
@@ -4422,7 +4489,7 @@ const updateExpressionVisitor = (node, st, callback) => {
4422
4489
  }
4423
4490
  else if (target.type === 'MemberExpression') {
4424
4491
  // The write reaches the key the lookup matched (`docs/backlog.md` A44).
4425
- const [object, , value, , property] = evaluateMember(target, st, callback);
4492
+ const [object, , value, fromContext, property] = evaluateMember(target, st, callback);
4426
4493
  // As in the identifier branch: one native conversion, before the write.
4427
4494
  let updated = value;
4428
4495
  const old = node.operator === '++' ? updated++ : updated--;
@@ -4431,8 +4498,10 @@ const updateExpressionVisitor = (node, st, callback) => {
4431
4498
  if (created) {
4432
4499
  consultMemberWrite(st, created, object, property);
4433
4500
  }
4434
- // Use safe property assignment to prevent prototype pollution
4435
- safeSetProperty(object, property, updated);
4501
+ // A `Registry` that is the context's original, reached through the
4502
+ // context, through its map; anything else through `safeSetProperty`; each
4503
+ // refusing a blocked name.
4504
+ writeMemberTarget(st, object, property, updated, fromContext === true);
4436
4505
  pushVisitorResult(node, st, node.prefix ? updated : old);
4437
4506
  }
4438
4507
  else {
@@ -5377,6 +5446,12 @@ class EvalContext {
5377
5446
  }
5378
5447
  /**
5379
5448
  * Gets the lookups registry.
5449
+ *
5450
+ * A lookup is called while a name is resolved, and how many times an
5451
+ * expression calls it is not part of the contract
5452
+ * (`docs/backlog-retired.md` A49): it can be called where JavaScript would
5453
+ * read nothing, as under `caseInsensitive` by `x = 1`, or more than once for
5454
+ * one read, and a registered read hook can add a call.
5380
5455
  */
5381
5456
  get lookups() {
5382
5457
  return this._lookups;
@@ -5539,9 +5614,18 @@ class EvalContext {
5539
5614
  * not an object that holds the key.
5540
5615
  *
5541
5616
  * Undefined means "no receiver of its own", and the member visitor then falls
5542
- * back to the object it was evaluating. Up to 0.6.x the prior-scope step
5543
- * re-tested the original context and could never answer, and the lookup step
5544
- * returned the lookup function itself (`docs/backlog-retired.md` A7).
5617
+ * back to the object it was evaluating.
5618
+ *
5619
+ * It decides by reading the value, through the original or a prior scope's
5620
+ * `get`, so a getter there runs where JavaScript reads nothing; how many
5621
+ * times an expression calls it is not part of the contract
5622
+ * (`docs/backlog-retired.md` A49). Case-sensitively, with a getter `g` on the
5623
+ * context, `this.g = 1` calls it once and `this.g += 1` twice, with or
5624
+ * without a read hook.
5625
+ *
5626
+ * Up to 0.6.x the prior-scope step re-tested the original context and could
5627
+ * never answer, and the lookup step returned the lookup function itself
5628
+ * (`docs/backlog-retired.md` A7).
5545
5629
  * @param key - The key to retrieve the value for.
5546
5630
  * @returns The `this` value associated with the key, or undefined.
5547
5631
  */
@@ -7015,6 +7099,15 @@ class EvalState {
7015
7099
  }
7016
7100
  }
7017
7101
 
7102
+ /**
7103
+ * The options `EvalService` and `CompilerService` pass on every parse, as
7104
+ * this object itself; `ParserService` and `DiscoveryService` copy it when
7105
+ * constructed. Read it or copy it; do not write into it. A value written into
7106
+ * it is not reliably seen: the parse cache remembers it by identity, so a text
7107
+ * cached before the write can keep its reading, and one parsed while it held
7108
+ * the value can keep that reading after it is written back
7109
+ * (`docs/backlog-retired.md` A34).
7110
+ */
7018
7111
  const defaultParserOptions = {
7019
7112
  ...defaultOptions,
7020
7113
  ecmaVersion: 2020,
@@ -7562,7 +7655,7 @@ const buildParseFingerprint = (options) => {
7562
7655
  * object the `parserOptions` getter returns, an options object a caller passes
7563
7656
  * again after writing into it, or the exported `defaultParserOptions`. A change
7564
7657
  * through the `parserOptions` setter installs a new object, and is seen
7565
- * (`docs/backlog.md` A34).
7658
+ * (`docs/backlog-retired.md` A34).
7566
7659
  */
7567
7660
  const parseFingerprint = (memo, serviceOptions, callOptions) => {
7568
7661
  let byCall = memo.get(serviceOptions);
@@ -7648,6 +7741,15 @@ class ParserService {
7648
7741
  /**
7649
7742
  * Gets the parser options: the constructor's, or the last value given to
7650
7743
  * the setter.
7744
+ *
7745
+ * Replace the object through the setter rather than write into the one this
7746
+ * returns: a value written into it is not reliably seen. The parse cache,
7747
+ * and `CompilerService`'s cache of compiled strings, remember each pair of
7748
+ * options objects, this one and a call's, by identity, not by their values.
7749
+ * A later parse through a pair seen before the write, as `EvalService`'s and
7750
+ * `CompilerService`'s are, keeps a cached text's earlier reading and caches
7751
+ * a new text as if the options had not changed; a parse through a new
7752
+ * call-options object sees the write (`docs/backlog-retired.md` A34).
7651
7753
  */
7652
7754
  get parserOptions() {
7653
7755
  return this._parserOptions;
@@ -7743,7 +7845,10 @@ class ParserService {
7743
7845
  * @description
7744
7846
  * Parses expression and returns ES6/ES2023 AST.
7745
7847
  * @param expr expression to parse
7746
- * @param options optional parser options
7848
+ * @param options optional parser options, merged over `parserOptions`. Pass
7849
+ * a new object for new options: a value written into an object already
7850
+ * passed is not reliably seen, since the cache remembers the object by
7851
+ * identity (`docs/backlog-retired.md` A34).
7747
7852
  * @returns The parsed AST (Abstract Syntax Tree).
7748
7853
  */
7749
7854
  parse(expr, options) {
@@ -7998,7 +8103,7 @@ class CompilerService extends BaseEval {
7998
8103
  * the `ParserService.parserOptions` setter reaches a string compiled before
7999
8104
  * it (`docs/colon-identifiers/phase-9-plan.md` § 3.2). The memo is
8000
8105
  * `ParserService`'s kind, and a write in place goes unseen here as there
8001
- * (`docs/backlog.md` A34). `null` when that parse bypasses `ParserService`'s
8106
+ * (`docs/backlog-retired.md` A34). `null` when that parse bypasses `ParserService`'s
8002
8107
  * cache - a callback or a `program` among its options, or a value JSON
8003
8108
  * cannot hold - and this cache then bypasses too, since a cached function
8004
8109
  * runs no callback.