# Add Account Lockout After Failed Logins to a Node.js App

Yes. An agent picks up the Linear issue, adds failed-attempt counting and a temporary lockout to your Express login, tests it without a database and opens a PR.

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

## What the agent does

The agent clones the app into its own cloud sandbox and reads the login path before changing it. In an Express app like OWASP/NodeGoat, `app/routes/session.js` handles `POST /login` by calling `userDAO.validateLogin(userName, password, callback)` and renders `login.html` with a `loginError` of `Invalid username` or `Invalid password`, with a comment pointing at the fix that uses one message for both. `app/data/user-dao.js` looks the user up with `usersCol.findOne({ userName })` on the MongoDB 2.x callback driver and compares the password; the bcrypt comparison is present but commented out. There is no counter, no timestamp and no limit: a script can try passwords against `admin` forever, and `artifacts/db-reset.js` seeds `admin`, `user1` and `user2` with known passwords. `package.json` runs tests with `grunt test`, whose `mochaTest:unit` target points at `test/unit/*.js`, a directory that does not exist, so `npm test` currently runs no tests at all.

It makes the lockout a property of the user record rather than of the process, because the app runs under `forever` and may run as several instances. `validateLogin` gains two fields on the user document, `failedLoginAttempts` and `lockUntil`. On a wrong password it increments the counter with `$inc` and, when the counter reaches the limit, sets `lockUntil` to now plus the lockout window with one `updateOne`; on a correct password it resets both with `$unset`. While `lockUntil` is in the future, the login is refused before the password is compared, so a locked account cannot be used to learn whether a guess was right. The limit and the window live in `config/env/all.js` as `maxLoginAttempts` and `lockoutMinutes` next to the existing `port` and `db`, with the test and production environment files able to override them.

In `session.js` the locked case renders the same generic message as a wrong password, with a short note on the account's lock in the server log, including the user name and the time the lock ends, so an operator can see a brute-force attempt without the attacker learning anything from the page. The agent applies the existing identical-error fix from the comments while it is there, since a lockout that leaks which user names exist is half a fix. `app/views/login.html` needs no change: it already renders whatever `loginError` it is given.

It proves the behaviour with the first unit tests the repository has. `test/unit/user-dao-lockout.js` builds a `UserDAO` around a fake `db` whose `collection('users')` returns an in-memory object with `findOne`, `updateOne` and the update operators the DAO uses, so the tests need no MongoDB and no network. They cover a wrong password incrementing the counter, the limit setting `lockUntil`, a correct password while locked still being refused, the lock expiring, and a success clearing both fields. Because `test/unit` now exists, `npm test` runs them through the existing Grunt target. The agent also runs `grunt precommit`, which runs jsbeautifier and jshint, and puts both outputs in the pull request.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add account lockout after repeated failed logins to this Express app. Read the login route, the user data access object, the config files and the test setup first, and say how a login fails today. Store a failed-attempt counter and a lock-until time on the user document with atomic updates, refuse login while locked before comparing the password, reset both on success, and put the attempt limit and lockout window in the config with the other settings. Render one generic error for wrong password, unknown user and locked account, and log the lock server-side with the user name and expiry. Write mocha unit tests around a fake users collection so they need no database, make sure the existing test command runs them, run the tests and lint, and open a pull request that links the Linear issue and explains every new field.",
  "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

What comes back is a pull request that links the Linear issue, changing `app/data/user-dao.js`, `app/routes/session.js` and `config/env/all.js`, and adding `test/unit/user-dao-lockout.js`. The description names the two new fields on the user document, the two new config keys and their defaults, the exact error message every failed login now shows, and the log line an operator will see when a lock starts.

The run's record keeps the `npm test` and `grunt precommit` runs from the sandbox, so a reviewer sees the lockout tests pass and jshint stay clean, and can read the fake collection the tests use to judge whether it models the driver calls faithfully.

Before merging, a reviewer chooses the limit and window for production, decides whether an administrator needs a way to clear a lock without waiting, and checks that the generic error does not break the Cypress end-to-end tests under `test/e2e`, which look for specific text on the login page.

## Run it on every Linear issue labelled security

Sign in to Linear once with `POST /me/connections {"type": "app", "name": "linear"}` and finish the authorize URL in the console. Then add an automation to the Project that has the app, with this prompt and a `linear` trigger on `linear.issue.labeled`, filtered to the label your security backlog uses. The trigger adds the issue after the prompt, so an issue that says which limit and window the team wants, or which accounts are being targeted, reaches the run without editing the prompt. Only a label change made by a person in your Rush org fires it, and the automation starts at most `max_runs_per_hour` runs in an hour.

The same body also starts from a script, with the issue as a second entry in `resources` as `https://linear.app/<workspace>/issue/<ID>`, read through your Linear connection, and a `request_id` that is a UUID v5 of the issue id so a retried call returns the run it already started.

## Why run it on Rush?

A lockout is easy to describe and easy to get subtly wrong: a counter kept in memory resets on every restart, a check after the password comparison still leaks timing, and a message that differs for locked accounts tells an attacker which user names exist. The agent reads the real route and data access code in its sandbox, keeps the state on the user document, and proves each rule with a test before the pull request exists.

The pull request links the issue it came from, and the run's record keeps every command and its output, so the reviewer argues about the limit and the window rather than about whether the tests were run. The same prompt handles the next security issue on the next service without anyone setting up a laptop for it.

## Frequently asked questions

### Why store the counter on the user document rather than in memory?

Because the app's `Procfile` and `forever` setup mean more than one process can serve logins, and a restart would clear an in-memory map. Two fields on the user document with `$inc` and `updateOne` make the count correct across processes and survive a deploy, and the fake collection in the tests models exactly those calls.

### Will it lock out real users who mistype a few times?

Only past the limit in `maxLoginAttempts`, and only for `lockoutMinutes`. Both live in `config/env/all.js` and can differ per environment. The pull request suggests values and asks the reviewer to confirm them, since the right limit depends on who uses the app.

### Does the lockout also apply to the signup or password change routes?

No. The change is to `POST /login` and the `validateLogin` function it calls. Signup validation in `session.js` and profile updates in `profile.js` are untouched, and the pull request says so, with a note on which of them might deserve a rate limit next.

### How do the tests run without MongoDB?

`UserDAO` takes a `db` object and asks it for `collection('users')`, so the test passes a fake that keeps users in an array and implements `findOne`, `updateOne` and the `$inc`, `$set` and `$unset` operators the DAO uses. No `mongod`, no Docker and no network, which is why the tests run in CI as fast as the lint does.

### Will the error message change break the end-to-end tests?

Yes, one of them. The Cypress spec `test/e2e/integration/login_spec.js` asserts on `Invalid password` and `Invalid username`, so with one generic message its two expectations need the new text. The agent lists the lines rather than editing tests it cannot run in the sandbox, and the pull request names them so the reviewer can update them in the same change.

## More Node.js jobs

- [Add CSRF Protection to a Node.js App](https://getrush.ai/run/add-csrf-protection/nodejs/)
- [Add ESLint to a Node.js App](https://getrush.ai/run/add-eslint/nodejs/)
- [Add Graceful Shutdown to a Node.js Server](https://getrush.ai/run/add-graceful-shutdown/nodejs/)

## The same job on other stacks

- [Add Account Lockout to a Passport Local Login](https://getrush.ai/run/add-account-lockout/passport/)
- [Add Account Lockout to a Mongoose and Express App](https://getrush.ai/run/add-account-lockout/mongoose/)

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

- [Make Celery Tasks Survive a Worker Crash With acks_late](https://getrush.ai/run/add-acks-late/celery/)

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