# Review: Add team invitations (#1)

**Verdict: Request changes.**

`3ed7d84` vs `5b4ff19`. The feature shape is right (migration, routes, tests all included, tokens excluded from the list projection), but there are four issues I'd block on: a privilege-escalation hole in invite creation, a SQL-injection + missing-authz combination in the list endpoint, async error handling that will crash or hang the API on ordinary failures, and predictable invite tokens. All are cheap to fix. Details below, ordered by severity.

---

## 1. BLOCKER — Any member can mint an `owner` invite

**Location:** `src/routes/invites.ts:15-23` (`POST /teams/:teamId/invites`)

The handler only checks that the requester is *some* member of the team, then inserts an invite with whatever `role` the request body supplies:

```ts
if (membership.rows.length === 0) {
  return res.status(403).json({ error: "Not a member of this team" });
}
...
await db.query(
  "INSERT INTO invites (team_id, email, role, token, expires_at) VALUES ($1, $2, $3, $4, $5)",
  [teamId, email.toLowerCase(), role, token, expiresAt]
);
```

**Impact:** A plain `member` — who per `src/teams.ts` may not even remove members (`canManage` is owner/admin only) — can invite themselves (or anyone) in as `owner`, fully bypassing the permission model this branch's own `main` established. The accept endpoint inserts `invite.role` verbatim, so the escalation is complete on acceptance. This contradicts the documented invariant "Owners and admins can manage membership."

**Fix:** Reuse the existing helpers instead of a bespoke membership query, and validate `role`:

```ts
const role = await getRole(req.params.teamId, req.user.id);
if (!canManage(role)) return res.status(403).json({ error: "Only admins can invite members" });

const { email, role: inviteRole } = req.body;
if (!EMAIL_RE.test(email ?? "")) return res.status(400).json({ error: "Invalid email" });
const allowed: Role[] = ["admin", "member"];        // never mintable: "owner"
if (!allowed.includes(inviteRole)) return res.status(400).json({ error: "Invalid role" });
```

(Decide separately whether admins may invite other admins or only `member`; either way `owner` must not be assignable here.)

## 2. BLOCKER — SQL injection + no authz on the invite list

**Location:** `src/routes/invites.ts:35-42` (`GET /teams/:teamId/invites`)

```ts
const { status = "pending" } = req.query;
const result = await db.query(
  `SELECT id, email, role, created_at FROM invites
   WHERE team_id = $1 AND status = '${status}'
   ORDER BY created_at DESC`,
  [req.params.teamId]
);
```

Two independent problems:

- `status` is interpolated into the SQL string. `?status=x' OR '1'='1` becomes `... AND status = 'x' OR '1'='1'`, which (AND binds tighter) returns **every invite across every team**. A `UNION` variant can exfiltrate the `token` column, which is excluded from the normal projection precisely because it's a membership credential — see finding 5 for what a leaked token buys.
- The handler has **no membership check at all**: any authenticated user of any team can list any team's pending invites, i.e. the invitee emails (PII) of every team in the system.

**Fix:** Parameterize `status`, allowlist its values, and gate the route on `canManage` (same check as finding 1):

```ts
const status = ["pending", "accepted"].includes(String(req.query.status))
  ? req.query.status : "pending";
await db.query(
  `SELECT id, email, role, created_at FROM invites
   WHERE team_id = $1 AND status = $2 AND expires_at > now()
   ORDER BY created_at DESC`,
  [req.params.teamId, status]
);
```

(Filtering on `expires_at > now()` also stops stale-but-never-accepted invites from piling up in the default listing.)

## 3. BLOCKER — Async errors are unhandled: one bad request can crash the API

**Location:** `src/routes/invites.ts` — all three handlers; also `src/app.ts` mount order is fine, but note `sendEmail` at line 31 is unawaited.

None of the three handlers use try/catch → `next(err)`, unlike every handler in `src/routes/teams.ts`. This stack is Express 4 (`^4.19.2`) + Node 20, where Express does not catch rejected promises from async handlers: the request hangs forever, and the unhandled rejection terminates the process by default. Reachable triggers, all from ordinary client input:

