sindresorhus/eslint-plugin-unicorn

Rule proposal: `.replace` or `.replaceAll` with non-literal replacement

已关闭

#2,309 创建于 2024年4月5日

 (3 条评论) (4 个反应) (0 位负责人)JavaScript (468 个派生)user submission
help wantednew rule

仓库指标

星标
 (5,022 个星标)
PR 合并指标
 (平均合并 1天 16小时) (30 天内合并 399 个 PR)

描述

Description

One might think that a function like this generates safe HTML because the argument is HTML-escaped.

function imageLink(url) {
  const IMAGE_TEMPLATE = '<img src="{url}">';
  return IMAGE_TEMPLATE.replace('{url}', htmlEscape(url));
}

But in fact there’s a very obscure cross-site scripting vulnerability here, abusing the $` replacement sequence interpreted by String.prototype.replace and .replaceAll!

imageLink("$` onerror=alert(1) ")
//=> '<img src="<img src=" onerror=alert(1) ">'

To protect against this mistake, it would be nice to have an ESLint rule that forbids use of .replace and .replaceAll where the second argument isn’t a string literal or a function.

Fail

IMAGE_TEMPLATE.replace('{url}', htmlEscape(url))

Pass

IMAGE_TEMPLATE.replace('{url}', () => htmlEscape(url))
IMAGE_TEMPLATE.replace('{url}', "https://example.com")

Additional Info

No response

贡献者指南