# Add Security Headers to a Koa App

Yes. An agent adds koa-helmet to your Koa app, fits the Content Security Policy to your templates, asserts the headers in supertest and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-security-headers/koa/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads how responses are built before it touches headers, because a Content Security Policy that is wrong for the templates breaks the pages it is meant to protect. In a project like koajs/examples, the root `package.json` pins `koa` at `^2.2.0`, `@koa/router` at `^8.0.5`, `koa-body` at `^4.0.8`, `koa-views` at `^6.0.2` and `swig-templates` at `^2.0.3`, with `mocha` `^5.0.0`, `supertest` `^3.0.0` and `should` `^3.3.2` for tests; `engines.node` is `>= 7.6`, the `test` script is `NODE_ENV=test mocha --harmony --reporter spec --require should */test.js`, and `.travis.yml` runs `npm run lint` and `npm test` on Node `stable` and `8`. There is no `.github` directory. The `blog` example is the one that renders HTML: `blog/app.js` exports `module.exports = new Koa()`, mounts `koa-logger`, the `koa-views` renderer from `blog/lib/render.js` (which maps `.html` to swig) and `koaBody()`, registers `GET /`, `GET /post/new`, `GET /post/:id` and `POST /post`, and calls `app.listen(3000)` only when `!module.parent`.

The templates decide the policy. `blog/views/layout.html` carries one inline `<style>` block for the page layout and loads no script at all; `new.html` posts a plain form to `/post`, and `list.html` and `show.html` are links and text. That is a good fit for Helmet's defaults: its Content Security Policy sets `default-src 'self'`, `script-src 'self'`, `script-src-attr 'none'`, `object-src 'none'`, `form-action 'self'`, `frame-ancestors 'self'`, `img-src 'self' data:` and `style-src 'self' https: 'unsafe-inline'`, so the inline stylesheet keeps working and a script injected into a post body does not. The agent chooses `koa-helmet`, a wrapper with no direct dependencies and peer ranges of `helmet` `^6 || ^7 || ^8` and `koa` `^2 || ^3`, and installs it with `helmet` 8. Both require Node 18, so the pull request raises `engines.node` to `>=18` and moves `.travis.yml` off Node 8, which cannot run the test suite with these packages anyway.

In `blog/app.js` the agent adds `const helmet = require('koa-helmet')` and `app.use(helmet())` as the first middleware, ahead of `logger()`, so a response produced by `ctx.throw(404, 'invalid post id')` in `show` carries the headers too. Helmet's default set is `Content-Security-Policy`, `Cross-Origin-Opener-Policy`, `Cross-Origin-Resource-Policy`, `Origin-Agent-Cluster`, `Referrer-Policy`, `Strict-Transport-Security` with `max-age=31536000; includeSubDomains`, `X-Content-Type-Options`, `X-DNS-Prefetch-Control`, `X-Download-Options`, `X-Frame-Options: SAMEORIGIN`, `X-Permitted-Cross-Domain-Policies` and `X-XSS-Protection`; it also strips `X-Powered-By`, which Koa never sets. The agent leaves `upgrade-insecure-requests` in the policy and says in the pull request that it is a no-op for the `http://localhost:3000` the example listens on, and that a deployment behind a TLS terminator is where `Strict-Transport-Security` takes effect.

The tests already mount the app with `supertest.agent(app.listen())` and close the server in `after`. The agent adds a `describe('security headers')` block to `blog/test.js` that requests `GET /` and asserts `content-security-policy` contains `default-src 'self'`, `x-frame-options` is `SAMEORIGIN`, `x-content-type-options` is `nosniff`, `referrer-policy` is `no-referrer` and `strict-transport-security` is present, then requests `GET /post/999` and asserts the 404 carries the same `x-frame-options`. It runs `npm test` and `npm run lint` under the repository's `eslint-config-koa` rules in its sandbox, and opens the page in its browser to confirm the inline stylesheet still applies and the new-post form still submits with the policy on.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add security headers to this Koa app with koa-helmet. Read package.json, .travis.yml, .eslintrc.yml, blog/app.js, blog/lib/render.js, every template in blog/views and blog/test.js first. Install koa-helmet and helmet, raise engines.node to what they need and update the CI Node versions to match. Mount helmet() as the first middleware in blog/app.js so error responses get the headers too. Keep Helmet's default Content Security Policy unless a template needs something it blocks, and if so loosen only that directive and explain why in the pull request. Add tests to blog/test.js that assert the Content-Security-Policy, X-Frame-Options, X-Content-Type-Options, Referrer-Policy and Strict-Transport-Security headers on a 200 and on a 404. Run npm test and npm run lint, load the blog pages in a browser to confirm the inline styles and the post form still work, and open a pull request with the output.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

