Open History to see the last commit
1/**
2 * Outbound email (PLAN.md task 9.2) via Cloudflare Email Workers: the
3 * `send_email` binding's structured send(). Until Email Routing / sender
4 * verification is set up on the modelschemas.com zone, sends fail with
5 * E_SENDER_NOT_VERIFIED — every failure (and the no-binding local case)
6 * falls back to a structured console line so the OTP is observable in dev
7 * output and `wrangler tail` instead of silently dropping a sign-in.
8 */
9
10export interface OutboundEmail {
11 to: string
12 subject: string
13 text: string
14}
15
16export type EmailSender = (email: OutboundEmail) => Promise<void>
17
18export const EMAIL_FROM = 'login@modelschemas.com'
19
20/** Minimal shape of the send_email binding's structured API. */
21export interface SendEmailBinding {
22 send: (message: {
23 to: string
24 from: string
25 subject: string
26 text: string
27 }) => Promise<unknown>
28}
29
30function logEmail(email: OutboundEmail, mode: string): void {
31 console.log(JSON.stringify({ job: 'email', mode, ...email }))
32}
33
34export function createEmailSender(binding?: SendEmailBinding): EmailSender {
35 if (!binding) {
36 return (email) => {
37 logEmail(email, 'dev-log')
38 return Promise.resolve()
39 }
40 }
41 return async (email) => {
42 try {
43 await binding.send({
44 to: email.to,
45 from: EMAIL_FROM,
46 subject: email.subject,
47 text: email.text,
48 })
49 } catch (error) {
50 logEmail(email, `send-failed: ${String(error)}`)
51 }
52 }
53}
54
55export function otpEmail(email: string, otp: string): OutboundEmail {
56 return {
57 to: email,
58 subject: `${otp} is your modelschemas sign-in code`,
59 text: `Your modelschemas sign-in code is ${otp}. It expires in 5 minutes.\n\nIf you didn't request this, ignore this email.`,
60 }
61}