Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -165,4 +165,12 @@ Social auth (GitHub + Google) shipped. Next: v0.9.0 — Webhooks + BYOK Resend m
- Webhook system: per-project config, HMAC-SHA256, retry, delivery logs
- BYOK Resend mail key: project-level Resend API key, custom domain mail
- Follow same encryption pattern as authProviders for storing Resend key
- Webhook model: separate MongoDB collection (not embedded in Project)
- Webhook model: separate MongoDB collection (not embedded in Project)

## Webhook system (v0.9.0) - Already done
- Model: packages/common/src/models/Webhook.js
- Delivery log: packages/common/src/models/WebhookDelivery.js
- Dispatcher: apps/public-api/src/utils/webhookDispatcher.js
- Queue: BullMQ + existing Redis connection
- Retry: exponential backoff, max 5 attempts, stop on 4xx
- Signature: HMAC-SHA256 in X-urBackend-Signature header
48 changes: 45 additions & 3 deletions apps/dashboard-api/src/controllers/project.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,12 @@ const sanitizeProjectResponse = (projectObj) => {
delete projectObj.publishableKey;
delete projectObj.secretKey;
delete projectObj.jwtSecret;
const resendConfig = projectObj.resendApiKey;
projectObj.hasResendApiKey =
resendConfig != null &&
typeof resendConfig === "object" &&
Object.keys(resendConfig).length > 0;
delete projectObj.resendApiKey;

projectObj.authProviders = sanitizeAuthProviders(projectObj.authProviders);

Expand Down Expand Up @@ -264,7 +270,10 @@ module.exports.getSingleProject = async (req, res) => {
"+authProviders.github.clientSecret.tag " +
"+authProviders.google.clientSecret.encrypted " +
"+authProviders.google.clientSecret.iv " +
"+authProviders.google.clientSecret.tag",
"+authProviders.google.clientSecret.tag " +
"+resendApiKey.encrypted " +
"+resendApiKey.iv " +
"+resendApiKey.tag",
);
if (!project)
return res.status(404).json({ error: "Project not found." });
Expand Down Expand Up @@ -1088,9 +1097,30 @@ module.exports.deleteAllFiles = async (req, res) => {

module.exports.updateProject = async (req, res) => {
try {
const { name, siteUrl } = req.body;
const { name, siteUrl, resendApiKey, resendFromEmail } = req.body;
const updateFields = {};
if (name !== undefined) updateFields.name = name;
if (resendFromEmail !== undefined) {
if (typeof resendFromEmail !== "string") {
return res.status(400).json({ error: "resendFromEmail must be a string." });
}
const trimmedFrom = resendFromEmail.trim();
if (trimmedFrom !== "") {
if (trimmedFrom.length > 255) {
return res.status(400).json({ error: "resendFromEmail is too long." });
}
let addressToValidate = trimmedFrom;
const bracketMatch = trimmedFrom.match(/<([^>]+)>$/);
if (bracketMatch) {
addressToValidate = bracketMatch[1].trim();
}
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(addressToValidate)) {
return res.status(400).json({ error: "resendFromEmail must be a valid format (e.g., 'me@domain.com' or 'App <me@domain.com>')." });
}
}
updateFields.resendFromEmail = trimmedFrom;
}
if (siteUrl !== undefined) {
if (siteUrl !== "" && typeof siteUrl !== "string") {
return res.status(400).json({ error: "siteUrl must be a string." });
Expand All @@ -1116,11 +1146,23 @@ module.exports.updateProject = async (req, res) => {
}
updateFields.siteUrl = siteUrl || "";
}
if (resendApiKey !== undefined) {
if (typeof resendApiKey !== "string" || !resendApiKey.trim()) {
return res
.status(400)
.json({ error: "resendApiKey must be a non-empty string." });
}
updateFields.resendApiKey = encrypt(resendApiKey.trim());
}

const project = await Project.findOneAndUpdate(
{ _id: req.params.projectId, owner: req.user._id },
{ $set: updateFields },
{ new: true },
{
new: true,
projection:
"+resendApiKey.encrypted +resendApiKey.iv +resendApiKey.tag",
},
);
if (!project) return res.status(404).json({ error: "Project not found." });

Expand Down
116 changes: 116 additions & 0 deletions apps/public-api/src/__tests__/mail.controller.test.js
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.',
}));
});
});
4 changes: 4 additions & 0 deletions apps/public-api/src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,12 @@ const { capture } = require('@kiroo/sdk');
const {emailQueue} = require('@urbackend/common');
const {authEmailQueue} = require('@urbackend/common');
const {initWebhookWorker} = require('@urbackend/common');
const {initAuthEmailWorker} = require('@urbackend/common');

// Initialize webhook worker
if (process.env.NODE_ENV !== 'test') {
initWebhookWorker();
initAuthEmailWorker();
}

app.use(express.json());
Expand Down Expand Up @@ -57,6 +59,7 @@ const dataRoute = require('./routes/data');
const userAuthRoute = require('./routes/userAuth');
const storageRoute = require('./routes/storage');
const schemaRoute = require('./routes/schemas');
const mailRoute = require('./routes/mail');

// ROUTES SETUP
app.use('/api/userAuth', limiter, logger, userAuthRoute);
Expand All @@ -74,6 +77,7 @@ const projectCorsPreflight = (req, res, next) => {
app.use('/api/data', projectCorsPreflight, limiter, logger, dataRoute);
app.use('/api/schemas', projectCorsPreflight, limiter, logger, schemaRoute);
app.use('/api/storage', projectCorsPreflight, limiter, logger, storageRoute);
app.use('/api/mail', projectCorsPreflight, limiter, logger, mailRoute);

app.get('/api/server-ip', async (req, res) => {
const ip = await getPublicIp();
Expand Down
147 changes: 147 additions & 0 deletions apps/public-api/src/controllers/mail.controller.js
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_...).",
});
}
Comment on lines +53 to +62

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.

⚠️ Potential issue | 🟠 Major

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 raw err.message. That breaks the public API contract and can leak upstream/Mongo details on unexpected failures. Please route these through AppError and 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
Verify each finding against the current code and only fix it if needed.

In `@apps/public-api/src/controllers/mail.controller.js` around lines 49 - 56, The
handler sendMail currently returns raw { error: ... } and err.message on early
returns and in the catch, breaking the public API contract; import and use the
AppError class and always respond with the standard envelope { success: boolean,
data: {}, message: string } on failures. Replace the secret-key check return
(and other early returns around the sendMail function, including the blocks
referenced at 61-67, 81-83, 121-135) so they either throw new
AppError("Forbidden. This action requires a Secret Key (sk_live_...).", 403) or
call res.status(...).json({ success: false, data: {}, message: "..." })
constructed from AppError; update the catch block to map any caught error to an
AppError (don’t expose err.message or DB errors) and respond with
res.status(appErr.statusCode||500).json({ success: false, data: {}, message:
appErr.message }). Ensure consumedQuotaKey cleanup/logic remains unchanged.


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 } : {}),
});
}
};
Loading
Loading