# Add Password Reset to a Fastify API

Yes. An agent adds forgot-password and reset-password routes to a Fastify app with a hashed one-time token, a migration, rate limits and tests, and opens a PR.

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

## What the agent does

The agent reads how the app is put together before it adds a route. In an API shaped like fastify/demo, `package.json` pins `fastify` ^5.10.0, TypeScript ~6.0.3 with `"type": "module"`, `knex` on `mysql2`, `postgrator` for migrations, `@fastify/session` with `@fastify/cookie`, `@fastify/rate-limit`, `@fastify/swagger` and `@fastify/type-provider-typebox`. `src/app.ts` autoloads `plugins/external`, then `plugins/app`, then `routes`. `src/routes/api/autohooks.ts` adds an `onRequest` hook that rejects any `/api` request without `request.session.user`, with `/api/auth/login` as the only exception. `src/routes/api/auth/index.ts` holds `POST /login`; `src/routes/api/users/index.ts` holds `PUT /update-password` behind a `rateLimit` of 3 per minute and the `UpdateCredentialsSchema` from `src/schemas/users.ts`, whose `PasswordSchema` requires 8 characters with upper, lower, digit and symbol. `src/plugins/app/password-manager.ts` hashes with `scrypt`; `src/plugins/app/users/users-repository.ts` has `findByEmail`, `updatePassword` and `findUserRolesByEmail`. There is no mail dependency anywhere in `package.json`.

It adds the storage first. `migrations/006.do.password_resets.sql` creates a `password_resets` table with `user_id` referencing `users`, a `token_hash` column, `expires_at`, `used_at` and `created_at`, and `006.undo.password_resets.sql` drops it, matching the `do`/`undo` pairs numbered 001 to 005 that `npm run db:migrate` applies. The repository gains `findById`, `createPasswordReset`, `findValidPasswordReset` and `markPasswordResetUsed`, each a `knex` call in the style of `findByEmail`. Only a SHA-256 hash of the token is stored; the raw token exists in the email and nowhere else.

Then the routes, in `src/routes/api/auth/index.ts` beside `/login`. `POST /forgot-password` takes `{ email }` on the existing `EmailSchema` from `src/schemas/common.ts`, looks the user up, and answers the same `200` body whether or not the address exists, so the endpoint cannot be used to list accounts. For a known user it writes a reset row with a token from `randomBytes`, an expiry one hour out, and hands the raw token to a new `mailer` decorator in `src/plugins/app/mailer.ts`. Because the demo sends no mail, the default mailer logs the reset link through `fastify.log` with the token redacted and the pull request marks the single function to replace with a provider call. `POST /reset-password` takes `{ token, newPassword }` with `PasswordSchema`, hashes the token, finds an unused, unexpired row, hashes the password with `passwordManager.hash`, calls `updatePassword` and marks the row used in one `knex.transaction`. Both routes join `/api/auth/login` in the `autohooks.ts` exception and both carry a per-route `rateLimit` of 3 per minute, the same figure `update-password` uses; both are tagged `Authentication` so they appear in Swagger.

Tests go in `test/routes/api/auth/password-reset.test.ts`, using `build` from `test/helper.ts` and `node:test` the way `test/routes/api/users/users.test.ts` does: insert a user through `app.knex('users')`, request a reset, read the row back, and assert that a wrong token, an expired token and a reused token are refused, that a bad password shape fails through `expectValidationError`, and that after a good reset `app.login` succeeds with the new password. The run then does what `.github/workflows/ci.yml` does: `npm run build -- --noEmit`, `npm run lint`, and `npm run db:migrate && npm run test` against a MySQL 8.4 with `RATE_LIMIT_MAX=4` and `CAN_SEED_DATABASE=1`.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add a password reset flow to this Fastify API and open a pull request. Read package.json, src/app.ts, src/server.ts, src/routes/api/autohooks.ts, src/routes/api/auth/index.ts, src/routes/api/users/index.ts, src/plugins/app/password-manager.ts, src/plugins/app/users/users-repository.ts, src/schemas/common.ts, src/schemas/users.ts, the migrations directory, test/helper.ts, test/routes/api/users/users.test.ts, .env.example and .github/workflows/ci.yml first. Add migrations/006.do.password_resets.sql and 006.undo.password_resets.sql for a password_resets table that stores a SHA-256 token hash, expires_at, used_at and the user id. Add POST /api/auth/forgot-password, which answers the same 200 body whether or not the email exists and for a known user stores a reset row and passes the raw token to a mailer decorator in src/plugins/app/mailer.ts that logs with the token redacted by default, and POST /api/auth/reset-password, which takes token and newPassword on the existing PasswordSchema, refuses wrong, expired and used tokens, and updates the password and marks the row used in one transaction. Exempt both routes in autohooks.ts and give each a per-route rateLimit of 3 per minute. Add test/routes/api/auth/password-reset.test.ts in the node:test style of the users tests covering every refusal and a login with the new password. Run npm run build -- --noEmit, npm run lint and npm run db:migrate && npm run test, and paste the test output in the pull request.",
  "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 adds two migration files, one mailer plugin, one test file and a block in `src/routes/api/auth/index.ts`, and edits `users-repository.ts` and `autohooks.ts`. The description shows the `node:test` output with the new cases listed by name, the `c8` coverage table that `npm run test` prints, and the Swagger entries for the two new routes.

