# Add Two-Factor Authentication to an Express and Mongoose API

Yes. An agent adds TOTP two-factor login to your Express and Mongoose API, with setup, recovery codes and a second login step, tested with supertest, and opens a PR.

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

## What the agent does

The agent starts from the login flow as it exists. In an API laid out like hagopj13/node-express-boilerplate, `src/routes/v1/auth.route.js` has eight routes (`register`, `login`, `logout`, `refresh-tokens`, `forgot-password`, `reset-password`, `send-verification-email`, `verify-email`), each guarded by a Joi schema from `src/validations/auth.validation.js`. `login` calls `authService.loginUserWithEmailAndPassword` and then `tokenService.generateAuthTokens`, which signs an access JWT and a refresh JWT with `config.jwt.secret` and saves the refresh token in the `Token` collection. `src/config/tokens.js` lists four token types, and `src/models/token.model.js` restricts its `type` enum to the three stored ones. `src/models/user.model.js` hides `password` from JSON with the `toJSON` plugin's `private: true`, `src/middlewares/auth.js` wraps `passport.authenticate('jwt')`, and `package.json` pins `mongoose ^5.7.7`, `passport-jwt ^4.0.0`, `jsonwebtoken ^8.5.1`, `joi ^17.3.0` and `jest ^26` with `supertest`. The tests in `tests/integration/auth.test.js` connect to `config.mongoose.url` through `tests/utils/setupTestDB.js`, so they need a MongoDB server.

The design keeps the existing tokens and adds one step. A `twoFactor` subdocument on the user holds `secret` and `pendingSecret` (both `private: true`), `enabled`, and `recoveryCodes`, an array of bcrypt hashes. `POST /v1/auth/2fa/setup`, behind `auth()`, calls otplib 13's `generateSecret()`, stores it as `pendingSecret`, builds the `otpauth://totp/` URI with `generateURI({ issuer, label: user.email, secret })` and returns the secret, the URI and a PNG data URL from the `qrcode` package's `toDataURL`. `POST /v1/auth/2fa/enable` takes a six-digit code, checks it against the pending secret with `verify({ secret, token, epochTolerance: 30 })`, which returns `{ valid, delta }` rather than a boolean, promotes the secret, sets `enabled`, and returns eight recovery codes once, in clear, while storing only their hashes. `POST /v1/auth/2fa/disable` requires a current code. The agent records the time step of the last accepted code so the same code cannot be replayed inside its tolerance window.

Login changes shape only for users with the flag set. `loginUserWithEmailAndPassword` still checks the password; the controller then looks at `user.twoFactor.enabled` and, when it is true, answers with `twoFactorRequired: true` and a new `twoFactor` token instead of the auth pair. That token is a fifth entry in `tokenTypes`, signed like the others with a five-minute expiry from a new `JWT_TWO_FACTOR_EXPIRATION_MINUTES` setting in `src/config/config.js` and `.env.example`, and saved in the `Token` collection so `POST /v1/auth/2fa/verify` can accept it once: it verifies the JWT, finds the stored document, checks the code or a recovery code, deletes the document and only then calls `generateAuthTokens`. The Joi schemas, the swagger comments above each route and `src/docs/components.yml` are extended so the generated docs show the new responses.

The tests follow the file's own pattern: `insertUsers` from `tests/fixtures/user.fixture.js`, then `request(app)` against each route. The agent generates a valid code in the test with otplib's `generate({ secret })` so it never guesses at time, and covers setup, enable with a wrong code, enable with a right code, login with the flag set, verify with a code, verify with a recovery code and the same recovery code twice, and disable. In its sandbox it installs a MongoDB server and starts `mongod` on the address in `.env.example` so `yarn test` runs the whole suite, then `yarn lint` and `yarn prettier`, because the repository's husky hook enforces both.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add TOTP two-factor authentication to this Express and Mongoose API. Read package.json, src/app.js, src/config/config.js, src/config/tokens.js, src/config/passport.js, src/models/user.model.js, src/models/token.model.js, src/services/auth.service.js, src/services/token.service.js, src/controllers/auth.controller.js, src/routes/v1/auth.route.js, src/validations/auth.validation.js, src/docs/components.yml, tests/utils/setupTestDB.js, tests/fixtures/user.fixture.js and tests/integration/auth.test.js first. Use otplib 13 (generateSecret, generate, verify, generateURI) and qrcode. Add a twoFactor subdocument on the user with a private secret, a pending secret, an enabled flag and bcrypt-hashed recovery codes; routes to set up, enable, disable and verify; a short-lived single-use twoFactor token type saved in the Token collection; and a login response that returns twoFactorRequired with that token when the flag is set, otherwise the same response as today. Guard against replaying a code inside the tolerance window. Extend the Joi schemas and the swagger comments. Write supertest integration tests next to the existing ones, generating codes with otplib in the test, start a MongoDB server in the sandbox, and run yarn test, yarn lint and yarn prettier. Open a pull request that quotes the test 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 touches `src/models/user.model.js`, `src/config/tokens.js`, `src/models/token.model.js`, `src/config/config.js`, `.env.example`, `src/services/auth.service.js`, `src/services/token.service.js`, `src/controllers/auth.controller.js`, `src/routes/v1/auth.route.js`, `src/validations/auth.validation.js`, `src/docs/components.yml` and `package.json`, and adds a `twoFactor.service.js` beside the other services plus the new tests in `tests/integration/auth.test.js`. Its description quotes the jest summary for the whole suite and the lint result, and shows the sequence a client follows: login, `twoFactorRequired`, verify, tokens.

