Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.1

0.6.1 / src / web / content_security_policy / violation.lucb

#==============================================================================================
#
#   violation - ContentSecurityPolicy::Violation: creating a violation for a global object or a
#   request, its URL, the blocked URI, the deprecated serialization and reporting it
#
#   DESCRIPTION:
#       Port of Libraries/LibWeb/ContentSecurityPolicy/Violation.cpp (lines 1-476) and the
#       inline functions of Violation.h (lines 43-81). Reporting fires a
#       securitypolicyviolation event in a queued task and, for a report-uri directive, fetches
#       the deprecated serialization (Fetch::Fetching::fetch, region p2c).
#
#       Copyright (c) 2025, Luke Wilde <luke@ladybird.org>
#       SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================

# mark: Creation ================================================================================

## Ported from Libraries/LibWeb/ContentSecurityPolicy/Violation.cpp:29 Web::ContentSecurityPolicy::Violation::Violation.
func content_security_policy_violation_construct(this: ContentSecurityPolicyViolation*, global_object: JsObject*?, policy: ContentSecurityPolicyPolicy*, directive: ak.String):
    # The default member initializers: no status, resource or referrer yet, line and column 0 (the empty sample is
    # the zeroed cell's).
    this.m_status = 0
    this.m_resource = ContentSecurityPolicyViolationResourceType.empty
    this.m_line_number = 0
    this.m_column_number = 0

    this.m_global_object = global_object
    this.m_policy = policy
    this.m_effective_directive = directive

## Ported from Libraries/LibWeb/ContentSecurityPolicy/Violation.cpp:37 Web::ContentSecurityPolicy::Violation::create_a_violation_object_for_global_policy_and_directive.
# https://w3c.github.io/webappsec-csp/#create-violation-for-global
pub func content_security_policy_violation_create_a_violation_object_for_global_policy_and_directive(realm: Realm*, global_object: JsObject*?, policy: ContentSecurityPolicyPolicy*, directive: ak.String) -> ContentSecurityPolicyViolation*:
    # 1. Let violation be a new violation whose global object is global, policy is policy, effective directive is
    #    directive, and resource is null.
    let violation = realm_create_content_security_policy_violation(realm, global_object, policy, directive)

    # FIXME: 2. If the user agent is currently executing script, and can extract a source file’s URL, line number,
    #           and column number from the global, set violation’s source file, line number, and column number
    #           accordingly.
    # SPEC ISSUE 1:  Is this kind of thing specified anywhere? I didn’t see anything that looked useful in [ECMA262].

    # 3. If global is a Window object, set violation’s referrer to global’s document's referrer.
    if let global = global_object:
        if let window = as_if_html_window((gc.Cell*)global):
            let referrer = dom_document_referrer(html_window_associated_document(window))
            violation.m_referrer = web_url.parser_basic_parse(ak.string_bytes_as_string_view(&referrer))

    # FIXME: 4. Set violation’s status to the HTTP status code for the resource associated with violation’s global object.
    # SPEC ISSUE 2: How, exactly, do we get the status code? We don’t actually store it anywhere.

    # 5. Return violation.
    return violation

## Ported from Libraries/LibWeb/ContentSecurityPolicy/Violation.cpp:62 Web::ContentSecurityPolicy::Violation::create_a_violation_object_for_request_and_policy.
# https://w3c.github.io/webappsec-csp/#create-violation-for-request
pub func content_security_policy_violation_create_a_violation_object_for_request_and_policy(realm: Realm*, request: FetchRequest*, policy: ContentSecurityPolicyPolicy*) -> ContentSecurityPolicyViolation*:
    # 1. Let directive be the result of executing § 6.8.1 Get the effective directive for request on request.
    let directive = content_security_policy_directives_get_the_effective_directive_for_request(request)

    # NOTE: The spec assumes that the effective directive of a Violation is a non-empty string.
    #       See the definition of m_effective_directive.
    let directive_name = directive else trap("VERIFY: directive.has_value()")

    # 2. Let violation be the result of executing § 2.4.1 Create a violation object for global, policy, and directive
    #      on request’s client’s global object, policy, and directive.
    let client = fetch_request_client(request) else trap("VERIFY: the request has a client")
    let violation = content_security_policy_violation_create_a_violation_object_for_global_policy_and_directive(realm, html_environment_settings_object_global_object(client), policy, ak.fly_string_to_string_const(&directive_name))

    # 3. Set violation’s resource to request’s url.
    # Spec Note: We use request’s url, and not its current url, as the latter might contain information about redirect
    #            targets to which the page MUST NOT be given access.
    violation.m_resource = ContentSecurityPolicyViolationResourceType.url(fetch_request_url(request))

    # 4. Return violation.
    return violation

