# Add API Key Authentication to a Koa API

Yes. An agent adds hashed API keys to your Koa and TypeORM app beside its JWT auth, with create and revoke routes, a header middleware, tests and a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-api-key-auth/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 requests are authenticated today. In an app laid out like javieraviles/node-typescript-koa-rest, `src/server.ts` opens a TypeORM `postgres` connection with `synchronize: true` and entities from `config.dbEntitiesPath`, then stacks `helmet.contentSecurityPolicy`, `cors()`, the winston middleware from `src/logger.ts`, `bodyParser()`, the unprotected router, `jwt({ secret: config.jwtSecret }).unless({ path: [/^\/swagger-/] })` and the protected router. `src/protectedRoutes.ts` is a `SwaggerRouter` from `koa-swagger-decorator` with the five `/users` routes and `DELETE /testusers`, and `src/controller/user.ts` reaches the database through `getManager().getRepository(User)` with `class-validator` on the entity from `src/entity/user.ts`. `package.json` pins `koa ^2.13.1`, `koa-jwt ^4.0.0`, `typeorm ^0.2.32`, `pg ^8.5.1` and `winston ^3.3.3`, tests with `jest ^26.6.3` through `ts-jest`, and declares `node 14.x.x`; `tests/controller/user.test.ts` mocks `typeorm` and `class-validator` with `jest.mock`, so the suite runs with no database. `.example.env` lists `PORT`, `NODE_ENV`, `JWT_SECRET` and `DATABASE_URL`.

A JWT identifies a person for a while; an API key identifies a machine client until someone revokes it, so it needs storage. The agent adds `src/entity/apiKey.ts` with `id`, `name`, `prefix` (the first characters of the secret, for display and lookup), `keyHash` (a SHA-256 of the full secret, which is enough for a random 32-byte value that no human chose), `createdAt`, `lastUsedAt` and a nullable `revokedAt`, and `synchronize: true` creates the table the way it created `user`. `src/middleware/apiKey.ts` reads `X-API-Key`, hashes it, looks up an unrevoked row by hash, puts the row on `ctx.state.apiKey`, and updates `lastUsedAt` no more than once a minute per key to keep a busy client from writing on every call. A missing header calls `next()` so the JWT middleware applies as before; a header that matches nothing answers `401` with a plain message, in the style the existing controllers use for `400`. The secret itself comes from `crypto.randomBytes` encoded as hex, which the Node 12 the CI workflow runs and the Node 14 in `engines` and the Dockerfile all encode the same way.

The two middlewares have to agree on who is exempt from what. `koa-jwt` uses `koa-unless`, which takes a `custom` predicate as well as `path`, so the JWT line becomes `.unless({ path: [/^\/swagger-/], custom: (ctx) => Boolean(ctx.state.apiKey) })`, and the API key middleware is mounted just before it. Key management stays behind the JWT: `src/controller/apiKey.ts` adds `POST /api-keys`, which returns the full secret once in the `201` body and stores only the hash, `GET /api-keys`, which lists name, prefix, dates and revocation, and `DELETE /api-keys/:id`, which sets `revokedAt`; a request authenticated with an API key cannot create or revoke keys. The controller uses the same `@request`, `@summary`, `@body` and `@tagsAll` decorators as `user.ts`, so the swagger page the `SwaggerRouter` serves documents the new routes without extra work.

Tests follow the suite's style, with `jest.mock("typeorm")` and a repository object whose `findOne` is a `jest.fn`. The middleware tests cover a valid key (state is set, `next` runs), a revoked key and an unknown key (`401`, `next` does not run), and no header (`next` runs, state is empty). The controller tests cover creation returning a hex secret whose hash equals what was saved, and revocation of an unknown id answering `400`. The agent runs `npm run lint`, which runs `tsc --noEmit` and then eslint with `--fix`, commits whatever eslint rewrote, runs `npm test`, and adds the routes to the README's endpoint table and a `curl` example with `X-API-Key` next to the existing bearer example.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add API key authentication to this Koa, TypeScript and TypeORM API alongside its JWT middleware. Read package.json, src/server.ts, src/config.ts, src/logger.ts, src/protectedRoutes.ts, src/unprotectedRoutes.ts, src/controller/user.ts, src/entity/user.ts, tests/controller/user.test.ts, .example.env, Dockerfile and README.md first. Add an ApiKey entity with id, name, prefix, keyHash, createdAt, lastUsedAt and a nullable revokedAt. Add src/middleware/apiKey.ts that reads X-API-Key, hashes it with SHA-256, loads an unrevoked key by hash, sets ctx.state.apiKey, updates lastUsedAt at most once a minute per key, answers 401 for an unknown or revoked key and calls next when the header is absent. Mount it before koa-jwt and add a custom predicate to the unless call so a request with a valid key skips the JWT. Add a controller with POST /api-keys returning the hex secret once, GET /api-keys and DELETE /api-keys/:id behind the JWT only, using the swagger decorators the user controller uses. Write jest tests for the middleware and controller with the suite's typeorm mocks. Run npm run lint and npm test, document the routes and a curl example in the README, and open a pull request that quotes 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 adds `src/entity/apiKey.ts`, `src/middleware/apiKey.ts`, `src/controller/apiKey.ts`, `tests/middleware/apiKey.test.ts` and `tests/controller/apiKey.test.ts`, and changes `src/server.ts` (the mount order and the `unless` predicate), `src/protectedRoutes.ts` (the three routes), `src/controller/index.ts` and `README.md`. Its description quotes the `jest` output, shows the `201` body of a key creation with the secret and the `401` for a revoked one, from a run against the `docker-compose.yml` Postgres in the sandbox.

