Skip to content

fix: send security response headers - #120

Merged
uniqueg merged 6 commits into
devfrom
fix/112-security-headers
Nov 19, 2026
Merged

uniqueg merged 6 commits into
devfrom
fix/112-security-headers

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 19, 2026 •

Copy link
Copy Markdown
Member

Summary

Krini sent no security response headers, although any script in its origin can read the user's access token from /auth/api/token, and the code editor loaded its syntax-check workers from cdn.jsdelivr.net. This PR covers finding M2 of the 0.1.0 pre-release review and the NOTICE line of L15.

  • Content Security Policy (src/proxy.ts, src/lib/security-headers.ts): a new nonce for each request, following the Next.js guide: script-src 'self' 'nonce-…' 'strict-dynamic', frame-ancestors 'none', object-src 'none', base-uri 'self', form-action 'self', worker-src 'self', connect-src 'self' https: (the TES and WES origins are known only at runtime), style-src 'self' 'unsafe-inline' (React, the Cloud Components and Ace set styles at runtime), img-src 'self' https: data: blob: (a login provider's logo may be an https URL, which the browser loads directly), font-src 'self'. 'unsafe-eval' and ws: wss: (hot reload) only under next dev.
    • Why a nonce and not a fixed script-src 'self' in headers(): Next.js renders inline scripts (RSC payload, bootstrap) and next-themes adds one, so script-src 'self' alone breaks the app, and 'unsafe-inline' would make the policy useless against injected scripts.
    • The root layout reads the nonce (for next-themes), so every page renders per request. Krini's pages read settings at runtime anyway.
  • Fixed headers (headers() in next.config.ts, every response): X-Content-Type-Options: nosniff, X-Frame-Options: DENY, Referrer-Policy: strict-origin-when-cross-origin and, in production builds only (not next dev), Strict-Transport-Security: max-age=63072000, without includeSubDomains. Browsers ignore HSTS over plain HTTP. poweredByHeader: false.
  • Ace self-hosted, jsdelivr dropped: @elixir-cloud/design hard-codes the CDN as Ace's workerPath and has no basePath option. Ace's setModuleUrl takes precedence over workerPath, though. So src/lib/ace-workers.ts points the six workers of the modes that design loads to /ace/worker-<lang>.js, and starts them from their URL, not from blob:. It runs in the then of the dynamic imports of the Cloud Components. scripts/copy-ace-workers.ts copies the workers from the ace-builds that design resolves, so the versions always match, into public/ace/ (git-ignored) before next dev and next build. The privacy notice no longer names the CDN.
  • NOTICE in the image (L15): COPY --from=build /app/LICENSE /app/NOTICE ./. NOTICE gains Ace's BSD notice, as Krini now serves Ace files itself. scripts/check-image.sh checks for LICENSE, NOTICE and /ace/worker-json.js.
  • Docs: a new "Security headers" section in docs/operator-guide/deployment.md, which also notes that a proxy must not replace the CSP. "Network access" and "Production considerations" no longer mention the CDN. docs/development/index.md explains the copy into public/ace/.

Verification

  • bun run lint: clean. bunx tsc --noEmit: clean.
  • bun run test:coverage: 279 tests passed, 100 % statements, branches, functions and lines. New unit tests cover the policy, the nonce, the fixed headers, the proxy (new nonce per request, nonce passed on to the rendering), the proxy matcher (pages and API routes match, static files don't), the Ace configuration, that every worker exists in ace-builds and gets copied, and that ACE_WORKERS is exactly the set of workers of the modes that @elixir-cloud/design imports.
  • CI=1 bun run test:e2e (Chromium and Firefox): 38 passed.
    • The fixtures now fail every e2e test on any securitypolicyviolation event or any request to cdn.jsdelivr.net. So the whole journey (login and logout through the mock IdP, the TES and WES lists, submitting a workflow and a task, task details, the privacy notice) runs under the CSP without a violation.
    • New e2e/security-headers.spec.ts checks the headers on three pages, that each response gets a new nonce and that the page's scripts carry it, that an image from an https origin (as a remote provider logo) breaks no policy, nosniff on a static file, and that the editor starts its JSON worker from /ace/worker-json.js (200) under the policy.
    • A throw-away spec (not committed) confirmed that the fixtures catch a violation: an injected inline onerror handler was blocked and reported in both browsers.
  • Not run locally: the Docker image build, the image e2e and scripts/check-image.sh. The CI jobs Build image and End-to-end tests (image) cover them.
  • CI on ed12de0 (before the Sourcery fix dec8e1c, which changes only the dev policy and its test): all GitHub checks passed, including CI passed, Build image (with check-image.sh), End-to-end tests (image), Chromium, Firefox, Scan image and CodeQL. There are no open code scanning alerts. The Vercel – krini preview fails, as it does on dev (30c7e34); it is not required.

Notes

  • The workflow form's editors use the language text, which has no worker. So today the CDN was contacted only by editors with JSON, YAML, XML, HTML, CSS or JavaScript. The e2e test switches an editor to JSON to exercise the worker path.
  • 'strict-dynamic' lets scripts that trusted scripts create through DOM APIs run. That is the trade-off Next.js recommends; markup injection (inline scripts and event handlers) is blocked.

Declined review findings

Two review rounds (adversarial and quality). Fixed in round 1:

  • img-src blocked remote provider logos (high)
  • HSTS was sent by next dev too
  • the proxy matcher and the ACE_WORKERS list were untested
  • leaking global stubs in the tests
  • no dev docs for public/ace/

Declined:

  • No runtime switch to turn HSTS off: headers() in next.config.ts is fixed at build time, so a switch would need a new setting read by the proxy. It is documented instead: don't serve Krini on a host that serves other services over plain HTTP, and don't send the header twice from an ingress.
  • Note in upgrading.md: that file belongs to another open PR for this release (session handling). The new behaviour is in "Security headers" in deployment.md, and the release notes can point to it.
  • Flag every request to an origin other than the app or the mocks (not only jsdelivr) in the fixtures: a blocked load already fails the tests as a CSP violation, and allowed https: loads (images, TES and WES) are wanted.
  • Shared directives() test helper for the unit and e2e tests: the two run in different runners (vitest, Playwright), so sharing the helper would couple them for 10 lines.
  • A loadEcc() helper for the six wrappers: a comment in src/lib/ace-workers.ts says every dynamic import of the Cloud Components must use withSelfHostedAce, and the e2e fixtures fail on any CDN request.

Round 2 found nothing high or medium. These lows are declined:

  • A test that every dynamic import of @elixir-cloud/*/react uses withSelfHostedAce: all six do. The comment in src/lib/ace-workers.ts states the rule, and the e2e fixtures fail on any CDN request.
  • Asserting the matcher's prefetch conditions: they are copied from the Next.js guide and only skip responses that are no documents.
  • A friendlier error when @elixir-cloud/design changes its layout: the test fails either way and names the file it read.
  • Sourcery: build-versioned worker URLs for rolling upgrades, and an atomic copy into public/ace/: answered in the threads. Old pages lose their _next/static chunks on a rollout anyway, and the copy runs once per image build.
  • Rejecting http: provider logos in parseProvider: the docs already require an https URL or a path. Checking the settings at start belongs to the follow-up for settings checks (finding L12-L14 of the review, fix: check the settings when Krini starts #103), not to this PR.

Open questions

None.

Closes #112

🤖 Generated with Claude Code

Summary by Sourcery

Protect application responses with nonce-based security headers and serve code-editor workers from the application origin.

New Features:

  • Add per-request Content Security Policy protection with nonce-based script authorization and restrictions on frames, plugins, workers, connections, and forms.
  • Self-host Ace editor workers so code-editor syntax checking no longer depends on jsdelivr.net.

Bug Fixes:

  • Prevent untrusted or third-party scripts from accessing application pages and tokens through missing security response headers.
  • Ensure the production container includes required license and third-party notices and serves the editor workers.

Enhancements:

  • Add standard security headers including nosniff, frame denial, referrer controls, production HSTS, and removal of the Next.js powered-by header.
  • Configure development and production security policies appropriately and pass CSP nonces through page rendering.

Build:

  • Copy the Ace workers matching the Cloud Components dependency into the public assets during development and production builds.
  • Include NOTICE alongside LICENSE in the Docker image and validate both files and the editor worker in image checks.

Deployment:

  • Document the security headers, CSP behavior, proxy requirements, and removal of browser CDN access from deployment guidance.

Documentation:

  • Update development and operator documentation to describe self-hosted editor workers and security-header requirements.
  • Remove the jsdelivr.net dependency from the privacy notice and network-access documentation.

Tests:

  • Add unit and end-to-end coverage for security headers, CSP nonces, request matching, self-hosted Ace workers, and container-served assets.
  • Make end-to-end fixtures fail on CSP violations and requests to the jsdelivr.net CDN.

Chores:

  • Strengthen test isolation by restoring global stubs between tests.

uniqueg and others added 4 commits November 19, 2026 11:03
Krini sent no security headers, while any script in its origin can
read the access token from /auth/api/token and the code editor loaded
its workers from cdn.jsdelivr.net.

- src/proxy.ts sends a Content Security Policy with a new nonce per
  request (script-src 'self' 'nonce-...' 'strict-dynamic',
  frame-ancestors 'none', object-src 'none', base-uri 'self',
  form-action 'self', worker-src 'self', connect-src 'self' https:);
  the root layout reads the nonce for next-themes, so all pages render
  per request
- next.config.ts sends X-Content-Type-Options, X-Frame-Options,
  Referrer-Policy and Strict-Transport-Security with every response,
  and no X-Powered-By
- the editor's workers are copied from ace-builds to public/ace/ before
  next dev and next build, and Ace loads them from there, so no script
  comes from a CDN; the privacy notice no longer names the CDN
- e2e: the fixtures fail every test on a CSP violation or a CDN
  request; a new spec checks the headers, the nonces and the worker
- docs: "Security headers" in deployment.md

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The image had LICENSE but not NOTICE, which carries the notices of
shadcn/ui, the fonts and now Ace, whose workers Krini serves itself.
The image check makes sure both files are there and that the image
serves the editor's workers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- unit tests for the proxy matcher (pages and API routes match,
  static files don't), and that ACE_WORKERS are exactly the workers
  of the modes that @elixir-cloud/design imports
- unstub globals after every test (vitest config)
- dev docs: the copy of the editor's workers into public/ace/

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- img-src allows https: origins: a login provider's logo may be an
  https URL, which the browser loads directly (unoptimized)
- Strict-Transport-Security only in production builds, as it binds
  the whole host to HTTPS (e.g. next dev --experimental-https)
- e2e: an image from the mock services' https origin breaks no policy

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@vercel

vercel Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
krini Ready Ready Preview Nov 19, 2026 11:19am UTC

@vercel
vercel Bot temporarily deployed to Preview – krini November 19, 2026 10:49 Inactive
@sourcery-ai

sourcery-ai Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

API

Define and send the per-response CSP nonce and fixed security headers, and pass the nonce to Next.js so rendered scripts and next-themes comply with the policy.

  • next.config.ts L2, L18-28
  • src/lib/security-headers.ts L1-91
  • src/proxy.ts L1-47

Uses of the API

Configure Ace workers after each Cloud Components module loads and pass the module through that configuration so editor workers use Krini’s origin.

  • src/app/dashboard/tasks/_components/ecc-tes-create-run-wrapper.tsx L4, L9
  • src/app/dashboard/tasks/_components/ecc-tes-run-wrapper.tsx L5, L11
  • src/app/dashboard/tasks/_components/ecc-tes-task-wrapper.tsx L5, L12
  • src/app/dashboard/workflows/_components/ecc-wes-create-run-wrapper.tsx L4, L10
  • src/app/dashboard/workflows/_components/ecc-wes-run-details-wrapper.tsx L5, L12
  • src/app/dashboard/workflows/_components/ecc-wes-run-wrapper.tsx L5, L11
  • src/app/layout.tsx L3, L27-32, L52
  • src/lib/ace-workers.ts L1-61

Implementation

Copy the Ace worker files from the dependency version used by the design components into the directory Krini serves.

  • scripts/copy-ace-workers.ts L1-9
  • src/lib/ace-worker-files.ts L1-42

UI

Remove the privacy notice’s disclosure of the Ace worker CDN now that the workers are self-hosted.

  • src/app/privacy/page.tsx L183 (removed lines)

Configuration

Wire worker copying into development and production builds, include NOTICE in the image, and extend the image check for the notice and worker asset.

  • .gitignore L21-25
  • Dockerfile L50
  • package.json L6-7
  • scripts/check-image.sh L6-8, L29-35, L58-63

Ensure Vitest restores global stubs between tests.

  • vitest.config.mts L15

Documentation

Document the self-hosted editor workers for development and explain the response security headers and deployment considerations.

  • NOTICE L28-54
  • docs/development/index.md L41-47
  • docs/operator-guide/deployment.md L362-364, L388-443

Tests

Test the CSP and nonce generation, fixed headers, proxy matching and nonce forwarding, and the availability and configuration of the self-hosted Ace workers.

  • src/lib/ace-worker-files.test.ts L1-79
  • src/lib/ace-workers.test.ts L1-56
  • src/lib/security-headers.test.ts L1-113
  • src/proxy.test.ts L1-67

Fail end-to-end tests on CSP violations or CDN requests and verify the response headers, nonce propagation, static-file MIME handling, remote images, and self-hosted editor workers.

  • e2e/fixtures.ts L4-5, L64-66, L78-97
  • e2e/security-headers.spec.ts L1-131

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@codecov

codecov Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (37ee4cf) to head (97754dc).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #120   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           20        23    +3     
  Lines          564       591   +27     
  Branches       160       163    +3     
=========================================
+ Hits           564       591   +27     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@read-the-docs-community

read-the-docs-community Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Documentation build overview

📚 krini | 🛠️ Build #36010922 | 📁 Comparing 97754dc against latest (30c7e34)

  🔍 Preview build  

3 files changed
± development/index.html
± operator-guide/configuration/index.html
± operator-guide/deployment/index.html

@uniqueg
uniqueg marked this pull request as ready for review November 19, 2026 10:53
@uniqueg
uniqueg requested a review from AnonymousXC as a code owner November 19, 2026 10:53
@sourcery-ai

sourcery-ai Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Linked issues

Checked at commit 97754dc

#112 fix: send security response headers · 6 of 6 met

# Requirement Status Notes
1 Send a nonce-based Content Security Policy with the requested restrictions ✅ Met The proxy creates a new nonce per request and sends the policy; the root layout passes the nonce to next-themes.
2 Self-host Ace’s workers so no script comes from a CDN ✅ Met The build and dev scripts copy Ace workers into public/ace/, and the Cloud Components wrappers configure Ace to load them from Krini.
3 Send the fixed security headers and disable X-Powered-By ✅ Met next.config.ts configures the requested headers, enables HSTS only in production, and sets poweredByHeader to false.
4 Ship NOTICE next to LICENSE in the image ✅ Met The Dockerfile copies both files into the image, and NOTICE includes Ace’s notice.
5 Add an end-to-end test of the headers and that the app runs without CSP violations ✅ Met The new spec checks response headers, nonces, and the self-hosted worker; the shared fixtures fail on CSP violations and CDN requests.
6 Document the security headers in docs/operator-guide/deployment.md ✅ Met

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 3 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="src/lib/ace-workers.ts" line_range="43" />
<code_context>
+                    (event) => {
+                        console.error(
+                            `CSP violation: ${event.effectiveDirective} ${event.blockedURI}`,
+                        );
+                    },
+                );
</code_context>
<issue_to_address>
**Rolling upgrades mix worker versions**

When a browser keeps an editor page from the old build and requests its worker during or after a rollout to a build with an incompatible Ace worker protocol, the old page's worker request can reach a new replica and receive a worker built for a protocol-incompatible Ace version, so the editor's syntax checks fail.

Use build-versioned worker URLs and keep each build's workers available for pages still running that build.
</issue_to_address>

### Comment 2
<location path="src/lib/ace-worker-files.ts" line_range="35" />
<code_context>
+function copyAceWorkers(target: string): void {
+    mkdirSync(target, { recursive: true });
+    for (const worker of ACE_WORKERS) {
+        copyFileSync(
+            aceWorkerSource(worker),
+            join(target, `worker-${worker}.js`),
</code_context>
<issue_to_address>
**Concurrent builds corrupt worker files**

When a build or dev startup runs while another server in the same checkout is serving `public/ace/`, and a worker request overlaps the copy, `copyAceWorkers` copies directly into the directory an active server serves, so overlapping or interrupted copies expose empty or incomplete worker files and the editor's syntax checks fail.

Copy the complete worker set to a staging directory and publish it atomically so serving processes never see an in-progress set.
</issue_to_address>

### Comment 3
<location path="src/lib/security-headers.ts" line_range="37" />
<code_context>
+        // login providers' logos may be `https` URLs (`docs/operator-guide/login.md`)
+        "img-src 'self' https: data: blob:",
+        "font-src 'self'",
+        "connect-src 'self' https:",
+        // the syntax checks of the code editor (`src/lib/ace-workers.ts`)
+        "worker-src 'self'",
</code_context>
<issue_to_address>
**Development hot reload stops**

When the dev server runs over HTTP in a browser that treats WebSocket schemes separately from the page’s scheme, the `connect-src 'self' https:` directive blocks the dev server’s `ws://` or `wss://` HMR connection, so hot reload stops working.

Allow the dev server’s WebSocket schemes by adding `ws:` and `wss:` to `connect-src`.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 3 findings to address first, and browsers cache the two-year HSTS policy and upgrade HTTP requests for this hostname on every port; if the host also serves an HTTP-only service, reverting the change will not immediately undo the resulting access failures for visitors who cached the policy. CSP-related breakage is otherwise reversible by correcting or removing the policy.

Blocking findings: src/lib/ace-workers.ts:43, src/lib/ace-worker-files.ts:35, src/lib/security-headers.ts:37


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread src/lib/ace-workers.ts Resolved
Comment thread src/lib/ace-worker-files.ts Resolved
Comment thread src/lib/security-headers.ts Resolved
Browsers in which 'self' doesn't cover WebSockets would block the hot
reload of next dev; production builds are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@vercel
vercel Bot temporarily deployed to Preview – krini November 19, 2026 11:01 Inactive
@vercel
vercel Bot temporarily deployed to Preview – krini November 19, 2026 11:19 Inactive
@uniqueg
uniqueg merged commit ececc90 into dev Nov 19, 2026
44 checks passed
@uniqueg
uniqueg deleted the fix/112-security-headers branch November 19, 2026 11:27
uniqueg added a commit that referenced this pull request Nov 19, 2026
Add the fixes of the pre-release review, merged into dev since the
last refresh: security headers and self-hosted editor workers (#112,
#120), session refresh and logout (#106, #111, #119), and the registry
URL example (#113, #114).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

This branch was previously deployed

1 inactive deployment
Preview – krini — 97754dc9 Deployed Nov 19, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix: send security response headers

1 participant