Skip to content

feat(emails): branded registrant confirmation email with calendar invite - #593

Merged
Ardnived merged 25 commits into
mainfrom
feat/registration-confirmation-email
Jul 20, 2026
Merged

Ardnived merged 25 commits into
mainfrom
feat/registration-confirmation-email

Conversation

@Ardnived

Copy link
Copy Markdown
Contributor

Reopened from #591 to get a fresh Railway preview environment. #591's preview database had persisted an earlier version of this branch's migration (before it was regenerated post-merge), so the renamed migration collided on redeploy and the smoke step couldn't reach a healthy preview. A new PR provisions a clean pr-<n> preview DB — the migration chain was verified to apply cleanly on a fresh database, so this is purely a CI-environment reset, no code change.

Summary

The Atlas widget tells registrants "the link to this class will be emailed to you", but nothing was ever sent — POST /api/events/:id/register created the registration and returned 201. Online registrants never received the join link at all.

  • Registrants now get a confirmation email branded with the client service they registered through, localized to their language, carrying the join URL (or the address + a Get Directions button) and a working calendar invite.
  • A send failure is logged and still returns 201 — the registrant is already registered by then.
  • Supersedes feat(events): registration gating, fullness + ics for atlas redesign #577 item 3 (ICS attachment) and item 5 (joining-info delivery — there was no delivery path; this is it).

Changes

  • src/collections/Clients/Clients.ts — logo / websiteUrl / supportEmail on the Atlas Config tab
  • src/plugins/email/brand.ts — getClientEmailBrand(), per-field fallback to the sahaj-atlas project brand. getEmailBrand and the manager/auth templates are untouched.
  • src/plugins/email/resendAdapter.ts — attachments + replyTo pass-through (were silently dropped)
  • src/collections/Registrations/Registrations.ts — client + locale provenance
  • src/lib/schedule/icsBuilder.ts — VCALENDAR envelope over buildRRuleTemporal
  • src/lib/translations/emailStrings.ts — server-side resolver for the new emails translations group
  • src/lib/notifications/registrationDetails.ts — event → email facts (sibling of eventDetails.ts, reusing its recurrence + address helpers)
  • src/lib/utilities/emailSafeText.ts — header/ICS injection sanitizers
  • src/emails/RegistrationConfirmationEmail.tsx — the template + plain-text alternative
  • src/collections/Events/endpoints/registerForEvent.ts — the send
  • scripts/preview-registration-emails.ts — Ethereal preview (fixtures, or FROM_DB=1 for real data)

Review found & fixed (this branch)

Three security/correctness bugs were caught and fixed during review, each with a regression test:

  1. ICS injection via the calendar name — ical-generator escapes the VEVENT SUMMARY/LOCATION/DESCRIPTION but not the calendar-level NAME/X-WR-CALNAME. A crafted event title injected real calendar lines (a working BEGIN:VALARM component). The /security-review pass missed this — it assumed the library escapes every field; verified by hand that the name is the exception.
  2. Subject header CRLF — the event title flows into the Subject; a CR/LF started a second header (Bcc:). Flagged by /security-review.
  3. ICS endTime RangeError — resolveEnd matched HH:MM but didn't bound-check, so 25:00 threw and — because the throw propagates past the send's best-effort boundary — suppressed the whole email, not just the attachment. Two code-review finders converged on it.

Sanitizers are centralized in emailSafeText.ts (stripNewlines / headerDisplayName), so #589's reminder job reuses one audited implementation. Dismissed findings: normalizeSpaces "no-op regex" (false positive — verified it's U+202F by hexdump), a resend stream-attachment "drop" (already handled — dropped-with-warning or sent via path), import-order nits (ESLint is green; it's the enforcement mechanism), and several "extract a helper" / generalization suggestions judged as ship-time scope creep the prior /simplify pass already declined.

Notes for the reviewer

Three things were load-bearing and non-obvious (from the original implementation):

  • The Resend adapter silently dropped fields — it hand-maps Payload's message onto Resend's payload, so attachments/replyTo didn't error, they just never arrived. The dev nodemailer adapter needed no change (it spreads ...message). Pinned by tests/unit/resend-adapter.spec.ts.
  • EXDATE had to be TZID-qualified — RRuleTemporal.toString() emits exclusions in UTC while DTSTART stays TZID-local, and clients frequently fail to match the two, so a cancelled session would still show. Routing exclusions through ical-generator's structured repeating yields EXDATE;TZID=…. Also: rrule-temporal keeps the RFC's 3TU BYDAY form, which ical-generator rejects, so monthly nth-weekday rules split into byDay + bySetPos.
  • VTIMEZONE is why @touch4it/ical-timezones is here — a bare DTSTART;TZID= with no matching VTIMEZONE is under-specified; Apple can float the time and drift a weekly class by an hour across a DST change. Both deps were confirmed with the user before adding.