A reviewer checks the hashing choice (SHA-256 of a random secret is fine; it would not be for a user-chosen password), that `GET /api-keys` never returns the hash, that the `lastUsedAt` throttle cannot lose the first use of a key, and whether key management should be limited to a role once the app has one; the entity and the routes are shaped so a role check slots into the controller.

Existing clients with a bearer token see no change. The swagger routes stay outside both middlewares, and `DELETE /testusers` stays where it was.

## Run it on every new machine client

The next integration that needs a key is the moment to check the scheme still holds. An automation on the Project with a `github` trigger on `pull_request.opened` and `pull_request.synchronize` runs read-only with a prompt that looks for routes added to `protectedRoutes.ts` that mutate keys without the JWT-only guard, or handlers that read `X-API-Key` directly instead of `ctx.state.apiKey`, and comments on the pull request. The trigger adds the pull request after the prompt and fills in no placeholder.

A handler on your own server that reads the comment sends this body to `POST /o/{org}/sessions` with the route's name appended to the prompt and the branch in `resources` as `https://github.com/your-org/your-app/tree/<branch>`, with a `request_id` that is a UUID v5 of the head SHA so a redelivery returns the run it already started. That run pushes the fix, and the key's `webhook_url` gets `run.completed`.

## Why run it on Rush?

Authentication middleware is only shown correct by the order it runs in and the requests it refuses, which a mocked unit test half covers. The agent starts the Postgres from `docker-compose.yml` in its own sandbox after installing Docker (`sudo apt-get install -y docker.io`, then `dockerd`; that package ships `docker-compose` v1), creates a key, calls `/users` with it, revokes it and calls again, and keeps those four responses in the run's record beside the tests.

Most teams have several Koa or Express services with a JWT and no story for machine clients, and each grows its own `X-API-Key` check by hand. One run per repository reads that service's auth stack and opens one pull request each, so the header name, the hashing and the revoke route are the same across all of them.

## Frequently asked questions

### Why SHA-256 rather than bcrypt for the key?

The secret is 32 random bytes the server generated, not a password a person chose, so there is nothing for a slow hash to defend against; a plain SHA-256 lets the lookup be an indexed equality on `keyHash`. The pull request says this so nobody later reuses the column for user passwords.

### Can an API key create other keys?

No. The three `/api-keys` routes require a JWT; the `unless` predicate only exempts a request from the JWT check when `ctx.state.apiKey` is set, and the key controller refuses when it is. Issuing and revoking keys stays a person's action.

### Does it change the existing tests?

No. `tests/controller/user.test.ts` mocks `typeorm` and calls controllers directly, so it never runs the middleware stack. The new tests use the same mocks and never open a connection.

### What about synchronize: true in production?

The app already relies on it for the `user` table, and the new entity follows the same path. A team that has moved to migrations writes one for `api_key`; the entity's columns are listed in the pull request for that.

### Is the secret ever logged?

No. The winston middleware logs method, URL, status and duration, not headers. The agent adds the key's `name` to that line when `ctx.state.apiKey` is set, which is the identifier a reviewer wants in logs, and never the header value.

## More Koa jobs

- [Add Compression to a Koa App](https://getrush.ai/run/add-compression/koa/)
- [Add CORS to a Koa App](https://getrush.ai/run/add-cors/koa/)
- [Add Test Coverage to CI for a Koa API](https://getrush.ai/run/add-coverage-to-ci/koa/)

## The same job on other stacks

- [Add API Key Authentication to a Litestar App](https://getrush.ai/run/add-api-key-auth/litestar/)
- [Add API Key Auth to a Serverless Framework API](https://getrush.ai/run/add-api-key-auth/serverless/)
- [Add API Key Authentication to a Slim 4 App](https://getrush.ai/run/add-api-key-auth/slim/)

## 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/)
