Skip to content

feat: add OTP-Token header to OTP emails - #15096

Merged
Meldiron merged 4 commits into
mainfrom
feat-otp-token-email-header
Oct 29, 2026
Merged

Meldiron merged 4 commits into
mainfrom
feat-otp-token-email-header

Conversation

@Meldiron

@Meldiron Meldiron commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

Adds the new OTP-Token email header to every Appwrite email that carries a one-time code. Mail clients, browsers and password managers can then read the code from the header and autofill it, but only on the origin it is bound to. That means less copying codes between tabs and less risk of a phished code being typed into a lookalike site.

OTP-Token: "123456"; origin="https://app.example.com"

Emails covered

Flow Endpoint
Email OTP login POST /v1/account/tokens/email
Password recovery (OTP) POST /v1/account/recovery/otp
Email verification (OTP) POST /v1/account/verifications/email/otp
MFA email challenge POST /v1/account/mfa/challenges (factor=email)

Magic URL, link-based recovery and verification emails carry no code, so they are unchanged.

How the origin is chosen

The code is bound to the request's Origin, which the existing CSRF hook in general.php has already checked against the project's registered platforms. The header is sent only when:

  1. The origin is potentially trustworthy (Secure Contexts): https, or http on localhost / *.localhost / 127.0.0.0/8 / [::1], as the draft requires (§3.1).
  2. It can be written in canonical RFC 6454 §6.2 form: lowercase, default port omitted, ASCII only, and nothing after the authority (no path, query, fragment or userinfo).

Otherwise no header is sent, and the email is exactly as before. This covers server SDK calls without an Origin, native mobile apps, custom schemes, browser extensions, and plain-http public hosts.

Implementation

  • New Appwrite\Auth\OTPToken value object (src/Appwrite/Auth/OTPToken.php). It canonicalizes the origin and writes the value as an RFC 9651 Structured Field: an sf-string item with an origin parameter. Escaping follows §3.3.3, and only printable ASCII is allowed.
  • The four call sites pass headers: to the Mail message. The plumbing already existed: Mail::$headers → mails worker → Utopia\Messaging\Messages\Email::$headers.
  • Encoding is safe on our own SMTP path: Utopia\SMTP\Mime\Header::line() applies RFC 2047 encoded-words only to non-ASCII values, so the quoted ASCII value is sent as-is. Long lines are folded at spaces, and the draft (§3.2 step 2) says receivers unfold before parsing. This avoids the bug reported against Resend, where a provider RFC 2047-encoded the quotes (Otp-Token: =?UTF-8?Q?=22123456=22...) and broke parsing.
  • .github/ci/e2e.json: the new file is mapped to the Account lane.

Things to note

  • The spec is an individual Internet-Draft (-01, Sept 2026). It is not yet adopted by a WG, and the header name is still open for bikeshedding (§7). Everything lives behind the single OTPToken::HEADER constant, so following a rename is a one-line change.
  • The draft's §4 Security Considerations is still TODO (DKIM binding is an open question). The code is already in the email body, so the header exposes nothing new to anyone who can read the message.
  • Not implemented: the optional token= parameter from §6.1 (Future Work), because it is not specified yet.

Test Plan

  • Unit (tests/unit/Auth/OTPTokenTest.php): header format, sf-string escaping, origin canonicalization (case, default ports, custom ports, loopback hosts, IPv4/IPv6 loopback), and rejection of insecure http, lookalike localhost.example.com, opaque null, custom schemes, extensions, path/query/userinfo, non-ASCII, and empty or control-character codes.
  • E2E:
    • AccountBase::testEmailOTPSession asserts that the maildev message has otp-token: "<code>"; origin="http://localhost", matching the code in the body.
    • AccountCustomServerTest::testCreateTokenWithSessionsKey asserts that an API-key request without an Origin sends no OTP-Token header.
  • ⚠️ I wrote this without a local PHP/Docker runtime, so the PHP has not been linted or run locally. Please rely on CI (unit, Account e2e lane, Pint, PHPStan).

Sources

Specification

Normative references used here

Prior art the draft builds on

Ecosystem and discussion

Related PRs and Issues

  • N/A

Checklist

  • Have you read the Contributing Guidelines on issues?
  • If the PR includes a change to an API's metadata (desc, label, params, etc.), does it also include updated API specs and example docs? (No API surface change.)

🤖 Generated with Claude Code

Bind email OTP codes to the requesting origin with the OTP-Token header
(draft-goto-otp-token), so mail clients and autofill can deliver the code
to that origin only. Covers email token, recovery OTP, verification OTP
and MFA email challenge emails.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@luxor-code-review

luxor-code-review Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

Review complete. 🟡 1 medium

💬 Inline comments (1)

🧹 Nitpicks (1) — 🟢 1 low
  • 🟢 Two validators disagree; header silently dropped for some platforms (account.php:3313) — The OTP-Token header is gated on $originValidator->isValid($request->getOrigin()), but that validator accepts origins OTPToken::from always rejects — registered browser-extension/Tauri/Capacitor platforms, the always-allowed appwrite-callback-<projectId> and exp schemes, and registered plain-HTTP platforms (app/controllers/api/account.php:3313).

