Skip to content

CSP nonce silently degrades to unsafe-inline without warning #3859

@SisyphusZheng

Description

@SisyphusZheng

Problem

When a route handler returns ctx.html() or ctx.json() instead of ctx.render(), the CSP middleware silently falls back to 'unsafe-inline' without any warning.

Root Cause

In packages/fresh/src/middlewares/csp.ts, when useNonce: true is configured:

  1. The middleware reads the nonce from the response: (res as any)[NONCE_SYMBOL] (line 119)
  2. ctx.render() sets this symbol via RenderState → response (context.ts:503)
  3. But ctx.html(), ctx.json(), ctx.text(), ctx.redirect() never set it
  4. When nonce is undefined, the CSP directive silently includes 'unsafe-inline' instead of 'nonce-${nonce}' (line 131-133)
  5. No warning is logged anywhere

This means a developer who configures useNonce: true thinking all routes are protected, but has some routes using ctx.html(), gets zero indication that those routes degraded to a weaker CSP.

Suggested Fix

Add a console.warn in development mode when useNonce: true is configured but no nonce was found on the response:

if (nonce === undefined && force) {
    console.warn(
        `CSP middleware configured with useNonce but no nonce found. ` +
        `Falling back to 'unsafe-inline'. Use ctx.render() or set the nonce manually.`,
    );
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions