cap icon indicating copy to clipboard operation
cap copied to clipboard

CSP - force usage of 'unsafe-eval' in script-src - 2

Open dioup opened this issue 5 months ago • 8 comments

bug description: This issue follows this previous issue #266 ,

affects:

  • [] standalone
  • [X] widget (ui)
  • [X] widget (wasm solver)
  • [] js server
  • [X] js solver

to reproduce: View previous issue

expected behavior: View previous issue

screenshots: I'm running a django app, and this is the base.html file and all my other .html file heritate from it.

        <script nonce="{{ csp_nonce }}">
            window.CAP_CSS_NONCE = "{{ csp_nonce }}";
            window.CAP_SCRIPT_NONCE = "{{ csp_nonce }}";
        </script>
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
                integrity="sha384-FKyoEForCGlyvwx9Hj09JcYn3nv7wiPVlz7YYwJrWVcXK/BmnVDxM+D2scQbITxI"
                nonce="{{ csp_nonce }}"
                crossorigin="anonymous"
                defer></script>
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/cap.min.js"
                crossorigin="anonymous"
                nonce="{{ csp_nonce }}"
                defer></script>
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/cap-floating.min.js"
                nonce="{{ csp_nonce }}"
                crossorigin="anonymous"
                defer></script>
        {% block extra_js %}
        {% endblock extra_js %}
    </body>
</html>

And the final page implements cap as is:

{% if CAP_WIDGET_ENDPOINT %}
                                <div class="mb-3">
                                    <cap-widget id="floating" data-cap-api-endpoint="{{ CAP_WIDGET_ENDPOINT }}"></cap-widget>
                                    {% for error in form.captcha.errors %}<div class="invalid-feedback d-block">{{ error }}</div>{% endfor %}
                                </div>
                            {% endif %}

Image

The CSP configuration is the following:

SECURE_CSP = {
    "default-src": [CSP.SELF],
    "script-src": [
        CSP.SELF,
        CSP.NONCE,
        "'wasm-unsafe-eval'",
    ],
    "connect-src": [
        CSP.SELF,
        CSP.NONCE,
        # "https://cdn.jsdelivr.net/npm/cap-widget",
        "https://cdn.jsdelivr.net/npm/@cap.js/",
        # "https://cdn.jsdelivr.net/npm/bootstrap",
        "https://cap.eurecom.cafe/",
    ],
    "style-src": [
        CSP.SELF,
        CSP.NONCE,
        # "'unsafe-hashes'",
        # "'sha256-MhtPZXr7+LpJUY5qtMutB+qWfQtMaPccfe7QXtCcEYc='",
    ],
    "img-src": [CSP.SELF, "data:"],
    "font-src": [
        CSP.SELF,
        "https://cdn.jsdelivr.net/npm/[email protected]/font/fonts/",
    ],
    "script-src-elem": [CSP.SELF, "'unsafe-inline'", "https://cdn.jsdelivr.net", ],
    "style-src-elem": [
        CSP.SELF,
        CSP.NONCE,
    ],
    "form-action": [CSP.SELF],
    "frame-src": [CSP.NONE],  # reCAPTCHA iframe
    "frame-ancestors": [CSP.NONE],
    "base-uri": [CSP.SELF],
    "worker-src": [CSP.SELF, "blob:"],
}

versions and environment: Firefox 148.0/Linux Mint/ Cap 1.55

additional context: I read the documentation regarding CSP and my main question is: does unsafe-eval need to be activated in order to make it work?

Thanks for your time and your help.

dioup avatar Jun 08 '26 14:06 dioup

@tiagozip Any ideas for this issue?

dioup avatar Jun 13 '26 12:06 dioup

disable instrumentation for the site key in the Cap admin dashboard (PUT /keys/:siteKey/config with {"instrumentation": false}).

oli217 avatar Jun 16 '26 13:06 oli217

i would not recommend doing this unless you absolutely have to. instrumentation is the one thing making cap significantly more resistant to bots than normal PoW

tiagozip avatar Jun 16 '26 13:06 tiagozip

After running into this myself and agreeing with @tiagozip that disabling instrumentation isn't a good trade-off, I implemented a different workaround that keeps instrumentation enabled and maintains a strict CSP on the parent page.

Iframe isolation approach

The idea is to serve the Cap widget in a dedicated iframe that has its own permissive CSP, while the parent page keeps script-src without 'unsafe-eval'.

Parent page (strict CSP)              /cap-frame (permissive CSP)
┌────────────────────────┐            ┌──────────────────────────────┐
│ no unsafe-eval         │            │ unsafe-eval ✓                │
│                        │◄─token────►│ wasm-unsafe-eval ✓           │
│ window.capSolve()      │            │ new Cap({ apiEndpoint })     │
│ <input hidden #token>  │            │   .solve() → postMessage     │
└────────────────────────┘            └──────────────────────────────┘

How it works:

  1. The parent page renders an invisible <iframe src="/cap-frame"> and a hidden <input> for the token
  2. On form submit, the parent calls window.capSolve(), which sends postMessage({ type: 'cap:start' }) to the iframe
  3. The iframe runs new Cap({ apiEndpoint }).solve() — instrumentation included — under its own permissive CSP
  4. Once resolved, the iframe sends postMessage({ type: 'cap:token', token }) back to the parent
  5. The parent fills the hidden input and submits to the server for /siteverify validation

The iframe's CSP header (set server-side, not inherited from the parent):

Content-Security-Policy:
  default-src 'none';
  script-src 'self' 'unsafe-inline' 'unsafe-eval' 'wasm-unsafe-eval' blob:;
  connect-src *;
  worker-src blob:;
  img-src data:;
  frame-ancestors 'self';

The parent page CSP remains strict — no 'unsafe-eval', no 'unsafe-inline' for scripts.


I implemented this as part of a Laravel package (oliweb/laravel-cap), so the specifics are PHP/Blade, but the approach is entirely framework-agnostic. The key insight is that CSP is per-document: an iframe's response headers define its own policy independently of the parent's.

For Django (or any backend), it would mean:

  • A dedicated view/route returning the Cap iframe page with its own permissive Content-Security-Policy response header
  • A small JS bridge on the parent side to trigger solving and receive the token via postMessage

This keeps instrumentation fully active while satisfying strict CSP requirements on the embedding page. Happy to share more details if useful.

oli217 avatar Jun 16 '26 19:06 oli217

I propose a server-controlled instrumentationMode: "full" | "strict-csp". Strict mode would omit only dynamic-code probes while preserving DOM instrumentation, PoW and server verification. The client would not be able to request the downgrade. I’ll include real CSP E2E tests, Firefox/Chromium coverage and before/after benchmarks. Would this API direction be acceptable?

antoniobezerra avatar Jul 16 '26 02:07 antoniobezerra

i mean, you'd have to remove a very large amount of probes, rendering instrumentation basically useless. id rather not.

tiagozip avatar Jul 16 '26 07:07 tiagozip

Hi @tiagozip,

What are your thoughts on this issue?

dioup avatar Jul 27 '26 10:07 dioup

Better sandboxing and CSP support should ship in the next version of Standalone.

tiagozip avatar Nov 08 '26 09:11 tiagozip