|
| 1 | +const { Resend } = require("resend"); |
| 2 | +const { z } = require("zod"); |
| 3 | +const { Project, decrypt, redis, sendMailSchema } = require("@urbackend/common"); |
| 4 | +const { |
| 5 | + getMonthKey, |
| 6 | + getEndOfMonthTtlSeconds, |
| 7 | + getMonthlyMailLimit, |
| 8 | +} = require("../utils/mailLimit"); |
| 9 | + |
| 10 | +const DEFAULT_FROM = process.env.EMAIL_FROM || "urBackend <urbackend@apps.bitbros.in>"; |
| 11 | + |
| 12 | +const getMailCountKey = (projectId, monthKey) => |
| 13 | + `project:mail:count:${projectId}:${monthKey}`; |
| 14 | + |
| 15 | +const loadProjectMailConfig = async (projectId) => { |
| 16 | + return Project.findById(projectId) |
| 17 | + .select("+resendApiKey.encrypted +resendApiKey.iv +resendApiKey.tag resendFromEmail") |
| 18 | + .lean(); |
| 19 | +}; |
| 20 | + |
| 21 | +const reserveMonthlyMailSlot = async (projectId, limit) => { |
| 22 | + if (redis.status !== "ready") { |
| 23 | + const err = new Error("Mail service unavailable. Redis is not ready."); |
| 24 | + err.statusCode = 503; |
| 25 | + throw err; |
| 26 | + } |
| 27 | + |
| 28 | + const now = new Date(); |
| 29 | + const monthKey = getMonthKey(now); |
| 30 | + const ttlSeconds = getEndOfMonthTtlSeconds(now); |
| 31 | + const key = getMailCountKey(projectId, monthKey); |
| 32 | + |
| 33 | + const luaScript = ` |
| 34 | + local current = redis.call("INCR", KEYS[1]) |
| 35 | + if current == 1 then |
| 36 | + redis.call("EXPIRE", KEYS[1], ARGV[1]) |
| 37 | + end |
| 38 | + return current |
| 39 | + `; |
| 40 | + const count = await redis.eval(luaScript, 1, key, ttlSeconds); |
| 41 | + |
| 42 | + if (count > limit) { |
| 43 | + await redis.decr(key); |
| 44 | + const err = new Error("Monthly mail limit exceeded."); |
| 45 | + err.statusCode = 429; |
| 46 | + err.limit = limit; |
| 47 | + throw err; |
| 48 | + } |
| 49 | + |
| 50 | + return { count, key }; |
| 51 | +}; |
| 52 | + |
| 53 | +module.exports.sendMail = async (req, res) => { |
| 54 | + let consumedQuotaKey = null; |
| 55 | + try { |
| 56 | + if (req.keyRole !== "secret") { |
| 57 | + return res.status(403).json({ |
| 58 | + success: false, |
| 59 | + data: {}, |
| 60 | + message: "Forbidden. This action requires a Secret Key (sk_live_...).", |
| 61 | + }); |
| 62 | + } |
| 63 | + |
| 64 | + const { to, subject, html, text } = sendMailSchema.parse(req.body || {}); |
| 65 | + const projectId = req.project?._id; |
| 66 | + |
| 67 | + if (!projectId) { |
| 68 | + return res.status(401).json({ success: false, data: {}, message: "Project context missing." }); |
| 69 | + } |
| 70 | + |
| 71 | + const project = await loadProjectMailConfig(projectId); |
| 72 | + if (!project) { |
| 73 | + return res.status(404).json({ success: false, data: {}, message: "Project not found." }); |
| 74 | + } |
| 75 | + |
| 76 | + const encryptedByokKey = |
| 77 | + project.resendApiKey && typeof project.resendApiKey === "object" && Object.keys(project.resendApiKey).length > 0 |
| 78 | + ? project.resendApiKey |
| 79 | + : null; |
| 80 | + const decryptedByokKey = encryptedByokKey ? decrypt(encryptedByokKey) : null; |
| 81 | + |
| 82 | + const usingByok = typeof decryptedByokKey === "string" && decryptedByokKey.trim().length > 0; |
| 83 | + const clientKey = usingByok |
| 84 | + ? decryptedByokKey.trim() |
| 85 | + : process.env.RESEND_API_KEY_2 || process.env.RESEND_API_KEY; |
| 86 | + |
| 87 | + if (!clientKey) { |
| 88 | + return res.status(500).json({ success: false, data: {}, message: "Resend API key is not configured." }); |
| 89 | + } |
| 90 | + |
| 91 | + const limit = getMonthlyMailLimit(req.project); |
| 92 | + const { count, key } = await reserveMonthlyMailSlot(projectId, limit); |
| 93 | + consumedQuotaKey = key; |
| 94 | + |
| 95 | + const resend = new Resend(clientKey); |
| 96 | + |
| 97 | + let fromAddress = DEFAULT_FROM; |
| 98 | + if (usingByok) { |
| 99 | + fromAddress = project.resendFromEmail && project.resendFromEmail.trim() |
| 100 | + ? project.resendFromEmail.trim() |
| 101 | + : "onboarding@resend.dev"; |
| 102 | + } |
| 103 | + |
| 104 | + const payload = { |
| 105 | + from: fromAddress, |
| 106 | + to, |
| 107 | + subject, |
| 108 | + }; |
| 109 | + if (typeof html === "string" && html.trim()) payload.html = html; |
| 110 | + if (typeof text === "string" && text.trim()) payload.text = text; |
| 111 | + |
| 112 | + const { data, error } = await resend.emails.send(payload); |
| 113 | + if (error) { |
| 114 | + throw new Error(error.message || "Failed to send mail."); |
| 115 | + } |
| 116 | + |
| 117 | + return res.status(200).json({ |
| 118 | + success: true, |
| 119 | + data: { |
| 120 | + id: data?.id || null, |
| 121 | + provider: usingByok ? "byok" : "default", |
| 122 | + monthlyUsage: count, |
| 123 | + monthlyLimit: limit, |
| 124 | + }, |
| 125 | + message: "Mail sent successfully.", |
| 126 | + }); |
| 127 | + } catch (err) { |
| 128 | + if (consumedQuotaKey) { |
| 129 | + await redis.decr(consumedQuotaKey).catch(() => {}); |
| 130 | + } |
| 131 | + |
| 132 | + if (err instanceof z.ZodError) { |
| 133 | + return res.status(400).json({ |
| 134 | + success: false, |
| 135 | + data: {}, |
| 136 | + message: err.issues?.[0]?.message || "Invalid mail payload.", |
| 137 | + }); |
| 138 | + } |
| 139 | + |
| 140 | + return res.status(err.statusCode || 500).json({ |
| 141 | + success: false, |
| 142 | + data: {}, |
| 143 | + message: err.message || "Failed to send mail.", |
| 144 | + ...(typeof err.limit === "number" ? { limit: err.limit } : {}), |
| 145 | + }); |
| 146 | + } |
| 147 | +}; |
0 commit comments