- `POST /teams/999/invites` — nonexistent team → FK violation on `invites.team_id` insert.
- `POST /teams/1/invites` with missing/non-string `email` → `email.toLowerCase()` `TypeError`.
- Mailer down/slow → `sendEmail` rejects; since it's unawaited, the client already got `201 {ok:true}` (a lie — no email was sent) and the rejection surfaces later as a crash.
- `POST /invites/:token/accept` by a user who is already a member → PK violation on `team_members`.

**Impact:** trivially reproducible DoS of the whole service; silent invite-send failures.

**Fix:** Wrap every handler in try/catch → `next(err)` (or add a small `asyncHandler` wrapper and use it on all routes), `await sendEmail(...)` before responding (or explicitly fire-and-forget with `.catch()` logged), validate inputs per finding 1, and return `409`/`204` for "already a member" instead of letting the constraint blow up.

## 4. HIGH — Predictable, non-unique invite tokens

**Location:** `src/routes/invites.ts:24`; `migrations/002_invites.sql:6`

```ts
const token = Math.random().toString(36).slice(2);
```

`Math.random()` is not a CSPRNG (V8's xorshift128+ state is recoverable from observed outputs), and the resulting string is only ~10–11 base36 chars (≤52 bits, sometimes shorter). Acceptance requires only the token, so a guessable/forged token is arbitrary team membership. `crypto` is already imported in this file but unused. Separately, `invites.token` has no UNIQUE constraint, so a collision makes `WHERE token = $1` match an arbitrary row.

**Fix:** `const token = crypto.randomBytes(32).toString("base64url");` and add to the migration:

```sql
token TEXT NOT NULL UNIQUE
```

## 5. HIGH — Accept flow: invite status never checked, not atomic, email not bound

**Location:** `src/routes/invites.ts:44-57` (`POST /invites/:token/accept`)

The handler checks existence and expiry but never `status`. Once user A accepts, the token remains usable until expiry; any other user B who obtains it is inserted into the team — the only guard is the `(team_id, user_id)` PK, which doesn't stop a *different* user. Two concurrent accepts also both succeed (check-then-insert race). And nothing ties acceptance to the invited address: `invite.email` is write-only data — any signed-in user with the token joins.

**Fix:** Make acceptance an atomic claim, and decide the email policy deliberately:

```ts
const claimed = await db.query(
  `UPDATE invites SET status = 'accepted'
   WHERE id = $1 AND status = 'pending' AND expires_at > now()
   RETURNING team_id, role`,
  [invite.id]
);
if (claimed.rows.length === 0) return res.status(410).json({ error: "Invite no longer valid" });
// then, in the same transaction, insert membership
```

If invites are meant to be bound to the invited person, also enforce `req.user.email === invite.email`. If the link is intentionally a bearer credential, that's defensible — but then finding 4 is non-negotiable, and the token must never be readable via finding 2's hole.

## 6. MEDIUM — Nonexistent team returns 500 (see #3), duplicate pending invites unthrottled

`POST /teams/:teamId/invites` never verifies the team exists; a `SELECT` before insert (or catching the FK error) should produce a `404`. Also consider rejecting a second `pending` invite for the same `(team_id, email)` — the same email then receives two live tokens with possibly different roles, and the list view gets noisy.

## 7. LOW — Migration polish

`migrations/002_invites.sql`: add `CHECK (status IN ('pending','accepted'))` and a CHECK on `role` mirroring `team_members`, plus an index on `(team_id, status)` for the list query. Cheap now, annoying later.

## 8. LOW — Tests don't cover (and can't catch) the above

- `test/invites.test.ts` calls the real `sendEmail` with an unset `MAILER_URL` (fetch to `undefined/send`). Because the call is unawaited, the rejection races the test run — the suite can fail nondeterministically. Mock it: `jest.mock("../src/email")`.
- Please add the cases this PR's bugs live in: plain `member` creating an invite → 403; `role: "owner"` → 400; `outsider` listing invites → 403; accepting an already-accepted invite → 410/409; `status` query injection attempts. Given that the happy-path tests passed while every blocker above shipped, the negative paths are where the value is.

---

**Summary:** approve the general design (out-of-band email token flow is the right call, and keeping `token` out of the list projection shows good instincts), but I'm requesting changes on 1–5. Happy to pair on the fixes — everything above is an afternoon of work, and findings 1+2+4 collapse to "reuse `getRole`/`canManage`, parameterize `$2`, and swap in `crypto.randomBytes`."
