dvPageContentSecurityPolicy function

String dvPageContentSecurityPolicy(
  1. String policy,
  2. String html, {
  3. Iterable<String> extraHtml = const <String>[],
})

policy with dvInlineScriptsSource replaced by the hashes of html's inline scripts. extraHtml adds the scripts of other HTML that may reach the same response (a streamed page's shell, before and after minifying).

Implementation

String dvPageContentSecurityPolicy(String policy, String html, {Iterable<String> extraHtml = const <String>[]}) {
  if (!policy.contains(dvInlineScriptsSource)) return policy;
  final List<String> hashes = <String>[...dvInlineScriptHashes(html)];
  for (final String more in extraHtml) {
    for (final String hash in dvInlineScriptHashes(more)) {
      if (!hashes.contains(hash)) hashes.add(hash);
    }
  }
  final String replacement = hashes.join(' ');
  return policy
      .replaceAll(dvInlineScriptsSource, replacement)
      .replaceAll(RegExp(r' {2,}'), ' ')
      .replaceAll(RegExp(r' +;'), ';')
      .trim();
}