## Ported from Libraries/LibWeb/ContentSecurityPolicy/Violation.cpp:84 Web::ContentSecurityPolicy::Violation::visit_edges (override).
pub func content_security_policy_violation_visit_edges_impl(base: gc.Cell*, visitor: gc.CellVisitor*):
    let this = (ContentSecurityPolicyViolation*)base
    gc.cell_visit_edges_impl(base, visitor)
    gc.cell_visitor_visit_cell(visitor, (gc.Cell*?)this.m_global_object)
    gc.cell_visitor_visit_cell_2(visitor, this.m_policy.cell())
    gc.cell_visitor_visit_cell(visitor, (gc.Cell*?)this.m_element)

# mark: Accessors (Violation.h) =================================================================

## Ported from Libraries/LibWeb/ContentSecurityPolicy/Violation.h:48 Web::ContentSecurityPolicy::Violation::status.
pub func content_security_policy_violation_status(this: ContentSecurityPolicyViolation*) -> u16:
    return this.m_status

## Ported from Libraries/LibWeb/ContentSecurityPolicy/Violation.h:49 Web::ContentSecurityPolicy::Violation::set_status.
pub func content_security_policy_violation_set_status(this: ContentSecurityPolicyViolation*, status: u16):
    this.m_status = status

## Ported from Libraries/LibWeb/ContentSecurityPolicy/Violation.h:51 Web::ContentSecurityPolicy::Violation::resource.
pub func content_security_policy_violation_resource(this: ContentSecurityPolicyViolation*) -> ContentSecurityPolicyViolationResourceType:
    return this.m_resource

## Ported from Libraries/LibWeb/ContentSecurityPolicy/Violation.h:52 Web::ContentSecurityPolicy::Violation::set_resource.
pub func content_security_policy_violation_set_resource(this: ContentSecurityPolicyViolation*, resource: ContentSecurityPolicyViolationResourceType):
    this.m_resource = resource

## Ported from Libraries/LibWeb/ContentSecurityPolicy/Violation.h:54 Web::ContentSecurityPolicy::Violation::referrer.
pub func content_security_policy_violation_referrer(this: ContentSecurityPolicyViolation*) -> web_url.Url?:
    return this.m_referrer

## Ported from Libraries/LibWeb/ContentSecurityPolicy/Violation.h:56 Web::ContentSecurityPolicy::Violation::policy.
pub func content_security_policy_violation_policy(this: ContentSecurityPolicyViolation*) -> ContentSecurityPolicyPolicy*:
    return this.m_policy

## Ported from Libraries/LibWeb/ContentSecurityPolicy/Violation.h:59 Web::ContentSecurityPolicy::Violation::disposition.
# https://w3c.github.io/webappsec-csp/#violation-disposition
pub func content_security_policy_violation_disposition(this: ContentSecurityPolicyViolation*) -> ContentSecurityPolicyPolicyDisposition:
    return content_security_policy_policy_disposition(this.m_policy)

## Ported from Libraries/LibWeb/ContentSecurityPolicy/Violation.h:61 Web::ContentSecurityPolicy::Violation::effective_directive.
pub func content_security_policy_violation_effective_directive(this: ContentSecurityPolicyViolation*) -> ak.String:
    return this.m_effective_directive

