Track HiveGrid Cloud planning reference
This commit is contained in:
1 parent
b3d5ea6764
commit
e341c5938a
5784 files changed
+1104929
-3
No files matched your search
@@ -0,0 +1,47 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
|
||||
/**
|
||||
* PII-protection regression test for EmailService.
|
||||
*
|
||||
* The legacy `console.log` printed `{ providerSettings, alias, hasTemplateData }`
|
||||
* which is borderline; we tightened it further (no full alias, only boolean).
|
||||
* This test asserts we never regress to logging `to`, `subject`, `body`, or `data`.
|
||||
*/
|
||||
describe("EmailService PII discipline", () => {
|
||||
const SOURCE = readFileSync(resolve(__dirname, "EmailService.ts"), "utf8");
|
||||
|
||||
it("contains no live console.* call sites", () => {
|
||||
const live = SOURCE.split("\n").filter((line, idx, all) => {
|
||||
if (!/console\.(log|error|warn|info|debug)\s*\(/.test(line)) return false;
|
||||
const trimmed = line.trimStart();
|
||||
if (trimmed.startsWith("//") || trimmed.startsWith("*")) return false;
|
||||
const prev = idx > 0 ? all[idx - 1].trim() : "";
|
||||
if (/eslint-disable-next-line[^\n]*no-console/.test(prev)) return false;
|
||||
return true;
|
||||
});
|
||||
expect(live).toEqual([]);
|
||||
});
|
||||
|
||||
it("never passes recipient address / subject / body / template-data as own logger fields", () => {
|
||||
// Pattern: emailLogger.<level>({ <key>: ... }) — flag if `<key>` is one of the PII fields.
|
||||
// Note: We check key positions (property keys), not value expressions like `Boolean(data)`.
|
||||
const pattern = /emailLogger\.(info|warn|error|debug)\s*\(\s*\{([\s\S]*?)\}/g;
|
||||
const forbiddenKeys = ["to", "subject", "body", "templateData", "recipient", "html", "text"];
|
||||
let match: RegExpExecArray | null;
|
||||
const offenders: string[] = [];
|
||||
while ((match = pattern.exec(SOURCE)) !== null) {
|
||||
const objContent = match[2];
|
||||
for (const key of forbiddenKeys) {
|
||||
const keyRe = new RegExp(`(^|[\\s,{])${key}\\s*:`, "m");
|
||||
if (keyRe.test(objContent)) offenders.push(`key "${key}" in ${match[0].slice(0, 80)}...`);
|
||||
}
|
||||
}
|
||||
expect(offenders, `emailLogger must not log PII fields: ${offenders.join("; ")}`).toEqual([]);
|
||||
});
|
||||
|
||||
it("uses createScopedLogger('email')", () => {
|
||||
expect(SOURCE).toMatch(/createScopedLogger\(\s*["']email["']\s*\)/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
import MailjetEmailService from "./MailjetEmailService";
|
||||
|
||||
async function send({
|
||||
provider,
|
||||
data,
|
||||
}: {
|
||||
provider: "mailjet";
|
||||
data: { to: string; subject: string; body: string };
|
||||
}) {
|
||||
if (provider !== "mailjet") {
|
||||
throw new Error("Invalid provider: " + provider);
|
||||
}
|
||||
|
||||
return await MailjetEmailService.send({
|
||||
data: { to: data.to, subject: data.subject, body: data.body },
|
||||
});
|
||||
}
|
||||
|
||||
export default {
|
||||
send,
|
||||
};
|
||||
@@ -0,0 +1,53 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("~/utils/db/appConfiguration.db.server", () => ({
|
||||
getAppConfiguration: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("./MailjetEmailService", () => ({
|
||||
sendEmailMailjet: vi.fn(async () => ({ provider: "queue", status: "queued", messageId: "job_1" })),
|
||||
}));
|
||||
|
||||
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
import { sendEmailMailjet } from "./MailjetEmailService";
|
||||
import { sendEmail } from "./EmailService";
|
||||
|
||||
const getAppConfigurationMock = vi.mocked(getAppConfiguration);
|
||||
const sendEmailMailjetMock = vi.mocked(sendEmailMailjet);
|
||||
|
||||
describe("EmailService queued delivery", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
delete process.env.MAILJET_API_KEY;
|
||||
delete process.env.MAILJET_FROM_EMAIL;
|
||||
getAppConfigurationMock.mockResolvedValue({
|
||||
email: {
|
||||
provider: "mailjet",
|
||||
fromEmail: "",
|
||||
fromName: "",
|
||||
supportEmail: "",
|
||||
},
|
||||
} as Awaited<ReturnType<typeof getAppConfiguration>>);
|
||||
});
|
||||
|
||||
it("queues mail without requiring Mailjet credentials in the web runtime", async () => {
|
||||
await sendEmail({
|
||||
request: new Request("https://admin.example.com/settings/transactional-emails"),
|
||||
to: "ada@example.com",
|
||||
subject: "Welcome",
|
||||
body: "<p>Hello</p>",
|
||||
alias: "registration-welcome",
|
||||
data: { firstName: "Ada" },
|
||||
});
|
||||
|
||||
expect(sendEmailMailjetMock).toHaveBeenCalledWith({
|
||||
data: {
|
||||
to: "ada@example.com",
|
||||
subject: "Welcome",
|
||||
body: "<p>Hello</p>",
|
||||
alias: "registration-welcome",
|
||||
data: { firstName: "Ada" },
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,63 @@
|
||||
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
import { createScopedLogger } from "~/utils/logger.server";
|
||||
import { sendEmailMailjet } from "./MailjetEmailService";
|
||||
|
||||
const emailLogger = createScopedLogger("email");
|
||||
|
||||
type EmailProvider = "mailjet";
|
||||
|
||||
export async function sendEmail({
|
||||
request,
|
||||
to,
|
||||
subject,
|
||||
body,
|
||||
alias,
|
||||
data,
|
||||
tenantId,
|
||||
priorityOverride,
|
||||
}: {
|
||||
request: Request;
|
||||
to: string;
|
||||
subject: string;
|
||||
body: string;
|
||||
alias?: string;
|
||||
data?: {
|
||||
[key: string]: any;
|
||||
};
|
||||
tenantId?: string | null;
|
||||
priorityOverride?: "critical" | "high" | "normal" | "low";
|
||||
}) {
|
||||
const config = await getEmailConfig({ request, throwError: true });
|
||||
if (!config) {
|
||||
throw new Error("Email provider not configured");
|
||||
}
|
||||
// Intentionally never log `to`, `subject`, `body`, or `data` (PII).
|
||||
// Only log provider class, presence-of-alias, and a generic flag for template data.
|
||||
emailLogger.info(
|
||||
{
|
||||
provider: config.provider,
|
||||
hasAlias: typeof alias === "string" && alias.length > 0,
|
||||
hasTemplateData: Boolean(data),
|
||||
},
|
||||
"Sending email",
|
||||
);
|
||||
return await sendEmailMailjet({ data: { to, subject, body, alias, data, tenantId, priorityOverride } });
|
||||
}
|
||||
|
||||
export async function getEmailProvider({ request }: { request: Request }) {
|
||||
const clientConfig = await getEmailConfig({ request });
|
||||
return clientConfig?.provider;
|
||||
}
|
||||
|
||||
export async function getEmailConfig({ request, throwError = false }: { request: Request; throwError?: boolean }) {
|
||||
const appConfiguration = await getAppConfiguration({ request });
|
||||
let provider = appConfiguration.email.provider;
|
||||
if (provider === "mailjet") {
|
||||
return appConfiguration.email;
|
||||
}
|
||||
emailLogger.error({ provider: provider ?? "<none>" }, "Email provider not configured");
|
||||
if (throwError) {
|
||||
throw new Error("Email provider not configured");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
import { afterEach, describe, expect, test, vi } from "vitest";
|
||||
import { buildRetryJobOptions, buildTransactionalMailJob, queueNames, type TypedQueue } from "@toolctrl/queue";
|
||||
import { sendEmailMailjet } from "./MailjetEmailService";
|
||||
|
||||
const runtimeQueue = {
|
||||
add: vi.fn(async () => ({ id: "job_from_env" })),
|
||||
close: vi.fn(async () => undefined),
|
||||
};
|
||||
|
||||
vi.mock("@toolctrl/queue/runtime", () => ({
|
||||
createQueue: vi.fn(() => runtimeQueue),
|
||||
}));
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
delete process.env.BULLMQ_REDIS_URL;
|
||||
delete process.env.REDIS_URL;
|
||||
});
|
||||
|
||||
function createQueueMock() {
|
||||
return {
|
||||
add: vi.fn(async () => ({ id: "job_123" })),
|
||||
} as unknown as TypedQueue<typeof queueNames.email> & {
|
||||
add: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
}
|
||||
|
||||
describe("sendEmailMailjet", () => {
|
||||
test("enqueues transactional email through the default queue provider", async () => {
|
||||
const queue = createQueueMock();
|
||||
|
||||
const result = await sendEmailMailjet(
|
||||
{
|
||||
data: {
|
||||
to: "user@example.com",
|
||||
subject: "Welcome",
|
||||
body: "<p>Hello</p>",
|
||||
alias: "registration-welcome",
|
||||
data: { firstName: "Ada" },
|
||||
},
|
||||
},
|
||||
{
|
||||
queue,
|
||||
}
|
||||
);
|
||||
|
||||
expect(result).toEqual({
|
||||
provider: "queue",
|
||||
status: "queued",
|
||||
messageId: "job_123",
|
||||
warnings: {
|
||||
queueName: queueNames.email,
|
||||
jobName: "send-transactional-email",
|
||||
},
|
||||
});
|
||||
|
||||
const descriptor = buildTransactionalMailJob({
|
||||
to: ["user@example.com"],
|
||||
subject: "Welcome",
|
||||
html: "<p>Hello</p>",
|
||||
templateData: { firstName: "Ada" },
|
||||
metadata: { alias: "registration-welcome" },
|
||||
});
|
||||
expect(queue.add).toHaveBeenCalledWith(
|
||||
"send-transactional-email",
|
||||
descriptor.payload,
|
||||
buildRetryJobOptions(descriptor)
|
||||
);
|
||||
});
|
||||
|
||||
test("fails closed when Redis is missing without falling back to synchronous mail", async () => {
|
||||
await expect(sendEmailMailjet(
|
||||
{
|
||||
data: {
|
||||
to: "user@example.com",
|
||||
subject: "Welcome",
|
||||
body: "<p>Hello</p>",
|
||||
alias: "registration-welcome",
|
||||
data: { firstName: "Ada" },
|
||||
},
|
||||
},
|
||||
{
|
||||
env: {},
|
||||
}
|
||||
)).rejects.toMatchObject({
|
||||
provider: "queue",
|
||||
message: "Set BULLMQ_REDIS_URL or REDIS_URL to enqueue transactional email jobs.",
|
||||
responseBody: {
|
||||
code: "missing_redis_connection",
|
||||
message: "Set BULLMQ_REDIS_URL or REDIS_URL to enqueue transactional email jobs.",
|
||||
requiredEnv: ["BULLMQ_REDIS_URL", "REDIS_URL"],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test("uses process Redis configuration by default", async () => {
|
||||
process.env.BULLMQ_REDIS_URL = "redis://localhost:6379/2";
|
||||
|
||||
const result = await sendEmailMailjet({
|
||||
data: {
|
||||
to: "user@example.com",
|
||||
subject: "Welcome",
|
||||
body: "<p>Hello</p>",
|
||||
alias: "registration-welcome",
|
||||
data: { firstName: "Ada" },
|
||||
},
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
provider: "queue",
|
||||
status: "queued",
|
||||
messageId: "job_from_env",
|
||||
warnings: {
|
||||
queueName: queueNames.email,
|
||||
jobName: "send-transactional-email",
|
||||
},
|
||||
});
|
||||
expect(runtimeQueue.add).toHaveBeenCalledOnce();
|
||||
expect(runtimeQueue.close).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
test("propagates enqueue failures to the caller", async () => {
|
||||
const queue = createQueueMock();
|
||||
const error = new Error("queue add failed");
|
||||
queue.add.mockRejectedValueOnce(error);
|
||||
|
||||
await expect(
|
||||
sendEmailMailjet(
|
||||
{
|
||||
data: {
|
||||
to: "user@example.com",
|
||||
subject: "Welcome",
|
||||
body: "<p>Hello</p>",
|
||||
alias: "registration-welcome",
|
||||
data: { firstName: "Ada" },
|
||||
},
|
||||
},
|
||||
{
|
||||
queue,
|
||||
}
|
||||
)
|
||||
).rejects.toBe(error);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,109 @@
|
||||
import { MailProviderError, type MailProvider } from "@toolctrl/mail";
|
||||
import {
|
||||
buildTransactionalMailJob,
|
||||
enqueueJob,
|
||||
queueNames,
|
||||
resolveRedisConnectionOptions,
|
||||
resolveRedisConnectionOptionsFromProcessEnv,
|
||||
type RedisConnectionEnv,
|
||||
type TypedQueue,
|
||||
} from "@toolctrl/queue";
|
||||
import { t as i18nT } from "i18next";
|
||||
|
||||
export type SendEmailMailjetDependencies = {
|
||||
env?: RedisConnectionEnv;
|
||||
queue?: TypedQueue<typeof queueNames.email>;
|
||||
};
|
||||
|
||||
export async function sendEmailMailjet(
|
||||
{
|
||||
data,
|
||||
}: {
|
||||
data: {
|
||||
to: string;
|
||||
subject?: string;
|
||||
body?: string;
|
||||
alias?: string;
|
||||
data?: {
|
||||
[key: string]: any;
|
||||
};
|
||||
tenantId?: string | null;
|
||||
priorityOverride?: "critical" | "high" | "normal" | "low";
|
||||
};
|
||||
},
|
||||
dependencies: SendEmailMailjetDependencies = {}
|
||||
) {
|
||||
const mailProvider = dependencies.queue
|
||||
? createTransactionalQueueProvider(dependencies.queue, data.alias, data.data)
|
||||
: createTransactionalQueueProviderFromEnv(dependencies.env, data.alias, data.data);
|
||||
|
||||
return await mailProvider.send({
|
||||
to: [data.to],
|
||||
subject: data.subject,
|
||||
html: data.body,
|
||||
tenantId: data.tenantId,
|
||||
priorityOverride: data.priorityOverride,
|
||||
});
|
||||
}
|
||||
|
||||
function createTransactionalQueueProviderFromEnv(env?: RedisConnectionEnv, alias?: string, templateData?: Record<string, unknown>): MailProvider {
|
||||
const connection = env ? resolveRedisConnectionOptions({ env }) : resolveRedisConnectionOptionsFromProcessEnv();
|
||||
|
||||
if (!connection) {
|
||||
return {
|
||||
id: "queue",
|
||||
async send() {
|
||||
const warning = {
|
||||
code: "missing_redis_connection",
|
||||
message: i18nT("mail.queue.errors.missingRedisConnection"),
|
||||
requiredEnv: ["BULLMQ_REDIS_URL", "REDIS_URL"],
|
||||
};
|
||||
throw new MailProviderError(warning.message, { provider: "queue", responseBody: warning });
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
id: "queue",
|
||||
async send(input) {
|
||||
const queueRuntimeModule = "@toolctrl/queue/runtime";
|
||||
const { createQueue } = (await import(/* @vite-ignore */ queueRuntimeModule)) as typeof import("@toolctrl/queue/runtime");
|
||||
const queue = createQueue(queueNames.email, { connection });
|
||||
try {
|
||||
return await createTransactionalQueueProvider(queue, alias, templateData).send(input);
|
||||
} finally {
|
||||
await queue.close();
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function createTransactionalQueueProvider(queue: TypedQueue<typeof queueNames.email>, alias?: string, templateData?: Record<string, unknown>): MailProvider {
|
||||
return {
|
||||
id: "queue",
|
||||
async send(input) {
|
||||
const descriptor = buildTransactionalMailJob({
|
||||
to: input.to.map((recipient) => (typeof recipient === "string" ? recipient : recipient.email)),
|
||||
subject: input.subject,
|
||||
html: input.html,
|
||||
templateData,
|
||||
metadata: alias ? { alias } : undefined,
|
||||
});
|
||||
const job = await enqueueJob(queue, descriptor);
|
||||
|
||||
return {
|
||||
provider: "queue",
|
||||
status: "queued",
|
||||
messageId: job.id,
|
||||
warnings: {
|
||||
queueName: descriptor.queueName,
|
||||
jobName: descriptor.jobName,
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export default {
|
||||
send: sendEmailMailjet,
|
||||
};
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
import { afterEach, describe, expect, test, vi } from "vitest";
|
||||
import { buildRetryJobOptions, buildTransactionalMailJob, queueNames, type TypedQueue } from "@toolctrl/queue";
|
||||
import { queueTransactionalEmail } from "./TransactionalEmailQueue.server";
|
||||
|
||||
const runtimeQueue = {
|
||||
add: vi.fn(async () => ({ id: "job_from_env" })),
|
||||
close: vi.fn(async () => undefined),
|
||||
};
|
||||
const originalRedisEnv = {
|
||||
BULLMQ_REDIS_URL: process.env.BULLMQ_REDIS_URL,
|
||||
REDIS_URL: process.env.REDIS_URL,
|
||||
};
|
||||
|
||||
function restoreRedisEnv() {
|
||||
for (const [key, value] of Object.entries(originalRedisEnv)) {
|
||||
if (value === undefined) {
|
||||
delete process.env[key];
|
||||
} else {
|
||||
process.env[key] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
vi.mock("@toolctrl/queue/runtime", () => ({
|
||||
createQueue: vi.fn(() => runtimeQueue),
|
||||
}));
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
restoreRedisEnv();
|
||||
});
|
||||
|
||||
describe("queueTransactionalEmail", () => {
|
||||
test("fails closed without Redis configuration", async () => {
|
||||
await expect(
|
||||
queueTransactionalEmail(
|
||||
{
|
||||
to: "user@example.com",
|
||||
subject: "Reset password",
|
||||
body: "<p>Reset</p>",
|
||||
alias: "password-reset",
|
||||
},
|
||||
{
|
||||
env: {},
|
||||
}
|
||||
)
|
||||
).rejects.toThrow("Redis connection required to enqueue transactional email.");
|
||||
});
|
||||
|
||||
test("enqueues transactional email payloads", async () => {
|
||||
const add = vi.fn(async () => ({ id: "job_1" }));
|
||||
const queue = { add } as unknown as TypedQueue<typeof queueNames.email>;
|
||||
|
||||
const result = await queueTransactionalEmail(
|
||||
{
|
||||
to: "user@example.com",
|
||||
subject: "Reset password",
|
||||
body: "<p>Reset</p>",
|
||||
alias: "password-reset",
|
||||
tenantId: "tenant_1",
|
||||
userId: "user_1",
|
||||
data: { action_url: "https://example.com/reset" },
|
||||
},
|
||||
{
|
||||
queue,
|
||||
}
|
||||
);
|
||||
|
||||
expect(result).toEqual({ enqueued: true, jobId: "job_1" });
|
||||
expect(add).toHaveBeenCalledOnce();
|
||||
const descriptor = buildTransactionalMailJob({
|
||||
to: ["user@example.com"],
|
||||
subject: "Reset password",
|
||||
html: "<p>Reset</p>",
|
||||
templateData: { action_url: "https://example.com/reset" },
|
||||
tenantId: "tenant_1",
|
||||
userId: "user_1",
|
||||
metadata: { alias: "password-reset" },
|
||||
});
|
||||
expect(add).toHaveBeenCalledWith(
|
||||
"send-transactional-email",
|
||||
descriptor.payload,
|
||||
expect.objectContaining({
|
||||
...buildRetryJobOptions(descriptor),
|
||||
// priority is resolved from tenantId; without a registered plan
|
||||
// lookup it falls back to NORMAL (5).
|
||||
priority: 5,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
test("uses process Redis configuration by default", async () => {
|
||||
process.env.BULLMQ_REDIS_URL = "redis://localhost:6379/2";
|
||||
|
||||
const result = await queueTransactionalEmail({
|
||||
to: "user@example.com",
|
||||
subject: "Reset password",
|
||||
body: "<p>Reset</p>",
|
||||
alias: "password-reset",
|
||||
});
|
||||
|
||||
expect(result).toEqual({ enqueued: true, jobId: "job_from_env" });
|
||||
expect(runtimeQueue.add).toHaveBeenCalledOnce();
|
||||
expect(runtimeQueue.close).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
test("propagates enqueue failures without synchronous mail fallback", async () => {
|
||||
const enqueueError = new Error("queue unavailable");
|
||||
const add = vi.fn(async () => {
|
||||
throw enqueueError;
|
||||
});
|
||||
const queue = { add } as unknown as TypedQueue<typeof queueNames.email>;
|
||||
|
||||
await expect(
|
||||
queueTransactionalEmail(
|
||||
{
|
||||
to: "user@example.com",
|
||||
subject: "Welcome",
|
||||
body: "<p>Welcome</p>",
|
||||
alias: "registration-welcome",
|
||||
data: { firstName: "Ada" },
|
||||
},
|
||||
{
|
||||
queue,
|
||||
}
|
||||
)
|
||||
).rejects.toThrow(enqueueError);
|
||||
|
||||
expect(add).toHaveBeenCalledOnce();
|
||||
const descriptor = buildTransactionalMailJob({
|
||||
to: ["user@example.com"],
|
||||
subject: "Welcome",
|
||||
html: "<p>Welcome</p>",
|
||||
templateData: { firstName: "Ada" },
|
||||
metadata: { alias: "registration-welcome" },
|
||||
});
|
||||
expect(add).toHaveBeenCalledWith(
|
||||
"send-transactional-email",
|
||||
expect.objectContaining({
|
||||
kind: "mail.transactional",
|
||||
templateData: { firstName: "Ada" },
|
||||
metadata: { alias: "registration-welcome" },
|
||||
}),
|
||||
buildRetryJobOptions(descriptor)
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,92 @@
|
||||
import {
|
||||
buildTransactionalMailJob,
|
||||
enqueueJob,
|
||||
queueNames,
|
||||
resolveRedisConnectionOptions,
|
||||
resolveRedisConnectionOptionsFromProcessEnv,
|
||||
type RedisConnectionEnv,
|
||||
type TypedQueue,
|
||||
} from "@toolctrl/queue";
|
||||
|
||||
export type QueueTransactionalEmailInput = {
|
||||
to: string;
|
||||
subject?: string;
|
||||
body?: string;
|
||||
alias?: string;
|
||||
tenantId?: string;
|
||||
userId?: string;
|
||||
data?: Record<string, unknown>;
|
||||
/**
|
||||
* Explicit BullMQ priority for this mail job. Use `"critical"` for
|
||||
* auth-flow mails (password-reset, magic-link, invitation, verification)
|
||||
* so they preempt low-priority batch jobs regardless of tenant plan.
|
||||
*/
|
||||
priorityOverride?: "critical" | "high" | "normal" | "low";
|
||||
};
|
||||
|
||||
export type QueueTransactionalEmailResult =
|
||||
| {
|
||||
enqueued: true;
|
||||
jobId?: string;
|
||||
};
|
||||
|
||||
type QueueTransactionalEmailDependencies = {
|
||||
env?: RedisConnectionEnv;
|
||||
queue?: TypedQueue<typeof queueNames.email>;
|
||||
};
|
||||
|
||||
export async function queueTransactionalEmail(
|
||||
input: QueueTransactionalEmailInput,
|
||||
dependencies: QueueTransactionalEmailDependencies = {}
|
||||
): Promise<QueueTransactionalEmailResult> {
|
||||
let queue = dependencies.queue;
|
||||
let shouldCloseQueue = false;
|
||||
const connection = queue
|
||||
? undefined
|
||||
: dependencies.env
|
||||
? resolveRedisConnectionOptions({ env: dependencies.env })
|
||||
: resolveRedisConnectionOptionsFromProcessEnv();
|
||||
|
||||
if (!queue && !connection) {
|
||||
throw new Error("Redis connection required to enqueue transactional email.");
|
||||
}
|
||||
|
||||
if (!queue && connection) {
|
||||
const queueRuntimeModule = "@toolctrl/queue/runtime";
|
||||
const { createQueue } = (await import(/* @vite-ignore */ queueRuntimeModule)) as typeof import("@toolctrl/queue/runtime");
|
||||
queue = createQueue(queueNames.email, {
|
||||
connection,
|
||||
});
|
||||
shouldCloseQueue = true;
|
||||
}
|
||||
if (!queue) {
|
||||
throw new Error("Email queue was not initialized.");
|
||||
}
|
||||
|
||||
try {
|
||||
const descriptor = buildTransactionalMailJob({
|
||||
to: [input.to],
|
||||
subject: input.subject,
|
||||
html: input.body,
|
||||
templateData: input.data,
|
||||
tenantId: input.tenantId,
|
||||
userId: input.userId,
|
||||
metadata: {
|
||||
alias: input.alias,
|
||||
},
|
||||
});
|
||||
const job = await enqueueJob(queue, descriptor, {
|
||||
...(input.tenantId !== undefined ? { tenantId: input.tenantId } : {}),
|
||||
...(input.priorityOverride !== undefined ? { priorityOverride: input.priorityOverride } : {}),
|
||||
});
|
||||
|
||||
return {
|
||||
enqueued: true,
|
||||
jobId: job.id,
|
||||
};
|
||||
} finally {
|
||||
if (shouldCloseQueue) {
|
||||
await queue.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { getMailjetProviderStatus, updateMailjetSettings } from "./TransactionalEmailSettings.server";
|
||||
import { getAppConfiguration, updateAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
|
||||
vi.mock("~/utils/db/appConfiguration.db.server", () => ({
|
||||
getAppConfiguration: vi.fn(),
|
||||
updateAppConfiguration: vi.fn(),
|
||||
}));
|
||||
|
||||
const request = new Request("https://admin.example.com/settings/transactional-emails");
|
||||
const getAppConfigurationMock = vi.mocked(getAppConfiguration);
|
||||
const updateAppConfigurationMock = vi.mocked(updateAppConfiguration);
|
||||
|
||||
function clearMailjetEnv() {
|
||||
delete process.env.MAILJET_API_KEY;
|
||||
delete process.env.MAILJET_SECRET_KEY;
|
||||
delete process.env.MAILJET_FROM_EMAIL;
|
||||
}
|
||||
|
||||
describe("TransactionalEmailSettings.server", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
clearMailjetEnv();
|
||||
|
||||
getAppConfigurationMock.mockResolvedValue({
|
||||
email: {
|
||||
provider: "mailjet",
|
||||
fromEmail: "",
|
||||
fromName: "Support",
|
||||
supportEmail: "support@example.com",
|
||||
},
|
||||
} as Awaited<ReturnType<typeof getAppConfiguration>>);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
clearMailjetEnv();
|
||||
});
|
||||
|
||||
it("uses Mailjet environment values as a redacted fallback status", async () => {
|
||||
process.env.MAILJET_API_KEY = "env-public-key";
|
||||
process.env.MAILJET_SECRET_KEY = "env-secret-key";
|
||||
process.env.MAILJET_FROM_EMAIL = "sender@example.com";
|
||||
|
||||
const status = await getMailjetProviderStatus({ request });
|
||||
|
||||
expect(status).toEqual({
|
||||
id: "mailjet",
|
||||
name: "Mailjet",
|
||||
configured: true,
|
||||
source: { apiKey: "environment", secretKey: "environment", fromEmail: "environment" },
|
||||
missing: [],
|
||||
});
|
||||
expect(JSON.stringify(status)).not.toContain("env-secret-key");
|
||||
});
|
||||
|
||||
it("reports the missing Mailjet keys by name when partially configured", async () => {
|
||||
process.env.MAILJET_API_KEY = "env-public-key";
|
||||
|
||||
const status = await getMailjetProviderStatus({ request });
|
||||
|
||||
expect(status.configured).toBe(false);
|
||||
expect(status.missing).toEqual(["MAILJET_SECRET_KEY", "MAILJET_FROM_EMAIL"]);
|
||||
});
|
||||
|
||||
it("rejects non-Mailjet provider updates", async () => {
|
||||
const form = createSettingsForm({ emailProvider: "smtp", apiKey: "new-secret-key" });
|
||||
|
||||
const result = await updateMailjetSettings(form);
|
||||
|
||||
expect(result).toEqual({ success: false, error: "Only Mailjet is supported for transactional email." });
|
||||
expect(updateAppConfigurationMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects submitted API keys because queued delivery is environment configured", async () => {
|
||||
const form = createSettingsForm({ apiKey: "new-secret-key" });
|
||||
|
||||
const result = await updateMailjetSettings(form);
|
||||
|
||||
expect(result).toEqual({ success: false, error: "Mailjet API keys are configured through environment variables only." });
|
||||
expect(updateAppConfigurationMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("updates support metadata only when the submitted API key is blank", async () => {
|
||||
const form = createSettingsForm({ apiKey: " " });
|
||||
|
||||
const result = await updateMailjetSettings(form);
|
||||
|
||||
expect(result).toEqual({ success: true });
|
||||
expect(updateAppConfigurationMock).toHaveBeenCalledWith({
|
||||
emailProvider: "mailjet",
|
||||
emailSupportEmail: "support@example.com",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
function createSettingsForm(overrides: Partial<Record<string, string>> = {}) {
|
||||
const form = new FormData();
|
||||
form.set("emailProvider", overrides.emailProvider ?? "mailjet");
|
||||
form.set("emailFromEmail", overrides.emailFromEmail ?? "sender@example.com");
|
||||
form.set("emailFromName", overrides.emailFromName ?? "Support");
|
||||
form.set("emailSupportEmail", overrides.emailSupportEmail ?? "support@example.com");
|
||||
form.set("apiKey", overrides.apiKey ?? "new-secret-key");
|
||||
return form;
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
import { loadWebConfig } from "@toolctrl/config";
|
||||
import { getAppConfiguration, updateAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
|
||||
export const MAILJET_PROVIDER_ID = "mailjet" as const;
|
||||
|
||||
type MailjetProviderId = typeof MAILJET_PROVIDER_ID;
|
||||
type MailjetSource = "environment" | "missing";
|
||||
|
||||
export type MailjetProviderStatus = {
|
||||
id: MailjetProviderId;
|
||||
name: "Mailjet";
|
||||
configured: boolean;
|
||||
source: {
|
||||
apiKey: MailjetSource;
|
||||
secretKey: MailjetSource;
|
||||
fromEmail: MailjetSource;
|
||||
};
|
||||
missing: string[];
|
||||
};
|
||||
|
||||
export type UpdateMailjetSettingsResult =
|
||||
| { success: true }
|
||||
| { success: false; error: string };
|
||||
|
||||
export async function getMailjetProviderStatus({ request }: { request: Request }): Promise<MailjetProviderStatus> {
|
||||
await getAppConfiguration({ request });
|
||||
|
||||
const mailjet = loadWebConfig().config.mailjet;
|
||||
|
||||
const source = {
|
||||
apiKey: mailjet.apiKey ? "environment" : "missing",
|
||||
secretKey: mailjet.secretKey ? "environment" : "missing",
|
||||
fromEmail: mailjet.fromEmail ? "environment" : "missing",
|
||||
} satisfies MailjetProviderStatus["source"];
|
||||
|
||||
const missing = [
|
||||
source.apiKey === "missing" ? "MAILJET_API_KEY" : null,
|
||||
source.secretKey === "missing" ? "MAILJET_SECRET_KEY" : null,
|
||||
source.fromEmail === "missing" ? "MAILJET_FROM_EMAIL" : null,
|
||||
].filter((item): item is string => Boolean(item));
|
||||
|
||||
return {
|
||||
id: MAILJET_PROVIDER_ID,
|
||||
name: "Mailjet",
|
||||
configured: missing.length === 0,
|
||||
source,
|
||||
missing,
|
||||
};
|
||||
}
|
||||
|
||||
export async function updateMailjetSettings(form: FormData): Promise<UpdateMailjetSettingsResult> {
|
||||
const provider = form.get("emailProvider")?.toString();
|
||||
if (provider !== MAILJET_PROVIDER_ID) {
|
||||
return { success: false, error: "Only Mailjet is supported for transactional email." };
|
||||
}
|
||||
|
||||
if (form.get("apiKey")?.toString().trim()) {
|
||||
return { success: false, error: "Mailjet API keys are configured through environment variables only." };
|
||||
}
|
||||
|
||||
await updateAppConfiguration({
|
||||
emailProvider: MAILJET_PROVIDER_ID,
|
||||
emailSupportEmail: form.get("emailSupportEmail")?.toString(),
|
||||
});
|
||||
|
||||
return { success: true };
|
||||
}
|
||||
Reference in new issue
Block a user