Skip to content

fix(email): deliver manager verification email with a working link - #675

Merged
sydevs-bot merged 3 commits into
mainfrom
claude/fix-manager-verify-url
Sep 2, 2026
Merged

sydevs-bot merged 3 commits into
mainfrom
claude/fix-manager-verify-url

Conversation

@sydevs-bot

@sydevs-bot sydevs-bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • The manager verification link pointed at /admin/verify/:token, which matches no Payload view — so no manager could ever verify, and an admin had to tick _verified by hand. It is now /admin/managers/verify/:token.
  • It failed silently, not with a 404: isPublicAdminRoute waves 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".
  • A failed send now reaches Sentry. It still does not throw — a throw would roll the manager creation back — so previously a production delivery failure existed only as a pino line.

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-675 reaching ✅ Success at 16:22:14Z. scripts/get-railway-preview-url.ts exits with Missing GITHUB_TOKEN / GITHUB_REPOSITORY / PR_HEAD_SHA — skipping discovery in 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 real auth.verify.generateEmailHTML into Mailpit from a throwaway script; serverEnv validation refused it (PAYLOAD_SECRET, WEMEDITATE_WEB_URL, SAHAJCLOUD_PREVIEW_SECRET and 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 / _verificationToken already exist (20260606_050852_initial_schema.ts:588-589).

Test results

  • Local lean gate: ✓ pnpm lint, pnpm typecheck, pnpm typecheck:tests, pnpm test:unit (119 files / 1541 specs)
  • Targeted specs: ✓ tests/int/manager-verification.int.spec.ts (1), tests/unit/manager-auth-urls.spec.ts (2)
  • CI: ✓ green on a362108 — lint, typecheck, typecheck:tests and pnpm test (unit + integration against the postgres:18 service container) all passed; pnpm test took 6m 35s.
  • Build: N/A — Railway builds on the preview deploy

⚠ 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 caveat tests/AGENTS.md documents — "'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.ts and its RAILWAY_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 on no routable verify link in the email body.

Manual verification

  1. Open the verification link in a private window. admin.autoLogin makes req.user truthy on every dev request, which takes the notFound() 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.
  2. Confirm the reset link still works. It is the sibling that was already correct, and it carries no collection slug; the two are now deliberately asymmetric.
  3. Answer the ticket's two open questions, which this PR does not: which environment the reported manager was created on, and whether RESEND_API_KEY is 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.subject to each Sentry capture. A user-messages send carries a subject the viewer wrote, and that collection 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 (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.js matches verify in the default: branch, gated on segmentTwo === 'verify', with routeParams.collection = segmentOne — so the slug segment is required and there is no collections/ prefix. reset is matched separately by name at case 2: against config.admin.routes.reset, which is why the sibling link written at the same time in the same shape happened to be right. config.routes.admin is not overridden in src/payload.config.ts, so /admin is Payload's default.

Cross-checked against the helper rather than by reading alone:

$ node -e "console.log(require('payload/shared').formatAdminURL({adminRoute:'/admin', path:'/managers/verify/TKN-123'}))"
/admin/managers/verify/TKN-123

Why the existing test proved nothing. tests/unit/email-templates.spec.ts passed https://cloud.test/admin/verify/TKN-123 in 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.ts calls the config's generateEmailHTML and builds its expectation from formatAdminURL, 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 _verificationToken off 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:235 passes email: payload.email and sendVerificationEmail.js:38 calls email.sendEmail(...), while payload.sendEmail is a separate wrapper that captured the adapter method by value at init — so every existing spy in tests/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

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
@sydevs-bot sydevs-bot self-assigned this Sep 2, 2026
@railway-app

railway-app Bot commented Sep 2, 2026 •

Copy link
Copy Markdown

🚅 Deployed to the SahajCloud-pr-675 environment in sahajcloud

Service Status Web Updated
SahajCloud ✅ Success (View Logs) Sep 2, 2026 at 6:11 pm UTC
1 service not affected by this PR
  • mailpit

@sydevs-bot

Copy link
Copy Markdown
Contributor Author

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 SahajCloud-pr-675 going Initializing → Building → Deploying → ✅ Success, the success at 16:22:14Z, and the commit status agrees. CI's "Discover Railway preview URL" step then ran from 16:27:21Z to 16:39:37Z — starting five minutes after that success — and still came up empty, so the smoke specs were skipped.

So the deploy worked and discovery did not find it. If this is worth chasing, the place to look is scripts/get-railway-preview-url.ts and its RAILWAY_API_TOKEN, not a preview that failed to build. I have not investigated further: it is CI infrastructure rather than this PR's diff, and this PR neither caused it nor is blocked by it. Say the word if you would like it filed.

Everything else stands: lint, typecheck, typecheck:tests and pnpm test (unit + integration on the postgres:18 service container) all passed on a362108.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

Comment thread src/collections/Managers/Managers.ts Resolved
Comment thread src/plugins/email/resendAdapter.ts Resolved
@Ardnived Ardnived assigned sydevs-bot and unassigned Ardnived Sep 2, 2026
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
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-675 September 2, 2026 18:08 Destroyed
@sydevs-bot
sydevs-bot merged commit f0ec974 into main Sep 2, 2026
2 checks passed
Ardnived pushed a commit that referenced this pull request Nov 5, 2026
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

This branch was successfully deployed

No deployments
sahajcloud / SahajCloud-pr-675 — da24487c Deployed Sep 2, 2026 by railway-app[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(email): deliver manager verification email with a working link

3 participants