## Ported from Libraries/LibWeb/ContentSecurityPolicy/Violation.h:63 Web::ContentSecurityPolicy::Violation::source_file.
pub func content_security_policy_violation_source_file(this: ContentSecurityPolicyViolation*) -> web_url.Url?:
    return this.m_source_file

## Ported from Libraries/LibWeb/ContentSecurityPolicy/Violation.h:64 Web::ContentSecurityPolicy::Violation::set_source_file.
pub func content_security_policy_violation_set_source_file(this: ContentSecurityPolicyViolation*, source_file: web_url.Url):
    this.m_source_file = source_file

## Ported from Libraries/LibWeb/ContentSecurityPolicy/Violation.h:66 Web::ContentSecurityPolicy::Violation::line_number.
pub func content_security_policy_violation_line_number(this: ContentSecurityPolicyViolation*) -> u32:
    return this.m_line_number

## Ported from Libraries/LibWeb/ContentSecurityPolicy/Violation.h:67 Web::ContentSecurityPolicy::Violation::set_line_number.
pub func content_security_policy_violation_set_line_number(this: ContentSecurityPolicyViolation*, line_number: u32):
    this.m_line_number = line_number

## Ported from Libraries/LibWeb/ContentSecurityPolicy/Violation.h:69 Web::ContentSecurityPolicy::Violation::column_number.
pub func content_security_policy_violation_column_number(this: ContentSecurityPolicyViolation*) -> u32:
    return this.m_column_number

## Ported from Libraries/LibWeb/ContentSecurityPolicy/Violation.h:70 Web::ContentSecurityPolicy::Violation::set_column_number.
pub func content_security_policy_violation_set_column_number(this: ContentSecurityPolicyViolation*, column_number: u32):
    this.m_column_number = column_number

## Ported from Libraries/LibWeb/ContentSecurityPolicy/Violation.h:72 Web::ContentSecurityPolicy::Violation::element.
pub func content_security_policy_violation_element(this: ContentSecurityPolicyViolation*) -> DomElement*?:
    return this.m_element

## Ported from Libraries/LibWeb/ContentSecurityPolicy/Violation.h:73 Web::ContentSecurityPolicy::Violation::set_element.
pub func content_security_policy_violation_set_element(this: ContentSecurityPolicyViolation*, element: DomElement*):
    this.m_element = element

## Ported from Libraries/LibWeb/ContentSecurityPolicy/Violation.h:75 Web::ContentSecurityPolicy::Violation::sample.
pub func content_security_policy_violation_sample(this: ContentSecurityPolicyViolation*) -> ak.String:
    return this.m_sample

## Ported from Libraries/LibWeb/ContentSecurityPolicy/Violation.h:76 Web::ContentSecurityPolicy::Violation::set_sample.
pub func content_security_policy_violation_set_sample(this: ContentSecurityPolicyViolation*, sample: ak.String):
    this.m_sample = sample

# mark: URLs and serialization ==================================================================

## Ported from Libraries/LibWeb/ContentSecurityPolicy/Violation.cpp:92 Web::ContentSecurityPolicy::Violation::url.
# https://w3c.github.io/webappsec-csp/#violation-url
pub func content_security_policy_violation_url(this: ContentSecurityPolicyViolation*) -> web_url.Url:
    # Each violation has a url which is its global object’s URL.
    if this.m_global_object == none:
        # FIXME: What do we return here?
        ak.dbgln("FIXME: Figure out URL for violation with null global object.")
        return web_url.url_empty()
    let global_object = this.m_global_object else trap("unreachable: checked above")

    let universal_scope = as_if_universal_global_scope_mixin((gc.Cell*)global_object) else trap("as<UniversalGlobalScopeMixin> failed")
    let global = html_relevant_global_object((JsObject*)html_universal_global_scope_mixin_this_impl(universal_scope))

    if let window = as_if_html_window((gc.Cell*)global):
        return dom_document_url(html_window_associated_document(window))

    if is_html_worker_global_scope((gc.Cell*)global):
        let worker = (HtmlWorkerGlobalScope*)global
        return html_worker_global_scope_url(worker)

    trap("TODO")

