dvAddContentSecurityPolicySources function

String dvAddContentSecurityPolicySources(
  1. String policy,
  2. Map<String, List<String>> additions
)

policy with every source in additions allowed, by directive name.

  • A directive the policy has gets the sources it does not already list. 'none' in it gives way to them.
  • A directive it lacks is written from what default-src allowed plus the sources, because a fetch directive that is present no longer falls back to default-src.
  • With no such directive and no default-src the policy does not restrict that kind of load, and it is left that way.
  • A script-src source is also added to script-src-elem when the policy has one, since that is what a <script> element is checked against.

Throws an ArgumentError for a source that is not an origin.

Implementation

String dvAddContentSecurityPolicySources(
  String policy,
  Map<String, List<String>> additions,
) {
  final Map<String, List<String>> wanted = <String, List<String>>{};
  additions.forEach((String directive, List<String> sources) {
    final String name = directive.trim().toLowerCase();
    if (!RegExp(r'^[a-z-]+-src(-elem|-attr)?$').hasMatch(name)) {
      throw ArgumentError.value(directive, 'additions',
          'is not a Content-Security-Policy fetch directive');
    }
    for (final String source in sources) {
      if (!dvIsContentSecurityPolicyOrigin(source)) {
        throw ArgumentError.value(source, 'additions',
            'is not an origin such as https://cdn.example.com');
      }
      final List<String> list = wanted.putIfAbsent(name, () => <String>[]);
      if (!list.contains(source)) list.add(source);
    }
  });
  return _addSources(policy, wanted);
}