This PR binds OTP codes to the requesting origin by attaching an RFC 9651-style OTP-Token structured-field header (code"; origin="https://host") to the email-OTP, email-verification, password-recovery, and MFA challenge emails. A new Appwrite\Auth\OTPToken class canonicalizes the request origin (scheme, host, port, loopback handling) and serializes the header, degrading safely to no header when the origin is missing or invalid.

Files Change
src/Appwrite/Auth/OTPToken.php New library canonicalizing origins and building the OTP-Token structured-field header value.
app/controllers/api/account.php Threads the header into the three OTP-email call sites (email token, verification, recovery) via originValidator injection.
src/Appwrite/Platform/Modules/Account/Http/Account/MFA/Challenges/Create.php Adds the same header to the MFA email-factor challenge email.
tests/unit/Auth/OTPTokenTest.php, tests/e2e/Services/Account/* Unit matrix for canonicalization/serialization plus e2e assertions on the delivered mail headers.
.github/ci/e2e.json Maps OTPToken.php to the Account e2e lane.

Reviewed commit: 9ba5e7e

@ghost

ghost commented Oct 29, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

The incremental changes preserve the test cases and use generator-based providers consistently with this repository's existing PHPUnit tests.

Adds a structured OTP-Token header containing the emailed code and a validated, canonical request origin to email OTP login, recovery, verification, and MFA challenge messages. The new OTPToken value object serializes the header, and unit and Account E2E tests cover formatting, origin handling, and the covered email flows. The latest test update converts data providers to generators and strengthens the successful-construction assertions.

Latest changes: The latest commit changes the OTPToken unit test providers from returned arrays to yielded iterators and replaces nullable assertions with instance assertions.

Verdict New comments Fixed Still open
✅ Approved 0 0 0
📂 Walkthrough · 8
File Change
.github/ci/e2e.json Maps OTPToken source changes to the Account E2E lane.
app/controllers/api/account.php Adds OTP-Token headers to email OTP login, recovery, and verification messages.
src/Appwrite/Auth/OTPToken.php Adds origin validation and structured-field serialization for OTP email headers.
src/Appwrite/Platform/Modules/Account/Http/Account/MFA/Challenges/Create.php Adds the OTP-Token header to email MFA challenge messages.
tests/e2e/Services/Account/AccountBase.php Checks that email OTP login sends a header matching the code and request origin.
tests/e2e/Services/Account/AccountCustomClientTest.php Checks OTP headers on verification, recovery, and MFA emails, including the MFA request origin.
tests/e2e/Services/Account/AccountCustomServerTest.php Checks that an email OTP request without Origin sends no OTP-Token header.
tests/unit/Auth/OTPTokenTest.php Covers header formatting, origin canonicalization and rejected inputs; the latest commit uses generator providers and stronger construction assertions.

Reviewed the commits since 654e195 · Details · Comment @hansi-codes review to re-run, or mention @hansi-codes with a question.

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟢 Tier S · Looks good to merge. Summary

@github-actions

Copy link
Copy Markdown

Security rules

No new WARNING or ERROR findings from security rules.

6 existing findings tracked in .semgrep/baseline.json
  • php.appwrite.guest-write-without-abuse-limit (3)
  • php.appwrite.secret-compare-timing (1)
  • php.appwrite.weak-secret-env-default (2)

Posted by Checks / Rules. Re-runs update this comment in place. Rule details and baseline: .semgrep/README.md.

@luxor-code-review luxor-code-review Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Adds origin-bound OTP-Token email headers to OTP flows via a new OTPToken canonicalization library, with unit and e2e coverage.

Key findings

@github-actions

github-actions Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → feat-otp-token-email-header (after).

Metric Before After Change
🚀 Requests/sec 205.72 215.15 ⚪ +4.6%
⏱️ Latency P50 82.13 ms 79.49 ms ⚪ -3.2%
⏱️ Latency P95 193.67 ms 190.88 ms ⚪ -1.4%
Per-scenario breakdown & investigation details

Metrics below reflect the current branch (after). Δ P95 compares against the base.

Scenario P50 (ms) P95 (ms) Requests RPS Δ P95 (ms)
API total 79.49 190.88 13,680 215.15 -2.79
Account 147.59 295.21 720 12.09 +11.37
TablesDB 76.45 139.17 7,440 120.28 -13.69
Storage 75.3 176.16 3,600 59.62 -20.6
Functions 119.9 253.21 1,920 32.4 +43.42

Top API waits (after)

API request Max wait (ms)
account.name.update 523.96
account.prefs.update 426.56
functions.delete 407.51
functions.variables.update 404.18
functions.create 376.63

The CSRF hook already validates the request origin; OTPToken::from()
enforces the draft's origin requirements.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Tier A · See the inline comments. Summary

Comment thread app/controllers/api/account.php Resolved

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟢 Tier S · Looks good to merge. Summary

@Meldiron
Meldiron merged commit 3ea1097 into main Oct 29, 2026
69 checks passed
hardikkaurani pushed a commit to hardikkaurani/appwrite that referenced this pull request Nov 11, 2026
Document the OTP-Token header that Appwrite adds to email OTP, email
verification, password recovery and MFA email challenge emails (appwrite#15096),
and add the announcement post and the 2026-11-11 changelog entry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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