A reviewer checks that an account without the flag gets exactly the old login response, that the secret and pending secret never appear in any JSON (the `toJSON` plugin is doing that work, so the field names must carry `private: true`), that recovery codes are returned once and stored hashed, and that the `twoFactor` token is deleted on first use. They also decide whether five minutes is the right life for the intermediate token and whether `epochTolerance: 30` (one period either side) matches their users' clocks.

The access and refresh tokens, the `auth()` middleware and every other route are unchanged, so existing clients keep working until they opt a user in.

## Run it on every Linear issue labelled security

In the console, add an automation on the Project with a `linear` trigger on `linear.issue.labeled` and the label `security`, with the prompt above as its text. When someone on your team adds the label to an issue describing a second factor, the run starts with the issue as its context, does the work in the Project's repository and opens a pull request on its own branch that links back to the issue. Changes made by an app integration never fire the trigger, so only a person's label starts a run.

To start the same run from your own backlog tool instead, send this body to `POST /o/{org}/sessions` with the issue's text appended to the prompt and a `request_id` that is a UUID v5 of the issue id, so a retried delivery returns the run already started rather than a second pull request.

## Why run it on Rush?

Two-factor code is the kind of change that looks right in a diff and fails on a clock. The agent proves it the only way that counts: it starts MongoDB, runs the suite with codes generated for the current time step, replays a code and watches it refused, and the run's record holds every command and its output beside the pull request.

The same change is needed by every API built from the same boilerplate, and each one needs the same care with token types, hidden fields and recovery codes. One run per repository, with the same prompt, produces one pull request each that a reviewer reads in the order the client uses it.

## Frequently asked questions

### Does this change login for users who have not set it up?

No. The controller branches on `user.twoFactor.enabled`, and a user without the flag gets the same `{ user, tokens }` response as before. Clients that know nothing about the new field keep working.

### Which authenticator apps work?

Any that reads an `otpauth://totp/` URI: otplib's defaults are SHA-1, six digits and a 30-second period, which is what Google Authenticator, Authy, 1Password and Microsoft Authenticator expect. The setup response includes the URI and a QR code data URL so the client can show either.

### What if the user loses their phone?

The enable step returns eight recovery codes once. Each is stored as a bcrypt hash and accepted by the verify route in place of a code, then removed, so a used code cannot be used again. The pull request's FAQ in the README tells users to keep them somewhere other than the phone.

### Why a separate twoFactor token instead of a flag on the access token?

Because an access token must mean the user is fully authenticated, and every protected route trusts it. A five-minute token of its own type, saved in the Token collection and deleted when the code is accepted, cannot reach `auth()` at all, since the JWT strategy rejects any type other than `access`.

### How do the tests get a valid code?

They call otplib's `generate({ secret })` with the secret the setup route returned, which produces the code for the current time step, the same one an authenticator app would show. Nothing in the tests sleeps or guesses.

## More Mongoose jobs

- [Fix "Model.find() no longer accepts a callback" After a Mongoose Upgrade](https://getrush.ai/run/fix-mongoose-callback-error/mongoose/)
- [Fix "DeprecationWarning: Mongoose: the `strictQuery` option will be switched back to `false` by default in Mongoose 7"](https://getrush.ai/run/fix-mongoose-strictquery-deprecation-warning/mongoose/)
- [Fix "MongoParseError: options usecreateindex, usefindandmodify are not supported" in Mongoose 6 and Later](https://getrush.ai/run/fix-mongoose-usecreateindex-not-supported/mongoose/)

## The same job on other stacks

- [Add Two-Factor Authentication to a Symfony App](https://getrush.ai/run/add-two-factor-auth/symfony/)
- [Add Two-Factor Authentication to a Filament Admin Panel](https://getrush.ai/run/add-two-factor-auth/filament/)

## More jobs like this: Turn a Linear label into a PR

- [Add Type Hints to a Flask Codebase](https://getrush.ai/run/add-type-hints/flask/)

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