plugin.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. "use strict";
  2. /**
  3. * Copyright (c) 2015-present, Waysact Pty Ltd
  4. *
  5. * This source code is licensed under the MIT license found in the
  6. * LICENSE file in the root directory of this source tree.
  7. */
  8. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  9. if (k2 === undefined) k2 = k;
  10. Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
  11. }) : (function(o, m, k, k2) {
  12. if (k2 === undefined) k2 = k;
  13. o[k2] = m[k];
  14. }));
  15. var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
  16. Object.defineProperty(o, "default", { enumerable: true, value: v });
  17. }) : function(o, v) {
  18. o["default"] = v;
  19. });
  20. var __importStar = (this && this.__importStar) || function (mod) {
  21. if (mod && mod.__esModule) return mod;
  22. var result = {};
  23. if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  24. __setModuleDefault(result, mod);
  25. return result;
  26. };
  27. Object.defineProperty(exports, "__esModule", { value: true });
  28. exports.Plugin = void 0;
  29. const path_1 = require("path");
  30. const fs_1 = require("fs");
  31. const assert = __importStar(require("typed-assert"));
  32. const util_1 = require("./util");
  33. const assetTypeIntegrityKeys = [
  34. ["js", "jsIntegrity"],
  35. ["css", "cssIntegrity"],
  36. ];
  37. class Plugin {
  38. constructor(compilation, options, reporter) {
  39. /**
  40. * @internal
  41. */
  42. this.assetIntegrity = new Map();
  43. /**
  44. * @internal
  45. */
  46. this.inverseAssetIntegrity = new Map();
  47. /**
  48. * @internal
  49. */
  50. this.hwpPublicPath = null;
  51. /**
  52. * @internal
  53. */
  54. this.sortedSccChunks = [];
  55. /**
  56. * @internal
  57. */
  58. this.chunkManifest = new Map();
  59. /**
  60. * @internal
  61. */
  62. this.hashByChunkId = new Map();
  63. /**
  64. * @internal
  65. */
  66. this.addMissingIntegrityHashes = (assets) => {
  67. Object.keys(assets).forEach((assetKey) => {
  68. const asset = assets[assetKey];
  69. let source;
  70. try {
  71. source = asset.source();
  72. }
  73. catch (_) {
  74. return;
  75. }
  76. this.updateAssetIntegrity(assetKey, util_1.computeIntegrity(this.options.hashFuncNames, source));
  77. });
  78. };
  79. /**
  80. * @internal
  81. */
  82. this.replaceAsset = (compiler, assets, hashByChunkId, chunkFile) => {
  83. const oldSource = assets[chunkFile].source();
  84. const hashFuncNames = this.options.hashFuncNames;
  85. const newAsset = new compiler.webpack.sources.ReplaceSource(assets[chunkFile], chunkFile);
  86. Array.from(hashByChunkId.entries()).forEach((idAndHash) => {
  87. const magicMarker = util_1.makePlaceholder(hashFuncNames, idAndHash[0]);
  88. const magicMarkerPos = oldSource.indexOf(magicMarker);
  89. if (magicMarkerPos >= 0) {
  90. newAsset.replace(magicMarkerPos, magicMarkerPos + magicMarker.length - 1, idAndHash[1], chunkFile);
  91. }
  92. });
  93. assets[chunkFile] = newAsset;
  94. return newAsset;
  95. };
  96. this.warnAboutLongTermCaching = (assetInfo) => {
  97. if ((assetInfo.fullhash ||
  98. assetInfo.chunkhash ||
  99. assetInfo.modulehash ||
  100. assetInfo.contenthash) &&
  101. !(assetInfo.contenthash &&
  102. this.compilation.compiler.options.optimization.realContentHash)) {
  103. this.reporter.warnOnce("Using [hash], [fullhash], [modulehash], or [chunkhash] is dangerous \
  104. with SRI. The same is true for [contenthash] when realContentHash is disabled. \
  105. Use [contenthash] and ensure realContentHash is enabled. See the README for \
  106. more information.");
  107. }
  108. };
  109. /**
  110. * @internal
  111. */
  112. this.processChunk = (chunk, assets) => {
  113. Array.from(util_1.findChunks(chunk))
  114. .reverse()
  115. .forEach((chunk) => this.processChunkAssets(chunk, assets));
  116. };
  117. this.processChunkAssets = (childChunk, assets) => {
  118. const files = Array.from(childChunk.files);
  119. files.forEach((sourcePath) => {
  120. if (assets[sourcePath]) {
  121. this.warnIfHotUpdate(assets[sourcePath].source());
  122. const newAsset = this.replaceAsset(this.compilation.compiler, assets, this.hashByChunkId, sourcePath);
  123. const integrity = util_1.computeIntegrity(this.options.hashFuncNames, newAsset.source());
  124. if (childChunk.id !== null) {
  125. this.hashByChunkId.set(childChunk.id, integrity);
  126. }
  127. this.updateAssetIntegrity(sourcePath, integrity);
  128. this.compilation.updateAsset(sourcePath, (x) => x, (assetInfo) => {
  129. if (!assetInfo) {
  130. return undefined;
  131. }
  132. this.warnAboutLongTermCaching(assetInfo);
  133. return {
  134. ...assetInfo,
  135. contenthash: Array.isArray(assetInfo.contenthash)
  136. ? [...new Set([...assetInfo.contenthash, integrity])]
  137. : assetInfo.contenthash
  138. ? [assetInfo.contenthash, integrity]
  139. : integrity,
  140. };
  141. });
  142. }
  143. else {
  144. this.reporter.warnOnce(`No asset found for source path '${sourcePath}', options are ${Object.keys(assets).join(", ")}`);
  145. }
  146. });
  147. };
  148. /**
  149. * @internal
  150. */
  151. this.addAttribute = (elName, source) => {
  152. if (!this.compilation.outputOptions.crossOriginLoading) {
  153. this.reporter.errorOnce("webpack option output.crossOriginLoading not set, code splitting will not work!");
  154. }
  155. return this.compilation.compiler.webpack.Template.asString([
  156. source,
  157. elName + `.integrity = ${util_1.sriHashVariableReference}[chunkId];`,
  158. elName +
  159. ".crossOrigin = " +
  160. JSON.stringify(this.compilation.outputOptions.crossOriginLoading) +
  161. ";",
  162. ]);
  163. };
  164. /**
  165. * @internal
  166. */
  167. this.processAssets = (assets) => {
  168. if (this.options.hashLoading === "lazy") {
  169. for (const scc of this.sortedSccChunks) {
  170. for (const chunk of scc.nodes) {
  171. this.processChunkAssets(chunk, assets);
  172. }
  173. }
  174. }
  175. else {
  176. Array.from(this.compilation.chunks)
  177. .filter((chunk) => chunk.hasRuntime())
  178. .forEach((chunk) => {
  179. this.processChunk(chunk, assets);
  180. });
  181. }
  182. this.addMissingIntegrityHashes(assets);
  183. };
  184. /**
  185. * @internal
  186. */
  187. this.hwpAssetPath = (src) => {
  188. assert.isNotNull(this.hwpPublicPath);
  189. return path_1.relative(this.hwpPublicPath, src);
  190. };
  191. /**
  192. * @internal
  193. */
  194. this.getIntegrityChecksumForAsset = (assets, src) => {
  195. if (this.assetIntegrity.has(src)) {
  196. return this.assetIntegrity.get(src);
  197. }
  198. const normalizedSrc = util_1.normalizePath(src);
  199. const normalizedKey = Object.keys(assets).find((assetKey) => util_1.normalizePath(assetKey) === normalizedSrc);
  200. if (normalizedKey) {
  201. return this.assetIntegrity.get(normalizedKey);
  202. }
  203. return undefined;
  204. };
  205. /**
  206. * @internal
  207. */
  208. this.processTag = (tag) => {
  209. if (tag.attributes &&
  210. Object.prototype.hasOwnProperty.call(tag.attributes, "integrity")) {
  211. return;
  212. }
  213. const tagSrc = util_1.getTagSrc(tag);
  214. if (!tagSrc) {
  215. return;
  216. }
  217. const src = this.hwpAssetPath(tagSrc);
  218. tag.attributes.integrity =
  219. this.getIntegrityChecksumForAsset(this.compilation.assets, src) ||
  220. util_1.computeIntegrity(this.options.hashFuncNames, fs_1.readFileSync(path_1.join(this.compilation.compiler.outputPath, src)));
  221. tag.attributes.crossorigin =
  222. this.compilation.compiler.options.output.crossOriginLoading ||
  223. "anonymous";
  224. };
  225. /**
  226. * @internal
  227. */
  228. this.beforeRuntimeRequirements = () => {
  229. if (this.options.hashLoading === "lazy") {
  230. const [sortedSccChunks, chunkManifest] = util_1.getChunkToManifestMap(this.compilation.chunks);
  231. this.sortedSccChunks = sortedSccChunks;
  232. this.chunkManifest = chunkManifest;
  233. }
  234. this.hashByChunkId.clear();
  235. };
  236. this.handleHwpPluginArgs = ({ assets }) => {
  237. this.hwpPublicPath = assets.publicPath;
  238. assetTypeIntegrityKeys.forEach(([a, b]) => {
  239. if (b) {
  240. assets[b] = assets[a]
  241. .map((filePath) => this.getIntegrityChecksumForAsset(this.compilation.assets, this.hwpAssetPath(filePath)))
  242. .filter(util_1.notNil);
  243. }
  244. });
  245. };
  246. this.updateHash = (input, oldHash) => {
  247. const assetKey = this.inverseAssetIntegrity.get(oldHash);
  248. if (assetKey && input.length === 1) {
  249. const newIntegrity = util_1.computeIntegrity(this.options.hashFuncNames, input[0]);
  250. this.inverseAssetIntegrity.delete(oldHash);
  251. this.assetIntegrity.delete(assetKey);
  252. this.updateAssetIntegrity(assetKey, newIntegrity);
  253. return newIntegrity;
  254. }
  255. return undefined;
  256. };
  257. this.handleHwpBodyTags = ({ headTags, bodyTags, }) => {
  258. this.addMissingIntegrityHashes(this.compilation.assets);
  259. headTags
  260. .concat(bodyTags)
  261. .forEach((tag) => this.processTag(tag));
  262. };
  263. this.compilation = compilation;
  264. this.options = options;
  265. this.reporter = reporter;
  266. }
  267. /**
  268. * @internal
  269. */
  270. warnIfHotUpdate(source) {
  271. if (source.indexOf("webpackHotUpdate") >= 0) {
  272. this.reporter.warnOnce("webpack-subresource-integrity may interfere with hot reloading. " +
  273. "Consider disabling this plugin in development mode.");
  274. }
  275. }
  276. /**
  277. * @internal
  278. */
  279. updateAssetIntegrity(assetKey, integrity) {
  280. if (!this.assetIntegrity.has(assetKey)) {
  281. this.assetIntegrity.set(assetKey, integrity);
  282. this.inverseAssetIntegrity.set(integrity, assetKey);
  283. }
  284. }
  285. getChildChunksToAddToChunkManifest(chunk) {
  286. var _a;
  287. return (_a = this.chunkManifest.get(chunk)) !== null && _a !== void 0 ? _a : new Set();
  288. }
  289. }
  290. exports.Plugin = Plugin;
  291. //# sourceMappingURL=plugin.js.map