4 Commits
Author SHA1 Message Date
AImighty Bot 5fe8562774 Courier 26.11.26: Scaleway als optionaler Versanddienst
ci / build (push) Successful in 36s
2026-11-27 10:08:51 +00:00
AImighty Bot 8d735a7e80 Courier 26.11.25: Abstand zwischen Hinweis und Karte
ci / build (push) Successful in 40s
2026-11-25 10:31:28 +00:00
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
29 changed files with 660 additions and 80 deletions

No files matched your search

+6 -1
View File
@@ -1,7 +1,7 @@
# Datenbank (lokal oder Olares-Middleware)
DATABASE_URL=postgresql://courier@127.0.0.1:55432/courier
# dry-run | resend | ses
# dry-run | resend | ses | scaleway
MAIL_TRANSPORT=dry-run
MAIL_FROM_DOMAIN=hubsport.club
@@ -23,3 +23,8 @@ RESEND_API_KEY=
# Öffentliche Adresse (für SNS-Webhook/Anzeige)
PUBLIC_BASE_URL=http://127.0.0.1:3400
# Scaleway Transactional Email (optional)
SCW_SECRET_KEY=
SCW_PROJECT_ID=
SCW_REGION=fr-par
+27 -6
View File
@@ -10,9 +10,9 @@ metadata:
name: courier
appid: courier
title: Courier
description: Transaktionsmail für deine Apps über Amazon SES.
description: Transaktionsmail für deine Apps über Amazon SES oder Scaleway.
icon: https://git.aimighty.olares.de/aimighty/courier/raw/branch/main/icon.png
version: 26.11.22
version: 26.11.26
categories:
- Applications
@@ -79,6 +79,27 @@ envs:
editable: false
applyOnChange: false
default: "arn:aws:sns:eu-west-1:945831802901:courier-ses-events"
- envName: SCW_SECRET_KEY
required: false
type: password
editable: true
applyOnChange: true
default: ""
description: "Scaleway API Secret Key (Transactional Email)."
- envName: SCW_PROJECT_ID
required: false
type: string
editable: true
applyOnChange: true
default: ""
description: "Scaleway Project ID für Transactional Email."
- envName: SCW_REGION
required: false
type: string
editable: true
applyOnChange: true
default: "fr-par"
description: "Scaleway-Region für Transactional Email."
- envName: MAIL_FROM_DOMAIN
required: true
type: string
@@ -94,8 +115,8 @@ envs:
options:
- title: Amazon SES
value: ses
- title: Resend (Übergang)
value: resend
- title: Scaleway Transactional Email
value: scaleway
- title: Dry-Run
value: dry-run
- envName: GLOBAL_DAILY_LIMIT
@@ -106,11 +127,11 @@ envs:
default: "1000"
spec:
versionName: '26.11.22'
versionName: '26.11.26'
fullDescription: |
**Courier** ist ein kleiner Versanddienst für transaktionale E-Mails:
eine Resend-kompatible HTTP-API, Warteschlange, Retry, Logs und
Zustellereignisse. Der Versand läuft über Amazon SES.
Zustellereignisse. Der Versand läuft über Amazon SES; optional über Scaleway Transactional Email.
**Funktionen**
- `POST /api/emails` und `/api/emails/batch` (Resend-kompatibel)
+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);
+1
View File
@@ -12,6 +12,7 @@ export async function GET() {
transport: config.transport,
fromDomain: config.fromDomain,
sesConfigured: Boolean(process.env.AWS_ACCESS_KEY_ID || process.env.AWS_PROFILE),
scalewayConfigured: Boolean(process.env.SCW_SECRET_KEY && process.env.SCW_PROJECT_ID),
});
} catch (error) {
return Response.json(
+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 },
],
},
{
+48
View File
@@ -40,6 +40,54 @@ export default function Docs() {
</p>
</section>
<section className="karte app-panel app-section">
<h2>Versanddienst wählen</h2>
<p className="app-muted">
Amazon SES bleibt der Standard. Ein API-Key kann optional über Scaleway
Transactional Email senden; die Auswahl steht beim Erzeugen des Keys unter{" "}
<a href="/keys">API-Keys</a>.
</p>
<pre className="app-code">{`# Scaleway (EU)
SCW_SECRET_KEY=SCW...
SCW_PROJECT_ID=<project-id>
SCW_REGION=fr-par`}</pre>
<p className="app-muted">
Die Absenderdomain muss im Scaleway-Konto verifiziert sein. Scaleway
unterstützt keine SES-SNS-Ereignisse; der Status bleibt dort zunächst
<code>sent</code>, bis ein eigener Webhook angebunden ist.
</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";
+18
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);
@@ -721,6 +735,10 @@ body {
flex-wrap: wrap;
}
.app-main > .ds-alert {
margin-bottom: var(--ds-space-6);
}
.app-section {
margin-top: var(--ds-space-6);
}
+5 -3
View File
@@ -11,12 +11,14 @@ export async function createKey(_previous: KeyState, formData: FormData): Promis
const app = String(formData.get("app") ?? "").trim().toLowerCase();
const name = String(formData.get("name") ?? "").trim();
const domain = String(formData.get("domain") ?? "hubsport.club").trim().toLowerCase();
const provider = String(formData.get("provider") ?? "").trim() || null;
const from = String(formData.get("from") ?? "").trim().toLowerCase();
const daily = Number(formData.get("daily") ?? 500);
const monthly = Number(formData.get("monthly") ?? 15000);
if (!/^[a-z0-9][a-z0-9_-]{1,30}$/.test(app)) return { error: "App-Name: 2–31 Zeichen, a–z, 0–9, _ oder -" };
if (!name) return { error: "Bezeichnung fehlt" };
if (provider && provider !== "ses" && provider !== "scaleway") return { error: "Unbekannter Versanddienst" };
if (!/^[a-z0-9.-]+\.[a-z]{2,}$/.test(domain)) return { error: "Ungültige Domain" };
if (!Number.isInteger(daily) || daily < 1 || daily > 100000) return { error: "Tageslimit ungültig" };
if (!Number.isInteger(monthly) || monthly < 1 || monthly > 1000000) return { error: "Monatslimit ungültig" };
@@ -25,9 +27,9 @@ export async function createKey(_previous: KeyState, formData: FormData): Promis
const key = generateKey();
try {
await query(
`insert into api_keys (app, name, prefix, key_hash, from_domain, allowed_from, daily_limit, monthly_limit)
values ($1,$2,$3,$4,$5,$6,$7,$8)`,
[app, name, keyPrefix(key), hashKey(key), domain, from ? [from] : null, daily, monthly],
`insert into api_keys (app, name, prefix, key_hash, from_domain, provider, allowed_from, daily_limit, monthly_limit)
values ($1,$2,$3,$4,$5,$6,$7,$8,$9)`,
[app, name, keyPrefix(key), hashKey(key), domain, provider, from ? [from] : null, daily, monthly],
);
} catch (error) {
return { error: error instanceof Error ? error.message : "Key konnte nicht gespeichert werden" };
+5
View File
@@ -74,6 +74,7 @@ export default async function Keys() {
<th>Bezeichnung</th>
<th>Prefix</th>
<th className="app-hide-sm">Domain</th>
<th>Versand</th>
<th>Limit</th>
<th className="app-hide-sm">Zuletzt</th>
<th>Status</th>
@@ -87,6 +88,7 @@ export default async function Keys() {
<td>{key.name}</td>
<td className="app-mono">{key.prefix}…</td>
<td className="app-hide-sm">{key.from_domain}</td>
<td>{key.provider === "scaleway" ? "Scaleway" : key.provider === "resend" ? "Resend" : "Amazon SES"}</td>
<td className="app-mono app-nowrap">
{key.daily_limit}/Tag · {key.monthly_limit}/Monat
</td>
@@ -132,6 +134,9 @@ export default async function Keys() {
</div>
<div className="app-mobile-item__meta">
<span className="app-mono">{key.prefix}…</span>
<span>
{key.provider === "scaleway" ? "Scaleway" : key.provider === "resend" ? "Resend" : "Amazon SES"}
</span>
<span className="app-mono">
{key.daily_limit}/Tag · {key.monthly_limit}/Monat
</span>
+4 -2
View File
@@ -67,7 +67,9 @@ export default async function Nachricht({ params }: { params: Promise<{ id: stri
<dd>
{message.cc_emails.join(", ") || "–"} / {message.bcc_emails.join(", ") || "–"}
</dd>
<dt>SES-ID</dt>
<dt>Versand</dt>
<dd>{message.provider === "scaleway" ? "Scaleway" : message.provider === "resend" ? "Resend" : "Amazon SES"}</dd>
<dt>Provider-ID</dt>
<dd className="app-mono">{message.provider_message_id || "–"}</dd>
<dt>Erstellt</dt>
<dd className="app-mono">{datum(message.created_at)}</dd>
@@ -110,7 +112,7 @@ export default async function Nachricht({ params }: { params: Promise<{ id: stri
<div className="ds-empty">
<p className="ds-empty__title">Noch keine Zustellereignisse</p>
<p className="ds-empty__text">
SES meldet Zustellung, Bounce und Beschwerde über SNS zurück.
SES meldet Zustellung, Bounce und Beschwerde über SNS zurück. Für Scaleway sind noch keine Ereignisse angebunden.
</p>
</div>
)}
+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>
</>
);
}
+11
View File
@@ -0,0 +1,11 @@
-- Optionaler Versandweg pro API-Key. NULL bedeutet: MAIL_TRANSPORT verwenden.
alter table api_keys
add column if not exists provider text;
alter table messages
add column if not exists provider text;
create index if not exists messages_provider_idx on messages (provider);
comment on column api_keys.provider is 'Optional provider override: ses, scaleway or resend; null uses MAIL_TRANSPORT';
comment on column messages.provider is 'Provider chosen at enqueue time; null uses MAIL_TRANSPORT at send time';
+5 -2
View File
@@ -1,13 +1,14 @@
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
import { config } from "./config";
import { config, type TransportName } from "./config";
import { query } from "./db";
export type ApiKey = {
id: string;
app: string;
fromDomain: string;
provider: TransportName | null;
allowedFrom: string[] | null;
dailyLimit: number;
monthlyLimit: number;
@@ -17,6 +18,7 @@ type KeyRow = {
id: string;
app: string;
from_domain: string;
provider: TransportName | null;
allowed_from: string[] | null;
daily_limit: number;
monthly_limit: number;
@@ -47,7 +49,7 @@ export async function authenticate(request: Request): Promise<ApiKey | null> {
if (!token.startsWith("ck_live_")) return null;
const { rows } = await query<KeyRow>(
`select id, app, from_domain, allowed_from, daily_limit, monthly_limit
`select id, app, from_domain, provider, allowed_from, daily_limit, monthly_limit
from api_keys
where key_hash = $1 and revoked_at is null`,
[hashKey(token)],
@@ -60,6 +62,7 @@ export async function authenticate(request: Request): Promise<ApiKey | null> {
id: row.id,
app: row.app,
fromDomain: row.from_domain,
provider: row.provider,
allowedFrom: row.allowed_from,
dailyLimit: row.daily_limit,
monthlyLimit: row.monthly_limit,
+5 -2
View File
@@ -1,7 +1,7 @@
export const config = {
fromDomain: process.env.MAIL_FROM_DOMAIN || "hubsport.club",
transport: (process.env.MAIL_TRANSPORT || "dry-run") as "dry-run" | "ses" | "resend",
transport: (process.env.MAIL_TRANSPORT || "dry-run") as TransportName,
databaseUrl:
process.env.DATABASE_URL ||
`postgresql://courier@127.0.0.1:${process.env.DB_PORT || "55432"}/courier`,
@@ -12,7 +12,10 @@ export const config = {
awsRegion: process.env.AWS_REGION || "eu-west-1",
sesConfigurationSet: process.env.SES_CONFIGURATION_SET || "courier-transactional",
resendApiKey: process.env.RESEND_API_KEY || "",
scalewaySecretKey: process.env.SCW_SECRET_KEY || "",
scalewayProjectId: process.env.SCW_PROJECT_ID || "",
scalewayRegion: process.env.SCW_REGION || "fr-par",
publicBaseUrl: process.env.PUBLIC_BASE_URL || "",
};
export type TransportName = typeof config.transport;
export type TransportName = "dry-run" | "ses" | "resend" | "scaleway";
+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
View File
@@ -88,6 +88,7 @@ export async function messageDetail(id: string) {
const { rows } = await query<{
id: string;
app: string;
provider: string | null;
provider_message_id: string | null;
from_email: string;
from_name: string | null;
@@ -120,6 +121,7 @@ export async function listApiKeys() {
name: string;
prefix: string;
from_domain: string;
provider: string | null;
allowed_from: string[] | null;
daily_limit: number;
monthly_limit: number;
+5 -3
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,
};
@@ -109,15 +110,16 @@ export async function enqueue(
const id = randomUUID();
const inserted = await client.query<{ id: string }>(
`insert into messages (
id, api_key_id, app, from_email, from_name, to_emails, cc_emails, bcc_emails,
id, api_key_id, app, provider, from_email, from_name, to_emails, cc_emails, bcc_emails,
reply_to, subject, status, payload, idempotency_key
) values ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,'queued',$11,$12)
) values ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,'queued',$12,$13)
on conflict (api_key_id, idempotency_key) do nothing
returning id`,
[
id,
apiKey.id,
apiKey.app,
apiKey.provider,
mail.from.address,
mail.from.name ?? null,
addressesOf(mail.to),
+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) {
+104 -32
View File
@@ -1,11 +1,10 @@
import { randomUUID } from "node:crypto";
import { SESv2Client, SendEmailCommand } from "@aws-sdk/client-sesv2";
import MailComposer from "nodemailer/lib/mail-composer";
import { addressesOf, formatMailbox } from "./address";
import { config } from "./config";
import { config, type TransportName } from "./config";
import type { StoredPayload } from "./queue";
export type SendResult = { providerMessageId: string };
@@ -27,6 +26,7 @@ function mimeOptions(payload: StoredPayload) {
filename: item.filename,
content: Buffer.from(item.content, "base64"),
contentType: item.content_type,
cid: item.content_id,
})),
};
}
@@ -42,51 +42,110 @@ function buildRaw(payload: StoredPayload): Promise<Buffer> {
});
}
export async function sendStored(payload: StoredPayload): Promise<SendResult> {
if (config.transport === "dry-run") {
console.log("[courier] dry-run", JSON.stringify({ from: payload.from, to: payload.to, subject: payload.subject }));
return { providerMessageId: `dry-${randomUUID()}` };
function failure(message: string, statusCode?: number, retryable = false): SendFailure {
return Object.assign(new Error(message), { statusCode, retryable });
}
async function sendResend(payload: StoredPayload): Promise<SendResult> {
if (!config.resendApiKey) throw failure("RESEND_API_KEY fehlt");
const response = await fetch("https://api.resend.com/emails", {
method: "POST",
headers: {
authorization: `Bearer ${config.resendApiKey}`,
"content-type": "application/json",
},
body: JSON.stringify({
from: formatMailbox(payload.from),
to: payload.to.map(formatMailbox),
cc: payload.cc.map(formatMailbox),
bcc: payload.bcc.map(formatMailbox),
reply_to: payload.reply_to.map(formatMailbox),
subject: payload.subject,
html: payload.html,
text: payload.text,
headers: payload.headers,
attachments: payload.attachments.map((item) => ({
filename: item.filename,
content: item.content,
content_type: item.content_type,
content_id: item.content_id,
})),
tags: payload.tags,
}),
});
if (!response.ok) {
const detail = await response.text();
throw failure(`Resend ${response.status}: ${detail}`, response.status, response.status === 429 || response.status >= 500);
}
const data = (await response.json()) as { id?: string };
if (!data.id) throw failure("Resend lieferte keine Message-ID");
return { providerMessageId: data.id };
}
function scalewayMailbox(mailbox: { address: string; name?: string }) {
return mailbox.name ? { email: mailbox.address, name: mailbox.name } : { email: mailbox.address };
}
async function sendScaleway(payload: StoredPayload): Promise<SendResult> {
if (!config.scalewaySecretKey) throw failure("SCW_SECRET_KEY fehlt");
if (!config.scalewayProjectId) throw failure("SCW_PROJECT_ID fehlt");
const additionalHeaders = Object.entries(payload.headers).map(([key, value]) => ({ key, value }));
if (payload.reply_to.length) {
additionalHeaders.push({ key: "Reply-To", value: payload.reply_to.map(formatMailbox).join(", ") });
}
if (config.transport === "resend") {
if (!config.resendApiKey) throw Object.assign(new Error("RESEND_API_KEY fehlt"), { retryable: false });
const response = await fetch("https://api.resend.com/emails", {
const endpoint = `https://api.scaleway.com/transactional-email/v1alpha1/regions/${encodeURIComponent(config.scalewayRegion)}/emails`;
let response: Response;
try {
response = await fetch(endpoint, {
method: "POST",
headers: {
authorization: `Bearer ${config.resendApiKey}`,
"X-Auth-Token": config.scalewaySecretKey,
"content-type": "application/json",
},
body: JSON.stringify({
from: formatMailbox(payload.from),
to: payload.to.map(formatMailbox),
cc: payload.cc.map(formatMailbox),
bcc: payload.bcc.map(formatMailbox),
reply_to: payload.reply_to.map(formatMailbox),
project_id: config.scalewayProjectId,
from: scalewayMailbox(payload.from),
to: payload.to.map(scalewayMailbox),
cc: payload.cc.map(scalewayMailbox),
bcc: payload.bcc.map(scalewayMailbox),
subject: payload.subject,
html: payload.html,
text: payload.text,
headers: payload.headers,
html: payload.html,
attachments: payload.attachments.map((item) => ({
filename: item.filename,
name: item.filename,
type: item.content_type || "application/octet-stream",
content: item.content,
content_type: item.content_type,
})),
tags: payload.tags,
additional_headers: additionalHeaders,
}),
});
if (!response.ok) {
const detail = await response.text();
const error = Object.assign(new Error(`Resend ${response.status}: ${detail}`), {
retryable: response.status === 429 || response.status >= 500,
statusCode: response.status,
});
throw error;
}
const data = (await response.json()) as { id?: string };
if (!data.id) throw Object.assign(new Error("Resend lieferte keine Message-ID"), { retryable: false });
return { providerMessageId: data.id };
} catch (error) {
throw Object.assign(error as Error, { retryable: true });
}
if (!response.ok) {
const detail = await response.text();
throw failure(
`Scaleway ${response.status}: ${detail}`,
response.status,
response.status === 429 || response.status >= 500,
);
}
const data = (await response.json()) as {
emails?: { id?: string; message_id?: string }[];
};
const first = data.emails?.[0];
const id = first?.message_id || first?.id;
if (!id) throw failure("Scaleway lieferte keine Message-ID");
return { providerMessageId: id };
}
async function sendSes(payload: StoredPayload): Promise<SendResult> {
const raw = await buildRaw(payload);
const client = new SESv2Client({ region: config.awsRegion });
try {
@@ -104,7 +163,7 @@ export async function sendStored(payload: StoredPayload): Promise<SendResult> {
EmailTags: payload.tags.map((tag) => ({ Name: tag.name, Value: tag.value })),
}),
);
if (!result.MessageId) throw Object.assign(new Error("SES lieferte keine Message-ID"), { retryable: false });
if (!result.MessageId) throw failure("SES lieferte keine Message-ID");
return { providerMessageId: result.MessageId };
} catch (error) {
const status = (error as { $metadata?: { httpStatusCode?: number } }).$metadata?.httpStatusCode;
@@ -117,3 +176,16 @@ export async function sendStored(payload: StoredPayload): Promise<SendResult> {
throw Object.assign(error as Error, { retryable, statusCode: status });
}
}
export async function sendStored(
payload: StoredPayload,
provider: TransportName = config.transport,
): Promise<SendResult> {
if (provider === "dry-run") {
console.log("[courier] dry-run", JSON.stringify({ from: payload.from, to: payload.to, subject: payload.subject }));
return { providerMessageId: `dry-${randomUUID()}` };
}
if (provider === "resend") return sendResend(payload);
if (provider === "scaleway") return sendScaleway(payload);
return sendSes(payload);
}
+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.26
appVersion: "26.11.26"
icon: https://git.aimighty.olares.de/aimighty/courier/raw/branch/main/icon.png
home: https://git.aimighty.olares.de/aimighty/courier
+27 -6
View File
@@ -10,9 +10,9 @@ metadata:
name: courier
appid: courier
title: Courier
description: Transaktionsmail für deine Apps über Amazon SES.
description: Transaktionsmail für deine Apps über Amazon SES oder Scaleway.
icon: https://git.aimighty.olares.de/aimighty/courier/raw/branch/main/icon.png
version: 26.11.22
version: 26.11.26
categories:
- Applications
@@ -79,6 +79,27 @@ envs:
editable: false
applyOnChange: false
default: "arn:aws:sns:eu-west-1:945831802901:courier-ses-events"
- envName: SCW_SECRET_KEY
required: false
type: password
editable: true
applyOnChange: true
default: ""
description: "Scaleway API Secret Key (Transactional Email)."
- envName: SCW_PROJECT_ID
required: false
type: string
editable: true
applyOnChange: true
default: ""
description: "Scaleway Project ID für Transactional Email."
- envName: SCW_REGION
required: false
type: string
editable: true
applyOnChange: true
default: "fr-par"
description: "Scaleway-Region für Transactional Email."
- envName: MAIL_FROM_DOMAIN
required: true
type: string
@@ -94,8 +115,8 @@ envs:
options:
- title: Amazon SES
value: ses
- title: Resend (Übergang)
value: resend
- title: Scaleway Transactional Email
value: scaleway
- title: Dry-Run
value: dry-run
- envName: GLOBAL_DAILY_LIMIT
@@ -106,11 +127,11 @@ envs:
default: "1000"
spec:
versionName: '26.11.22'
versionName: '26.11.26'
fullDescription: |
**Courier** ist ein kleiner Versanddienst für transaktionale E-Mails:
eine Resend-kompatible HTTP-API, Warteschlange, Retry, Logs und
Zustellereignisse. Der Versand läuft über Amazon SES.
Zustellereignisse. Der Versand läuft über Amazon SES; optional über Scaleway Transactional Email.
**Funktionen**
- `POST /api/emails` und `/api/emails/batch` (Resend-kompatibel)
+9
View File
@@ -46,6 +46,10 @@ spec:
value: {{ .Values.olaresEnv.SES_CONFIGURATION_SET | quote }}
- name: SNS_TOPIC_ARN
value: {{ .Values.olaresEnv.SNS_TOPIC_ARN | quote }}
- name: SCW_PROJECT_ID
value: {{ .Values.olaresEnv.SCW_PROJECT_ID | quote }}
- name: SCW_REGION
value: {{ .Values.olaresEnv.SCW_REGION | quote }}
- name: TZ
value: {{ .Values.app.timezone | quote }}
- name: PORT
@@ -72,6 +76,11 @@ spec:
secretKeyRef:
name: courier-secrets
key: SNS_WEBHOOK_TOKEN
- name: SCW_SECRET_KEY
valueFrom:
secretKeyRef:
name: courier-secrets
key: SCW_SECRET_KEY
readinessProbe:
httpGet:
path: /api/health/
+9
View File
@@ -42,6 +42,10 @@ spec:
value: {{ .Values.olaresEnv.SES_CONFIGURATION_SET | quote }}
- name: SNS_TOPIC_ARN
value: {{ .Values.olaresEnv.SNS_TOPIC_ARN | quote }}
- name: SCW_PROJECT_ID
value: {{ .Values.olaresEnv.SCW_PROJECT_ID | quote }}
- name: SCW_REGION
value: {{ .Values.olaresEnv.SCW_REGION | quote }}
- name: TZ
value: {{ .Values.app.timezone | quote }}
- name: AWS_ACCESS_KEY_ID
@@ -64,6 +68,11 @@ spec:
secretKeyRef:
name: courier-secrets
key: SNS_WEBHOOK_TOKEN
- name: SCW_SECRET_KEY
valueFrom:
secretKeyRef:
name: courier-secrets
key: SCW_SECRET_KEY
resources:
requests:
cpu: 50m
+1
View File
@@ -10,3 +10,4 @@ stringData:
AWS_SECRET_ACCESS_KEY: {{ .Values.olaresEnv.AWS_SECRET_ACCESS_KEY | quote }}
API_KEY_PEPPER: {{ .Values.olaresEnv.API_KEY_PEPPER | quote }}
SNS_WEBHOOK_TOKEN: {{ .Values.olaresEnv.SNS_WEBHOOK_TOKEN | quote }}
SCW_SECRET_KEY: {{ .Values.olaresEnv.SCW_SECRET_KEY | quote }}
+3
View File
@@ -24,6 +24,9 @@ olaresEnv:
SNS_WEBHOOK_TOKEN: ""
SES_CONFIGURATION_SET: "courier-transactional"
SNS_TOPIC_ARN: "arn:aws:sns:eu-west-1:945831802901:courier-ses-events"
SCW_SECRET_KEY: ""
SCW_PROJECT_ID: ""
SCW_REGION: "fr-par"
MAIL_FROM_DOMAIN: "hubsport.club"
MAIL_TRANSPORT: "ses"
GLOBAL_DAILY_LIMIT: "1000"
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "courier",
"version": "26.11.22",
"version": "26.11.26",
"private": true,
"scripts": {
"dev": "next dev -H 0.0.0.0 -p 3400",
+6 -3
View File
@@ -1,3 +1,4 @@
import { config } from "../lib/config";
import { query } from "../lib/db";
import { sendStored, type SendFailure } from "../lib/transport";
import type { StoredPayload } from "../lib/queue";
@@ -8,6 +9,7 @@ const POLL_MS = 1000;
type Claimed = {
id: string;
attempts: number;
provider: string | null;
payload: StoredPayload;
};
@@ -34,7 +36,7 @@ async function claim(): Promise<Claimed | null> {
limit 1
for update skip locked
)
returning id, attempts, payload`,
returning id, attempts, provider, payload`,
);
return rows[0] ?? null;
}
@@ -49,14 +51,15 @@ async function run() {
}
try {
const result = await sendStored(job.payload);
const provider = (job.provider || config.transport) as typeof config.transport;
const result = await sendStored(job.payload, provider);
await query(
`update messages
set status = 'sent', provider_message_id = $2, sent_at = now(), error = null
where id = $1`,
[job.id, result.providerMessageId],
);
console.log(`[courier-worker] ${job.id} gesendet (${result.providerMessageId})`);
console.log(`[courier-worker] ${job.id} über ${provider} gesendet (${result.providerMessageId})`);
} catch (error) {
const failure = error as SendFailure;
const retry = failure.retryable !== false && job.attempts < MAX_ATTEMPTS;