{"version":3,"file":"subresource-integrity.mjs","sources":["../../../../lib/web/subresource-integrity/subresource-integrity.js"],"sourcesContent":["'use strict'\n\nconst assert = require('node:assert')\nconst { runtimeFeatures } = require('../../util/runtime-features.js')\n\n/**\n * @typedef {object} Metadata\n * @property {SRIHashAlgorithm} alg - The algorithm used for the hash.\n * @property {string} val - The base64-encoded hash value.\n */\n\n/**\n * @typedef {Metadata[]} MetadataList\n */\n\n/**\n * @typedef {('sha256' | 'sha384' | 'sha512')} SRIHashAlgorithm\n */\n\n/**\n * @type {Map<SRIHashAlgorithm, number>}\n *\n * The valid SRI hash algorithm token set is the ordered set « \"sha256\",\n * \"sha384\", \"sha512\" » (corresponding to SHA-256, SHA-384, and SHA-512\n * respectively). The ordering of this set is meaningful, with stronger\n * algorithms appearing later in the set.\n *\n * @see https://w3c.github.io/webappsec-subresource-integrity/#valid-sri-hash-algorithm-token-set\n */\nconst validSRIHashAlgorithmTokenSet = new Map([['sha256', 0], ['sha384', 1], ['sha512', 2]])\n\n// https://nodejs.org/api/crypto.html#determining-if-crypto-support-is-unavailable\n/** @type {import('node:crypto')} */\nlet crypto\n\nif (runtimeFeatures.has('crypto')) {\n  crypto = require('node:crypto')\n  const cryptoHashes = crypto.getHashes()\n\n  // If no hashes are available, we cannot support SRI.\n  if (cryptoHashes.length === 0) {\n    validSRIHashAlgorithmTokenSet.clear()\n  }\n\n  for (const algorithm of validSRIHashAlgorithmTokenSet.keys()) {\n    // If the algorithm is not supported, remove it from the list.\n    if (cryptoHashes.includes(algorithm) === false) {\n      validSRIHashAlgorithmTokenSet.delete(algorithm)\n    }\n  }\n} else {\n  // If crypto is not available, we cannot support SRI.\n  validSRIHashAlgorithmTokenSet.clear()\n}\n\n/**\n * @typedef GetSRIHashAlgorithmIndex\n * @type {(algorithm: SRIHashAlgorithm) => number}\n * @param {SRIHashAlgorithm} algorithm\n * @returns {number} The index of the algorithm in the valid SRI hash algorithm\n * token set.\n */\n\nconst getSRIHashAlgorithmIndex = /** @type {GetSRIHashAlgorithmIndex} */ (Map.prototype.get.bind(\n  validSRIHashAlgorithmTokenSet))\n\n/**\n * @typedef IsValidSRIHashAlgorithm\n * @type {(algorithm: string) => algorithm is SRIHashAlgorithm}\n * @param {*} algorithm\n * @returns {algorithm is SRIHashAlgorithm}\n */\n\nconst isValidSRIHashAlgorithm = /** @type {IsValidSRIHashAlgorithm} */ (\n  Map.prototype.has.bind(validSRIHashAlgorithmTokenSet)\n)\n\n/**\n * @param {Uint8Array} bytes\n * @param {string} metadataList\n * @returns {boolean}\n *\n * @see https://w3c.github.io/webappsec-subresource-integrity/#does-response-match-metadatalist\n */\nconst bytesMatch = runtimeFeatures.has('crypto') === false || validSRIHashAlgorithmTokenSet.size === 0\n  // If node is not built with OpenSSL support, we cannot check\n  // a request's integrity, so allow it by default (the spec will\n  // allow requests if an invalid hash is given, as precedence).\n  ? () => true\n  : (bytes, metadataList) => {\n    // 1. Let parsedMetadata be the result of parsing metadataList.\n      const parsedMetadata = parseMetadata(metadataList)\n\n      // 2. If parsedMetadata is empty set, return true.\n      if (parsedMetadata.length === 0) {\n        return true\n      }\n\n      // 3. Let metadata be the result of getting the strongest\n      //    metadata from parsedMetadata.\n      const metadata = getStrongestMetadata(parsedMetadata)\n\n      // 4. For each item in metadata:\n      for (const item of metadata) {\n      // 1. Let algorithm be the item[\"alg\"].\n        const algorithm = item.alg\n\n        // 2. Let expectedValue be the item[\"val\"].\n        const expectedValue = item.val\n\n        // See https://github.com/web-platform-tests/wpt/commit/e4c5cc7a5e48093220528dfdd1c4012dc3837a0e\n        // \"be liberal with padding\". This is annoying, and it's not even in the spec.\n\n        // 3. Let actualValue be the result of applying algorithm to bytes .\n        const actualValue = applyAlgorithmToBytes(algorithm, bytes)\n\n        // 4. If actualValue is a case-sensitive match for expectedValue,\n        //    return true.\n        if (caseSensitiveMatch(actualValue, expectedValue)) {\n          return true\n        }\n      }\n\n      // 5. Return false.\n      return false\n    }\n\n/**\n * @param {MetadataList} metadataList\n * @returns {MetadataList} The strongest hash algorithm from the metadata list.\n */\nfunction getStrongestMetadata (metadataList) {\n  // 1. Let result be the empty set and strongest be the empty string.\n  const result = []\n  /** @type {Metadata|null} */\n  let strongest = null\n\n  // 2. For each item in set:\n  for (const item of metadataList) {\n    // 1. Assert: item[\"alg\"] is a valid SRI hash algorithm token.\n    assert(isValidSRIHashAlgorithm(item.alg), 'Invalid SRI hash algorithm token')\n\n    // 2. If result is the empty set, then:\n    if (result.length === 0) {\n      // 1. Append item to result.\n      result.push(item)\n\n      // 2. Set strongest to item.\n      strongest = item\n\n      // 3. Continue.\n      continue\n    }\n\n    // 3. Let currentAlgorithm be strongest[\"alg\"], and currentAlgorithmIndex be\n    // the index of currentAlgorithm in the valid SRI hash algorithm token set.\n    const currentAlgorithm = /** @type {Metadata} */ (strongest).alg\n    const currentAlgorithmIndex = getSRIHashAlgorithmIndex(currentAlgorithm)\n\n    // 4. Let newAlgorithm be the item[\"alg\"], and newAlgorithmIndex be the\n    // index of newAlgorithm in the valid SRI hash algorithm token set.\n    const newAlgorithm = item.alg\n    const newAlgorithmIndex = getSRIHashAlgorithmIndex(newAlgorithm)\n\n    // 5. If newAlgorithmIndex is less than currentAlgorithmIndex, then continue.\n    if (newAlgorithmIndex < currentAlgorithmIndex) {\n      continue\n\n    // 6. Otherwise, if newAlgorithmIndex is greater than\n    // currentAlgorithmIndex:\n    } else if (newAlgorithmIndex > currentAlgorithmIndex) {\n      // 1. Set strongest to item.\n      strongest = item\n\n      // 2. Set result to « item ».\n      result[0] = item\n      result.length = 1\n\n    // 7. Otherwise, newAlgorithmIndex and currentAlgorithmIndex are the same\n    // value. Append item to result.\n    } else {\n      result.push(item)\n    }\n  }\n\n  // 3. Return result.\n  return result\n}\n\n/**\n * @param {string} metadata\n * @returns {MetadataList}\n *\n * @see https://w3c.github.io/webappsec-subresource-integrity/#parse-metadata\n */\nfunction parseMetadata (metadata) {\n  // 1. Let result be the empty set.\n  /** @type {MetadataList} */\n  const result = []\n\n  // 2. For each item returned by splitting metadata on spaces:\n  for (const item of metadata.split(' ')) {\n    // 1. Let expression-and-options be the result of splitting item on U+003F (?).\n    const expressionAndOptions = item.split('?', 1)\n\n    // 2. Let algorithm-expression be expression-and-options[0].\n    const algorithmExpression = expressionAndOptions[0]\n\n    // 3. Let base64-value be the empty string.\n    let base64Value = ''\n\n    // 4. Let algorithm-and-value be the result of splitting algorithm-expression on U+002D (-).\n    const algorithmAndValue = [algorithmExpression.slice(0, 6), algorithmExpression.slice(7)]\n\n    // 5. Let algorithm be algorithm-and-value[0].\n    const algorithm = algorithmAndValue[0]\n\n    // 6. If algorithm is not a valid SRI hash algorithm token, then continue.\n    if (!isValidSRIHashAlgorithm(algorithm)) {\n      continue\n    }\n\n    // 7. If algorithm-and-value[1] exists, set base64-value to\n    // algorithm-and-value[1].\n    if (algorithmAndValue[1]) {\n      base64Value = algorithmAndValue[1]\n    }\n\n    // 8. Let metadata be the ordered map\n    // «[\"alg\" → algorithm, \"val\" → base64-value]».\n    const metadata = {\n      alg: algorithm,\n      val: base64Value\n    }\n\n    // 9. Append metadata to result.\n    result.push(metadata)\n  }\n\n  // 3. Return result.\n  return result\n}\n\n/**\n * Applies the specified hash algorithm to the given bytes\n *\n * @typedef {(algorithm: SRIHashAlgorithm, bytes: Uint8Array) => string} ApplyAlgorithmToBytes\n * @param {SRIHashAlgorithm} algorithm\n * @param {Uint8Array} bytes\n * @returns {string}\n */\nconst applyAlgorithmToBytes = (algorithm, bytes) => {\n  return crypto.hash(algorithm, bytes, 'base64')\n}\n\n/**\n * Compares two base64 strings, allowing for base64url\n * in the second string.\n *\n * @param {string} actualValue base64 encoded string\n * @param {string} expectedValue base64 or base64url encoded string\n * @returns {boolean}\n */\nfunction caseSensitiveMatch (actualValue, expectedValue) {\n  // Ignore padding characters from the end of the strings by\n  // decreasing the length by 1 or 2 if the last characters are `=`.\n  let actualValueLength = actualValue.length\n  if (actualValueLength !== 0 && actualValue[actualValueLength - 1] === '=') {\n    actualValueLength -= 1\n  }\n  if (actualValueLength !== 0 && actualValue[actualValueLength - 1] === '=') {\n    actualValueLength -= 1\n  }\n  let expectedValueLength = expectedValue.length\n  if (expectedValueLength !== 0 && expectedValue[expectedValueLength - 1] === '=') {\n    expectedValueLength -= 1\n  }\n  if (expectedValueLength !== 0 && expectedValue[expectedValueLength - 1] === '=') {\n    expectedValueLength -= 1\n  }\n\n  if (actualValueLength !== expectedValueLength) {\n    return false\n  }\n\n  for (let i = 0; i < actualValueLength; ++i) {\n    if (\n      actualValue[i] === expectedValue[i] ||\n      (actualValue[i] === '+' && expectedValue[i] === '-') ||\n      (actualValue[i] === '/' && expectedValue[i] === '_')\n    ) {\n      continue\n    }\n    return false\n  }\n\n  return true\n}\n\nmodule.exports = {\n  applyAlgorithmToBytes,\n  bytesMatch,\n  caseSensitiveMatch,\n  isValidSRIHashAlgorithm,\n  getStrongestMetadata,\n  parseMetadata\n}\n"],"names":["assert","require$$0","runtimeFeatures","require$$1","validSRIHashAlgorithmTokenSet","Map","crypto","has","require$$2","cryptoHashes","getHashes","length","clear","algorithm","keys","includes","delete","getSRIHashAlgorithmIndex","prototype","get","bind","isValidSRIHashAlgorithm","bytesMatch","size","bytes","metadataList","parsedMetadata","parseMetadata","metadata","getStrongestMetadata","item","alg","expectedValue","val","caseSensitiveMatch","applyAlgorithmToBytes","result","strongest","push","currentAlgorithm","currentAlgorithmIndex","newAlgorithm","newAlgorithmIndex","split","algorithmExpression","base64Value","algorithmAndValue","slice","hash","actualValue","actualValueLength","expectedValueLength","i","subresourceIntegrity"],"mappings":"yXAEA,MAAMA,OAASC,YACTC,iBAAsBC,yBA0BtBC,8BAAgC,IAAIC,IAAI,CAAC,CAAC,SAAU,GAAI,CAAC,SAAU,GAAI,CAAC,SAAU;;;AAIxF,IAAIC,SAEJ,GAAIJ,gBAAgBK,IAAI,UAAW,CACjCD,SAASE,OACT,MAAMC,aAAeH,SAAOI;qDAGA;IAAxBD,aAAaE,QACfP,8BAA8BQ,QAGhC,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