## Ported from Libraries/LibWeb/ContentSecurityPolicy/Violation.cpp:116 Web::ContentSecurityPolicy::strip_url_for_use_in_reports.
# https://w3c.github.io/webappsec-csp/#strip-url-for-use-in-reports
func content_security_policy_strip_url_for_use_in_reports(url: web_url.Url) -> ak.String:
    var stripped = url

    # 1. If url’s scheme is not an HTTP(S) scheme, then return url’s scheme.
    let scheme = web_url.url_scheme(&stripped)
    if not fetch_is_http_or_https_scheme(ak.string_bytes_as_string_view(&scheme)):
        return scheme

    # 2. Set url’s fragment to the empty string.
    # FIXME: File spec issue about potentially meaning `null` here, as using empty string leaves a stray # at the end.
    web_url.url_set_fragment(&stripped, none)

    # 3. Set url’s username to the empty string.
    web_url.url_set_username(&stripped, ak.StringView())

    # 4. Set url’s password to the empty string.
    web_url.url_set_password(&stripped, ak.StringView())

    # 5. Return the result of executing the URL serializer on url.
    return web_url.url_serialize(&stripped)

## Ported from Libraries/LibWeb/ContentSecurityPolicy/Violation.cpp:138 Web::ContentSecurityPolicy::Violation::obtain_the_blocked_uri_of_resource.
# https://w3c.github.io/webappsec-csp/#obtain-violation-blocked-uri
func content_security_policy_violation_obtain_the_blocked_uri_of_resource(this: ContentSecurityPolicyViolation*) -> ak.String:
    # 1. Assert: resource is a URL or a string.
    # 2. If resource is a URL, return the result of executing § 5.4 Strip URL for use in reports on resource.
    # 3. Return resource.
    match this.m_resource:
        .url(url): return content_security_policy_strip_url_for_use_in_reports(url)
        .resource(resource):
            match resource:
                .inline_: return ak.string_from_str("inline")
                .eval: return ak.string_from_str("eval")
                .wasm_eval: return ak.string_from_str("wasm-eval")
                .trusted_types_policy: return ak.string_from_str("trusted-types-policy")
                .trusted_types_sink: return ak.string_from_str("trusted-types-sink")
                _: trap("VERIFY_NOT_REACHED")
        .empty: trap("VERIFY: m_resource.has<URL::URL>() || m_resource.has<Resource>()")

## Ported from Libraries/LibWeb/ContentSecurityPolicy/Violation.cpp:162 Web::ContentSecurityPolicy::original_disposition_to_string.
func content_security_policy_original_disposition_to_string(disposition: ContentSecurityPolicyPolicyDisposition) -> ak.String:
    match disposition:
        .enforce: return ak.string_from_str("enforce")
        .report: return ak.string_from_str("report")
        _: trap("VERIFY_NOT_REACHED")

## `body.value.set(key, Infra::JSONValue { value })` of obtain_the_deprecated_serialization.
func content_security_policy_json_set(object: InfraJsonObject*, key: str, value: InfraJsonBaseValue):
    _ = ak.ordered_hash_map_set(&object.value, ak.string_from_str(key), InfraJsonTopLevel.json_value(InfraJsonValue.json_base_value(value)))

