ses 2.0.0 → 2.2.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.
@@ -1,14 +1,22 @@
1
- import { Object, DataView, Reflect, Number } from './commons.js';
2
-
3
- const { is, defineProperty, entries } = Object;
4
- const { apply } = Reflect;
5
-
6
- const { prototype: dataViewPrototype } = DataView;
1
+ import {
2
+ RangeError,
3
+ dataViewPrototype,
4
+ MAX_SAFE_INTEGER,
5
+ apply,
6
+ defineProperty,
7
+ entries,
8
+ getOwnPropertyDescriptor,
9
+ hasOwn,
10
+ is,
11
+ max,
12
+ trunc,
13
+ uncurryThis,
14
+ } from './commons.js';
7
15
 
8
16
  /**
9
17
  * These `FERAL*` methods open up the NaN side-channel on some platforms,
10
18
  * like v8. Thus, we need to encapsulate them and replace them with wrappers
11
- * that canonicaize NaNs.
19
+ * that canonicalize NaNs.
12
20
  */
13
21
  const {
14
22
  setFloat16: FERAL_SET_FLOAT16,
@@ -20,61 +28,201 @@ const {
20
28
  setBigUint64,
21
29
  } = dataViewPrototype;
22
30
 
23
- // See https://webidl.spec.whatwg.org/#js-unrestricted-double which implies
24
- // that this is the canonical NaN for web standards.
25
- // Casual googling stongly suggests that this is also the cosmWasm
26
- // canonical NaN. But I have not yet found an authoritative page stating this.
27
- const canonicalNaN = 0x7ff8000000000000n;
31
+ const dataViewGetBuffer = uncurryThis(
32
+ // @ts-expect-error we know it is there on all conforming platforms
33
+ getOwnPropertyDescriptor(dataViewPrototype, 'buffer').get,
34
+ );
35
+
36
+ /**
37
+ * See https://webidl.spec.whatwg.org/#js-unrestricted-double which implies
38
+ * that this is the canonical NaN for web standards.
39
+ * Casual googling strongly suggests that this is also the cosmWasm
40
+ * canonical NaN. But I have not yet found an authoritative page stating this.
41
+ *
42
+ * As noted there, WebIDL choses this value because
43
+ * > The `NaN` value ... is chosen simply because it is the quiet NaN
44
+ * > with the lowest value when its bit pattern is interpreted as an 64-bit
45
+ * > unsigned integer.
46
+ *
47
+ * See https://github.com/endojs/endo/pull/3214#discussion_r3155852021
48
+ */
49
+ const canonicalNaN64Encoding = 0x7ff8_0000_0000_0000n;
50
+
51
+ /**
52
+ * As of this writing (April 29, 2026) all implementations agree that a
53
+ * ***literal*** `NaN` seems to encode in 32 bits as `0x7fc00000`.
54
+ * See https://github.com/endojs/endo/pull/3214#discussion_r3162974396
55
+ *
56
+ * Applying WebIDL's rationale for the 64 bit float
57
+ * > The `NaN` value ... is chosen simply because it is the quiet NaN
58
+ * > with the lowest value when its bit pattern is interpreted as an 64-bit
59
+ * > unsigned integer.
60
+ *
61
+ * to the 32 bit case agrees with the choice the implementations make
62
+ * for the 32 bit encoding of a ***literal*** `NaN`.
63
+ *
64
+ * See https://github.com/endojs/endo/pull/3214#discussion_r3155852021
65
+ */
66
+ const canonicalNaN32Encoding = 0x7fc0_0000;
67
+
68
+ /**
69
+ * As of this writing (April 29, 2026) all implementations that implement
70
+ * float16 (with the almost surely unintentional exception of QuickJS),
71
+ * agree that a ***literal*** `NaN` seems to encode in 16 bits as `0x7e00`.
72
+ * See https://github.com/endojs/endo/pull/3214#discussion_r3162974396
73
+ *
74
+ * Applying WebIDL's rationale for the 64 bit float
75
+ * > The `NaN` value ... is chosen simply because it is the quiet NaN
76
+ * > with the lowest value when its bit pattern is interpreted as an 64-bit
77
+ * > unsigned integer.
78
+ *
79
+ * to the 16 bit case agrees with the choice those implementations make
80
+ * for the 16 bit encoding of a ***literal*** `NaN`.
81
+ *
82
+ * See https://github.com/endojs/endo/pull/3214#discussion_r3155852021
83
+ */
84
+ const canonicalNaN16Encoding = 0x7e00;
85
+
86
+ /**
87
+ * Perform `RequireInternalSlot(obj, [[DataView]])` as needed in
88
+ * SetViewValue.
89
+ * https://tc39.es/ecma262/multipage/structured-data.html#sec-setviewvalue
90
+ * https://tc39.es/ecma262/#sec-get-dataview.prototype.buffer
91
+ *
92
+ * @param {unknown} obj
93
+ * @returns {void}
94
+ */
95
+ const requireDataView = obj => {
96
+ dataViewGetBuffer(obj);
97
+ };
98
+
99
+ /**
100
+ * Emulate the internal `ToIndex` from
101
+ * https://tc39.es/ecma262/multipage/abstract-operations.html#sec-toindex
102
+ *
103
+ * @param {unknown} v
104
+ * @returns {number}
105
+ */
106
+ const toIndex = v => {
107
+ // @ts-expect-error Math.trunc uses the internal `ToNumber` to coerce its
108
+ // argument, whatever it is, to an integer number.
109
+ const n = trunc(v);
110
+ if (n === 0 || is(n, NaN)) {
111
+ return 0;
112
+ }
113
+ if (n < 0 || n > MAX_SAFE_INTEGER) {
114
+ throw RangeError('Invalid offset');
115
+ }
116
+ return n;
117
+ };
118
+
119
+ /**
120
+ * Expose the internal `ToNumber` from
121
+ * https://tc39.es/ecma262/multipage/abstract-operations.html#sec-tonumber
122
+ * We can't just use `Number(value)` because that is backed by `ToNumeric`,
123
+ * which coerces bigint output from `ToPrimitive` rather than throwing a
124
+ * TypeError as required of `ToNumber` (e.g., `Number({ valueOf: () => 42n })`
125
+ * returns 42).
126
+ *
127
+ * @param {unknown} v
128
+ * @returns {number}
129
+ */
130
+ const toNumber = v =>
131
+ // @ts-expect-error Math.max uses the internal `ToNumber` to coerce its
132
+ // argument, whatever it is, to a number.
133
+ max(v);
28
134
 
29
- // Use method shorthand syntax to be this-sensitive but now be constructable
30
- // nor have a `prototype` property.
135
+ /**
136
+ * Correctly guarding the `setFloat*` built-ins requires performing
137
+ * `ToNumber(value)` ourselves, because a non-NaN value such as
138
+ * `{ valueOf: () => {} }` gets coerced **to** NaN. But, according to
139
+ * [SetViewValue](https://tc39.es/ecma262/multipage/structured-data.html#sec-setviewvalue),
140
+ * we must first perform the observable
141
+ * `RequireInternalSlot(view, [[DataView]])` and `ToIndex(requestIndex)` steps
142
+ * (in that order). If those steps complete successfully, we have number-coerced
143
+ * `byteOffset` and `value` values that will pass those same steps internal to
144
+ * the implementation without incurring further observable interactions.
145
+ *
146
+ * We added these coercions to defend against an attack noticed by
147
+ * https://github.com/deepview-autofix .
148
+ * We were vulnerable to `value` being an
149
+ * object with a `valueOf` method that returns a (bad) NaN, since it
150
+ * would bypass the is NaN check. See where the
151
+ * `tame-nan*-sidechannel.test.js test cases mention "coercion attack".
152
+ *
153
+ * Uses method shorthand syntax to be `this`-sensitive but not be constructable
154
+ * nor have a `prototype` property.
155
+ */
31
156
  const methods = {
32
157
  /**
33
158
  * @param {number} byteOffset
34
159
  * @param {number} value
35
- * @param {boolean} [littleEndian]
160
+ * @param {boolean} [isLittleEndian]
36
161
  */
37
- setFloat16(byteOffset, value, littleEndian = undefined) {
162
+ setFloat16(byteOffset, value, isLittleEndian = undefined) {
163
+ requireDataView(this);
164
+ byteOffset = toIndex(byteOffset);
165
+ value = toNumber(value);
38
166
  if (is(value, NaN)) {
39
167
  return apply(setUint16, this, [
40
168
  byteOffset,
41
- Number(canonicalNaN),
42
- littleEndian,
169
+ canonicalNaN16Encoding,
170
+ isLittleEndian,
43
171
  ]);
44
172
  } else {
45
- return apply(FERAL_SET_FLOAT16, this, [byteOffset, value, littleEndian]);
173
+ return apply(FERAL_SET_FLOAT16, this, [
174
+ byteOffset,
175
+ value,
176
+ isLittleEndian,
177
+ ]);
46
178
  }
47
179
  },
180
+
48
181
  /**
49
182
  * @param {number} byteOffset
50
183
  * @param {number} value
51
- * @param {boolean} [littleEndian]
184
+ * @param {boolean} [isLittleEndian]
52
185
  */
53
- setFloat32(byteOffset, value, littleEndian = undefined) {
186
+ setFloat32(byteOffset, value, isLittleEndian = undefined) {
187
+ requireDataView(this);
188
+ byteOffset = toIndex(byteOffset);
189
+ value = toNumber(value);
54
190
  if (is(value, NaN)) {
55
191
  return apply(setUint32, this, [
56
192
  byteOffset,
57
- Number(canonicalNaN),
58
- littleEndian,
193
+ canonicalNaN32Encoding,
194
+ isLittleEndian,
59
195
  ]);
60
196
  } else {
61
- return apply(FERAL_SET_FLOAT32, this, [byteOffset, value, littleEndian]);
197
+ return apply(FERAL_SET_FLOAT32, this, [
198
+ byteOffset,
199
+ value,
200
+ isLittleEndian,
201
+ ]);
62
202
  }
63
203
  },
204
+
64
205
  /**
65
206
  * @param {number} byteOffset
66
207
  * @param {number} value
67
- * @param {boolean} [littleEndian]
208
+ * @param {boolean} [isLittleEndian]
68
209
  */
69
- setFloat64(byteOffset, value, littleEndian = undefined) {
210
+ setFloat64(byteOffset, value, isLittleEndian = undefined) {
211
+ requireDataView(this);
212
+ byteOffset = toIndex(byteOffset);
213
+ value = toNumber(value);
70
214
  if (is(value, NaN)) {
71
215
  return apply(setBigUint64, this, [
72
216
  byteOffset,
73
- canonicalNaN,
74
- littleEndian,
217
+ canonicalNaN64Encoding,
218
+ isLittleEndian,
75
219
  ]);
76
220
  } else {
77
- return apply(FERAL_SET_FLOAT64, this, [byteOffset, value, littleEndian]);
221
+ return apply(FERAL_SET_FLOAT64, this, [
222
+ byteOffset,
223
+ value,
224
+ isLittleEndian,
225
+ ]);
78
226
  }
79
227
  },
80
228
  };
@@ -94,10 +242,12 @@ const methods = {
94
242
  */
95
243
  export const tameNaNSideChannel = () => {
96
244
  for (const [name, method] of entries(methods)) {
97
- defineProperty(dataViewPrototype, name, {
98
- // Since we're redefining properties that already exist, by omitting the
99
- // other descriptor attributes here, they are unchanged.
100
- value: method,
101
- });
245
+ if (hasOwn(dataViewPrototype, name)) {
246
+ defineProperty(dataViewPrototype, name, {
247
+ // Since we're redefining properties that already exist, by omitting the
248
+ // other descriptor attributes here, they are unchanged.
249
+ value: method,
250
+ });
251
+ }
102
252
  }
103
253
  };
@@ -0,0 +1,75 @@
1
+ import {
2
+ freeze,
3
+ getOwnPropertyDescriptors,
4
+ create,
5
+ objectPrototype,
6
+ getPrototypeOf,
7
+ ownKeys,
8
+ fromEntries,
9
+ TypeError,
10
+ arrayPush,
11
+ Temporal, // may be undefined on old JS engines
12
+ } from './commons.js';
13
+
14
+ import { permitted } from './permits.js';
15
+
16
+ /**
17
+ * Tame the `Temporal` namespace object.
18
+ *
19
+ * The `%InitialTemporal%` is indeed the original `Temporal` namespace
20
+ * object, to remain present on the start compartment.
21
+ *
22
+ * The `%SharedTemporal%` is the safe shared `Temporal` namespace object,
23
+ * to be endowed by default on the gloabl of all constructed compartments.
24
+ * This differs only by the omission of `Temporal.Now`, which is the source of
25
+ * the dynamic non-determinism of the ever-changing current time, and the
26
+ * glacial dynamic non-determinism of current timezone and UTC offset (daylight
27
+ * savings time).
28
+ *
29
+ * The remaining source of glacial dynamic non-determinism is locale
30
+ * sensitivity, which `Temporal` provides only via `toLocaleString` methods.
31
+ * This is handled by `tame-locale-methods.js` in the same way as all other
32
+ * `*Locale*` methods.
33
+ *
34
+ * `tameTemporalObject` is modeletd on `tameMathObject` and `tameDateConstructor`
35
+ */
36
+ const tameTemporalObject = () => {
37
+ if (Temporal === undefined) {
38
+ return {};
39
+ }
40
+
41
+ if (typeof Temporal !== 'object') {
42
+ throw new TypeError(`unexpected typeof Temporal: ${typeof Temporal}`);
43
+ }
44
+ if (getPrototypeOf(Temporal) !== objectPrototype) {
45
+ throw new TypeError(
46
+ `unexpected Temporal __proto__: ${getPrototypeOf(Temporal)}`,
47
+ );
48
+ }
49
+
50
+ const initialTemporal = Temporal;
51
+ const { Now: _, ...otherDescriptors } =
52
+ getOwnPropertyDescriptors(initialTemporal);
53
+ const sharedTemporal = create(objectPrototype, otherDescriptors);
54
+
55
+ const initialTemporalPermit = permitted['%InitialTemporal%'];
56
+ const intrinsicEntries = [];
57
+ for (const topName of ownKeys(Temporal)) {
58
+ const topPermitName = initialTemporalPermit[topName];
59
+ const topPermit = permitted[topPermitName];
60
+ if (typeof topPermit === 'object') {
61
+ const topVal = initialTemporal[topName];
62
+ arrayPush(intrinsicEntries, [topPermitName, topVal]);
63
+ }
64
+ }
65
+
66
+ const result = {
67
+ ...fromEntries(intrinsicEntries),
68
+ '%InitialTemporal%': initialTemporal,
69
+ '%SharedTemporal%': sharedTemporal,
70
+ };
71
+ return result;
72
+ };
73
+ freeze(tameTemporalObject);
74
+
75
+ export default tameTemporalObject;
package/src/transforms.js CHANGED
@@ -3,9 +3,10 @@
3
3
  import {
4
4
  FERAL_REG_EXP,
5
5
  SyntaxError,
6
+ freezeRegexp,
6
7
  regexpReplace,
8
+ regexpSearch,
7
9
  sealRegexp,
8
- stringSearch,
9
10
  stringSlice,
10
11
  stringSplit,
11
12
  freeze,
@@ -21,7 +22,7 @@ import { getSourceURL } from './get-source-url.js';
21
22
  * @returns {number}
22
23
  */
23
24
  function getLineNumber(src, pattern) {
24
- const index = stringSearch(src, pattern);
25
+ const index = regexpSearch(pattern, src);
25
26
  if (index < 0) {
26
27
  return -1;
27
28
  }
@@ -177,9 +178,8 @@ export const evadeImportExpressionTest = src => {
177
178
 
178
179
  // /////////////////////////////////////////////////////////////////////////////
179
180
 
180
- const someDirectEvalPattern = new FERAL_REG_EXP(
181
- '(^|[^.])\\beval(\\s*\\()',
182
- 'g',
181
+ const someDirectEvalPattern = freezeRegexp(
182
+ new FERAL_REG_EXP('(^|[^.])\\beval(\\s*\\()'),
183
183
  );
184
184
 
185
185
  /**
@@ -0,0 +1,29 @@
1
+ /**
2
+ * @module In the spirit of ../src/commons.js, this module captures native
3
+ * functions specific to the XS engine during initialization, so vetted shims
4
+ * are free to modify any intrinsic without risking the integrity of SES.
5
+ */
6
+
7
+ /// <reference types="ses"/>
8
+
9
+ import {
10
+ getOwnPropertyDescriptor,
11
+ globalThis,
12
+ uncurryThis,
13
+ } from '../src/commons.js';
14
+
15
+ /** @type {typeof Compartment} */
16
+ export const NativeStartCompartment = /** @type {any} */ (globalThis)
17
+ .Compartment;
18
+ export const nativeCompartmentPrototype = NativeStartCompartment.prototype;
19
+ export const nativeImport = uncurryThis(nativeCompartmentPrototype.import);
20
+ export const nativeImportNow = uncurryThis(
21
+ nativeCompartmentPrototype.importNow,
22
+ );
23
+ /** @type {(compartment: any, source: string) => unknown} */
24
+ export const nativeEvaluate = uncurryThis(nativeCompartmentPrototype.evaluate);
25
+ /** @type {(compartment: typeof Compartment) => typeof globalThis} */
26
+ export const nativeGetGlobalThis = uncurryThis(
27
+ // @ts-expect-error we know it is there on XS
28
+ getOwnPropertyDescriptor(nativeCompartmentPrototype, 'globalThis').get,
29
+ );
@@ -0,0 +1,134 @@
1
+ /**
2
+ * @module Provides a XS-specific variation on the behavior of
3
+ * ../compartment-shim.js, completing the story that begins in
4
+ * ./compartment.js, adding a Compartment constructor adapter to the global
5
+ * scope and transforming all of the methods of a native compartment into
6
+ * thunks that will alternately delegate to its native or shim behaviors
7
+ * depending on the __native__ Compartment constructor option.
8
+ */
9
+
10
+ /// <reference types="ses"/>
11
+
12
+ import { defineProperty, globalThis, weakmapGet } from '../src/commons.js';
13
+ import {
14
+ NativeStartCompartment,
15
+ nativeCompartmentPrototype,
16
+ nativeImport,
17
+ nativeImportNow,
18
+ nativeEvaluate,
19
+ nativeGetGlobalThis,
20
+ } from './commons.js';
21
+ import {
22
+ ShimStartCompartment,
23
+ adaptCompartmentConstructors,
24
+ privateFields,
25
+ shimEvaluate,
26
+ shimGetGlobalThis,
27
+ shimImport,
28
+ shimImportNow,
29
+ } from './compartment.js';
30
+
31
+ const adapterFunctions = {
32
+ evaluate(source, options) {
33
+ const fields = weakmapGet(privateFields, this);
34
+ if (fields === undefined) {
35
+ return nativeEvaluate(this, source);
36
+ }
37
+ const { delegateNative } = fields;
38
+ if (delegateNative) {
39
+ const { transforms, nativeEval } = fields;
40
+ for (let i = 0; i < transforms.length; i += 1) {
41
+ const transform = transforms[i];
42
+ source = transform(source);
43
+ }
44
+ return nativeEval(source);
45
+ } else {
46
+ return shimEvaluate(this, source, options);
47
+ }
48
+ },
49
+
50
+ async import(specifier) {
51
+ await null;
52
+ const fields = weakmapGet(privateFields, this);
53
+ if (fields === undefined) {
54
+ return nativeImport(this, specifier);
55
+ }
56
+ const { noNamespaceBox, delegateNative } = fields;
57
+ const delegateImport = delegateNative ? nativeImport : shimImport;
58
+ const namespace = delegateImport(this, specifier);
59
+ return noNamespaceBox ? namespace : { namespace: await namespace };
60
+ },
61
+
62
+ importNow(specifier) {
63
+ const fields = weakmapGet(privateFields, this);
64
+ if (fields === undefined) {
65
+ return nativeImportNow(this, specifier);
66
+ }
67
+ const { delegateNative } = fields;
68
+ const delegateImportNow = delegateNative ? nativeImportNow : shimImportNow;
69
+ return delegateImportNow(this, specifier);
70
+ },
71
+ };
72
+
73
+ defineProperty(nativeCompartmentPrototype, 'evaluate', {
74
+ value: adapterFunctions.evaluate,
75
+ writable: true,
76
+ configurable: true,
77
+ enumerable: false,
78
+ });
79
+
80
+ defineProperty(nativeCompartmentPrototype, 'import', {
81
+ value: adapterFunctions.import,
82
+ writable: true,
83
+ configurable: true,
84
+ enumerable: false,
85
+ });
86
+
87
+ defineProperty(nativeCompartmentPrototype, 'importNow', {
88
+ value: adapterFunctions.importNow,
89
+ writable: true,
90
+ configurable: true,
91
+ enumerable: false,
92
+ });
93
+
94
+ defineProperty(nativeCompartmentPrototype, 'globalThis', {
95
+ get() {
96
+ const fields = weakmapGet(privateFields, this);
97
+ if (fields === undefined) {
98
+ return nativeGetGlobalThis(this);
99
+ }
100
+ const { delegateNative } = fields;
101
+ const delegateGetGlobalThis = delegateNative
102
+ ? nativeGetGlobalThis
103
+ : shimGetGlobalThis;
104
+ return delegateGetGlobalThis(this);
105
+ },
106
+ configurable: true,
107
+ enumerable: false,
108
+ });
109
+
110
+ defineProperty(nativeCompartmentPrototype, 'name', {
111
+ get() {
112
+ const fields = weakmapGet(privateFields, this);
113
+ if (fields === undefined) {
114
+ return undefined;
115
+ }
116
+ const { name } = fields;
117
+ return name;
118
+ },
119
+ configurable: true,
120
+ enumerable: false,
121
+ });
122
+
123
+ // Adapt the start compartment's native Compartment to the SES-compatibility
124
+ // adapter.
125
+ // Before Lockdown, the Compartment constructor in transitive child
126
+ // Compartments is not (and cannot be) hardened.
127
+ const noHarden = object => object;
128
+ // @ts-expect-error TypeScript is not inferring from the types above that
129
+ // Compartment is on globalThis.
130
+ globalThis.Compartment = adaptCompartmentConstructors(
131
+ NativeStartCompartment,
132
+ ShimStartCompartment,
133
+ noHarden,
134
+ );