All jobs

Add JWT Login to a Koa API

Yes. An agent adds register and login routes that issue HS256 tokens your koa-jwt middleware already verifies, hashes passwords, tests it, and opens a PR.

Run this on RushOpens the console with this prompt ready to send, in a Project that has your repository.

What the agent does

The agent starts by finding out what the API already does with tokens. In an API laid out like javieraviles/node-typescript-koa-rest, src/server.ts builds a Koa 2.13.1 app with koa-helmet, @koa/cors, a winston logger, koa-bodyparser, an unprotected @koa/router that serves only GET /, and then jwt({ secret: config.jwtSecret }).unless({ path: [/^\/swagger-/] }) from koa-jwt 4.0.0, so every route mounted after that line needs a valid bearer token. The protected router is a SwaggerRouter from koa-swagger-decorator with GET, POST, PUT and DELETE on /users, and deleteUser already reads ctx.state.user.email to refuse deleting someone else. What is missing is any route that issues a token: src/config.ts reads JWT_SECRET with the fallback your-secret-whatever, the README sends readers to jwt.io to sign one by hand, and package-lock.json lists jsonwebtoken 8.5.1 only as a dependency of koa-jwt. There is no password column on the User entity and no bcrypt package.

The agent adds a password column to src/entity/user.ts with select: false, so the existing find() and findOne() calls in UserController keep returning users without it, plus a @Length rule beside the existing @Length(10, 80) on name and @IsEmail() on email. TypeORM 0.2.32 runs with synchronize: true in this app, so the column appears on the next start against the postgres:10-alpine service in docker-compose.yml with no migration to write. Hashing uses bcryptjs rather than the native bcrypt: the Dockerfile installs on node:14-alpine with npm install, and a package that needs no compiler keeps that image build as it is.

A new src/controller/auth.ts holds register and login. register validates a User with class-validator exactly as createUser does, hashes the password and saves through getManager().getRepository(User). login loads the user with addSelect("user.password"), compares with bcryptjs.compare, and on success signs { id, email } with jsonwebtoken using config.jwtSecret and HS256, the algorithm the README names, with an expiry read from a new JWT_EXPIRES_IN entry in config.ts and .example.env. The token carries email because deleteUser compares it. Both routes go on unprotectedRoutes.ts, which server.ts mounts before the koa-jwt line, so nothing in the unless list changes and the swagger pages stay reachable as before. jsonwebtoken and bcryptjs become direct dependencies in package.json with their @types packages, because the project compiles with noImplicitAny.

Tests follow the pattern already in tests/controller/user.test.ts, which mocks typeorm and class-validator with jest.mock and calls the static controller methods with a hand-built Context. tests/controller/auth.test.ts checks that register answers 201 and never stores the plain password, that login answers 200 with a token that jwt.verify decodes with config.jwtSecret to the user's id and email, and that a wrong password answers 401 without saying which field was wrong. The agent runs npm run lint, which is tsc --noEmit followed by eslint with the project's double-quote and semicolon rules, and npm test, which is Jest 26 with ts-jest over tests/**. It also reads .github/workflows/ci.yml, sees runs-on: ubuntu-16.04 and actions/setup-node@v1 with Node 12, and says in the pull request that the runner label is one GitHub no longer provides, without changing it in the same change.

Start it with one API call

POST https://api.phoenix.so/o/{org}/sessions with this body:

{
  "agent": "claude",
  "input": "Add first-party JWT authentication to this Koa + TypeScript API. Read package.json, package-lock.json, src/server.ts, src/config.ts, src/unprotectedRoutes.ts, src/protectedRoutes.ts, src/controller/user.ts, src/entity/user.ts, tests/controller/user.test.ts, .example.env, Dockerfile and .github/workflows/ci.yml first. The app already verifies tokens with koa-jwt and reads ctx.state.user.email in deleteUser, but nothing issues a token. Add a password column to the User entity with select: false, hash passwords with bcryptjs, and add POST /auth/register and POST /auth/login on the unprotected router that sign { id, email } with jsonwebtoken, HS256 and config.jwtSecret, with an expiry from a new JWT_EXPIRES_IN setting. Add jsonwebtoken, bcryptjs and their @types as dependencies. Write tests/controller/auth.test.ts in the same mocked style as the user controller tests, covering register, login, a wrong password and that the token verifies with the secret. Run npm run lint and npm test, update .example.env and the README's authentication section, and open a pull request that quotes the test output and notes anything in ci.yml you did not change.",
  "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/controller/auth.ts and tests/controller/auth.test.ts, changes src/entity/user.ts (the password column), src/controller/index.ts (the export), src/unprotectedRoutes.ts (two routes), src/config.ts and .example.env (the expiry setting), package.json and package-lock.json (two dependencies and their types), and the README section that currently points at jwt.io. Its description quotes the lint and Jest output and shows a curl login and the Authorization: Bearer call that follows it.

A reviewer reads three things: that no response ever includes the password hash, which select: false guarantees for the existing routes and the login query must preserve; that the signed payload matches what deleteUser and any future route read from ctx.state.user; and that register is meant to be public. If the team would rather keep sign-up behind the protected POST /users, as the README's Auth0 note suggests, that is one route removal from the diff.

The README's position that authentication belongs to an external provider is kept in the text, with the new routes described as the option for teams that run without one.

Run it on every new API repository

A team that starts services from this boilerplate sends this body once per new repository from its own server, each POST /o/{org}/sessions naming that repository in resources with a request_id that is a UUID v5 of the repository's full name, so a retried call returns the run it already started instead of a second pull request. Each run reads that repository's entity and config files and adapts the routes to what it finds.

An automation on the Project with a github trigger on pull_request.opened can also read each later pull request that touches src/controller/auth.ts and comment on whether the password still never leaves the server; automation runs read and comment, they do not push, so the pull request that adds the routes comes from the API call above.

The use case this job follows, with its automation and trigger: Hand off a long task.

Why run it on Rush?

Authentication is the change nobody wants to merge on faith. The agent runs the real TypeScript compiler, the project's eslint rules and the Jest suite in its own sandbox, and the pull request carries that output, so the reviewer starts from a passing build rather than from a diff and a promise.

The work is specific to the files it found: the unless list, the select: false column, the email claim that deleteUser depends on. A team with several Koa services starts the same request against each one at once and gets one pull request per service, each shaped by that service's own entities and routers.

Frequently asked questions

Does it change how koa-jwt protects the existing routes?

No. The jwt({ secret }) line in src/server.ts and its unless list stay as they are. The new routes sit on the unprotected router, which is mounted before that middleware, so GET /users and the rest still need a bearer token.

Why bcryptjs and not bcrypt?

The Dockerfile runs npm install on node:14-alpine, which has no compiler. bcryptjs is pure JavaScript, so the image builds unchanged. The hashing API is the same hash and compare.

Will tokens made on jwt.io keep working?

Yes, as long as they are signed with the same JWT_SECRET and HS256. The middleware does not care who signed a token. Routes that read ctx.state.user.email need the claim present, which the new login includes.

Is a database migration needed?

Not in this app. src/server.ts opens TypeORM with synchronize: true, so the new column is created on start. A project that has turned synchronize off gets a migration file in the same pull request instead.

What about refresh tokens or logout?

The change issues one access token with an expiry. Refresh tokens need a place to store them, which this API does not have yet, and the agent says so in the pull request rather than adding a table for it.

More Koa jobs

The same job on other stacks

Keep reading