-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathtransform-code.js
More file actions
256 lines (236 loc) · 6.87 KB
/
Copy pathtransform-code.js
File metadata and controls
256 lines (236 loc) · 6.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
/**
* @import {BinaryExpression, Expression, Node, TemplateElement} from '@babel/types'
* @import {NodePath} from '@babel/traverse'
*/
const evadeRegexp = /import\s*\(|<!--|-->/g;
// The replacement collection for regexp patterns matching the evadeRegexp is only applied to the first matched character, so it is necessary for the regexpReplacements to be maintained together with the evadeRegexp.
const regexpReplacements = {
i: '\\x69',
'<': '\\x3C',
'-': '\\x2D',
};
/**
* Copy the location from one AST node to another (round-tripping through JSON
* to sever references), updating the target's end position as if it had zero
* length.
*
* @param {Node} target
* @param {Node} src
*/
const adoptStartFrom = (target, src) => {
try {
const srcLoc = src.loc;
if (!srcLoc) return;
const loc = /** @type {typeof srcLoc} */ (
JSON.parse(JSON.stringify(srcLoc))
);
const start = loc?.start;
target.loc = loc;
// Text of the new node is likely shorter than text of the old (e.g.,
// "import(<url>)" -> "im"), and in such cases we don't ever want rendering
// of the new node to claim too much real estate so we future-proof by
// making it appear to be zero-width and trusting in recovery of the actual
// location immediately afterwards.
if (start) target.loc.end = /** @type {typeof start} */ ({ ...start });
} catch (_err) {
// Ignore errors; this is purely opportunistic.
}
};
/**
* Creates a BinaryExpression adding two expressions
*
* @param {Expression} left
* @param {string} rightString
* @returns {BinaryExpression}
*/
const addStringToExpressions = (left, rightString) => ({
type: 'BinaryExpression',
operator: '+',
left,
right: {
type: 'StringLiteral',
value: rightString,
},
});
/**
* Break up problematic substrings into concatenation expressions, e.g.
* `"import("` -> `"im"+"port("`.
*
* @param {NodePath} p
*/
export const evadeStrings = p => {
const { node } = p;
if (node.type !== 'StringLiteral') {
return;
}
const { value } = node;
/** @type {Expression | undefined} */
let expr;
let lastIndex = 0;
for (const match of value.matchAll(evadeRegexp)) {
const index = match.index + 2;
const part = value.substring(lastIndex, index);
expr = !expr
? { type: 'StringLiteral', value: part }
: addStringToExpressions(expr, part);
if (lastIndex === 0) adoptStartFrom(expr, p.node);
lastIndex = index;
}
if (expr) {
expr = addStringToExpressions(expr, value.substring(lastIndex));
p.replaceWith(expr);
}
};
/**
* Break up problematic substrings in template literals with empty-string
* expressions, e.g. `import(` -> `im${''}port(`.
*
* @param {NodePath} p
*/
export const evadeTemplates = p => {
const node = p.node;
// The transform is only meaning-preserving if not part of a
// TaggedTemplateExpression, so these need to be excluded until a motivating
// case shows up. It should be possible to wrap the tag with a function that
// omits expressions we insert, but that's a lot of work to do preemptively.
// https://github.com/endojs/endo/pull/3026#discussion_r2632507228
if (
node.type !== 'TemplateLiteral' ||
p.parent.type === 'TaggedTemplateExpression'
) {
return;
}
const { quasis } = node;
// Check if any quasi needs transformation
if (!quasis.some(quasi => quasi.value.raw.search(evadeRegexp) !== -1)) return;
/** @type {TemplateElement[]} */
const newQuasis = [];
/** @type {Expression[]} */
const newExpressions = [];
/**
* @param {string} quasiValue
*/
const addQuasi = quasiValue => {
// Insert empty expression to break the pattern
newExpressions.push({
type: 'StringLiteral',
value: '',
});
// Add chunk from lastIndex to nextSplitIndex
newQuasis.push({
type: 'TemplateElement',
value: {
raw: quasiValue,
cooked: quasiValue,
},
tail: false,
});
};
// eslint-disable-next-line @endo/restrict-comparison-operands
for (let i = 0; i < quasis.length; i += 1) {
const quasi = quasis[i];
// We're not currently preserving raw vs. cooked literal data.
const quasiValue = quasi.value.raw;
let lastIndex = 0;
for (const match of quasiValue.matchAll(evadeRegexp)) {
const index = match.index + 2;
const raw = quasiValue.substring(lastIndex, index);
if (lastIndex === 0) {
// Literal text up to our first cut point.
newQuasis.push({
type: 'TemplateElement',
value: { raw, cooked: raw },
tail: false,
});
} else {
addQuasi(raw);
}
lastIndex = index;
}
if (lastIndex !== 0) {
addQuasi(quasiValue.substring(lastIndex));
} else {
newQuasis.push(quasi);
}
// Add original expression between quasis
// eslint-disable-next-line @endo/restrict-comparison-operands
if (i < node.expressions.length) {
// @ts-ignore whatever was there, must still be allowed.
newExpressions.push(node.expressions[i]);
}
}
// Mark last quasi as tail
if (newQuasis.length > 0) {
newQuasis[newQuasis.length - 1].tail = true;
}
/** @type {Node} */
const replacement = {
type: 'TemplateLiteral',
quasis: newQuasis,
expressions: newExpressions,
};
adoptStartFrom(replacement, p.node);
p.replaceWith(replacement);
};
/**
* Transforms RegExp literals containing "import" to use a character class
* to break the pattern detection.
*
* `/import(/` -> `/im[p]ort(/`
*
* @param {NodePath} p
* @returns {void}
*/
export const evadeRegexpLiteral = p => {
const { node } = p;
if (node.type !== 'RegExpLiteral') {
return;
}
const { pattern } = node;
if (pattern.search(evadeRegexp) !== -1) {
node.pattern = pattern.replace(
evadeRegexp,
s => regexpReplacements[s[0]] + s.substring(1),
);
}
};
/**
* Prevents `-->` from appearing in output by transforming
* `x-->y` to `(0,x--)>y`.
*
* @param {NodePath} p
* @returns {void}
*/
export const evadeDecrementGreater = p => {
const { node } = p;
if (
node.type === 'BinaryExpression' &&
node.operator === '>' &&
node.left.type === 'UpdateExpression' &&
node.left.operator === '--' &&
!node.left.prefix
) {
// Wrap the UpdateExpression in a SequenceExpression: (0, x--)
node.left = {
type: 'SequenceExpression',
expressions: [{ type: 'NumericLiteral', value: 0 }, node.left],
};
}
};
const EVADE_METHODS = ['import', 'eval'];
/**
* @param {NodePath} p
*/
export const evadeMethod = p => {
// find class and object definitions with a method name we need to evade.
// E.g. import() -> `['import']()`
const isMethod = p.isObjectMethod() || p.isClassMethod();
if (
isMethod &&
p.node.key.type === 'Identifier' &&
EVADE_METHODS.includes(p.node.key.name)
) {
p.node.computed = true;
p.node.key = { type: 'StringLiteral', value: p.node.key.name };
}
};