2 Commits
Author SHA1 Message Date
AImighty Bot a74d6ef05e Courier 26.11.24: optionale Vorlage sport-v1 mit Vorschau
ci / build (push) Successful in 30s
2026-11-24 06:09:50 +00:00
AImighty Bot 67d0d2eeba Courier 26.11.23: Inline-Anhänge mit Content-ID
ci / build (push) Successful in 30s
2026-11-24 05:49:49 +00:00
15 changed files with 410 additions and 25 deletions

No files matched your search

+2 -2
View File
@@ -12,7 +12,7 @@ metadata:
title: Courier
description: Transaktionsmail für deine Apps über Amazon SES.
icon: https://git.aimighty.olares.de/aimighty/courier/raw/branch/main/icon.png
version: 26.11.22
version: 26.11.24
categories:
- Applications
@@ -106,7 +106,7 @@ envs:
default: "1000"
spec:
versionName: '26.11.22'
versionName: '26.11.24'
fullDescription: |
**Courier** ist ein kleiner Versanddienst für transaktionale E-Mails:
eine Resend-kompatible HTTP-API, Warteschlange, Retry, Logs und
+11 -7
View File
@@ -1,7 +1,8 @@
import { authenticate, fromAllowed } from "@/lib/api-key";
import { parseBatchInput, parseMailInput } from "@/lib/mail-input";
import { MailValidationError } from "@/lib/schema";
import { apiError, serverError, unauthorized, validationError } from "@/lib/http";
import { enqueue, QuotaExceededError, SuppressedError } from "@/lib/queue";
import { batchSchema, normalizeMail } from "@/lib/schema";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
@@ -17,15 +18,18 @@ export async function POST(request: Request) {
return validationError("Ungültiges JSON");
}
const parsed = batchSchema.safeParse(body);
if (!parsed.success) {
return validationError(parsed.error.issues.map((issue) => issue.message).join("; "));
let items: unknown[];
try {
items = parseBatchInput(body);
} catch (error) {
if (error instanceof MailValidationError) return validationError(error.message);
return serverError();
}
const ids: { id: string }[] = [];
for (const [index, item] of parsed.data.entries()) {
for (const [index, item] of items.entries()) {
try {
const mail = normalizeMail(item, key.fromDomain);
const mail = parseMailInput(item, key.fromDomain);
if (!fromAllowed(key, mail.from.address)) {
return validationError(`Absender ${mail.from.address} ist für diesen Key nicht erlaubt (Index ${index})`);
}
@@ -38,7 +42,7 @@ export async function POST(request: Request) {
if (error instanceof SuppressedError) {
return apiError(422, "recipient_suppressed", `${error.message} (Index ${index})`);
}
if (error instanceof Error && error.name === "MailValidationError") {
if (error instanceof MailValidationError) {
return validationError(`${error.message} (Index ${index})`);
}
console.error("[courier] batch:", error);
+4 -8
View File
@@ -1,5 +1,6 @@
import { authenticate, fromAllowed } from "@/lib/api-key";
import { normalizeMail, sendSchema } from "@/lib/schema";
import { parseMailInput } from "@/lib/mail-input";
import { MailValidationError } from "@/lib/schema";
import { serverError, unauthorized, validationError } from "@/lib/http";
import { enqueue, QuotaExceededError, SuppressedError } from "@/lib/queue";
import { apiError } from "@/lib/http";
@@ -18,13 +19,8 @@ export async function POST(request: Request) {
return validationError("Ungültiges JSON");
}
const parsed = sendSchema.safeParse(body);
if (!parsed.success) {
return validationError(parsed.error.issues.map((issue) => issue.message).join("; "));
}
try {
const mail = normalizeMail(parsed.data, key.fromDomain);
const mail = parseMailInput(body, key.fromDomain);
if (!fromAllowed(key, mail.from.address)) {
return validationError(`Absender ${mail.from.address} ist für diesen Key nicht erlaubt`);
}
@@ -37,7 +33,7 @@ export async function POST(request: Request) {
if (error instanceof SuppressedError) {
return apiError(422, "recipient_suppressed", error.message);
}
if (error instanceof Error && error.name === "MailValidationError") {
if (error instanceof MailValidationError) {
return validationError(error.message);
}
console.error("[courier] send:", error);
+2
View File
@@ -10,6 +10,7 @@ import {
Globe,
KeyRound,
LayoutDashboard,
LayoutTemplate,
Mail,
type LucideIcon,
} from "lucide-react";
@@ -30,6 +31,7 @@ const groups: { title: string; items: Item[] }[] = [
{ href: "/domains", label: "Domains", icon: Globe },
{ href: "/keys", label: "API-Keys", icon: KeyRound },
{ href: "/suppressions", label: "Suppressions", icon: Ban },
{ href: "/templates", label: "Vorlagen", icon: LayoutTemplate },
],
},
{
+30
View File
@@ -40,6 +40,36 @@ export default function Docs() {
</p>
</section>
<section className="karte app-panel app-section">
<h2>Gemeinsame Vorlage (optional)</h2>
<p className="app-muted">
Mit <code>template: &quot;sport-v1&quot;</code> rendert Courier ein gemeinsames,
mailclient-sicheres Layout. Ohne dieses Feld bleiben <code>html</code>/<code>text</code>{" "}
unverändert. Eine Vorschau gibt es unter <a href="/templates">Vorlagen</a>.
</p>
<pre className="app-code">{`POST /api/emails/
{
"from": "ablaeufe <ablaeufe@hubsport.club>",
"to": "trainer@example.com",
"subject": "Freigabe: Fahrtkosten",
"template": "sport-v1",
"brand": { "name": "Eintracht Munster", "accent": "#7c3aed" },
"content": {
"title": "Freigabe: Fahrtkosten",
"paragraphs": ["Hallo Kai,", "…"],
"facts": [{ "label": "Summe", "value": "40,00 €" }],
"button": { "label": "Jetzt freigeben", "url": "https://…" },
"note": "Die Freigabe ist bis Freitag möglich."
}
}`}</pre>
<p className="app-muted">
Logo: <code>brand.logo_cid</code> setzen und einen Anhang mit derselben{" "}
<code>content_id</code> mitsenden. Erlaubte Blöcke: <code>title</code>,{" "}
<code>preheader</code>, <code>paragraphs</code>, <code>facts</code>,{" "}
<code>button</code>, <code>note</code>, <code>footer</code>.
</p>
</section>
<section className="karte app-panel app-section">
<h2>Resend-SDK</h2>
<pre className="app-code">{`import { Resend } from "resend";
+14
View File
@@ -702,6 +702,20 @@ body {
line-height: var(--ds-leading-relaxed);
}
.app-mail-preview {
width: 100%;
height: 46rem;
border: var(--ds-border-thin) solid var(--ds-border);
border-radius: var(--ds-radius-surface);
background: var(--ds-surface-sunken);
}
@media (max-width: 47.99rem) {
.app-mail-preview {
height: 58rem;
}
}
.app-key {
display: block;
padding: var(--ds-space-3);
+116
View File
@@ -0,0 +1,116 @@
import { PageHeader } from "@/app/page-header";
import { renderSportTemplate, type TemplateSendInput } from "@/lib/mail-template";
export const metadata = { title: "Courier – Vorlagen" };
const sample: TemplateSendInput = {
from: "ablaeufe <ablaeufe@hubsport.club>",
to: "trainer@example.com",
subject: "Freigabe: Fahrtkosten",
template: "sport-v1",
brand: {
name: "Eintracht Munster",
accent: "#7c3aed",
},
content: {
title: "Freigabe: Fahrtkosten",
preheader: "Eine neue Fahrtkosten-Abrechnung wartet auf deine Freigabe.",
paragraphs: [
"Hallo Kai,",
"für die Fahrt zum Auswärtsspiel am Sonntag liegt eine neue Abrechnung vor. Bitte prüfe die Angaben und gib sie frei.",
],
facts: [
{ label: "Mannschaft", value: "U15" },
{ label: "Spiel", value: "TSV Nord – Eintracht Munster" },
{ label: "Summe", value: "40,00 €" },
],
button: { label: "Jetzt freigeben", url: "https://ablaeufe.olares.de/freigaben/42" },
note: "Die Freigabe ist bis Freitag, 18:00 Uhr möglich.",
footer: "Abläufe · Eintracht Munster · Diese Mail wurde automatisch versendet.",
},
};
const jsonExample = `{
"from": "ablaeufe <ablaeufe@hubsport.club>",
"to": "trainer@example.com",
"subject": "Freigabe: Fahrtkosten",
"template": "sport-v1",
"brand": {
"name": "Eintracht Munster",
"accent": "#7c3aed"
},
"content": {
"title": "Freigabe: Fahrtkosten",
"paragraphs": ["Hallo Kai,", "…"],
"facts": [{ "label": "Summe", "value": "40,00 €" }],
"button": { "label": "Jetzt freigeben", "url": "https://…" },
"note": "Die Freigabe ist bis Freitag möglich."
}
}`;
export default function Templates() {
const { html } = renderSportTemplate(sample);
return (
<>
<PageHeader
title="Vorlagen"
lead="Gemeinsames Mail-Design für die Sport-Apps. Optional: Roh-HTML und Text funktionieren unverändert weiter."
eyebrow="Courier"
code={false}
/>
<div className="app-grid app-grid--sidebar">
<section className="karte app-panel" aria-labelledby="template-preview">
<div className="app-panel__head">
<h2 id="template-preview">sport-v1</h2>
<span className="ds-badge">optional</span>
</div>
<iframe
className="app-mail-preview"
title="Vorschau der Vorlage sport-v1"
sandbox=""
srcDoc={html}
/>
</section>
<aside className="karte app-panel" aria-labelledby="template-info">
<div className="app-panel__head">
<h2 id="template-info">So funktioniert&apos;s</h2>
</div>
<p className="app-muted">
Apps senden nur noch Inhalt und Branding. Courier rendert daraus ein
mailclient-sicheres HTML und den Text.
</p>
<ul className="app-steps">
<li>
<code>template: &quot;sport-v1&quot;</code> aktiviert die Vorlage.
</li>
<li>
<code>brand</code> liefert Name, Akzentfarbe und optional ein Logo.
</li>
<li>
<code>content</code> enthält Titel, Absätze, Fakten, Button und Hinweis.
</li>
</ul>
<h2 className="app-section">Optional</h2>
<p className="app-muted">
Ohne <code>template</code> bleibt alles wie bisher: Mails mit{" "}
<code>html</code> oder <code>text</code> werden unverändert versendet.
</p>
<h2 className="app-section">Logo einbetten</h2>
<p className="app-muted">
<code>brand.logo_cid</code> setzen und einen Anhang mit derselben{" "}
<code>content_id</code> mitsenden. Courier erzeugt daraus{" "}
<code>cid:</code>-Bilder.
</p>
<h2 className="app-section">Beispiel</h2>
<pre className="app-code">{jsonExample}</pre>
</aside>
</div>
</>
);
}
+30
View File
@@ -0,0 +1,30 @@
import { z } from "zod";
import { templateSendSchema, templateToMail } from "./mail-template";
import { MailValidationError, normalizeMail, sendSchema, type NormalizedMail } from "./schema";
export const batchInputSchema = z.array(z.unknown()).min(1).max(100);
export function parseMailInput(body: unknown, fromDomain: string): NormalizedMail {
if (body && typeof body === "object" && "template" in body) {
const parsed = templateSendSchema.safeParse(body);
if (!parsed.success) {
throw new MailValidationError(parsed.error.issues.map((issue) => issue.message).join("; "));
}
return templateToMail(parsed.data, fromDomain);
}
const parsed = sendSchema.safeParse(body);
if (!parsed.success) {
throw new MailValidationError(parsed.error.issues.map((issue) => issue.message).join("; "));
}
return normalizeMail(parsed.data, fromDomain);
}
export function parseBatchInput(body: unknown): unknown[] {
const parsed = batchInputSchema.safeParse(body);
if (!parsed.success) {
throw new MailValidationError(parsed.error.issues.map((issue) => issue.message).join("; "));
}
return parsed.data;
}
+185
View File
@@ -0,0 +1,185 @@
import { z } from "zod";
import { MailValidationError, normalizeMail, type NormalizedMail } from "./schema";
const httpUrl = z
.string()
.url()
.max(2000)
.refine((value) => /^https?:\/\//i.test(value), "Nur http(s)-Links sind erlaubt");
const mailbox = z.union([z.string().min(3), z.array(z.string().min(3)).min(1).max(50)]);
const attachment = z.object({
filename: z.string().min(1).max(255),
content: z.string().min(1),
content_type: z.string().min(3).max(200).optional(),
content_id: z.string().min(1).max(200).optional(),
});
export const sportTemplateSchema = z.object({
template: z.literal("sport-v1"),
brand: z.object({
name: z.string().min(1).max(80),
accent: z.string().regex(/^#[0-9a-fA-F]{6}$/).optional(),
logo_cid: z.string().regex(/^[A-Za-z0-9._-]{1,100}$/).optional(),
}),
content: z.object({
title: z.string().min(1).max(200).optional(),
preheader: z.string().max(200).optional(),
paragraphs: z.array(z.string().max(4000)).max(20).optional(),
facts: z
.array(z.object({ label: z.string().min(1).max(40), value: z.string().min(1).max(300) }))
.max(20)
.optional(),
button: z.object({ label: z.string().min(1).max(80), url: httpUrl }).optional(),
note: z.string().max(1200).optional(),
footer: z.string().max(300).optional(),
}),
});
export const templateSendSchema = z.object({
from: z.string().min(3),
to: mailbox,
cc: mailbox.optional(),
bcc: mailbox.optional(),
reply_to: mailbox.optional(),
subject: z.string().min(1).max(998),
template: z.literal("sport-v1"),
brand: sportTemplateSchema.shape.brand,
content: sportTemplateSchema.shape.content,
attachments: z.array(attachment).max(20).optional(),
tags: z
.array(z.object({ name: z.string().min(1).max(256), value: z.string().min(1).max(256) }))
.max(50)
.optional(),
});
export type TemplateSendInput = z.infer<typeof templateSendSchema>;
const INK = "#18181b";
const MUTED = "#52525b";
const SUBTLE = "#71717a";
const BORDER = "#e4e4e7";
const SURFACE = "#fafafa";
const ACTION = "#09090b";
const LINK = "#6d28d9";
const FONT = "-apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif";
function e(value: string): string {
return value
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#39;");
}
function linkify(value: string): string {
return e(value).replace(
/https?:\/\/[^\s<]+/g,
(url) =>
`<a href="${url}" style="color:${LINK};text-decoration:underline;word-break:break-all">${url}</a>`,
);
}
function button(url: string, label: string): string {
const u = e(url);
const t = e(label);
return `<table role="presentation" cellpadding="0" cellspacing="0" border="0" style="margin:8px 0 4px">
<tr><td style="border-radius:8px;background:${ACTION}">
<!--[if mso]><v:roundrect xmlns:v="urn:schemas-microsoft-com:vml" href="${u}" style="height:44px;v-text-anchor:middle;width:280px" arcsize="18%" stroke="f" fillcolor="${ACTION}"><center style="color:#ffffff;font-family:Arial,sans-serif;font-size:15px;font-weight:bold">${t}</center></v:roundrect><![endif]-->
<!--[if !mso]><!--><a href="${u}" style="display:inline-block;padding:12px 24px;font-family:${FONT};font-size:15px;font-weight:600;line-height:20px;color:#ffffff;text-decoration:none;border-radius:8px">${t}</a><!--<![endif]-->
</td></tr></table>
<p style="margin:0 0 16px;font-size:12px;line-height:16px;color:${SUBTLE};word-break:break-all">${u}</p>`;
}
function factsTable(facts: { label: string; value: string }[]): string {
return `<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" style="margin:0 0 16px;border-collapse:collapse;border-bottom:1px solid ${BORDER}">
${facts
.map(
(fact) =>
`<tr><td style="padding:8px 16px 8px 0;border-top:1px solid ${BORDER};color:${MUTED};font-size:14px;line-height:20px;vertical-align:top;white-space:nowrap">${e(fact.label)}</td><td style="padding:8px 0;border-top:1px solid ${BORDER};color:${INK};font-size:14px;line-height:20px;vertical-align:top">${linkify(fact.value)}</td></tr>`,
)
.join("")}
</table>`;
}
function paragraphs(items: string[]): string {
return items
.map(
(item) =>
`<p style="margin:0 0 16px;font-size:15px;line-height:24px;color:${INK}">${linkify(item).replace(/\n/g, "<br>")}</p>`,
)
.join("");
}
export function renderSportTemplate(input: TemplateSendInput): { html: string; text: string } {
const brand = input.brand;
const content = input.content;
const accent = brand.accent ?? "#7c3aed";
const title = content.title ?? input.subject;
const preheader = content.preheader ?? content.paragraphs?.[0]?.slice(0, 140) ?? title;
const logo = brand.logo_cid
? `<img src="cid:${brand.logo_cid}" width="40" height="40" alt="" style="display:block;border:0;width:40px;height:40px;object-fit:contain">`
: "";
const brandBlock = `<table role="presentation" cellpadding="0" cellspacing="0" border="0"><tr>${logo ? `<td style="padding-right:12px;vertical-align:middle">${logo}</td>` : ""}<td style="vertical-align:middle;font-size:15px;line-height:20px;font-weight:600;color:${INK}">${e(brand.name)}</td></tr></table>`;
const footer = content.footer ?? `${brand.name} · Diese Mail wurde automatisch versendet.`;
const html = `<!doctype html>
<html lang="de" xmlns:v="urn:schemas-microsoft-com:vml">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="light"><meta name="supported-color-schemes" content="light"><title>${e(title)}</title></head>
<body style="margin:0;padding:0;background:${SURFACE};font-family:${FONT};color:${INK}">
<div style="display:none;max-height:0;overflow:hidden;opacity:0">${e(preheader)}</div>
<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" style="background:${SURFACE}"><tr><td align="center" style="padding:24px 12px">
<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="600" style="width:100%;max-width:600px;background:#ffffff;border:1px solid ${BORDER};border-radius:16px;border-collapse:separate;overflow:hidden">
<tr><td style="padding:24px 32px 16px;border-bottom:2px solid ${accent}">${brandBlock}</td></tr>
<tr><td style="padding:32px 32px 8px"><h1 style="margin:0 0 24px;font-size:22px;line-height:28px;font-weight:700;color:${INK}">${e(title)}</h1>
${content.paragraphs?.length ? paragraphs(content.paragraphs) : ""}
${content.facts?.length ? factsTable(content.facts) : ""}
${content.button ? button(content.button.url, content.button.label) : ""}
${content.note ? `<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" style="margin:8px 0 8px;background:#f5f3ff;border-left:3px solid ${accent};border-radius:8px"><tr><td style="padding:12px 16px;font-size:14px;line-height:22px;color:${INK}"><strong>Hinweis:</strong> ${linkify(content.note)}</td></tr></table>` : ""}
</td></tr>
<tr><td style="padding:16px 32px 24px;background:${SURFACE};border-top:1px solid ${BORDER};font-size:12px;line-height:16px;color:${SUBTLE}">${e(footer)}</td></tr>
</table></td></tr></table></body></html>`;
const textParts = [
title,
...(content.paragraphs ?? []),
...(content.facts ?? []).map((fact) => `${fact.label}: ${fact.value}`),
...(content.button ? [`${content.button.label}: ${content.button.url}`] : []),
...(content.note ? [`Hinweis: ${content.note}`] : []),
footer,
];
return { html, text: textParts.filter(Boolean).join("\n\n") };
}
export function templateToMail(
input: TemplateSendInput,
fromDomain: string,
): NormalizedMail {
if (input.brand.logo_cid) {
const hasLogo = input.attachments?.some((item) => item.content_id === input.brand.logo_cid);
if (!hasLogo) {
throw new MailValidationError(
`Logo-Anhang mit content_id "${input.brand.logo_cid}" fehlt`,
);
}
}
const rendered = renderSportTemplate(input);
return normalizeMail(
{
from: input.from,
to: input.to,
cc: input.cc,
bcc: input.bcc,
reply_to: input.reply_to,
subject: input.subject,
html: rendered.html,
text: rendered.text,
attachments: input.attachments,
tags: input.tags,
},
fromDomain,
);
}
+2 -1
View File
@@ -34,7 +34,7 @@ export type StoredPayload = {
html?: string;
text?: string;
headers: Record<string, string>;
attachments: { filename: string; content: string; content_type?: string }[];
attachments: { filename: string; content: string; content_type?: string; content_id?: string }[];
tags: { name: string; value: string }[];
};
@@ -57,6 +57,7 @@ export function storedPayload(mail: NormalizedMail): StoredPayload {
filename: item.filename,
content: item.content.toString("base64"),
content_type: item.contentType,
content_id: item.contentId,
})),
tags: mail.tags,
};
+8 -2
View File
@@ -13,6 +13,7 @@ const attachmentInput = z.object({
filename: z.string().min(1).max(255),
content: z.string().min(1),
content_type: z.string().min(3).max(200).optional(),
content_id: z.string().min(1).max(200).optional(),
});
export const sendSchema = z
@@ -51,7 +52,7 @@ export type NormalizedMail = {
html?: string;
text?: string;
headers: Record<string, string>;
attachments: { filename: string; content: Buffer; contentType?: string }[];
attachments: { filename: string; content: Buffer; contentType?: string; contentId?: string }[];
tags: { name: string; value: string }[];
};
@@ -105,7 +106,12 @@ export function normalizeMail(input: SendInput, fromDomain: string): NormalizedM
const attachments = (input.attachments ?? []).map((item) => {
const content = Buffer.from(item.content, "base64");
if (content.length === 0) throw new MailValidationError("Leerer Anhang");
return { filename: item.filename, content, contentType: item.content_type };
return {
filename: item.filename,
content,
contentType: item.content_type,
contentId: item.content_id,
};
});
const total = attachments.reduce((sum, item) => sum + item.content.length, 0);
if (total > 10 * 1024 * 1024) {
+1
View File
@@ -27,6 +27,7 @@ function mimeOptions(payload: StoredPayload) {
filename: item.filename,
content: Buffer.from(item.content, "base64"),
contentType: item.content_type,
cid: item.content_id,
})),
};
}
+2 -2
View File
@@ -2,7 +2,7 @@ apiVersion: v2
name: courier
description: Transaktionsmail-Gateway für hubsport.club über Amazon SES.
type: application
version: 26.11.22
appVersion: "26.11.22"
version: 26.11.24
appVersion: "26.11.24"
icon: https://git.aimighty.olares.de/aimighty/courier/raw/branch/main/icon.png
home: https://git.aimighty.olares.de/aimighty/courier
+2 -2
View File
@@ -12,7 +12,7 @@ metadata:
title: Courier
description: Transaktionsmail für deine Apps über Amazon SES.
icon: https://git.aimighty.olares.de/aimighty/courier/raw/branch/main/icon.png
version: 26.11.22
version: 26.11.24
categories:
- Applications
@@ -106,7 +106,7 @@ envs:
default: "1000"
spec:
versionName: '26.11.22'
versionName: '26.11.24'
fullDescription: |
**Courier** ist ein kleiner Versanddienst für transaktionale E-Mails:
eine Resend-kompatible HTTP-API, Warteschlange, Retry, Logs und
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "courier",
"version": "26.11.22",
"version": "26.11.24",
"private": true,
"scripts": {
"dev": "next dev -H 0.0.0.0 -p 3400",