Skip to content

feat: preferred email - #1392

Open
Haviles04 wants to merge 17 commits into
mainfrom
feat/preferred-email
Open

Haviles04 wants to merge 17 commits into
mainfrom
feat/preferred-email

Conversation

@Haviles04

@Haviles04 Haviles04 commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Issue number

Relevant issue number

  • Resolves #

Please check the following

  • Do the tests still pass? (see Run the Tests)
  • Is the code formatted properly? (see Linting (Formatting))
  • For New Features:
    • Have tests been added to cover any new features or fixes?
    • Has the documentation been updated accordingly?

Please describe additional details for testing this change

RetriggerView in GreptileConfidence Score: 5/5

No new blocking issue was established in this review.

Summary

Adds a preferred email flow with six-digit codes and an optional news opt-in.

  • Signed-in users can verify a preferred email and news choice.
  • The home page prompts signed-in users who lack a verified email.

Reviews (12) · Last reviewed commit: "Merge branch 'main' into feat/preferred-..." · Reviewed by Greptile

@Haviles04 Haviles04 added the version-minor An update that warrants a bumping the project's minor version (e.g. 4.0.0 => 4.1.0) label Oct 8, 2026
@Haviles04
Haviles04 marked this pull request as ready for review November 4, 2026 19:44
Comment thread api/controllers/UserController.js Resolved
Comment thread api/models/UserEmail.js Resolved
Comment thread api/controllers/user-email/verify.js Resolved
Comment thread api/controllers/user-email/verify.js Resolved
@Haviles04

Haviles04 commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor Author

SQL migration

Staging and production run with migrate: 'safe', so the useremail table needs to be created manually before this is deployed. Column types match what sails-postgresql generates for the UserEmail model.

CREATE TABLE IF NOT EXISTS "useremail" (
  "id" SERIAL PRIMARY KEY,
  "createdAt" TIMESTAMPTZ,
  "updatedAt" TIMESTAMPTZ,
  "user" INTEGER NOT NULL UNIQUE REFERENCES "user"("id") ON DELETE CASCADE,
  "email" TEXT UNIQUE,
  "pendingEmail" TEXT,
  "verificationCode" TEXT,
  "codeExpiresAt" TIMESTAMPTZ,
  "codeSentAt" TIMESTAMPTZ,
  "attempts" INTEGER DEFAULT 0,
  "promotional" BOOLEAN DEFAULT false,
  "pendingPromotional" BOOLEAN DEFAULT false
);
  • "user" UNIQUE enforces one row per user. The foreign key keeps the database from holding an email row for a user that doesn't exist. ON DELETE CASCADE deletes a user's email row along with the user, so wipe-database (dev/staging), which deletes users and email rows in parallel, can't fail on the constraint.
  • "email" UNIQUE enforces one verified email per address across users. Postgres allows multiple NULLs, so users who haven't verified yet don't conflict. The model can't declare this itself because sails-disk rejects unique on nullable attributes, so the controllers also check it.
  • pendingPromotional holds the opt-in chosen with pendingEmail. It's copied to promotional only when that email is verified, so abandoning verification never changes the stored opt-in.

CREATE TABLE IF NOT EXISTS does nothing if a useremail table already exists, even with a different shape, so run \d useremail afterward to confirm the columns match.

Deploy also needs GMAIL_USER and GMAIL_APP_PASSWORD set in the environment.

@itsalaidbacklife itsalaidbacklife left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed the full diff at 67176aa. The backend flow is carefully built: hashed codes, attempt reservation via compare-and-set, the cooldown claimed before sending, and a timing-safe compare. All five locales have full key parity. The dialog-stacking fix (isOpen computed) and its regression test in home.spec.js look right.

Three real findings inline (SMTP failure vs. cooldown, promotional staging, i18n fallback) plus one small dedupe suggestion.

On the migration SQL from the PR comment: I checked each column type against config/models.js and they match what sails-postgresql emits. email TEXT UNIQUE is safe against case variants because hasValidEmail lowercases before anything reaches the column. Two minor notes: CREATE TABLE IF NOT EXISTS no-ops against a table that already exists with a different shape (worth a \d useremail on staging), and the DDL lives only in a PR comment, so it may be worth checking in or documenting in docs/setup-development.md.

🤖 Generated with Claude Code

Comment thread api/policies/hasValidEmail.js Resolved
@Haviles04

Copy link
Copy Markdown
Contributor Author