The pull request changes `package.json` (two new dependencies and the `engines` floor), `package-lock.json` if the repository has one, `.travis.yml`, `blog/app.js` and `blog/test.js`. Its description lists every header the middleware adds with its default value, quotes the Content Security Policy line by line against what `layout.html` needs, and pastes the `mocha` and `eslint` output.

A reviewer sees the two-line change to the app and the assertions beside the existing `Blog` tests, so the headers are verified the same way the routes are. The run's record keeps the `curl -i localhost:3000/` the agent made after mounting the middleware, with the full header block, and a screenshot of the blog pages rendering under the policy.

Before merging, a reviewer decides whether `Strict-Transport-Security` belongs on an app that may also be served over plain HTTP in development, whether `frame-ancestors 'self'` is right if the pages are ever embedded, and whether the other examples in the repository that render HTML should get the same two lines. Nothing changes in the routes, the templates or the renderer.

## Run it on every Koa service without security headers

A team with several Koa services sends this body once per repository to `POST /o/{org}/sessions`, each with its own repository in `resources` and a `request_id` that is a UUID v5 of the repository's full name, so a retried call returns the run already started rather than opening a second pull request. Each run reads its own templates, so a service with inline scripts gets a nonce-based `script-src` proposal and an explanation instead of a policy that silently breaks its pages.

Afterwards, an automation on the Project with a `github` trigger on `pull_request.opened` and the prompt "if this pull request adds a template with an inline script, a third-party stylesheet or an external image, check whether the Content Security Policy in app.js still allows it and comment with the directive to change" keeps the policy honest as the templates grow. The trigger adds the pull request after the prompt, and only work by an owner, member or collaborator fires it.

## Why run it on Rush?

Security headers are easy to add and easy to get wrong: a `style-src` that forgets `'unsafe-inline'` blanks a page that relies on an inline stylesheet, and nobody notices until a browser console shows the refusal. The agent reads the templates, picks the policy against them, loads the pages in a real browser in its sandbox and keeps the screenshots, so the review is of evidence rather than of a diff that looks right.

The `npm test` and `npm run lint` output, the `curl -i` header block and the browser session all stay with the run. A team that owns a handful of Koa services runs them at once, each in its own sandbox, and gets one pull request per repository with the same proof attached.

## Frequently asked questions

### Will the Content Security Policy break my pages?

Not the ones in this example, whose only inline content is a stylesheet that Helmet's default `style-src 'self' https: 'unsafe-inline'` allows. The agent reads every template before choosing the policy, and if yours load scripts inline or from a CDN it loosens only the directive that needs it and says why in the pull request. It also loads the pages in a browser under the policy before opening the pull request.

### Why does the pull request change the Node version?

Because `helmet` 8 and `koa-helmet` 9 both declare `engines.node` `>= 18`, and the repository's `package.json` still says `>= 7.6` with `.travis.yml` testing Node 8. The agent raises the floor to 18 and updates CI to match, and notes in the pull request that older Node versions are past their end of life.

### Does it work with Koa 3?

Yes. `koa-helmet` 9 lists `koa` `^2 || ^3` as a peer dependency, and it ships both CommonJS and ES module builds, so `require('koa-helmet')` in this repository's CommonJS files and an `import` in an ES module project both work.

### Why is the middleware mounted before the logger and the router?

Koa middleware runs in registration order, and `koa-helmet` sets the headers on the way in, before `await next()`. Putting it first means a 404 from `ctx.throw` in the `show` handler, or an error page, carries the same headers as a normal response. The test the agent adds checks exactly that on `GET /post/999`.

### Can I turn off Strict-Transport-Security for development?

Yes. `helmet({ strictTransportSecurity: false })` disables that one header while keeping the rest, and a browser ignores the header on a plain HTTP response anyway. The agent keeps the default on and explains in the pull request that the header only matters once the service is behind TLS.

## More Koa jobs

- [Add Soft Delete to a Koa API](https://getrush.ai/run/add-soft-delete/koa/)
- [Add Structured Logging to a Koa API](https://getrush.ai/run/add-structured-logging/koa/)
- [Fix Failing GitHub Actions Checks in a Koa API](https://getrush.ai/run/fix-failing-ci/koa/)

## The same job on other stacks

- [Add Security Headers to a Leptos Axum App](https://getrush.ai/run/add-security-headers/leptos/)
- [Add Security Headers to a Litestar App](https://getrush.ai/run/add-security-headers/litestar/)
- [Add Security Headers to a Node.js App](https://getrush.ai/run/add-security-headers/nodejs/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
