# Verdict: Request changes

Reviewed `add-team-invites` (`3ed7d84`) against `main` (`5b4ff19`). The invitation routes introduce authorization bypasses, SQL injection, and unhandled asynchronous failures.

## Findings (highest severity first)

### 1. [P1] Parameterize the invitation status filter
**Location:** `src/routes/invites.ts:36–41`

`status` is interpolated directly into SQL. Any authenticated user can submit `status=pending' OR true --` to bypass the team filter. A compatible `UNION SELECT` can also expose other tables, including session tokens; parameterizing `teamId` does not protect this interpolation.

**Fix:** Bind status as `$2`, validate it against the supported status values, and reject non-string query values. Add a regression test using an injection payload.

### 2. [P1] Enforce membership-management permissions and restrict grantable roles
**Location:** `src/routes/invites.ts:14–27`

The creation check accepts every team member, despite `canManage()` explicitly reserving membership management for owners/admins. It also persists any supplied role. An ordinary member can invite an attacker-controlled second account as `admin` or `owner`; an invited owner cannot subsequently be removed through the existing removal endpoint. Checking only `canManage()` would still let an admin mint owners.

**Fix:** Require `canManage(membership.rows[0]?.role)` and validate the requested role against an explicit grant policy. Reject `owner` here unless there is a separately authorized ownership workflow; reject unknown roles with 400. Test both ordinary-member creation and unauthorized role grants.

### 3. [P1] Forward asynchronous route failures to Express
**Location:** `src/routes/invites.ts:10–12, 25–27, 35–46`

These async handlers lack the `try/catch` and `next(err)` used by the existing team routes. Express 4 does not automatically handle rejected handler promises. For example, an authenticated member posting `{ "role": "member" }` triggers `email.toLowerCase()` on `undefined`: the request gets no error response, and the default Node 20 unhandled-rejection behavior can terminate the API process. Database failures have the same problem across all three routes.

**Fix:** Wrap all handlers with an Express-4-compatible async error wrapper, or use `try/catch` and `next(err)`. Validate request fields before using them. Test malformed input and rejected database queries to ensure controlled responses rather than unhandled rejections.

### 4. [P1] Bind redemption to the invited email address
**Location:** `src/routes/invites.ts:47–57`

Acceptance never compares `invite.email` with `req.user.email`. Any signed-in account holding a forwarded or leaked link can join the team with the invited role, even when the invitation names someone else.

**Fix:** Compare the authenticated account's email with the invitation email using consistent normalization, and reject mismatches before changing membership. Add a test showing that an unrelated account cannot redeem the token.

### 5. [P1] Consume invitations once, atomically
**Location:** `src/routes/invites.ts:47–59`

Acceptance checks expiration but ignores `status`. An accepted invitation remains usable until expiry: after an administrator removes the recipient, that recipient can reuse the original link to rejoin. The separate membership insert and status update also leave partial state if the second query fails, and a status check alone would not prevent concurrent redemption.

**Fix:** Use a transaction on one checked-out database client. Lock the invitation row, require it to be pending and unexpired, verify the recipient, insert membership, and mark it accepted before committing. Roll back on failure. Test replay after member removal and concurrent acceptance.

### 6. [P1] Authorize access to each team's invitation list
**Location:** `src/routes/invites.ts:35–43`

`requireAuth` is the only access check. An authenticated outsider can enumerate team IDs and retrieve invitee email addresses, roles, and invitation history, even though the existing team endpoint hides teams from non-members. This leak remains after fixing the SQL injection.

**Fix:** Check access to the requested team before querying invitations; use `getRole()` and preferably `canManage()` for invitation administration. Add an outsider-access regression test.

### 7. [P2] Await email delivery or durably enqueue it
**Location:** `src/routes/invites.ts:30–32`

`sendEmail()` returns a promise, but it is neither awaited nor caught. A mailer failure still produces a 201 even though no invitation was delivered, and produces an unhandled rejection that can terminate the process. Adding a surrounding route `try/catch` alone will not catch this detached rejection.

**Fix:** Await delivery within the guarded handler and return a controlled failure, with a retry strategy for the already-created invitation; alternatively, durably enqueue delivery and acknowledge only after enqueueing succeeds. Test a rejected mailer request.

### 8. [P2] Generate invitation secrets with a cryptographic RNG
**Location:** `src/routes/invites.ts:22`; `migrations/002_invites.sql:6`

`Math.random()` is not suitable for bearer credentials and provides no cryptographic unpredictability guarantee. These tokens authorize team membership, potentially with elevated privileges. The schema also does not enforce token uniqueness despite acceptance selecting the first matching row.

**Fix:** Use the already-imported `crypto`, for example `crypto.randomBytes(32).toString("hex")`, and add a unique constraint on `invites.token`.

## Validation

`npm run build` passed. Route-level reproductions with mocked database/email dependencies confirmed the permission bypasses, unchecked recipient/status, raw SQL interpolation, and unhandled rejection paths. PostgreSQL integration tests were not run because no test database was provisioned.