@itsalaidbacklife thanks for the review. All four inline points are addressed in 0e682f9 (replies on each thread). On the two SQL notes: I added a reminder to the SQL comment to run \d useremail after CREATE TABLE IF NOT EXISTS and confirm the columns match, plus the new pendingPromotional column (#1392 (comment)). Moving the DDL into docs/setup-development.md is still open.

@Haviles04

Copy link
Copy Markdown
Contributor Author
preferred-email-add-and-verify.mp4

# Conflicts:
#	src/routes/home/HomeView.vue
#	tests/e2e/specs/out-of-game/home.spec.js
Comment thread src/stores/auth.js Resolved

@itsalaidbacklife itsalaidbacklife left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed at dffe00b5. The concurrency work continues to hold up — the staged pendingPromotional, the send-failure rollback matched on the code hash, and the authVersion guards are all correct, and all four points from my Nov 7 review are properly addressed.

One blocking item: the cross-account rate limit added in a0889aaa fixed the amplification it was aimed at, but introduced an address-lockout regression. Details and three suggested changes inline on request-code.js.

The rest are small — one real UX bug in the Send Code path, two bits of resend polish, a missing sails.log.error, and one edge case in the auth store.

Separately, the fact that a verified email can never be changed or its opt-in withdrawn is now tracked in #1492 as agreed follow-up, so nothing needed here for that.

🤖 Generated with Claude Code


// Also limit each address across all accounts, so new accounts can't be used to send it more
// than one code per cooldown
const pendingForAddress = await UserEmail.find({ pendingEmail: email, user: { '!=': userId } });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requesting changes on this block — it introduced an address-lockout regression.

The cross-account check does stop multi-account amplification, and that part works. But it can't distinguish an attacker's pending row from anyone else's, so it also blocks the address's legitimate owner. One free account re-requesting the same address every 61s holds that block indefinitely, and the address doesn't need to be registered with Cuttle at all — the check is on pendingEmail, so you can pre-emptively block a future signup.

Worth noting what the gate actually buys, because it's narrower than it looks. It only binds at 2+ accounts (one account reaches 1/60s either way), and it caps concentration on one address, not volume — an attacker spreading across 100 addresses at 1/60s each is completely unimpeded. So it doesn't protect the shared Gmail quota, which is the thing whose exhaustion breaks verification for every user.

Three changes:

1. Remove this check (lines 35-38). It charges bystanders for a narrow guarantee and misses the attack that actually takes the app down. On its own this returns to the pre-a0889aaa behaviour, which was not worse.

2. Replace the flat 60s cooldown with an escalating one, per account. Grow the interval with each unverified request from the same account — roughly 60s → 2m → 5m → 15m → 1h → 1h… — and reset to the first step on successful verification.

This is nearly free for legitimate users: send a code, maybe one resend, verify, counter clears. An attacker never verifies, so they climb immediately — about 5 sends in the first hour from a given account, then 1/hour. Sustaining today's 60/hour against one target goes from 1 account to ~12 rotating ones, each with a shrinking yield. Because the budget belongs to the requester, there's no lockout surface.

3. Add a global cap on total verification sends per hour, sized under the provider limit. On breach: stop sending, return a distinct error, log loudly.

(1) and (2) raise the cost per attacker; only (3) guarantees that enough accounts can't exhaust the shared quota. The reason to cap in-app rather than let Gmail refuse is that a provider cutoff stops the next message but does nothing about the thousands already delivered to people who never asked. Those produce complaints and bounces, and that reputation damage outlives the quota reset — legitimate codes start landing in spam. A cap below the quota stops it before the damage is done. It's also an unambiguous "this endpoint is under attack" signal, where a provider cutoff surfaces as scattered SMTP errors after the fact.

Storage for (2) and (3) is a counter plus a timestamp. If a general rate-limiting layer is coming, this is a good first consumer — key it on req.session.usr rather than the session itself, since one account can get unlimited sessions just by re-logging in.

This also closes the cumulative-cap gap, since that's the same underlying issue this commit was aimed at.

color="primary"
variant="flat"
:loading="loading"
:disabled="!isEmailFormValid"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Send Code isn't gated by the cooldown, unlike Resend.

Resend has :disabled="resendCooldown > 0" (line 70), but this is gated only on form validity. The common path hits it: send a code, notice a typo, Back, fix the address, Send Code → bare 429 "Please wait a minute before requesting another code", with none of the countdown Resend gives.

:disabled="!isEmailFormValid || resendCooldown > 0" would match. Worth considering whether Back should surface the remaining cooldown too, since from the email step there's currently no indication one is running.

loading.value = true;
errorMessage.value = '';
try {
await authStore.requestEmailCode(submitted.value.email, submitted.value.promotional);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

resendCode doesn't clear code, unlike sendCode (line 207).

Stale digits stay in the OTP input after a resend, and Verify stays enabled because code.length === 6. One click burns one of the five attempts on a code the resend just invalidated. Adding code.value = ''; here matches sendCode.

errorMessage.value = '';
try {
await authStore.requestEmailCode(submitted.value.email, submitted.value.promotional);
startCooldown();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

startCooldown() only runs on success, so a 429'd resend leaves the button immediately clickable.

The user can only reach Resend when resendCooldown is already 0, so if the server rejects on its own cooldown there's nothing to stop them hammering it. Harmless server-side, but each click is another failed round trip with no feedback that a wait is in progress.

Starting the cooldown on a 429 as well as on success would handle it — ideally reading the remaining time from the response rather than assuming a full 60s.


return res.ok({ email: saved.email, promotional: saved.promotional });
} catch (err) {
return res.badRequest(err);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Catch-all passes a raw Error and never logs it.

Sails' default badRequest logs at verbose, which is invisible at the default level, so a failed verification leaves no trace. Outside production it also sends err.stack as a plain-text body; the client's response.json() then fails and falls back to verifyFailed, so the user sees something sane but you have no record of what broke.

request-code.js:76-78 already does this correctly (sails.log.error(err) then a keyed message) — this is just inconsistent with it.

Comment thread src/stores/auth.js
}
// Don't apply the result to a different account if the user logged out or switched
// accounts while this was pending
if (authVersion !== this.authVersion) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor: when this guard fires the dialog still reports success.

The early return here isn't distinguishable from a successful verification by the caller, so verifyCode in EmailPreferenceDialog.vue:236-238 closes the dialog and shows "Email verified!" even though nothing was applied to the store. Only reachable if the user switches accounts mid-verification, so very low priority — but throwing instead of returning, or returning a flag, would let the dialog stay quiet.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

version-minor An update that warrants a bumping the project's minor version (e.g. 4.0.0 => 4.1.0)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants