dvDocumentSlotCspSources function

Map<String, List<String>> dvDocumentSlotCspSources(
  1. DVWebDocumentSlots slots, {
  2. String readFile(
    1. String path
    )?,
})

The third-party origins the snippets load from, by the directive that governs each load: script-src for a <script src>, style-src for a stylesheet, frame-src for an iframe, img-src for an image, media-src for audio and video. Same-origin and relative URLs need no addition, and plain-http URLs are left out: a secure page refuses them whatever its policy says.

Implementation

Map<String, List<String>> dvDocumentSlotCspSources(DVWebDocumentSlots slots, {String Function(String path)? readFile}) {
  final Map<String, List<String>> sources = <String, List<String>>{};
  void add(String directive, String? origin) {
    if (origin == null) return;
    final List<String> list = sources.putIfAbsent(directive, () => <String>[]);
    if (!list.contains(origin)) list.add(origin);
  }

  for (final String html in dvResolveDocumentSlots(slots, readFile: readFile).values) {
    for (final RegExpMatch match in _loader.allMatches(html)) {
      final String attributes = match.group(2) ?? '';
      switch (match.group(1)!.toLowerCase()) {
        case 'script':
          add('script-src', _origin(_attribute(attributes, 'src')));
        case 'link':
          final String rel = (_attribute(attributes, 'rel') ?? '').toLowerCase();
          if (rel.split(RegExp(r'\s+')).contains('stylesheet'))
            add('style-src', _origin(_attribute(attributes, 'href')));
        case 'iframe' || 'frame':
          add('frame-src', _origin(_attribute(attributes, 'src')));
        case 'img':
          add('img-src', _origin(_attribute(attributes, 'src')));
        default:
          add('media-src', _origin(_attribute(attributes, 'src')));
      }
    }
  }
  return sources;
}