On a repository with this `CI` workflow the pull request runs the TypeScript build, the `neostandard` lint and the test suite on Node 22 and 24 against a MySQL service, with the new migration applied by `npm run db:migrate` before the tests start.

A reviewer checks that `forgot-password` never reveals whether an address exists, that the stored value is a hash and not the token, that the reset marks the row used inside the same transaction as the password update, and that the `mailer` decorator is the only place that needs a real provider. Then they wire that function to their email service and set the public URL the link should point at.

## Run it on every Fastify service with login but no reset

A team with several Fastify services sends one `POST /o/{org}/sessions` per repository with this prompt and that repository in `resources`. Each run reads its own session plugin, schema folder and migration numbering, so a service on Postgres with `knex` gets a Postgres migration and a service that already has a mail plugin gets its reset email sent through it, and each opens its own pull request with tests in that project's runner.

Give the API key a `webhook_url` and Rush POSTs `run.completed` when each turn ends, with the `session_url` to read the pull request and the test output from.

## Why run it on Rush?

A reset flow is the part of an auth system that attackers probe first: an endpoint that answers differently for unknown emails lists your users, and a token stored in clear turns a database read into an account takeover. In a Rush sandbox the agent runs the project's own `node:test` suite against a real MySQL, including the refusals for expired and reused tokens and a login with the new password, and keeps that output in the run's record, so the pull request shows the flow working rather than describing it.

The demo's conventions are specific: autoloaded plugin folders, TypeBox schemas, a session hook that denies by default, numbered `do`/`undo` migrations. An agent that reads them produces a change that looks like the rest of the codebase, and the same request body does that on every Fastify service a team owns, one sandbox each.

## Frequently asked questions

### The app has no email library. What does it send?

Nothing, by default. The run adds a `mailer` decorator whose `sendPasswordReset` logs the event through `fastify.log` with the token redacted, and the pull request points at that one function as the place to call a provider. The tests read the token from the database row, so they do not depend on mail.

### Does it log existing sessions out after a reset?

The demo registers `@fastify/session` without a store, so sessions live in process memory and there is no list to revoke from. The pull request says so and notes that a service with a Redis or database session store can delete the user's sessions in the same transaction.

### Why hash the token if it expires in an hour?

Because a read of the `password_resets` table within that hour would otherwise hand over a working link. A SHA-256 hash costs nothing to compute on each attempt and makes the stored row useless on its own.

### Will the rate limit block my tests?

The existing tests run with `RATE_LIMIT_MAX=4`, and the new routes carry their own per-route limit of 3 per minute like `update-password` does. The new test file builds a fresh app per case the way `users.test.ts` does, so the counters start empty.

## More Fastify jobs

- [Add Prometheus Metrics to a Fastify App](https://getrush.ai/run/add-prometheus-metrics/fastify/)
- [Add a Redis Session Store to a Fastify App from a Linear Issue](https://getrush.ai/run/add-redis-sessions/fastify/)
- [Add Request IDs and Structured Logging to a Fastify App](https://getrush.ai/run/add-request-id-logging/fastify/)

## The same job on other stacks

- [Add Password Reset to a Filament Admin Panel](https://getrush.ai/run/add-password-reset/filament/)
- [Add a Password Reset Flow to a Symfony App](https://getrush.ai/run/add-password-reset/symfony/)
- [Add Password Reset to an AdonisJS App](https://getrush.ai/run/add-password-reset/adonisjs/)

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