ACE.js enhances website security through Content Security Policy

I've been working on setting up a helmet-csp with ace running smoothly. Here's how my helmet-setup looks:

var csp = require("helmet-csp");

app.use(csp({
    directives: {
        defaultSrc: ["'self'", "https://localhost:8000"],
        styleSrc: ["'self'", "'unsafe-inline'"],
        sandbox: ["allow-forms", "allow-scripts", "allow-same-origin"],
        reportUri: "/report-violation",
        scriptSrc: ["'self'", "'unsafe-inline'",
        "https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.0/ace.js",
        "https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.0/theme-monokai.js",
        "https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.0/mode-javascript.js"]
    }
}));

The implementation of the script includes this setup (the src is linked to a local embedment of ace):

<script src="../../src-min-noconflict/ace.js" type="text/javascript" charset="utf-8"></script>
<script>

    var editor = ace.edit("editor");
    editor.getSession().setUseWorker(false);
    editor.setTheme("ace/theme/monokai");
    editor.getSession().setMode("ace/mode/javascript");

</script>

Although there are no significant errors, I am frequently seeing these messages in the browser console:

Refused to create a worker from 'blob:https://localhost:8000/34145ece-2c95-403b-92b0-79d02a5b4edd' because it violates the following Content Security Policy directive: "default-src 'self' https://localhost:8000". Note that 'worker-src' was not explicitly set, so 'default-src' is used as a fallback.

and

Could not load worker DOMException: Failed to construct 'Worker': Access to the script at 'blob:https://localhost:8000/701e5193-c7f3-47b4-94da-c2086bfc2dd4' is denied by the document's Content Security Policy.
    at new u (https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.0/ace.js:1:305119)
    at createWorker (https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.0/mode-javascript.js:1:22584)
    at p.$startWorker (https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.0/ace.js:1:159829)
    at p.$onChangeMode (https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.0/ace.js:1:159064)
    at p.<anonymous> (https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.0/ace.js:1:158825)
    at https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.0/ace.js:1:55143
    at Array.forEach (native)
    at https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.0/ace.js:1:55120
    at n (https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.0/ace.js:1:936)
    at a (https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.0/ace.js:1:1487)

I've tried various solutions found online but haven't had any luck. Any assistance would be greatly appreciated!

Answer №1

After encountering some issues with the worker on my project, I had to make adjustments by adding specific child-src policies. It turned out that allowing blobs from that origin was necessary for the worker to function properly.

app.use(csp({
    directives: {
        defaultSrc: ["'self'"],
        imgSrc: ["data: *"],
        childSrc: ["blob: *"],
        styleSrc: ["'self'", "'unsafe-inline'",
        "https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"],
        sandbox: ["allow-forms", "allow-scripts", "allow-same-origin"],
        scriptSrc: ["'self'", "'unsafe-inline'", "https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.0/ace.js",
        "https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.0/theme-monokai.js",
        "https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.0/mode-javascript.js",
        "https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.0/worker-javascript.js"],
        fontSrc: ["'self'", "https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/fonts/fontawesome-webfont.woff2?v=4.7.0",
        "https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/fonts/fontawesome-webfont.woff?v=4.7.0]",
        "https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/fonts/fontawesome-webfont.ttf?v=4.7.0",
        "https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.0/worker-javascript.js"]
    }
}));

Furthermore, I made additional modifications to the script in order to ensure its functionality. The changes seemed to have solved the problem, although the reason behind it remains unclear:

<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.0/ace.js"></script>
<script>
    var textarea = document.querySelector("#content");

    var editor = ace.edit("editor");
    editor.setTheme("ace/theme/monokai");
    editor.getSession().setMode("ace/mode/javascript");

    editor.getSession().on("change", function () {
        textarea.innerHTML = editor.getSession().getValue();
    });

    textarea.innerHTML = editor.getSession().getValue();
</script>

Answer №2

Ace URLs do not need to be included in the "script-src" directive; you can simply use the following code:

scriptSrc: ['self', 'unsafe-eval', 'blob:', 'data:'],

This should suffice.

Answer №3

I've configured my Apache web server headers to enforce a content security policy. By including blob: in the script-src directive, everything seems to be functioning properly.

Header set Content-Security-Policy "default-src 'self'; media-src *; img-src ; font-src 'self' data:; script-src 'self' 'unsafe-eval' 'unsafe-inline' blob: https://.googleapis.com https://.google.com https://.google-analytics.com https://*.gstatic.com; style-src 'self' 'unsafe-inline'; object-src 'self';"

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Revising text for real-time editing

Most of us are familiar with the functionality on StackOverFlow that allows you to preview your text before posting a question. I'm interested in implementing a similar feature on my website and am looking for some guidance on how to get started. I ...

What is the best method for arranging drop-down menu options in alphabetical order?

