-
Notifications
You must be signed in to change notification settings - Fork 68
Feat/v0.9.0 byok mail #84
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
cafdd53
feat: implement per-project BYOK resend mail and auth routing
yash-pouranik a78f289
fix: rollback monthly mail quota on failed BYOK deliveries and valida…
yash-pouranik 2d9b53c
fix: resolve ReDoS vulnerability in sender email regex validation
yash-pouranik 68c62f8
fix: address copilot review suggestions for byok validation and worke…
yash-pouranik 4713e2e
fix multiple import of initauthworker
yash-pouranik e7a1fd1
fix multiple import of initauthworker
yash-pouranik 72ba39d
fix: make redis quota reservation atomic and standardize error responses
yash-pouranik File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,116 @@ | ||
| 'use strict'; | ||
|
|
||
| process.env.REDIS_URL = process.env.REDIS_URL || "redis://localhost:6379/0"; | ||
| process.env.ENCRYPTION_KEY = process.env.ENCRYPTION_KEY || "0123456789012345678901234567890a"; | ||
|
|
||
| jest.mock('resend', () => { | ||
| const sendMock = jest.fn(() => Promise.resolve({ data: { id: 'mail-123' }, error: null })); | ||
| return { | ||
| Resend: jest.fn(() => ({ | ||
| emails: { send: sendMock }, | ||
| })), | ||
| __sendMock: sendMock, | ||
| }; | ||
| }); | ||
|
|
||
| jest.mock('@urbackend/common', () => { | ||
| const { sendMailSchema } = require('../../../../packages/common/src/utils/input.validation'); | ||
| const redisMock = { | ||
| status: 'ready', | ||
| incr: jest.fn(), | ||
| expire: jest.fn(), | ||
| decr: jest.fn(), | ||
| }; | ||
|
|
||
| return { | ||
| sendMailSchema, | ||
| Project: { findById: jest.fn() }, | ||
| decrypt: jest.fn(), | ||
| redis: redisMock, | ||
| }; | ||
| }); | ||
|
|
||
| const { Resend } = require('resend'); | ||
| const { Project, decrypt, redis } = require('@urbackend/common'); | ||
| const mailController = require('../controllers/mail.controller'); | ||
|
|
||
| const makeReq = () => ({ | ||
| keyRole: 'secret', | ||
| project: { _id: 'proj_1' }, | ||
| body: { to: 'user@example.com', subject: 'Hello', text: 'This is a message.' }, | ||
| }); | ||
|
|
||
| const makeRes = () => { | ||
| const res = { status: jest.fn(), json: jest.fn() }; | ||
| res.status.mockReturnValue(res); | ||
| res.json.mockReturnValue(res); | ||
| return res; | ||
| }; | ||
|
|
||
| const mockProjectConfig = (payload) => { | ||
| Project.findById.mockReturnValue({ | ||
| select: jest.fn(() => ({ | ||
| lean: jest.fn(() => Promise.resolve(payload)), | ||
| })), | ||
| }); | ||
| }; | ||
|
|
||
| describe('mail.controller', () => { | ||
| beforeEach(() => { | ||
| jest.clearAllMocks(); | ||
| process.env.RESEND_API_KEY = 'default-key'; | ||
| process.env.EMAIL_FROM = 'mail@urbackend.app'; | ||
| }); | ||
|
|
||
| test('sends mail using BYOK key when configured', async () => { | ||
| const req = makeReq(); | ||
| const res = makeRes(); | ||
|
|
||
| mockProjectConfig({ _id: 'proj_1', resendApiKey: {} }); | ||
| decrypt.mockReturnValue('byok-key'); | ||
| redis.incr.mockResolvedValue(1); | ||
|
|
||
| await mailController.sendMail(req, res); | ||
|
|
||
| expect(redis.incr).toHaveBeenCalledTimes(1); | ||
| expect(redis.expire).toHaveBeenCalledTimes(1); | ||
| expect(res.status).toHaveBeenCalledWith(200); | ||
| expect(res.json).toHaveBeenCalledWith(expect.objectContaining({ | ||
| success: true, | ||
| data: expect.objectContaining({ provider: 'byok', monthlyUsage: 1 }), | ||
| })); | ||
| }); | ||
|
|
||
| test('falls back to default key when BYOK missing', async () => { | ||
| const req = makeReq(); | ||
| const res = makeRes(); | ||
|
|
||
| mockProjectConfig({ _id: 'proj_1', resendApiKey: null }); | ||
| decrypt.mockReturnValue(null); | ||
| redis.incr.mockResolvedValue(2); | ||
|
|
||
| await mailController.sendMail(req, res); | ||
|
|
||
| expect(res.status).toHaveBeenCalledWith(200); | ||
| expect(res.json).toHaveBeenCalledWith(expect.objectContaining({ | ||
| data: expect.objectContaining({ provider: 'default', monthlyUsage: 2 }), | ||
| })); | ||
| }); | ||
|
|
||
| test('enforces monthly limit', async () => { | ||
| const req = makeReq(); | ||
| const res = makeRes(); | ||
|
|
||
| mockProjectConfig({ _id: 'proj_1', resendApiKey: null }); | ||
| decrypt.mockReturnValue(null); | ||
| redis.incr.mockResolvedValue(101); | ||
|
|
||
| await mailController.sendMail(req, res); | ||
|
|
||
| expect(redis.decr).toHaveBeenCalledTimes(1); | ||
| expect(res.status).toHaveBeenCalledWith(429); | ||
| expect(res.json).toHaveBeenCalledWith(expect.objectContaining({ | ||
| error: 'Monthly mail limit exceeded.', | ||
| })); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,147 @@ | ||
| const { Resend } = require("resend"); | ||
| const { z } = require("zod"); | ||
| const { Project, decrypt, redis, sendMailSchema } = require("@urbackend/common"); | ||
| const { | ||
| getMonthKey, | ||
| getEndOfMonthTtlSeconds, | ||
| getMonthlyMailLimit, | ||
| } = require("../utils/mailLimit"); | ||
|
|
||
| const DEFAULT_FROM = process.env.EMAIL_FROM || "urBackend <urbackend@apps.bitbros.in>"; | ||
|
|
||
| const getMailCountKey = (projectId, monthKey) => | ||
| `project:mail:count:${projectId}:${monthKey}`; | ||
|
|
||
| const loadProjectMailConfig = async (projectId) => { | ||
| return Project.findById(projectId) | ||
| .select("+resendApiKey.encrypted +resendApiKey.iv +resendApiKey.tag resendFromEmail") | ||
| .lean(); | ||
| }; | ||
|
|
||
| const reserveMonthlyMailSlot = async (projectId, limit) => { | ||
| if (redis.status !== "ready") { | ||
| const err = new Error("Mail service unavailable. Redis is not ready."); | ||
| err.statusCode = 503; | ||
| throw err; | ||
| } | ||
|
|
||
| const now = new Date(); | ||
| const monthKey = getMonthKey(now); | ||
| const ttlSeconds = getEndOfMonthTtlSeconds(now); | ||
| const key = getMailCountKey(projectId, monthKey); | ||
|
|
||
| const luaScript = ` | ||
| local current = redis.call("INCR", KEYS[1]) | ||
| if current == 1 then | ||
| redis.call("EXPIRE", KEYS[1], ARGV[1]) | ||
| end | ||
| return current | ||
| `; | ||
| const count = await redis.eval(luaScript, 1, key, ttlSeconds); | ||
|
|
||
| if (count > limit) { | ||
| await redis.decr(key); | ||
| const err = new Error("Monthly mail limit exceeded."); | ||
| err.statusCode = 429; | ||
| err.limit = limit; | ||
| throw err; | ||
| } | ||
|
|
||
| return { count, key }; | ||
| }; | ||
|
|
||
| module.exports.sendMail = async (req, res) => { | ||
| let consumedQuotaKey = null; | ||
| try { | ||
| if (req.keyRole !== "secret") { | ||
| return res.status(403).json({ | ||
| success: false, | ||
| data: {}, | ||
| message: "Forbidden. This action requires a Secret Key (sk_live_...).", | ||
| }); | ||
| } | ||
|
|
||
| const { to, subject, html, text } = sendMailSchema.parse(req.body || {}); | ||
| const projectId = req.project?._id; | ||
|
|
||
| if (!projectId) { | ||
| return res.status(401).json({ success: false, data: {}, message: "Project context missing." }); | ||
| } | ||
|
|
||
| const project = await loadProjectMailConfig(projectId); | ||
| if (!project) { | ||
| return res.status(404).json({ success: false, data: {}, message: "Project not found." }); | ||
| } | ||
|
|
||
| const encryptedByokKey = | ||
| project.resendApiKey && typeof project.resendApiKey === "object" && Object.keys(project.resendApiKey).length > 0 | ||
| ? project.resendApiKey | ||
| : null; | ||
| const decryptedByokKey = encryptedByokKey ? decrypt(encryptedByokKey) : null; | ||
|
|
||
| const usingByok = typeof decryptedByokKey === "string" && decryptedByokKey.trim().length > 0; | ||
| const clientKey = usingByok | ||
| ? decryptedByokKey.trim() | ||
| : process.env.RESEND_API_KEY_2 || process.env.RESEND_API_KEY; | ||
|
|
||
| if (!clientKey) { | ||
| return res.status(500).json({ success: false, data: {}, message: "Resend API key is not configured." }); | ||
| } | ||
|
|
||
| const limit = getMonthlyMailLimit(req.project); | ||
| const { count, key } = await reserveMonthlyMailSlot(projectId, limit); | ||
| consumedQuotaKey = key; | ||
|
|
||
| const resend = new Resend(clientKey); | ||
|
|
||
| let fromAddress = DEFAULT_FROM; | ||
| if (usingByok) { | ||
| fromAddress = project.resendFromEmail && project.resendFromEmail.trim() | ||
| ? project.resendFromEmail.trim() | ||
| : "onboarding@resend.dev"; | ||
| } | ||
|
|
||
| const payload = { | ||
| from: fromAddress, | ||
| to, | ||
| subject, | ||
| }; | ||
| if (typeof html === "string" && html.trim()) payload.html = html; | ||
| if (typeof text === "string" && text.trim()) payload.text = text; | ||
|
|
||
| const { data, error } = await resend.emails.send(payload); | ||
| if (error) { | ||
| throw new Error(error.message || "Failed to send mail."); | ||
| } | ||
|
|
||
| return res.status(200).json({ | ||
| success: true, | ||
| data: { | ||
| id: data?.id || null, | ||
| provider: usingByok ? "byok" : "default", | ||
| monthlyUsage: count, | ||
| monthlyLimit: limit, | ||
| }, | ||
| message: "Mail sent successfully.", | ||
| }); | ||
| } catch (err) { | ||
| if (consumedQuotaKey) { | ||
| await redis.decr(consumedQuotaKey).catch(() => {}); | ||
| } | ||
|
|
||
| if (err instanceof z.ZodError) { | ||
| return res.status(400).json({ | ||
| success: false, | ||
| data: {}, | ||
| message: err.issues?.[0]?.message || "Invalid mail payload.", | ||
| }); | ||
| } | ||
|
|
||
| return res.status(err.statusCode || 500).json({ | ||
| success: false, | ||
| data: {}, | ||
| message: err.message || "Failed to send mail.", | ||
| ...(typeof err.limit === "number" ? { limit: err.limit } : {}), | ||
| }); | ||
| } | ||
| }; | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Return the standard public API error envelope here.
The success path is already shaped correctly, but the early returns and catch block switch back to
{ error: ... }and rawerr.message. That breaks the public API contract and can leak upstream/Mongo details on unexpected failures. Please route these throughAppErrorand respond with the standard{ success, data, message }shape on errors too. As per coding guidelines,apps/public-api/src/**/*.js: All API endpoints must return response format{ success: bool, data: {}, message: "" }and use AppError class for errors. Never raw throw, never expose MongoDB errors to client.Also applies to: 61-67, 81-83, 121-135
🤖 Prompt for AI Agents