subresource-integrity-plugin.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. var _webpack = require("next/dist/compiled/webpack/webpack");
  6. var _crypto = _interopRequireDefault(require("crypto"));
  7. var _constants = require("../../../shared/lib/constants");
  8. function _interopRequireDefault(obj) {
  9. return obj && obj.__esModule ? obj : {
  10. default: obj
  11. };
  12. }
  13. const PLUGIN_NAME = "SubresourceIntegrityPlugin";
  14. class SubresourceIntegrityPlugin {
  15. constructor(algorithm){
  16. this.algorithm = algorithm;
  17. }
  18. apply(compiler) {
  19. compiler.hooks.make.tap(PLUGIN_NAME, (compilation)=>{
  20. compilation.hooks.afterOptimizeAssets.tap({
  21. name: PLUGIN_NAME,
  22. stage: _webpack.webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS
  23. }, (assets)=>{
  24. // Collect all the entrypoint files.
  25. let files = new Set();
  26. for (const entrypoint of compilation.entrypoints.values()){
  27. const iterator = entrypoint == null ? void 0 : entrypoint.getFiles();
  28. if (!iterator) {
  29. continue;
  30. }
  31. for (const file of iterator){
  32. files.add(file);
  33. }
  34. }
  35. // For each file, deduped, calculate the file hash.
  36. const hashes = {};
  37. for (const file of files.values()){
  38. // Get the buffer for the asset.
  39. const asset = assets[file];
  40. if (!asset) {
  41. throw new Error(`could not get asset: ${file}`);
  42. }
  43. // Get the buffer for the asset.
  44. const buffer = asset.buffer();
  45. // Create the hash for the content.
  46. const hash = _crypto.default.createHash(this.algorithm).update(buffer).digest().toString("base64");
  47. hashes[file] = `${this.algorithm}-${hash}`;
  48. }
  49. const json = JSON.stringify(hashes, null, 2);
  50. const file1 = "server/" + _constants.SUBRESOURCE_INTEGRITY_MANIFEST;
  51. assets[file1 + ".js"] = new _webpack.sources.RawSource("self.__SUBRESOURCE_INTEGRITY_MANIFEST=" + json);
  52. assets[file1 + ".json"] = new _webpack.sources.RawSource(json);
  53. });
  54. });
  55. }
  56. }
  57. exports.SubresourceIntegrityPlugin = SubresourceIntegrityPlugin;
  58. //# sourceMappingURL=subresource-integrity-plugin.js.map