Is there a way to organize the options alphabetically in the dropdown menu of Material-UI? I understand that arrays can be sorted easily using arr.sort(). However, when I try const options = [...].sort(), I still see unsorted values in the dropdown menu. ...

It is not possible to recycle a TinyMCE editor that is embedded in a popup

Having a frustrating issue with the TinyMCE Editor plugin embedded within a Fancybox pop-up window. I have a list of objects with Edit links that trigger an AJAX call to retrieve content from the server and place it in a <textarea>. A TinyMCE editor ...

What mechanism enables the scores on this sports ticker to refresh automatically without relying on ajax calls?

While browsing scores on , I found myself intrigued by the way they update their scores without using ajax calls or iframes. It's a mystery to me how this functionality is achieved. Can anyone shed some light on how it works? ...

Having trouble sending data from AJAX to PHP

My goal is to implement a "load more" feature in my web app that automatically calls a PHP file to load additional products as soon as the page is fully loaded. In order to achieve this, I am using AJAX to call the PHP file: $(document).ready(function() { ...

Sending data and redirecting to a new URL by linking multiple responses together

As a beginner in javascript, I wanted to confirm if my code is appropriate. I am currently using JavaScript to handle a PUT request. My main goal is to return the updated Sequelize model as a response and then redirect the user back to the local /. Can I ...

What is the best way to bind a model to a directive in Angular.js?

I have been experimenting with different methods to create a two-way binding between my directive and repeater, but so far I haven't been successful. Although I have tried various strategies suggested online, the current setup does not pass item.myDat ...

Repeating Elements with Angular and Utilizing a Touch Keyboard

Currently, I am developing a table with various fields and the ability to add new rows. The goal is to display all the inputted data at the end. This application is specifically designed for touch screen monitors, so I have created a custom keyboard for in ...

Creating a custom dialog box using JavaScript

How can I create a customized dialog box in the center without displaying "the host name says..." using CSS? function myFunction() { alert("Record Save"); } Thank you in advance! ...

Fixing extended properties on an express request can be done by following these steps

I've been working on a JavaScript middleware where I can extract user information using the "req" object in the route handler. When I log currentUser, I get the expected value, but I'm encountering a TypeScript error warning: Property 'curre ...

What is the best way to horizontally align three animated progress bars alongside images?

Check out this jsfiddle that shows a vertical alignment of the progress bars. How can I modify it to align them horizontally and centered? https://jsfiddle.net/bLe0jLar/ .wrapper { width: 100px; height: 100px; } .wrapper > #bar, #bar2, #bar3 { ...

Currently in the process of executing 'yarn build' to complete the integration of the salesforce plugin, encountering a few error messages along the way

I've been referencing the Github repository at this link for my project. Following the instructions in the readme file, I proceeded with running a series of commands which resulted in some issues. The commands executed were: yarn install sfdx plugi ...

Steps for compiling JSX on the server side

I am currently developing an express server using webpack to render a React app server-side. However, I am encountering an issue with compiling JSX files. When I run the webpack build, I receive the following error: ERROR in /src/components/Hello.js M ...

Is Valums Ajax file Upload capable of handling the uploaded file?

Currently, I am utilizing the Valums Ajax Fileupload script found at These are the settings I have configured: function createUploader(){ var uploader = new qq.FileUploader({ element: document.getElementById('file-uploader-de ...

What is the best way to set a specific image as the initial image when loading 'SpriteSpin'?

I'm currently working on creating a 360-degree view using the SpriteSpin API. Everything is functioning as expected, but I have an additional request. I need to specify a specific image to be the initial landing image when the page loads. The landing ...

Tips for automatically resizing a canvas to fit the content within a scrollable container?

I have integrated PDF JS into my Vue3 project to overlay a <canvas id="draw_canvas"> on the rendered pdf document. This allows me to draw rectangles programmatically over the pdf, serving as markers for specific areas. The rendering proces ...

Deactivating the idle timer in React Native: A Step-by-Step Guide

Currently, I am working on an app that involves a timer using RN. However, I have noticed that after approximately 1 minute and 50 seconds, the device's screen starts to dim in preparation for sleep mode. ...

While working with passport.js and ngrok, the issue of req.user being undefined arises due to cors

When logging in with OAuth on the frontend using http localhost and calling req.user in the backend using https ngrok, it returns undefined. The same issue arises if both the backend and frontend utilize ngrok. However, things function properly when the ba ...

Exploring the magic of Node JS and integrating it with Twitter OAuth

I am new to working with Node JS and attempting to connect to Twitter using it. I have a JavaScript file located in the E:/ directory, but I'm unsure whether I should create a module folder or not with the provided code snippet. var express = req ...

Utilizing OrbitControls with SVGRenderer displays a pair of SVG elements positioned at opposite ends

In my project, I have created two scenes and two renderers. One scene is for a simple 3D mesh sphere, while the other is for an SVG circle. The SVG scene is positioned on top of the Mesh scene, acting as an overlay. Both the sphere and the circle are place ...