-
Notifications
You must be signed in to change notification settings - Fork 48.3k
/
Copy pathsafe-string-coercion.js
374 lines (349 loc) · 11.4 KB
/
safe-string-coercion.js
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
*/
'use strict';
function isEmptyLiteral(node) {
return (
node.type === 'Literal' &&
typeof node.value === 'string' &&
node.value === ''
);
}
function isStringLiteral(node) {
return (
// TaggedTemplateExpressions can return non-strings
(node.type === 'TemplateLiteral' &&
node.parent.type !== 'TaggedTemplateExpression') ||
(node.type === 'Literal' && typeof node.value === 'string')
);
}
// Symbols and Temporal.* objects will throw when using `'' + value`, but that
// pattern can be faster than `String(value)` because JS engines can optimize
// `+` better in some cases. Therefore, in perf-sensitive production codepaths
// we require using `'' + value` for string coercion. The only exception is prod
// error handling code, because it's bad to crash while assembling an error
// message or call stack! Also, error-handling code isn't usually perf-critical.
//
// Non-production codepaths (tests, devtools extension, build tools, etc.)
// should use `String(value)` because it will never crash and the (small) perf
// difference doesn't matter enough for non-prod use cases.
//
// This rule assists enforcing these guidelines:
// * `'' + value` is flagged with a message to remind developers to add a DEV
// check from shared/CheckStringCoercion.js to make sure that the user gets a
// clear error message in DEV is the coercion will throw. These checks are not
// needed if throwing is not possible, e.g. if the value is already known to
// be a string or number.
// * `String(value)` is flagged only if the `isProductionUserAppCode` option
// is set. Set this option for prod code files, and don't set it for non-prod
// files.
const ignoreKeys = [
'range',
'raw',
'parent',
'loc',
'start',
'end',
'_babelType',
'leadingComments',
'trailingComments',
];
function astReplacer(key, value) {
return ignoreKeys.includes(key) ? undefined : value;
}
/**
* Simplistic comparison between AST node. Only the following patterns are
* supported because that's almost all (all?) usage in React:
* - Identifiers, e.g. `foo`
* - Member access, e.g. `foo.bar`
* - Array access with numeric literal, e.g. `foo[0]`
*/
function isEquivalentCode(node1, node2) {
return (
JSON.stringify(node1, astReplacer) === JSON.stringify(node2, astReplacer)
);
}
function isDescendant(node, maybeParentNode) {
let parent = node.parent;
while (parent) {
if (!parent) {
return false;
}
if (parent === maybeParentNode) {
return true;
}
parent = parent.parent;
}
return false;
}
function isSafeTypeofExpression(originalValueNode, node) {
if (node.type === 'BinaryExpression') {
// Example: typeof foo === 'string'
if (node.operator !== '===') {
return false;
}
const {left, right} = node;
// left must be `typeof original`
if (left.type !== 'UnaryExpression' || left.operator !== 'typeof') {
return false;
}
if (!isEquivalentCode(left.argument, originalValueNode)) {
return false;
}
// right must be a literal value of a safe type
const safeTypes = ['string', 'number', 'boolean', 'undefined', 'bigint'];
if (right.type !== 'Literal' || !safeTypes.includes(right.value)) {
return false;
}
return true;
} else if (node.type === 'LogicalExpression') {
// Examples:
// * typeof foo === 'string' && typeof foo === 'number
// * typeof foo === 'string' && someOtherTest
if (node.operator === '&&') {
return (
isSafeTypeofExpression(originalValueNode, node.left) ||
isSafeTypeofExpression(originalValueNode, node.right)
);
} else if (node.operator === '||') {
return (
isSafeTypeofExpression(originalValueNode, node.left) &&
isSafeTypeofExpression(originalValueNode, node.right)
);
}
}
return false;
}
/**
Returns true if the code is inside an `if` block that validates the value
excludes symbols and objects. Examples:
* if (typeof value === 'string') { }
* if (typeof value === 'string' || typeof value === 'number') { }
* if (typeof value === 'string' || someOtherTest) { }
@param - originalValueNode Top-level expression to test. Kept unchanged during
recursion.
@param - node Expression to test at current recursion level. Will be undefined
on non-recursive call.
*/
function isInSafeTypeofBlock(originalValueNode, node) {
if (!node) {
node = originalValueNode;
}
let parent = node.parent;
while (parent) {
if (!parent) {
return false;
}
// Normally, if the parent block is inside a type-safe `if` statement,
// then all child code is also type-safe. But there's a quirky case we
// need to defend against:
// if (typeof obj === 'string') { } else if (typeof obj === 'object') {'' + obj}
// if (typeof obj === 'string') { } else {'' + obj}
// In that code above, the `if` block is safe, but the `else` block is
// unsafe and should report. But the AST parent of the `else` clause is the
// `if` statement. This is the one case where the parent doesn't confer
// safety onto the child. The code below identifies that case and keeps
// moving up the tree until we get out of the `else`'s parent `if` block.
// This ensures that we don't use any of these "parents" (really siblings)
// to confer safety onto the current node.
if (
parent.type === 'IfStatement' &&
!isDescendant(originalValueNode, parent.alternate)
) {
const test = parent.test;
if (isSafeTypeofExpression(originalValueNode, test)) {
return true;
}
}
parent = parent.parent;
}
}
const missingDevCheckMessage =
'Missing DEV check before this string coercion.' +
' Check should be in this format:\n' +
' if (__DEV__) {\n' +
' checkXxxxxStringCoercion(value);\n' +
' }';
const prevStatementNotDevCheckMessage =
'The statement before this coercion must be a DEV check in this format:\n' +
' if (__DEV__) {\n' +
' checkXxxxxStringCoercion(value);\n' +
' }';
/**
* Does this node have an "is coercion safe?" DEV check
* in the same block?
*/
function hasCoercionCheck(node) {
// find the containing statement
let topOfExpression = node;
while (!topOfExpression.parent.body) {
topOfExpression = topOfExpression.parent;
if (!topOfExpression) {
return 'Cannot find top of expression.';
}
}
const containingBlock = topOfExpression.parent.body;
const index = containingBlock.indexOf(topOfExpression);
if (index <= 0) {
return missingDevCheckMessage;
}
const prev = containingBlock[index - 1];
// The previous statement is expected to be like this:
// if (__DEV__) {
// checkFormFieldValueStringCoercion(foo);
// }
// where `foo` must be equivalent to `node` (which is the
// mixed value being coerced to a string).
if (
prev.type !== 'IfStatement' ||
prev.test.type !== 'Identifier' ||
prev.test.name !== '__DEV__'
) {
return prevStatementNotDevCheckMessage;
}
let maybeCheckNode = prev.consequent;
if (maybeCheckNode.type === 'BlockStatement') {
const body = maybeCheckNode.body;
if (body.length === 0) {
return prevStatementNotDevCheckMessage;
}
if (body.length !== 1) {
return (
'Too many statements in DEV block before this coercion.' +
' Expected only one (the check function call). ' +
prevStatementNotDevCheckMessage
);
}
maybeCheckNode = body[0];
}
if (maybeCheckNode.type !== 'ExpressionStatement') {
return (
'The DEV block before this coercion must only contain an expression. ' +
prevStatementNotDevCheckMessage
);
}
const call = maybeCheckNode.expression;
if (
call.type !== 'CallExpression' ||
call.callee.type !== 'Identifier' ||
!/^check(\w+?)StringCoercion$/.test(call.callee.name) ||
!call.arguments.length
) {
// `maybeCheckNode` should be a call of a function named checkXXXStringCoercion
return (
'Missing or invalid check function call before this coercion.' +
' Expected: call of a function like checkXXXStringCoercion. ' +
prevStatementNotDevCheckMessage
);
}
const same = isEquivalentCode(call.arguments[0], node);
if (!same) {
return (
'Value passed to the check function before this coercion' +
' must match the value being coerced.'
);
}
}
function isOnlyAddingStrings(node) {
if (node.operator !== '+') {
return;
}
if (isStringLiteral(node.left) && isStringLiteral(node.right)) {
// It's always safe to add string literals
return true;
}
if (node.left.type === 'BinaryExpression' && isStringLiteral(node.right)) {
return isOnlyAddingStrings(node.left);
}
}
function checkBinaryExpression(context, node) {
if (isOnlyAddingStrings(node)) {
return;
}
if (
node.operator === '+' &&
(isEmptyLiteral(node.left) || isEmptyLiteral(node.right))
) {
let valueToTest = isEmptyLiteral(node.left) ? node.right : node.left;
if (
(valueToTest.type === 'TypeCastExpression' ||
valueToTest.type === 'AsExpression') &&
valueToTest.expression
) {
valueToTest = valueToTest.expression;
}
if (
valueToTest.type === 'Identifier' &&
['i', 'idx', 'lineNumber'].includes(valueToTest.name)
) {
// Common non-object variable names are assumed to be safe
return;
}
if (
valueToTest.type === 'UnaryExpression' ||
valueToTest.type === 'UpdateExpression'
) {
// Any unary expression will return a non-object, non-symbol type.
return;
}
if (isInSafeTypeofBlock(valueToTest)) {
// The value is inside an if (typeof...) block that ensures it's safe
return;
}
const coercionCheckMessage = hasCoercionCheck(valueToTest);
if (!coercionCheckMessage) {
// The previous statement is a correct check function call, so no report.
return;
}
context.report({
node,
message:
coercionCheckMessage +
'\n' +
"Using `'' + value` or `value + ''` is fast to coerce strings, but may throw." +
' For prod code, add a DEV check from shared/CheckStringCoercion immediately' +
' before this coercion.' +
' For non-prod code and prod error handling, use `String(value)` instead.',
});
}
}
function coerceWithStringConstructor(context, node) {
const isProductionUserAppCode =
context.options[0] && context.options[0].isProductionUserAppCode;
if (isProductionUserAppCode && node.callee.name === 'String') {
context.report(
node,
"For perf-sensitive coercion, avoid `String(value)`. Instead, use `'' + value`." +
' Precede it with a DEV check from shared/CheckStringCoercion' +
' unless Symbol and Temporal.* values are impossible.' +
' For non-prod code and prod error handling, use `String(value)` and disable this rule.'
);
}
}
module.exports = {
meta: {
schema: [
{
type: 'object',
properties: {
isProductionUserAppCode: {
type: 'boolean',
default: false,
},
},
additionalProperties: false,
},
],
},
create(context) {
return {
BinaryExpression: node => checkBinaryExpression(context, node),
CallExpression: node => coerceWithStringConstructor(context, node),
};
},
};