middleware.csp_nonce

Page actions AI-ready formats and sharing
Open LLM text
Share with AI
Ask Claude Ask ChatGPT Ask Gemini Ask Copilot

CSP nonce middleware — per-request nonce for Content-Security-Policy.

Generates a cryptographically random nonce per request, stores it in a ContextVar, and injects it into the CSP header on the way out.

CSP nonce middleware — per-request nonce for Content-Security-Policy.

Generates a cryptographically random nonce per request, stores it in a ContextVar, and injects it into the CSP header on the way out.

middleware.csp_nonce

Name Type Default Description
type
qualified_name
element_type
description
source_file
line_number
is_autodoc
autodoc_element
_autodoc_template
_autodoc_url_path
_autodoc_page_type
title
doc_content_hash

Symbols on this page

_set_csp_nonce
function
def _set_csp_nonce(value: str) -> Token

Set the request-scoped CSP nonce ContextVar, returning its reset token.

Internal helper sochirp.server.sendercan re-establish the nonce while aStreamingResponsegenerator drains, without importing the middleware class (keeps the server -> middleware layering one-directional, mirroringrequest_varusage).

Parameters

Name Type Default Description
value str
_reset_csp_nonce
function
def _reset_csp_nonce(token: Token) -> None

Reset the CSP nonce ContextVar from a token returned by_set_csp_nonce().

Parameters

Name Type Default Description
token Token
get_csp_nonce
function
def get_csp_nonce() -> str

Return the CSP nonce for the current request.

RaisesLookupErrorif called outside a request with CSP nonces enabled.

No parameters.

csp_nonce
function
def csp_nonce() -> str

Template global:{{ csp_nonce() }} for <script nonce="...">.

Returns empty string if nonces are not enabled (never breaks templates).

No parameters.

nonce_inline_scripts
function
def nonce_inline_scripts(html: str, nonce: str) -> str

Addnonce="..." to inline <script> tags that lack src/nonce.

Templates that ship inline bootstraps without{{ csp_nonce() }}(notably chirp-ui's theme + shell runtime scripts) would otherwise be blocked by the per-request nonce CSP thatuse_chirp_ui()auto-wires.

Parameters

Name Type Default Description
html str
nonce str
CSPNonceMiddleware
class

Generate a per-request nonce and inject it into the CSP header.

Usage::

app.add_middleware(CSPNonceMiddleware())

Then in templates::

<script nonce="{{ csp_nonce() }}">...</script>

View source · /home/runner/work/chirp/chirp/site/../src/chirp/middleware/csp_nonce.py:1