## Ported from Libraries/LibWeb/ContentSecurityPolicy/Violation.cpp:176 Web::ContentSecurityPolicy::Violation::obtain_the_deprecated_serialization.
# https://w3c.github.io/webappsec-csp/#deprecated-serialize-violation
func content_security_policy_violation_obtain_the_deprecated_serialization(this: ContentSecurityPolicyViolation*, realm: Realm*) -> ak.ByteBuffer:
    # 1. Let body be a map with its keys initialized as follows:
    var body = InfraJsonObject()

    # "document-uri"
    #    The result of executing § 5.4 Strip URL for use in reports on violation's url.
    content_security_policy_json_set(&body, "document-uri", .string(content_security_policy_strip_url_for_use_in_reports(content_security_policy_violation_url(this))))

    # "referrer"
    #    The result of executing § 5.4 Strip URL for use in reports on violation's referrer.
    # FIXME: File spec issue that referrer can be null here.
    var referrer = InfraJsonBaseValue.empty
    if let referrer_url = this.m_referrer:
        referrer = .string(content_security_policy_strip_url_for_use_in_reports(referrer_url))

    content_security_policy_json_set(&body, "referrer", referrer)

    # "blocked-uri"
    #    The result of executing § 5.2 Obtain the blockedURI of a violation’s resource on violation’s resource.
    content_security_policy_json_set(&body, "blocked_uri", .string(content_security_policy_violation_obtain_the_blocked_uri_of_resource(this)))

    # "effective-directive"
    #    violation's effective directive
    content_security_policy_json_set(&body, "effective-directive", .string(this.m_effective_directive))

    # "violated-directive"
    #    violation's effective directive
    content_security_policy_json_set(&body, "violated-directive", .string(this.m_effective_directive))

    # "original-policy"
    #    The serialization of violation's policy
    content_security_policy_json_set(&body, "original-policy", .string(content_security_policy_policy_pre_parsed_policy_string(this.m_policy)))

    # "disposition"
    #    The disposition of violation's policy
    content_security_policy_json_set(&body, "disposition", .string(content_security_policy_original_disposition_to_string(content_security_policy_violation_disposition(this))))

    # "status-code"
    #    violation's status
    content_security_policy_json_set(&body, "status-code", .u16_(this.m_status))

    # "script-sample"
    #    violation's sample
    # Spec Note: The name script-sample was chosen for compatibility with an earlier iteration of this feature which
    #            has shipped in Firefox since its initial implementation of CSP. Despite the name, this field will
    #            contain samples for non-script violations, like stylesheets. The data contained in a
    #            SecurityPolicyViolationEvent object, and in reports generated via the new report-to directive, is
    #            named in a more encompassing fashion: sample.
    content_security_policy_json_set(&body, "script-sample", .string(this.m_sample))

    # 2. If violation’s source file is not null:
    if let source_file = this.m_source_file:
        # 1. Set body["source-file'] to the result of executing § 5.4 Strip URL for use in reports on violation’s
        #    source file.
        content_security_policy_json_set(&body, "source-file", .string(content_security_policy_strip_url_for_use_in_reports(source_file)))

        # 2. Set body["line-number"] to violation’s line number.
        content_security_policy_json_set(&body, "line-number", .u32_(this.m_line_number))

        # 3. Set body["column-number"] to violation’s column number.
        content_security_policy_json_set(&body, "column-number", .u32_(this.m_column_number))

    # 3. Assert: If body["blocked-uri"] is not "inline", then body["sample"] is the empty string.
    # FIXME: File spec issue that body["sample"] should be body["script-sample"]
    # FIXME: This is not a valid assertion, since Eval, TrustedTypesSink and TrustedTypesPolicy provide a sample. https://github.com/w3c/webappsec-csp/issues/788
    let provides_a_sample = match this.m_resource:
        .resource(resource) => resource == ContentSecurityPolicyViolationResource.inline_ or resource == ContentSecurityPolicyViolationResource.eval or resource == ContentSecurityPolicyViolationResource.trusted_types_sink or resource == ContentSecurityPolicyViolationResource.trusted_types_policy
        _ => false
    if not provides_a_sample:
        assert(ak.string_is_empty(&this.m_sample))

    # 4. Return the result of serialize an infra value to JSON bytes given «[ "csp-report" → body ]».
    var csp_report = InfraJsonObject()
    _ = ak.ordered_hash_map_set(&csp_report.value, ak.string_from_str("csp-report"), InfraJsonTopLevel.infra_json_object(body))

    var execution_context: HtmlTemporaryExecutionContext = ---
    html_temporary_execution_context_construct_realm(&execution_context, realm, HtmlTemporaryExecutionContextCallbacksEnabled.no)
    defer html_temporary_execution_context_destruct(&execution_context)
    return infra_serialize_an_infra_value_to_json_bytes(realm, InfraJsonTopLevel.infra_json_object(csp_report))

## Ported from Libraries/LibWeb/ContentSecurityPolicy/Violation.cpp:256 Web::ContentSecurityPolicy::original_disposition_to_bindings_disposition.
func content_security_policy_original_disposition_to_bindings_disposition(disposition: ContentSecurityPolicyPolicyDisposition) -> BindSecurityPolicyViolationEventDisposition:
    match disposition:
        .enforce: return BindSecurityPolicyViolationEventDisposition.enforce
        .report: return BindSecurityPolicyViolationEventDisposition.report
        _: trap("VERIFY_NOT_REACHED")

# mark: Reporting a violation ===================================================================

## The captures of report_a_violation's queued task: `[this, global, target, &realm]`.
struct ContentSecurityPolicyViolationReportAViolationTask:
    var this: ContentSecurityPolicyViolation*
    var global: JsObject*?
    var target: DomElement*?
    var realm: Realm*

## Ported from Libraries/LibWeb/ContentSecurityPolicy/Violation.cpp:270 Web::ContentSecurityPolicy::Violation::report_a_violation.
# https://w3c.github.io/webappsec-csp/#report-violation
pub func content_security_policy_violation_report_a_violation(this: ContentSecurityPolicyViolation*, realm: Realm*):
    let report_only = " (report only)" if content_security_policy_violation_disposition(this) == ContentSecurityPolicyPolicyDisposition.report else ""
    let blocked_uri = content_security_policy_violation_obtain_the_blocked_uri_of_resource(this)
    ak.dbgln(f"Content Security Policy violation{report_only}: Refusing access to resource '{ak.string_view_text(ak.string_bytes_as_string_view(&blocked_uri))}' because it does not appear in the '{ak.string_view_text(ak.string_bytes_as_string_view(&this.m_effective_directive))}' directive.")

    # 1. Let global be violation’s global object.
    let global = this.m_global_object

    # 2. Let target be violation’s element.
    let target = this.m_element

    # 3. Queue a task to run the following steps:
    # Spec Note: We "queue a task" here to ensure that the event targeting and dispatch happens after JavaScript
    #            completes execution of the task responsible for a given violation (which might manipulate the DOM).
    let captures = new ContentSecurityPolicyViolationReportAViolationTask(this = this, global = global, target = target, realm = realm) else trap("out of memory")
    _ = html_queue_a_task(HtmlTaskSource.unspecified, none, none, gc.create_function0[unit](realm_heap(realm), ak.Function0[unit](call = content_security_policy_violation_report_a_violation_task, context = captures)))

