Repository navigation
fix(email): deliver manager verification email with a working link - #675
Conversation
Creating a manager emails a verification link that matches no view, so the manager can never verify and an admin has to tick `_verified` by hand. `Managers.ts` built `/admin/verify/:token`. Payload serves the verify view at `/:collectionSlug/verify/:token` (`getRouteData.js` — the `default:` branch, gated on `segmentTwo === 'verify'`), so the slug segment is required and there is no `collections/` prefix: `/admin/managers/verify/:token`. A two-segment URL falls into `case 2:`, which only knows `reset`, a collection and a global — `ViewToRender` stays null and the default view is returned. It fails SILENTLY rather than 404ing, which is why it survived since #483. `isPublicAdminRoute` returns true for any route containing `/verify/`, so the auth gate never fires and a logged-out recipient — the real-world case — is redirected to `/admin` and then to the login form. Reproducing locally shows a 404 instead, because `admin.autoLogin` makes `req.user` truthy on every dev request. The sibling reset link written at the same time is correct, because `reset` IS matched by name at two segments. Also reports a failed send to Sentry. Every path in the Resend adapter returns rather than throws — deliberately, since `sendVerificationEmail` runs inside the manager-create transaction and a throw would roll the account back — so nothing reaches the Sentry plugin's `afterError` hook, and a production delivery failure existed only as a pino line. The three paths now capture explicitly and still do not throw. Tests: - `tests/unit/manager-auth-urls.spec.ts` pins the URL the CONFIG builds, with expectations composed from Payload's own `formatAdminURL`. The existing template spec could not have caught this: it passes a URL in and asserts it round-trips, so a wrong URL round-trips just as happily. Its fixtures are corrected here too, so they stop documenting the broken shape. - `tests/int/manager-verification.int.spec.ts` closes the loop — creates a manager, extracts the token from the EMAIL rather than the row, verifies with it, and asserts `_verified` flips and login stops throwing `UnverifiedEmail`. It asserts that error by NAME, because a wrong password would also throw there and make the final login look like a pass for free. Both specs were watched failing with the defect reintroduced at its real site (the template literal in `Managers.ts`), then restored. Closes #320 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mva72DLxKBWJkgLkRXKwnA
Found in this branch's own security pass, which the trigger pattern requires because the diff touches `src/collections/Managers/`. The first version attached `message.subject` to each capture. A `user-messages` send carries a subject the VIEWER wrote (`ScreenUserMessages` passes `message.subject` straight through, wrapped by `sendUserMessage` as `[client] subject`), and `user-messages` is in `RESTRICTED_COLLECTIONS` precisely because it holds personal data — so that would have copied restricted free text into a third-party error tracker on every delivery failure. Nothing from the message goes now. The pino line beside each capture already carries the detail, in the log system meant to hold it. The Resend API error's own `message`/`name` stay: those are the provider's, not the sender's. Documented in `docs/rules/email.md` beside the non-throwing rule, and in the adapter, so the next reader does not "enrich" them back. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mva72DLxKBWJkgLkRXKwnA
|
🚅 Deployed to the SahajCloud-pr-675 environment in sahajcloud
1 service not affected by this PR
|
|
Correcting myself on the smoke note above — the preview environment is not missing. I have fixed the body; this comment is so the change is not silent. Railway's own bot comment on this PR reports So the deploy worked and discovery did not find it. If this is worth chasing, the place to look is Everything else stands: 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
Eight lines restating what the route is, where three carry the only part a reader cannot get from the code: dropping the slug segment fails SILENTLY, because `isPublicAdminRoute` waves any path containing `/verify/` past the auth gate, so a logged-out recipient lands on the login form instead of a 404. The rest duplicated `tests/int/manager-verification.int.spec.ts`, which explains the same route at the assertion that pins it. The circular- import note went with it: `Managers.slug` inside `Managers` fails loudly at runtime, so it does not need a comment to prevent it. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_018v3xF7dEdnpu1JWMDEVSht
Both findings from the security review of this PR's endpoint. **A dropped email reported success, after destroying the old token.** `payload.sendEmail` does not throw here: every failure path in `resendAdapter` returns instead, deliberately, because the same adapter runs inside the manager-create transaction where a throw would roll the account back. So the endpoint's try/catch was dead code for the ordinary delivery failure — a missing RESEND_API_KEY, a Resend outage — and the sequence was: rotate the token (revoking the link the manager may already be holding), drop the message, log "re-sent", return 200. That is the #320/#675 silent email failure, reintroduced on the path built to rescue it. The adapter's three drop paths now return `{ ok: false, reason }` alongside the Sentry capture they already made. It is a return value, not a throw, so the non-fatal contract is unchanged and every existing caller — all of which ignore the result — behaves exactly as before. Only an explicit `ok: false` counts: Payload's console adapter stands in wherever email is unconfigured and resolves undefined, which must keep reading as sent. The endpoint restores the previous token when it sees a drop, rather than merely reporting one. A failed resend now leaves the manager exactly as it found them, with any outstanding link still working, and answers 502 saying so — which is strictly better than telling an admin to retry an account they have just locked out of its own rescue. **The password hash was being handed to the email template renderer.** `showHiddenFields: true` returns `hash`, `salt` and `resetPasswordToken` too, and the whole object was spread into the `user` passed to `generateEmailHTML`, whose output is emailed. Nothing reads them — `VerifyEmail` takes `name` and `email` — so this was never exploitable, but it is live credentials crossing into a renderer one careless template edit from mattering, and it is wider than Payload's own create path, which passes the post-afterRead doc with hidden fields stripped. Now an explicit projection of id / name / email / collection / the new token. The new assertion was watched failing twice, at both sites that would really cause it: ignoring the drop (the behaviour above) leaves the token rotated, and reporting the drop without restoring leaves it rotated too. Both go red; neither half of the assertion is decorative. Also verified since the review, which flagged it as unchecked: the route is genuinely reachable and the gate genuinely fires on a real HTTP request. Against a booted dev server, `POST /api/managers/1/resend-verification` with no credentials answers 403 while `POST /api/managers/1/no-such-endpoint` answers 404 — so the path is registered, `routeParams.id` arrives, and the 403 is this handler rather than a catch-all. The integration specs call the handler directly and cannot see any of that. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_014oQ3V1YBH5pnFvprMCbB6A
Summary
/admin/verify/:token, which matches no Payload view — so no manager could ever verify, and an admin had to tick_verifiedby hand. It is now/admin/managers/verify/:token.isPublicAdminRoutewaves any route containing/verify/past the auth gate, so a logged-out recipient was redirected to the login form. Indistinguishable from "they never got the email".Changes
src/collections/Managers/Managers.ts— the one-line URL fix, with the route shape recorded beside it.src/plugins/email/resendAdapter.ts— Sentry capture on the three non-throwing failure paths.docs/rules/email.md— why the adapter must not throw and therefore reports itself; and a table of the two token URLs, which have deliberately different shapes.Preview
The preview deployed fine; I just could not discover its URL, and neither could CI. Railway's bot reports
SahajCloud-pr-675reaching ✅ Success at 16:22:14Z.scripts/get-railway-preview-url.tsexits withMissing GITHUB_TOKEN / GITHUB_REPOSITORY / PR_HEAD_SHA — skipping discoveryin my sandbox, so I have no URL to give you rather than one I constructed — and CI's own discovery step came up empty too (see the smoke note below). The environment is in the Railway dashboard.Email previews
None, and I would rather say so than hand you a link I did not verify. There is no
scripts/preview-auth-emails.ts— the four preview scripts cover registration, notification, reminder/digest and event mail. I tried to drive the realauth.verify.generateEmailHTMLinto Mailpit from a throwaway script;serverEnvvalidation refused it (PAYLOAD_SECRET,WEMEDITATE_WEB_URL,SAHAJCLOUD_PREVIEW_SECRETand more are unset here), and the script was deleted rather than committed. The rendered link is asserted in both new specs instead.Migration
None — no schema change.
_verified/_verificationTokenalready exist (20260606_050852_initial_schema.ts:588-589).Test results
pnpm lint,pnpm typecheck,pnpm typecheck:tests,pnpm test:unit(119 files / 1541 specs)tests/int/manager-verification.int.spec.ts(1),tests/unit/manager-auth-urls.spec.ts(2)a362108—lint,typecheck,typecheck:testsandpnpm test(unit + integration against the postgres:18 service container) all passed;pnpm testtook 6m 35s.⚠ The green check does not mean the smoke lane ran. Step 13, "Run smoke specs against the Railway preview", is
skipped: discovery found nothing, and step 12 ("Warn when the smoke lane was skipped") fired instead. That is the exact caveattests/AGENTS.mddocuments — "'Lint, Test & Smoke: pass' can mean smoke never ran".This is not a preview that failed to build (an earlier version of this section said so, and was wrong — corrected in a comment below rather than silently). Railway reported ✅ Success at 16:22:14Z; CI's discovery step ran 16:27:21Z → 16:39:37Z, starting five minutes after that, and still found nothing. So if it is worth chasing, the place to look is
scripts/get-railway-preview-url.tsand itsRAILWAY_API_TOKEN— not the deploy. Nothing in this diff touches an endpoint the smoke specs exercise, so I do not believe it is hiding anything here; happy to file it separately if you want.Both new specs were watched failing. The defect was reintroduced at its real site — the template literal in
Managers.ts— and each went red before being restored: the unit spec on the URL assertion, the integration spec onno routable verify link in the email body.Manual verification
admin.autoLoginmakesreq.usertruthy on every dev request, which takes thenotFound()branch — so logged in you see a 404 where a real recipient saw a silent redirect to the login form. Neither is the bug's real face.RESEND_API_KEYis set on the production Railway service. Both are dashboard-only. If other transactional mail is arriving, the key is set and this URL was the whole bug.Notes for reviewer
One finding from this branch's own security pass, worth your eye. The first version attached
message.subjectto each Sentry capture. Auser-messagessend carries a subject the viewer wrote, and that collection is inRESTRICTED_COLLECTIONSprecisely because it holds personal data — so that would have copied restricted free text into a third-party error tracker on every delivery failure. Nothing from the message goes now (second commit). Push back if you would rather trade that for a more actionable Sentry issue; the pino line beside each capture still has the detail.Scope held to the ticket. Two things it lists as out of scope were left alone: re-sending to managers already stuck unverified (admins keep using the manual toggle), and surfacing send failures in the admin UI (that belongs with #664). The preview-links-point-at-production defect the ticket found while investigating is also untouched — it is a real, separate bug.
Detail — how the route claim was verified, and why the old test could not catch this
The route, read from Payload's own source rather than inferred.
node_modules/@payloadcms/next/dist/views/Root/getRouteData.jsmatches verify in thedefault:branch, gated onsegmentTwo === 'verify', withrouteParams.collection = segmentOne— so the slug segment is required and there is nocollections/prefix.resetis matched separately by name atcase 2:againstconfig.admin.routes.reset, which is why the sibling link written at the same time in the same shape happened to be right.config.routes.adminis not overridden insrc/payload.config.ts, so/adminis Payload's default.Cross-checked against the helper rather than by reading alone:
Why the existing test proved nothing.
tests/unit/email-templates.spec.tspassedhttps://cloud.test/admin/verify/TKN-123in as a prop and asserted it came back out. A wrong URL round-trips exactly as happily as a right one — the template is not the thing that decides the URL. That spec is still valuable as a render contract, so it stays; its fixtures are corrected here only so they stop documenting the broken shape, and a note at the top says where the shape is actually pinned.tests/unit/manager-auth-urls.spec.tscalls the config'sgenerateEmailHTMLand builds its expectation fromformatAdminURL, so it cannot drift from the router in the direction the bug went. It also asserts the two plausible-but-dead shapes are absent — including the four-segment/admin/collections/managers/verify/, which is the obvious "fix" for someone who notices the slug is missing and reaches for the list route.Why the integration spec reads the token out of the email. Reading
_verificationTokenoff the row would pass even if the template embedded no token at all. It also asserts the pre-verification login failure by error name (UnverifiedEmail) — a wrong password would throw there too, and would make the final successful login look like a pass for free.Per the ticket's warning,
vi.spyOn(payload, 'sendEmail')is not used:create.js:235passesemail: payload.emailandsendVerificationEmail.js:38callsemail.sendEmail(...), whilepayload.sendEmailis a separate wrapper that captured the adapter method by value at init — so every existing spy intests/int/is blind to auth mail.createTestEnvironmentWithEmail()+findEmailByTo()is used instead.The integration lane had to be brought up first, and doing so surfaced a defect in #674 — reported on that PR, not fixed here.
Closes #320
🤖 Written by the sydevs autonomous loop — see what this is
🤖 Generated with Claude Code
https://claude.ai/code/session_01Mva72DLxKBWJkgLkRXKwnA