Deviations from the ticket: the translations global is not export-only (an ad-hoc read already existed in Events/hooks/eventTitle.ts; the new resolver generalizes it), and there are 19 locales, not 17 (validation uses isValidLocale).

Migration

  • New migration: src/migrations/20260719_213905_registration_client_locale_and_client_email_branding.ts
  • Impact: additive only — a locale enum; nullable columns on clients/_clients_v/registrations; the emails jsonb column on the Atlas translations locale tables; FKs with ON DELETE set null; indexes.
  • Reversible: yes — down drops all of it. Nullable is deliberate: existing rows predate client/locale, so the send treats an unset locale as en and an unset client as the default Atlas brand, no backfill needed.
  • Regenerated after merging main (feat(events): add website field to the Details tab #590's events.website): the original timestamp sorted after feat(events): add website field to the Details tab #590 but its snapshot predated it — the out-of-order snapshot trap. Regeneration also caught a real gap: the emails translations column had been created by no migration (dev/tests use push:true, so it passed; prod applies migrations only, and the Emails admin tab would have failed to save). Both healed — the new snapshot is the full current schema.

Follow-ups (not in this PR)

  • Email amplification — the endpoint sends mail to a caller-supplied address behind a published client key + Cloudflare rate limiting. Not open, but a leaked key could burn the Resend quota; per-destination throttling deserves its own issue.
  • Client branding data is placeholder — 25/26 local services have color1 = #000000 and none have a logo/supportEmail/website, so most emails currently render a black header and route replies to us. Either backfill the data, or (a one-liner) treat #000000 as unset in getClientEmailBrand. Left as a data decision.
  • tests is excluded from tsconfig, so pnpm typecheck doesn't cover test files (surfaced a name: null impossible-state in a test). Worth closing separately.

Test Results

  • Unit: 788 passed (74 files) — incl. ICS builder, template, presentation helpers, translation resolver, Resend adapter, and the new injection/sanitizer specs
  • Integration: 23 passed in event-registration.int.spec.ts; translations-globals guard updated for the new Emails tab
  • Lint ✓ · Typecheck ✓ · full pnpm test green locally

Manual verification

The ICS "imports into Google and Apple Calendar" criterion can't be automated — unit tests pin the wire format (VTIMEZONE present, TZID-qualified DTSTART/EXDATE, exact RRULE across one-off / weekly / fortnightly / monthly / bounded-with-exclusions), but import a real invite.ics to confirm. pnpm tsx scripts/preview-registration-emails.ts (add FROM_DB=1 for real data) sends every state to a throwaway Ethereal inbox; download the .ics and import it into both clients.

🤖 Generated with Claude Code

Ardnived and others added 25 commits July 18, 2026 16:08
ICS generation for the registrant confirmation email. ical-generator (MIT)
has zero runtime dependencies and builds the VCALENDAR envelope;
@touch4it/ical-timezones supplies real VTIMEZONE components via
ical-generator's `timezone.generator` hook.

VTIMEZONE matters: a bare `DTSTART;TZID=Europe/London` with no matching
VTIMEZONE is under-specified per RFC 5545. Google resolves IANA names
anyway, but Apple Calendar is inconsistent and can float the time — which
would drift a weekly class by an hour across a DST boundary.

Refs #582

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Clients gains `logo`, `websiteUrl`, and `supportEmail` on the Atlas Config
tab, and `getClientEmailBrand(client)` resolves them into the existing
`EmailBrand` shape used by every template.

Each field falls back independently to the `sahaj-atlas` project brand, so a
service that configured only a colour still gets a sensible product name and
icon. The logo resolves through Cloudflare Images with an explicit
`format=png` variant — the default `auto` negotiates WebP/AVIF from request
headers an email client doesn't send, and Outlook renders neither.

`getEmailBrand` and the manager/auth templates that call it are untouched.

Refs #582

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
A registration now records where it came from, so the confirmation email —
and the reminder from #589, sent days later — can brand and localize itself
without re-deriving provenance.

`locale` is a select over the 19 configured app locales rather than the broad
ISO 639-1 list used for `Clients.locale` / `Events.languages`: it selects a
translation the CMS actually has. `getLocaleOptions()` derives those options
from `LOCALES` so the list stays single-sourced.

Refs #582

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Purely additive: a locale enum, nullable columns on clients/_clients_v/
registrations, FKs with ON DELETE set null, and their indexes. `down`
reverses all of it.

Nullable is deliberate — existing registrations predate `client`/`locale`, so
the send path treats an unset locale as `en` and an unset client as the
default Atlas brand rather than requiring a backfill.

Refs #582

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…pter

The adapter hand-maps Payload's SendEmailOptions onto Resend's payload and
forwarded only from/to/subject/html/text, so `attachments` and `replyTo` were
silently dropped — no error, just a missing calendar invite and replies
landing with us instead of the client service.

nodemailer allows a Readable `content` that Resend's REST API cannot accept,
so the mapper narrows to string/Buffer (or a hosted `path`) and logs anything
it drops, rather than forwarding a payload that 422s opaquely.

The dev nodemailerAdapter needs no change — verified it spreads `...message`
straight into `transport.sendMail()`, so both fields already pass through.

Refs #582

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`computeIcalRule` exposes a DTSTART/RRULE/EXDATE fragment, but a fragment is
not importable — a client needs the VCALENDAR envelope. This wraps it, taking
every recurrence value from buildRRuleTemporal() so timezone, COUNT/UNTIL
bounds, and EXDATE exclusions keep one source of truth.

Three things were needed to clear the "imports into Google *and* Apple" bar:

- VTIMEZONE. A bare DTSTART;TZID with no matching component is
  under-specified; Apple can fall back to floating local time and drift a
  weekly class by an hour across a DST change.
- TZID-qualified EXDATE. RRuleTemporal.toString() emits exclusions in UTC
  while DTSTART stays TZID-local, and clients frequently fail to match the
  two — so a cancelled session still shows. Routing exclusions through
  ical-generator's structured `repeating` yields EXDATE;TZID=...
- BYDAY prefix split. rrule-temporal keeps the RFC's '3TU' form; ical-generator
  validates byDay against a bare two-letter enum and throws, so monthly
  nth-weekday rules split into byDay + bySetPos.

A one-off stays a plain VEVENT — its internal FREQ=DAILY;COUNT=1 modelling
must not leak out and render a single class as a series.

Refs #582

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Adds the `emails` group to the Atlas translations schema (it becomes an admin
tab automatically) and a resolver that reads it for a locale, so templates take
resolved strings as props and never issue a payload.find themselves.

Two fallback layers, because they catch different failures. Payload's own
locale fallback covers a wholly untranslated locale — the JSON field is unset,
so the English field substitutes wholesale. It does *not* cover a partially
translated locale: fallback is per field, not per key, so a blob that exists
but omits a key resolves to undefined and renders blank. English key defaults
cover that, plus an unfilled key and a fresh install.

A failed read logs and yields English rather than throwing — a missing
translation must not stop a confirmation email going out.

Note: the ticket describes the global as export-only, but there is already an
ad-hoc server-side read of `event.titlePrefix` in Events/hooks/eventTitle.ts.
This generalizes that pattern (including its promise memoization, which avoids
a stampede when several sends share a request) rather than inventing one.

Refs #582

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…n email

Sibling to eventDetails.ts, which shapes the same Event for the manager
verification email. `recurrencePhrase` and `addressOneLine` are exported from
there and reused rather than reimplemented — two emails describing the same
class differently would be a bug of its own.

Registrant-specific additions: a start–end time span carrying the timezone, a
maps link preferring geocoded coordinates over the address text, and a session
count for count-bounded courses only (an until-bounded run's total needs the
recurrence expanded, which the ICS attachment already covers).

Location is a discriminated union rather than nullable fields, so the template
cannot render an address and a join link at once — and an online event with no
URL degrades to `unspecified` instead of an empty button.

Description uses Payload's own convertLexicalToPlaintext rather than a
hand-rolled Lexical walker.

Refs #582

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Reads as a guest email, not an admin notification. EventVerificationEmail is
built around a coloured callout banner demanding action by a deadline; this has
no callout, no deadline, and no urgency colour — a labelled itinerary whose only
accent is the client service's own brand.

EmailLayout / BrandButton / styles are reused unchanged. The one addition is a
local label-above-value row; it stays in this file rather than the shared layout
until a second template wants it.

The join URL renders twice for online events — as the CTA and as selectable
plain text — because button-stripping clients are common and that URL is the
single most important thing in the email.

Ships a plain-text alternative beside the component so the two can't drift; the
adapters accept one and no template sent it before.

Refs #582

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Composes the four new seams — client branding, localized copy, shaped event
facts, and the ICS attachment — and sends from the register endpoint.

The send is best-effort: the registrant is already registered by the time it
runs, so a failure is logged and the response stays 201. It is awaited rather
than fire-and-forget, since a floating promise can be killed by the runtime
when the response returns, dropping the email silently.

`sendRegistrationConfirmation` itself throws; the policy lives at the call site
where the response is decided. #589's reminder job will want retry, not
swallow, from the same function.

An unsupported `locale` is a 400 rather than a silent default to `en`, so a
widget bug is visible instead of quietly shipping every registrant English.

`From` stays CONTACT_EMAIL — Resend verifies senders per domain, so we can't
send as the client. The client name carries the branding and Reply-To routes
replies to their supportEmail.

Refs #582

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…nd path

Per the /simplify efficiency pass: loading the client's branding and resolving
the localized copy are independent reads that ran back to back inside the
registration request.

The second result is discarded at the call site on purpose — resolveEmailStrings
memoizes its in-flight promise on req.context, so the call inside the send
reuses this one rather than issuing a second read.

Refs #582

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
- email.md: add the two missing templates to the table (EventVerificationEmail
  was already absent), contrast manager-alert vs registrant-itinerary styling,
  document getClientEmailBrand + the per-domain sender constraint, and warn
  that the Resend adapter hand-maps fields so an unmapped one is silently
  dropped (how attachments/replyTo went missing).
- globals.md: correct the stale Atlas tab list (was "Common, Map, Location"),
  add Emails, and record that Payload's locale fallback is per field rather
  than per key — the trap that makes a new translation key render blank.

Refs #582

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
timeSpan() derived the end instant by adding the wall-clock delta to the start
as *real* time. That is wrong whenever the span crosses a DST boundary: on the
day London leaves BST, a 01:00-03:00 event covers two wall-clock hours but
three real ones, so `endTime: 03:00` rendered as "2:00 AM".

`endTime` is a same-day wall-clock string, so it is now formatted as written
rather than reconstructed as an instant — which removes the Date arithmetic
along with the bug, and reuses the existing `getLocalTimeHHMM` helper for the
ordering guard.

Found by probing the DST edge case during the finalize review pass.

Refs #582

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`Clients.name` is a free-text field that lands in the From display name. A CR/LF
in it would terminate the header and let whatever follows be injected as another
one — `Bcc:` being the obvious abuse. Quotes and angle brackets go too, since
the display name is emitted unquoted inside `Name <addr>`.

Setting the field needs admin access, so this is defence in depth rather than a
live hole; sanitizing where a value becomes a header is cheap and also covers
rows that already exist.

Raised by the /security-review pass.

Refs #582

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The guard asserts the Atlas translations tab list exactly, so adding the
`emails` group legitimately changes it. Caught by CI — the local gate runs the
targeted specs, and this cross-cutting guard lives in another file.

Refs #582

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…tion email

Sends the confirmation in each meaningful state — online/offline, a partly
translated locale, branded / unbranded / half-configured client, one-off, and a
minimal event where every optional section collapses — to a throwaway Ethereal
inbox, with the .ics attached for import testing.

It drives the real sendRegistrationConfirmation() through a stub payload (its
only Payload touchpoints are findGlobal, sendEmail and logger) rather than
recomposing the message, so the preview shows the actual subject, From,
Reply-To, HTML, text part and attachment, and can't drift from production.

Fixture detail that matters: schedules anchor to a real weekday at a real local
hour, and the course exclusion lands three weeks in — on an actual occurrence.
A `now + N days` fixture inherits the current time-of-day (the preview read
"5:04 PM") and an exclusion that misses an occurrence yields no EXDATE at all,
silently turning the cancelled-session scenario into a plain one.

Also fixes a unit test that passed `name: null` to getClientEmailBrand — an
impossible state, since Clients.name is required. It went unnoticed because
tsconfig excludes `tests`, so `pnpm typecheck` does not cover test files.

Refs #582

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
In-person registrations now get a primary CTA styled exactly like the online
"Join the class online" button (same BrandButton, same brand gradient), instead
of a small inline "View on map" text link.

Both event types now place their CTA in the same slot, so the layout reads the
same either way. Only the online one still repeats its URL as plain text: if a
client strips the button, the join link is otherwise unrecoverable, whereas the
venue address is still in the detail row directly above.

`map_link` is renamed to `directions_cta` to match `online_cta` and to reflect
that it labels a button rather than a link. Renaming is safe — the `emails`
translations group is new in this branch and unreleased, so no locale has data
under the old key.

Refs #582

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Renders the confirmation against a representative spread of real published
services and events from the local database — useful for seeing the template
with production-shaped content (long titles, other languages, missing optional
fields) rather than tidy fixtures.

Read-only, and query-driven rather than hardcoded ids so it works on any
database. Events are selected from a single fetched pool and filtered in JS:
`schedule.firstDate_tz` is a Postgres enum column, so a `like` on it has no
matching operator and errors at the driver.

The client/event pairing is deliberately arbitrary — a registration's client is
whoever holds the API key that called the endpoint, not a property of the event.

Refs #582

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…endar line

The title now heads the white detail block instead of floating above it, so the
card reads as one unit: what the class is, then when and where.

Removes "A calendar invite is attached to this email." — the attachment is
visible in the client on its own, so the line was noise. The `calendar_hint`
string and the `hasCalendarAttachment` prop go with it rather than lingering as
dead code; the calendar itself is still best-effort and simply absent when the
schedule can't be resolved.

Refs #582

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…d accent

The accent is already carried by the header, the row labels and the CTA; the
title reads as content, not as another piece of chrome. Uses #333333 — the
layout's existing body colour — so no new shade enters the palette.

Refs #582

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Resolves the migration chain against #590 (events.website). My migration was
regenerated under a new timestamp (20260719_213905, was 20260718_231450) so its
snapshot base is #590's — healing the out-of-order snapshot trap. The
regeneration also surfaced and fixed a real gap: the `emails` translations
column (sy_atlas_translations_locales.emails + its _v companion) was created by
no migration, because the original was generated before the emails group was
added. Dev/tests use push:true so it went unnoticed; prod applies migrations
only, so the Emails admin tab would have failed to save in production.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… title

Two sinks took the event title unsanitized, both reachable by a manager (same
trust boundary as the client-name From fix already in this branch):

- ICS calendar `name`. ical-generator escapes the VEVENT TEXT fields but NOT
  the calendar-level NAME / X-WR-CALNAME, so a title with a raw CR/LF injected
  real calendar lines — a crafted title produced a working BEGIN:VALARM...
  END:VALARM component (and could inject a second VEVENT). The security review
  missed this — it assumed the library escapes every field; verified by hand
  that the calendar name is the exception.
- Email Subject. The title is interpolated into confirmation_subject, and a
  CR/LF there starts a second header (Bcc: the obvious abuse). Flagged by the
  security review.

Centralizes the sanitizers in src/lib/utilities/emailSafeText.ts (stripNewlines
for a Subject / ICS property; headerDisplayName adds quote/bracket stripping for
the unquoted From display name), replacing the local headerSafe — so #589's
reminder job reuses one audited implementation rather than copying it.

Also pins the loadEmailClient invariant: overrideAccess is required (the clients
collection is unreadable by API clients, like the users upsert beside it) and is
safe only because clientId is always req.user.id — documented so a refactor
can't source it from the request body and turn it into an IDOR.

Refs #582

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
resolveEnd() matched HH:MM but didn't bound-check it, so an endTime like
'25:00' (or a malformed '10:75') reached Temporal.with() and threw a
RangeError. The Events schema validates endTime, but this builder also serves
imported/legacy rows that skipped it — and the throw propagates past the send's
best-effort boundary, suppressing the *whole* confirmation email rather than
just the attachment. Now bounded to match the sibling minutesOfDay(), falling
back to the default duration.

Found by two independent code-review finders converging on the same line.

Refs #582

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…-name trap

Notes emailSafeText.ts (stripNewlines / headerDisplayName) and the two
easy-to-miss sinks: the ICS calendar NAME/X-WR-CALNAME is NOT escaped by
ical-generator (unlike the VEVENT TEXT fields), and the event title flows into
the Subject. The security review missed the ICS one, so it's worth pinning.

Refs #582

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-593 July 20, 2026 00:35 Destroyed
@railway-app

railway-app Bot commented Jul 20, 2026

Copy link
Copy Markdown

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

Service Status Web Updated (UTC)
SahajCloud ✅ Success (View Logs) Web Jul 20, 2026 at 12:35 am

@Ardnived
Ardnived merged commit 8084b1e into main Jul 20, 2026
2 of 3 checks passed
@Ardnived
Ardnived deleted the feat/registration-confirmation-email branch July 20, 2026 13:44

This branch was successfully deployed

No deployments
sahajcloud / SahajCloud-pr-593 — bc920b49 Deployed Jul 20, 2026 by railway-app[bot]
sahajcloud / SahajCloud-pr-591 — bc920b49 Deployed Jul 19, 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.

1 participant