## The steps of report_a_violation's queued task.
func content_security_policy_violation_report_a_violation_task(context: void*?):
    let captures = (ContentSecurityPolicyViolationReportAViolationTask*)(context else trap("no captures"))
    let this = captures.this
    let global = captures.global
    let target = captures.target
    let realm = captures.realm
    let vm = realm_vm(realm)

    var target_as_object = (JsObject*?)target

    # 1. If target is not null, and global is a Window, and target’s shadow-including root is not global’s
    #    associated Document, set target to null.
    # Spec Note: This ensures that we fire events only at elements connected to violation’s policy’s Document.
    #            If a violation is caused by an element which isn’t connected to that document, we’ll fire the
    #            event at the document rather than the element in order to ensure that the violation is visible
    #            to the document’s listeners.
    if let target_element = target:
        if let global_object = global:
            if let window = as_if_html_window((gc.Cell*)global_object):
                if dom_node_shadow_including_root(target_element.dom_node()) != html_window_associated_document(window).dom_node():
                    target_as_object = none

    # 2. If target is null:
    if target_as_object == none:
        # 1. Set target to violation’s global object.
        target_as_object = this.m_global_object

        # 2. If target is a Window, set target to target’s associated Document.
        if let object = target_as_object:
            if let window = as_if_html_window((gc.Cell*)object):
                target_as_object = (JsObject*)html_window_associated_document(window)

    # 3. If target implements EventTarget, fire an event named securitypolicyviolation that uses the
    #    SecurityPolicyViolationEvent interface at target with its attributes initialized as follows:
    if let object = target_as_object:
        if is_dom_event_target((gc.Cell*)object):
            let event_target = (DomEventTarget*)object

            var event_init = ContentSecurityPolicySecurityPolicyViolationEventInit(document_uri = ak.string_new(), referrer = ak.string_new(), blocked_uri = ak.string_new(),
                                                                                   violated_directive = ak.string_new(), effective_directive = ak.string_new(), original_policy = ak.string_new(), source_file = ak.string_new(), sample = ak.string_new())

            # bubbles
            #    true
            event_init.event_init.bubbles = true

            # composed
            #    true
            # Spec Note: We set the composed attribute, which means that this event can be captured on its way
            #            into, and will bubble its way out of a shadow tree. target, et al will be automagically
            #            scoped correctly for the main tree.
            event_init.event_init.composed = true

            # documentURI
            #    The result of executing § 5.4 Strip URL for use in reports on violation's url.
            event_init.document_uri = content_security_policy_strip_url_for_use_in_reports(content_security_policy_violation_url(this))

            # referrer
            #    The result of executing § 5.4 Strip URL for use in reports on violation's referrer.
            # FIXME: File spec issue for referrer being potentially null.
            if let referrer = this.m_referrer:
                event_init.referrer = content_security_policy_strip_url_for_use_in_reports(referrer)
            else:
                event_init.referrer = ak.string_new()

            # blockedURI
            #    The result of executing § 5.2 Obtain the blockedURI of a violation's resource on violation’s
            #    resource.
            event_init.blocked_uri = content_security_policy_violation_obtain_the_blocked_uri_of_resource(this)

            # effectiveDirective
            #    violation's effective directive
            event_init.effective_directive = this.m_effective_directive

            # violatedDirective
            #    violation's effective directive
            # Spec Note: Both effectiveDirective and violatedDirective are the same value. This is intentional
            #            to maintain backwards compatibility.
            event_init.violated_directive = this.m_effective_directive

            # originalPolicy
            #    The serialization of violation's policy
            event_init.original_policy = content_security_policy_policy_pre_parsed_policy_string(this.m_policy)

            # disposition
            #    violation's disposition
            event_init.disposition = content_security_policy_original_disposition_to_bindings_disposition(content_security_policy_violation_disposition(this))

            # sourceFile
            #    The result of executing § 5.4 Strip URL for use in reports on violation’s source file, if
            #    violation's source file is not null, or null otherwise.
            if let source_file = this.m_source_file:
                event_init.source_file = content_security_policy_strip_url_for_use_in_reports(source_file)
            else:
                event_init.source_file = ak.string_new()

            # statusCode
            #    violation's status
            event_init.status_code = this.m_status

            # lineNumber
            #    violation’s line number
            event_init.line_number = this.m_line_number

            # columnNumber
            #    violation’s column number
            event_init.column_number = this.m_column_number

            # sample
            #    violation's sample
            event_init.sample = this.m_sample

            let event = content_security_policy_security_policy_violation_event_create(realm, html_event_names_securitypolicyviolation, &event_init)
            dom_event_set_is_trusted(event.dom_event(), true)
            _ = dom_event_target_dispatch_event(event_target, event.dom_event())

    # 4. If violation’s policy’s directive set contains a directive named "report-uri" directive:
    if let report_uri_directive = content_security_policy_policy_get_directive_by_name(this.m_policy, ak.fly_string_bytes_as_string_view(&content_security_policy_directives_names_report_uri)):
        # 1. If violation’s policy’s directive set contains a directive named "report-to", skip the remaining
        #    substeps.
        if not content_security_policy_policy_contains_directive_with_name(this.m_policy, ak.fly_string_bytes_as_string_view(&content_security_policy_directives_names_report_to)):
            # 1. For each token of directive’s value:
            var tokens = content_security_policy_directive_value(report_uri_directive)
            for token in ak.vector_span(&tokens):
                # 1. Let endpoint be the result of executing the URL parser with token as the input, and
                #    violation’s url as the base URL.
                let endpoint = domurl_parse(ak.string_bytes_as_string_view(&token), content_security_policy_violation_url(this))

                # 2. If endpoint is not a valid URL, skip the remaining substeps.
                if let endpoint_url = endpoint:
                    # 3. Let request be a new request, initialized as follows:
                    let request = fetch_request_create(vm)

                    # method
                    #    "POST"
                    fetch_request_set_method(request, ak.byte_string_from_str("POST"))

                    # url
                    #    violation’s url
                    # FIXME: File spec issue that this is incorrect, it should be `endpoint` instead.
                    fetch_request_set_url(request, endpoint_url)

                    # origin
                    #    violation's global object's relevant settings object's origin
                    # FIXME: File spec issue that global object can be null, so we use the realm to get the ESO instead.
                    let environment_settings_object = bind_principal_host_defined_environment_settings_object(realm)
                    fetch_request_set_origin(request, FetchRequestOriginType.origin(html_environment_settings_object_origin(environment_settings_object)))

                    # traversable for user prompts
                    #    "no-traversable"
                    fetch_request_set_traversable_for_user_prompts(request, FetchRequestTraversableForUserPromptsType.fetch_request_traversable_for_user_prompts(FetchRequestTraversableForUserPrompts.no_traversable))

                    # client
                    #    violation's global object's relevant settings object
                    fetch_request_set_client(request, environment_settings_object)

                    # destination
                    #    "report"
                    fetch_request_set_destination(request, FetchRequestDestination.report)

                    # initiator
                    #    ""
                    fetch_request_set_initiator(request, none)

                    # credentials mode
                    #    "same-origin"
                    fetch_request_set_credentials_mode(request, FetchRequestCredentialsMode.same_origin)

                    # keepalive
                    #    "true"
                    fetch_request_set_keepalive(request, true)

                    # header list
                    #    A header list containing a single header whose name is "Content-Type", and value is
                    #    "application/csp-report"
                    let header_list = http_header_list_create()
                    http_header_list_append(header_list, http_header_create(ak.sv("Content-Type"), ak.sv("application/csp-report")))
                    fetch_request_set_header_list(request, header_list)

                    # body
                    #    The result of executing § 5.3 Obtain the deprecated serialization of violation on
                    #    violation
                    fetch_request_set_body(request, FetchRequestBodyType.byte_buffer(content_security_policy_violation_obtain_the_deprecated_serialization(this, realm)))

                    # redirect mode
                    #    "error"
                    fetch_request_set_redirect_mode(request, FetchRequestRedirectMode.error_)

                    # 4. Fetch request. The result will be ignored.
                    let algorithms = fetch_algorithms_create(vm, FetchAlgorithmsInput())
                    _ = fetch_fetching_fetch(realm, request, algorithms)

        # 5. If violation's policy's directive set contains a directive named "report-to" directive:
        if let report_to_directive = content_security_policy_policy_get_directive_by_name(this.m_policy, ak.fly_string_bytes_as_string_view(&content_security_policy_directives_names_report_to)):
            _ = report_to_directive
            ak.dbgln("FIXME: Implement report-to directive in violation reporting")