【问题标题】:Subresource integrity for es6 import or workeres6 import 或 worker 的子资源完整性
【发布时间】:2019-03-09 06:05:27
【问题描述】:

<script> 接受integrity 属性,这样我就可以安全地加载模块了:

<script type="module"
  src="https://example.com/module.mjs"
  integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
  crossorigin="anonymous"
></script>

但是在脚本中加载模块时如何保证安全呢?

  • 带导入:
import foo from "https://example.com/module.mjs"
  • 动态导入:
import("https://example.com/module.mjs").then(console.log)
  • 甚至是网络工作者:
const myWorker = new Worker('worker.js')

【问题讨论】:

  • 对不起,我没有回答您的问题,但我想知道您是如何实现 src 文件的散列部分的?
  • @henhen,你说的是integrity 属性吗?您可以在这里了解所有信息:developer.mozilla.org/en-US/docs/Web/Security/…
  • 是的,我已经阅读了该文件。我只是不明白如何将它合并到我的项目中,例如 Node/React 项目?我的 package.json 中是否必须有一个脚本才能运行命令来生成哈希值?在示例中,它使用cat FILENAME.js | openssl dgst -sha384 -binary | openssl base64 -A,其中FILENAME.js 是他们想要散列的文件。但我想知道是否必须将其合并到我的 package.json 中并将其分配给全局变量。也可以代替 FILENAME.js 将我的 CDN 链接放在那里吗?
  • 如果我在我的机器上本地为我的文件生成一个哈希值,我假设相同的密钥在环境中不起作用?我的文件在我的组织中使用,我想知道我在本地生成的一个密钥是否可以让任何使用它的人工作。
  • 看起来已经有这样的问题,答案类似于我的建议:stackoverflow.com/questions/45804660/… :)

标签: es6-modules subresource-integrity


【解决方案1】:

请看这个问题

Is it possible to use subresource integrity with ES6 module imports?

您可以使用 RequireJS,并将您的代码转换为 AMD 或 UMD 来实现此目的。 RequireJS 有一个 onNodeCreated 钩子,它可以让您在将脚本标记添加到文档之前访问它。您可以将 sri 属性添加到脚本标签中:

onNodeCreated: function(node, config, module, path) { node.setAttribute('integrity', integrityForModule); node.setAttribute('crossorigin', 'anonymous'); }

信用:https://stackoverflow.com/a/37065379

我使用 Webpack(目标是 UMD)和 RequireJS。将相关模块放在 webpack 配置文件的 external 部分,所以模块不会被编译成转译代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-02
    • 1970-01-01
    • 2016-07-05
    • 2017-12-22
    • 2016-02-22
    • 2018-07-23
    • 2017-01-15
    • 2017-10-18
    相关资源
    最近更新 更多