Courier: Mail-Gateway mit Resend-API, Queue und SES-Transport
ci / build (push) Successful in 25s

This commit is contained in:
AImighty Bot committed 2026-11-22 14:20:34 +00:00
commit 2c0d7ec225
61 files changed
+5612

No files matched your search

+25
View File
@@ -0,0 +1,25 @@
# Datenbank (lokal oder Olares-Middleware)
DATABASE_URL=postgresql://courier@127.0.0.1:55432/courier
# dry-run | resend | ses
MAIL_TRANSPORT=dry-run
MAIL_FROM_DOMAIN=hubsport.club
GLOBAL_DAILY_LIMIT=1000
# Amazon SES (eu-west-1)
AWS_REGION=eu-west-1
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
SES_CONFIGURATION_SET=courier-transactional
SNS_TOPIC_ARN=
SNS_WEBHOOK_TOKEN=
# API-Keys (HMAC-Pepper, lang und zufällig)
API_KEY_PEPPER=dev-only-pepper
# Nur für den Übergang: Resend als Transport
RESEND_API_KEY=
# Öffentliche Adresse (für SNS-Webhook/Anzeige)
PUBLIC_BASE_URL=http://127.0.0.1:3400
+18
View File
@@ -0,0 +1,18 @@
name: ci
on:
push:
branches: [main]
pull_request:
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: "22"
- run: npm ci
- run: npm run typecheck
- run: npm run build
+126
View File
@@ -0,0 +1,126 @@
name: release
on:
workflow_dispatch:
inputs:
version:
description: "Version ohne v (muss olares/Chart.yaml entsprechen)"
required: true
default: "26.11.1"
permissions:
contents: write
packages: write
env:
GITEA_API: https://git.aimighty.olares.de/api/v1
REGISTRY: git.aimighty.olares.de/aimighty
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Version prüfen
env:
V: ${{ inputs.version }}
run: |
CHART=$(awk '/^version:/{print $2}' olares/Chart.yaml | tr -d '"')
[ "$V" = "$CHART" ] || { echo "::error::Version $V != Chart.yaml $CHART"; exit 1; }
- uses: actions/setup-node@v4
with:
node-version: "22"
- run: npm ci
- run: npm run typecheck
- run: npm run build
- name: install helm
run: |
for url in \
"https://git.aimighty.olares.de/aimighty/ci-tools/releases/download/helm-3.16.2/helm-v3.16.2-linux-amd64.tar.gz" \
"https://get.helm.sh/helm-v3.16.2-linux-amd64.tar.gz"; do
if curl -fsSL --retry 3 --retry-all-errors --max-time 180 -o /tmp/helm.tgz "$url" \
&& tar -tzf /tmp/helm.tgz >/dev/null 2>&1; then break; fi
done
tar -C /tmp -xzf /tmp/helm.tgz
install -m 0755 /tmp/linux-amd64/helm /usr/local/bin/helm
helm version --short
- name: Chart prüfen und packen
env:
V: ${{ inputs.version }}
run: |
helm lint olares -f olares/values-olares-stub.yaml
mkdir -p dist
helm package olares -d dist
test -f "dist/courier-$V.tgz"
- name: Docker-Daemon des Runners finden (dind am Bridge-Gateway)
run: |
read -r _ dest gw _ < <(awk '$2=="00000000" {print; exit}' /proc/net/route)
GW="$(printf "%d.%d.%d.%d" 0x${gw:6:2} 0x${gw:4:2} 0x${gw:2:2} 0x${gw:0:2})"
ok=0
for KANDIDAT in "$GW" "172.17.0.1"; do
[ -n "$KANDIDAT" ] || continue
if DOCKER_HOST="tcp://$KANDIDAT:2375" docker version >/dev/null 2>&1; then
echo "DOCKER_HOST=tcp://$KANDIDAT:2375" >> "$GITHUB_ENV"
ok=1
break
fi
done
[ "$ok" = "1" ] || { echo "::error::kein Docker-Daemon gefunden"; exit 1; }
- uses: docker/setup-buildx-action@v3
- name: Login to Gitea registry
uses: docker/login-action@v3
with:
registry: git.aimighty.olares.de
username: ${{ github.actor }}
password: ${{ secrets.REGISTRY_TOKEN }}
- name: Build & push
uses: docker/build-push-action@v6
with:
context: .
file: ./Dockerfile
platforms: linux/amd64
push: true
tags: |
${{ env.REGISTRY }}/courier:${{ inputs.version }}
${{ env.REGISTRY }}/courier:latest
- uses: actions/upload-artifact@v4
with:
name: chart
path: dist/courier-${{ inputs.version }}.tgz
release:
needs: build
runs-on: ubuntu-latest
permissions:
contents: write
env:
V: ${{ inputs.version }}
steps:
- uses: actions/download-artifact@v4
with:
name: chart
path: dist
- name: Tag und Release anlegen
env:
GITEA_TOKEN: ${{ secrets.MARKT_TOKEN }}
run: |
NOTES="courier $V — Image ${REGISTRY}/courier:$V, Chart im Anhang."
BODY=$(python3 -c 'import json,sys; print(json.dumps({"tag_name":"v"+sys.argv[1],"target_commitish":sys.argv[2],"name":"v"+sys.argv[1],"body":sys.argv[3]}))' "$V" "${{ github.sha }}" "$NOTES")
RID=$(curl -sS -X POST -H "Authorization: token $GITEA_TOKEN" -H "Content-Type: application/json" \
"$GITEA_API/repos/$GITHUB_REPOSITORY/releases" -d "$BODY" \
| python3 -c "import sys,json; print(json.load(sys.stdin).get('id') or '')")
[ -n "$RID" ] || { echo "Release-Anlage fehlgeschlagen"; exit 1; }
curl -sS -X POST -H "Authorization: token $GITEA_TOKEN" \
-F "attachment=@dist/courier-$V.tgz" \
"$GITEA_API/repos/$GITHUB_REPOSITORY/releases/$RID/assets?name=courier-$V.tgz" >/dev/null
echo "### v$V angelegt" >> "${GITHUB_STEP_SUMMARY:-/dev/null}"
+47
View File
@@ -0,0 +1,47 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# env files (can opt-in for committing if needed)
.env*
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
# lokale Daten
.env
.env.local
!.env.example
*.log
+39
View File
@@ -0,0 +1,39 @@
# syntax=docker/dockerfile:1
FROM node:22-alpine AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --no-audit --no-fund
FROM node:22-alpine AS build
WORKDIR /app
ENV NEXT_TELEMETRY_DISABLED=1
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run build
FROM node:22-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production \
NEXT_TELEMETRY_DISABLED=1 \
PORT=3000 \
HOSTNAME=0.0.0.0 \
TZ=Europe/Berlin
COPY --from=build /app/.next ./.next
COPY --from=build /app/node_modules ./node_modules
COPY --from=build /app/public ./public
COPY --from=build /app/package.json ./package.json
COPY --from=build /app/next.config.ts ./next.config.ts
COPY --from=build /app/tsconfig.json ./tsconfig.json
COPY --from=build /app/lib ./lib
COPY --from=build /app/scripts ./scripts
COPY --from=build /app/db ./db
COPY --from=build /app/types ./types
RUN chmod +x ./scripts/entrypoint.sh
USER node
EXPOSE 3000
ENTRYPOINT ["sh", "scripts/entrypoint.sh"]
+167
View File
@@ -0,0 +1,167 @@
olaresManifest.version: '0.12.0'
olaresManifest.type: app
apiVersion: 'v3'
workloadReplicas:
courier: 1
courier-worker: 1
metadata:
name: courier
appid: courier
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.1
categories:
- Applications
entrances:
- name: courier
host: courier
port: 3000
title: Courier
icon: https://git.aimighty.olares.de/aimighty/courier/raw/branch/main/icon.png
authLevel: internal
invisible: false
openMethod: window
middleware:
postgres:
username: courier
databases:
- name: courier
envs:
- envName: AWS_ACCESS_KEY_ID
required: true
type: password
editable: false
applyOnChange: false
default: ""
description: "IAM-Zugang courier-ses (nur SES senden)."
- envName: AWS_SECRET_ACCESS_KEY
required: true
type: password
editable: false
applyOnChange: false
default: ""
description: "Secret zum IAM-Zugang courier-ses."
- envName: AWS_REGION
required: true
type: string
editable: false
applyOnChange: false
default: "eu-west-1"
- envName: API_KEY_PEPPER
required: true
type: password
editable: false
applyOnChange: false
default: ""
description: "Pepper für die Hashes der Courier-API-Keys."
- envName: SNS_WEBHOOK_TOKEN
required: true
type: password
editable: false
applyOnChange: false
default: ""
description: "Zufälliger Token im SNS-Webhook-Pfad."
- envName: SES_CONFIGURATION_SET
required: true
type: string
editable: false
applyOnChange: false
default: "courier-transactional"
- envName: SNS_TOPIC_ARN
required: true
type: string
editable: false
applyOnChange: false
default: "arn:aws:sns:eu-west-1:945831802901:courier-ses-events"
- envName: MAIL_FROM_DOMAIN
required: true
type: string
editable: true
applyOnChange: true
default: "hubsport.club"
- envName: MAIL_TRANSPORT
required: true
type: string
editable: true
applyOnChange: true
default: "ses"
options:
- title: Amazon SES
value: ses
- title: Resend (Übergang)
value: resend
- title: Dry-Run
value: dry-run
- envName: GLOBAL_DAILY_LIMIT
required: false
type: int
editable: true
applyOnChange: true
default: "1000"
spec:
versionName: '26.11.1'
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.
**Funktionen**
- `POST /api/emails` und `/api/emails/batch` (Resend-kompatibel)
- API-Keys pro App mit Domain- und Absenderbeschränkung
- Tages- und Monatslimits, Idempotency-Key
- Queue mit Retry und Backoff
- Bounce-/Complaint-Verarbeitung über SNS, Suppression-Liste
- Übersicht und Nachrichten-Detail im Web
**Technik**
Next.js 15, PostgreSQL (Olares-Middleware), Amazon SES (eu-west-1).
developer: AImighty
website: https://git.aimighty.olares.de/aimighty/courier
sourceCode: https://git.aimighty.olares.de/aimighty/courier
submitter: AImighty
locale:
- de-DE
doc: https://git.aimighty.olares.de/aimighty/courier#readme
license:
- text: Proprietary
supportArch:
- amd64
requiredCpu: 250m
requiredMemory: 512Mi
requiredDisk: 1Gi
limitedCpu: 1000m
limitedMemory: 1Gi
limitedDisk: 5Gi
options:
policies:
- entranceName: courier
description: Mail-API für Apps
uriRegex: ^/api/(emails|health)(/.*)?(\?.*)?$
level: public
oneTime: false
validDuration: 0s
- entranceName: courier
description: SES-Ereignisse von SNS
uriRegex: ^/api/webhooks/ses(/.*)?(\?.*)?$
level: public
oneTime: false
validDuration: 0s
dependencies:
- name: olares
type: system
version: '>=1.12.6-0 <2.0.0'
allowMultipleInstall: false
allowedOutboundPorts:
- 443
runAsUser: "1000"
appScope:
clusterScoped: false
apiTimeout: 30
+67
View File
@@ -0,0 +1,67 @@
# Courier
Transaktionsmail-Gateway für die Apps auf Olares. Nimmt Mail per
Resend-kompatibler HTTP-API an, legt sie in eine Warteschlange und sendet über
Amazon SES. Absenderdomain: `hubsport.club`.
## Status
- API, Queue, Retry, API-Keys, Web-Übersicht und Worker stehen.
- Transport `dry-run` und `resend` sind eingebaut, `ses` ist implementiert.
- SES-Identity `hubsport.club` (eu-west-1) ist angelegt, DKIM/DNS noch offen.
- SES Production Access ist noch nicht freigegeben (Sandbox: 200/Tag).
## Lokal
```bash
cp .env.example .env
npm ci
npm run db:migrate
npm run db:key -- --app plan --name Plan
npm run dev # http://127.0.0.1:3400
npm run worker # in einem zweiten Terminal
```
Ohne `MAIL_TRANSPORT=ses` landet jede Mail nur im Log (`dry-run`).
## API
```bash
curl -X POST http://127.0.0.1:3400/api/emails \
-H "Authorization: Bearer ck_live_…" \
-H "Content-Type: application/json" \
-d '{
"from": "plan <plan@hubsport.club>",
"to": "kunde@example.com",
"subject": "Test",
"html": "<p>Hallo</p>"
}'
```
Unterstützt: `from`, `to`, `cc`, `bcc`, `reply_to`, `subject`, `html`, `text`,
`headers`, `attachments`, `tags`, `Idempotency-Key`; dazu
`POST /api/emails/batch`, `GET /api/emails/:id` und `GET /api/health`.
Fehler kommen im Resend-Format (`statusCode`, `name`, `message`).
## SES
```bash
npm run ses:records
```
Gibt die Cloudflare-Records für DKIM, MAIL FROM und DMARC aus. Danach im
AWS-Console den Production Access beantragen (SES → Account dashboard).
Zustellereignisse kommen per SNS auf `/api/webhooks/ses?token=…`.
## Olares
Chart unter `olares/`. Werte für AWS und SNS kommen aus `.secrets.md` in
`olares/values.yaml` (nie committen). Prüfen:
```bash
helm lint olares -f olares/values-olares-stub.yaml
helm template courier olares -f olares/values-olares-stub.yaml >/dev/null
```
Die öffentlichen Pfade sind auf die Mail-API, den Health-Check und den
SNS-Webhook begrenzt; die Oberfläche bleibt hinter Olares-Authelia.
+41
View File
@@ -0,0 +1,41 @@
import { authenticate } from "@/lib/api-key";
import { query } from "@/lib/db";
import { apiError, unauthorized } from "@/lib/http";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
export async function GET(request: Request, context: { params: Promise<{ id: string }> }) {
const key = await authenticate(request);
if (!key) return unauthorized();
const { id } = await context.params;
const { rows } = await query<{
id: string;
status: string;
subject: string;
to_emails: string[];
created_at: string;
sent_at: string | null;
completed_at: string | null;
error: string | null;
}>(
`select id, status, subject, to_emails, created_at, sent_at, completed_at, error
from messages
where id = $1 and api_key_id = $2`,
[id, key.id],
);
const message = rows[0];
if (!message) return apiError(404, "not_found", "Nachricht nicht gefunden");
return Response.json({
id: message.id,
status: message.status,
subject: message.subject,
to: message.to_emails,
created_at: message.created_at,
sent_at: message.sent_at,
completed_at: message.completed_at,
error: message.error,
});
}
+50
View File
@@ -0,0 +1,50 @@
import { authenticate, fromAllowed } from "@/lib/api-key";
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";
export async function POST(request: Request) {
const key = await authenticate(request);
if (!key) return unauthorized();
let body: unknown;
try {
body = await request.json();
} catch {
return validationError("Ungültiges JSON");
}
const parsed = batchSchema.safeParse(body);
if (!parsed.success) {
return validationError(parsed.error.issues.map((issue) => issue.message).join("; "));
}
const ids: { id: string }[] = [];
for (const [index, item] of parsed.data.entries()) {
try {
const mail = normalizeMail(item, key.fromDomain);
if (!fromAllowed(key, mail.from.address)) {
return validationError(`Absender ${mail.from.address} ist für diesen Key nicht erlaubt (Index ${index})`);
}
const result = await enqueue(key, mail, null);
ids.push({ id: result.id });
} catch (error) {
if (error instanceof QuotaExceededError) {
return apiError(429, "rate_limit_exceeded", error.message);
}
if (error instanceof SuppressedError) {
return apiError(422, "recipient_suppressed", `${error.message} (Index ${index})`);
}
if (error instanceof Error && error.name === "MailValidationError") {
return validationError(`${error.message} (Index ${index})`);
}
console.error("[courier] batch:", error);
return serverError();
}
}
return Response.json({ data: ids });
}
+46
View File
@@ -0,0 +1,46 @@
import { authenticate, fromAllowed } from "@/lib/api-key";
import { normalizeMail, sendSchema } from "@/lib/schema";
import { serverError, unauthorized, validationError } from "@/lib/http";
import { enqueue, QuotaExceededError, SuppressedError } from "@/lib/queue";
import { apiError } from "@/lib/http";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
export async function POST(request: Request) {
const key = await authenticate(request);
if (!key) return unauthorized();
let body: unknown;
try {
body = await request.json();
} catch {
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);
if (!fromAllowed(key, mail.from.address)) {
return validationError(`Absender ${mail.from.address} ist für diesen Key nicht erlaubt`);
}
const result = await enqueue(key, mail, request.headers.get("idempotency-key"));
return Response.json({ id: result.id });
} catch (error) {
if (error instanceof QuotaExceededError) {
return apiError(429, "rate_limit_exceeded", error.message);
}
if (error instanceof SuppressedError) {
return apiError(422, "recipient_suppressed", error.message);
}
if (error instanceof Error && error.name === "MailValidationError") {
return validationError(error.message);
}
console.error("[courier] send:", error);
return serverError();
}
}
+22
View File
@@ -0,0 +1,22 @@
import { config } from "@/lib/config";
import { query } from "@/lib/db";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
export async function GET() {
try {
await query("select 1");
return Response.json({
ok: true,
transport: config.transport,
fromDomain: config.fromDomain,
sesConfigured: Boolean(process.env.AWS_ACCESS_KEY_ID || process.env.AWS_PROFILE),
});
} catch (error) {
return Response.json(
{ ok: false, error: error instanceof Error ? error.message : "Datenbank nicht erreichbar" },
{ status: 503 },
);
}
}
+50
View File
@@ -0,0 +1,50 @@
import { safeEqual } from "@/lib/api-key";
import { config } from "@/lib/config";
import { handleSesNotification } from "@/lib/events";
import { confirmSubscription, verifySns, type SnsEnvelope } from "@/lib/sns";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
export async function POST(request: Request) {
const token = new URL(request.url).searchParams.get("token") ?? "";
if (config.snsWebhookToken && !safeEqual(token, config.snsWebhookToken)) {
return new Response("forbidden", { status: 403 });
}
let envelope: SnsEnvelope;
try {
envelope = (await request.json()) as SnsEnvelope;
} catch {
return new Response("invalid json", { status: 400 });
}
try {
await verifySns(envelope);
} catch (error) {
console.error("[courier] SNS:", error);
return new Response("invalid signature", { status: 403 });
}
if (envelope.Type === "SubscriptionConfirmation") {
try {
await confirmSubscription(envelope);
return new Response("confirmed", { status: 200 });
} catch (error) {
console.error("[courier] SNS confirm:", error);
return new Response("confirmation failed", { status: 502 });
}
}
if (envelope.Type === "Notification") {
try {
await handleSesNotification(envelope.Message, envelope.MessageId);
return new Response("ok", { status: 200 });
} catch (error) {
console.error("[courier] SNS event:", error);
return new Response("retry", { status: 500 });
}
}
return new Response("ok", { status: 200 });
}
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

+378
View File
@@ -0,0 +1,378 @@
:root {
--am-blau: #051729;
--am-blau-hell: #102b45;
--am-gold: #caa960;
--am-gold-hell: #e5cf9f;
--am-text: #12202e;
--am-muted: #5b6b7a;
--am-flaeche: #f5f7f9;
--am-karte: #ffffff;
--am-rand: #d9e0e6;
--am-gruen: #1f6f4a;
--am-rot: #9b2c2c;
--am-orange: #8a5a00;
--am-radius: 8px;
--am-space: 4px;
--am-font: var(--font-geist-sans), system-ui, sans-serif;
--am-mono: var(--font-geist-mono), ui-monospace, monospace;
}
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
padding: 0;
}
body {
background: var(--am-flaeche);
color: var(--am-text);
font-family: var(--am-font);
font-size: 15px;
line-height: 1.55;
}
a {
color: var(--am-blau);
text-decoration-color: var(--am-gold);
text-underline-offset: 3px;
}
a:hover {
text-decoration-thickness: 2px;
}
h1,
h2,
h3 {
color: var(--am-blau);
line-height: 1.2;
margin: 0 0 calc(var(--am-space) * 4);
}
h1 {
font-size: 28px;
}
h2 {
font-size: 20px;
}
p {
margin: 0 0 calc(var(--am-space) * 4);
}
code,
.mono {
font-family: var(--am-mono);
font-size: 13px;
}
.kopf {
background: var(--am-blau);
color: #fff;
border-bottom: 4px solid var(--am-gold);
}
.kopf-inhalt {
max-width: 1180px;
margin: 0 auto;
padding: 16px 24px;
display: flex;
align-items: center;
gap: 28px;
flex-wrap: wrap;
}
.marke {
color: #fff;
font-size: 20px;
font-weight: 700;
letter-spacing: 0.02em;
text-decoration: none;
display: inline-flex;
align-items: center;
gap: 10px;
}
.marke::before {
content: "";
width: 10px;
height: 24px;
background: var(--am-gold);
display: inline-block;
}
.nav {
display: flex;
gap: 4px;
flex-wrap: wrap;
}
.nav a {
color: #e8eef3;
text-decoration: none;
padding: 10px 14px;
border-radius: var(--am-radius);
min-height: 44px;
display: inline-flex;
align-items: center;
}
.nav a:hover,
.nav a[aria-current="page"] {
background: var(--am-blau-hell);
color: #fff;
}
.inhalt {
max-width: 1180px;
margin: 0 auto;
padding: 32px 24px 64px;
}
.lead {
color: var(--am-muted);
max-width: 70ch;
}
.karten {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(190px, 1fr));
gap: 16px;
margin-bottom: 32px;
}
.karte {
background: var(--am-karte);
border: 1px solid var(--am-rand);
border-radius: var(--am-radius);
padding: 20px;
}
.karte .zahl {
font-family: var(--am-mono);
font-size: 30px;
color: var(--am-blau);
display: block;
margin-bottom: 4px;
}
.karte .label {
color: var(--am-muted);
font-size: 13px;
text-transform: uppercase;
letter-spacing: 0.06em;
}
.abschnitt {
background: var(--am-karte);
border: 1px solid var(--am-rand);
border-radius: var(--am-radius);
padding: 24px;
margin-bottom: 24px;
}
.abschnitt-kopf {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
flex-wrap: wrap;
margin-bottom: 16px;
}
.abschnitt-kopf h2 {
margin: 0;
}
.tabelle {
width: 100%;
border-collapse: collapse;
}
.tabelle th,
.tabelle td {
text-align: left;
padding: 12px 10px;
border-bottom: 1px solid var(--am-rand);
vertical-align: top;
}
.tabelle th {
font-size: 12px;
text-transform: uppercase;
letter-spacing: 0.06em;
color: var(--am-muted);
font-weight: 600;
}
.tabelle tr:last-child td {
border-bottom: none;
}
.status {
display: inline-block;
padding: 2px 8px;
border-radius: 999px;
border: 1px solid currentColor;
font-size: 12px;
font-weight: 600;
}
.status-queued,
.status-sending {
color: var(--am-orange);
}
.status-sent,
.status-delivered {
color: var(--am-gruen);
}
.status-failed,
.status-bounced,
.status-complained {
color: var(--am-rot);
}
.knopf {
display: inline-flex;
align-items: center;
justify-content: center;
min-height: 44px;
padding: 10px 18px;
border-radius: var(--am-radius);
border: 1px solid var(--am-gold);
background: var(--am-gold);
color: var(--am-blau);
font: inherit;
font-weight: 650;
cursor: pointer;
text-decoration: none;
}
.knopf:hover {
background: var(--am-gold-hell);
}
.knopf-sekundaer {
background: transparent;
color: var(--am-blau);
border-color: var(--am-rand);
}
.knopf-gefahr {
background: transparent;
color: var(--am-rot);
border-color: var(--am-rot);
}
.knopf:focus-visible,
.nav a:focus-visible,
input:focus-visible,
select:focus-visible,
textarea:focus-visible {
outline: 3px solid var(--am-gold);
outline-offset: 2px;
}
.formular {
display: grid;
gap: 14px;
max-width: 620px;
}
.feld {
display: grid;
gap: 6px;
}
.feld label {
font-weight: 600;
font-size: 14px;
}
.feld input,
.feld select,
.feld textarea {
font: inherit;
padding: 10px 12px;
min-height: 44px;
border: 1px solid var(--am-rand);
border-radius: var(--am-radius);
background: #fff;
color: var(--am-text);
}
.feld .hinweis {
color: var(--am-muted);
font-size: 13px;
}
.zeile {
display: flex;
gap: 12px;
align-items: center;
flex-wrap: wrap;
}
.hinweis {
color: var(--am-muted);
}
.fehler {
color: var(--am-rot);
font-weight: 600;
}
.erfolg {
color: var(--am-gruen);
font-weight: 600;
}
.schluessel {
display: block;
padding: 12px;
background: #fff8e6;
border: 1px solid var(--am-gold);
border-radius: var(--am-radius);
word-break: break-all;
}
.leer {
color: var(--am-muted);
padding: 24px 0;
}
details {
border-top: 1px solid var(--am-rand);
padding-top: 12px;
margin-top: 12px;
}
summary {
cursor: pointer;
min-height: 44px;
display: flex;
align-items: center;
font-weight: 600;
}
@media (max-width: 640px) {
.inhalt {
padding: 24px 16px 48px;
}
.tabelle {
display: block;
overflow-x: auto;
}
h1 {
font-size: 24px;
}
}
+45
View File
@@ -0,0 +1,45 @@
"use server";
import { revalidatePath } from "next/cache";
import { generateKey, hashKey, keyPrefix } from "@/lib/api-key";
import { query } from "@/lib/db";
export type KeyState = { key?: string; error?: string };
export async function createKey(_previous: KeyState, formData: FormData): Promise<KeyState> {
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 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 (!/^[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" };
if (from && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(from)) return { error: "Ungültige Absenderadresse" };
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],
);
} catch (error) {
return { error: error instanceof Error ? error.message : "Key konnte nicht gespeichert werden" };
}
revalidatePath("/keys");
return { key };
}
export async function revokeKey(formData: FormData): Promise<void> {
const id = String(formData.get("id") ?? "");
if (!id) return;
await query(`update api_keys set revoked_at = now() where id = $1 and revoked_at is null`, [id]);
revalidatePath("/keys");
}
+56
View File
@@ -0,0 +1,56 @@
"use client";
import { useActionState } from "react";
import { createKey, type KeyState } from "./actions";
export function KeyForm() {
const [state, action, pending] = useActionState<KeyState, FormData>(createKey, {});
return (
<>
<form action={action} className="formular">
<div className="feld">
<label htmlFor="app">App</label>
<input id="app" name="app" required placeholder="plan" autoComplete="off" />
<span className="hinweis">Technischer Name, z. B. plan, lunch oder places.</span>
</div>
<div className="feld">
<label htmlFor="name">Bezeichnung</label>
<input id="name" name="name" required placeholder="Plan" autoComplete="off" />
</div>
<div className="feld">
<label htmlFor="domain">Absenderdomain</label>
<input id="domain" name="domain" defaultValue="hubsport.club" required autoComplete="off" />
</div>
<div className="feld">
<label htmlFor="from">Nur diese Absenderadresse (optional)</label>
<input id="from" name="from" placeholder="noreply@hubsport.club" autoComplete="off" />
</div>
<div className="zeile">
<div className="feld">
<label htmlFor="daily">Tageslimit</label>
<input id="daily" name="daily" type="number" min={1} defaultValue={500} required />
</div>
<div className="feld">
<label htmlFor="monthly">Monatslimit</label>
<input id="monthly" name="monthly" type="number" min={1} defaultValue={15000} required />
</div>
</div>
<div>
<button className="knopf" type="submit" disabled={pending}>
{pending ? "Erzeuge…" : "API-Key erzeugen"}
</button>
</div>
</form>
{state.error ? <p className="fehler">{state.error}</p> : null}
{state.key ? (
<div style={{ marginTop: 20 }}>
<p className="erfolg">Key erzeugt. Er wird nur jetzt angezeigt:</p>
<code className="schluessel">{state.key}</code>
</div>
) : null}
</>
);
}
+95
View File
@@ -0,0 +1,95 @@
import { datum } from "@/lib/format";
import { listApiKeys } from "@/lib/queries";
import { KeyForm } from "./key-form";
import { revokeKey } from "./actions";
export const dynamic = "force-dynamic";
export default async function Keys() {
let keys: Awaited<ReturnType<typeof listApiKeys>> = [];
let error = "";
try {
keys = await listApiKeys();
} catch (cause) {
error = cause instanceof Error ? cause.message : "Datenbank nicht erreichbar";
}
return (
<>
<h1>API-Keys</h1>
<p className="lead">
Jede App bekommt einen eigenen Key. Der Key gilt nur für die eingetragene Absenderdomain und
wird nur gehasht gespeichert.
</p>
{error ? <p className="fehler">Datenbank nicht erreichbar: {error}</p> : null}
<section className="abschnitt">
<h2>Neuen Key erzeugen</h2>
<KeyForm />
</section>
<section className="abschnitt">
<h2>Vorhandene Keys</h2>
{keys.length ? (
<table className="tabelle">
<thead>
<tr>
<th>App</th>
<th>Bezeichnung</th>
<th>Prefix</th>
<th>Domain</th>
<th>Limit</th>
<th>Zuletzt</th>
<th>Status</th>
<th />
</tr>
</thead>
<tbody>
{keys.map((key) => (
<tr key={key.id}>
<td>{key.app}</td>
<td>{key.name}</td>
<td className="mono">{key.prefix}…</td>
<td>{key.from_domain}</td>
<td className="mono">
{key.daily_limit}/Tag · {key.monthly_limit}/Monat
</td>
<td className="mono">{datum(key.last_used_at)}</td>
<td>{key.revoked_at ? <span className="status status-failed">gesperrt</span> : <span className="status status-sent">aktiv</span>}</td>
<td>
{key.revoked_at ? null : (
<form action={revokeKey}>
<input type="hidden" name="id" value={key.id} />
<button className="knopf knopf-gefahr" type="submit">
Sperren
</button>
</form>
)}
</td>
</tr>
))}
</tbody>
</table>
) : (
<p className="leer">Noch keine Keys.</p>
)}
</section>
<section className="abschnitt">
<h2>Verwendung</h2>
<p>Die API ist weitgehend Resend-kompatibel:</p>
<pre className="mono">{`curl -X POST https://courier.hubsport.club/api/emails \\
-H "Authorization: Bearer ck_live_…" \\
-H "Content-Type: application/json" \\
-d '{
"from": "plan <plan@hubsport.club>",
"to": "kunde@example.com",
"subject": "Test",
"html": "<p>Hallo</p>"
}'`}</pre>
</section>
</>
);
}
+33
View File
@@ -0,0 +1,33 @@
import type { Metadata } from "next";
import { GeistMono } from "geist/font/mono";
import { GeistSans } from "geist/font/sans";
import "./globals.css";
export const metadata: Metadata = {
title: "Courier",
description: "Transaktionsmail für hubsport.club",
robots: { index: false, follow: false },
};
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="de" className={`${GeistSans.variable} ${GeistMono.variable}`}>
<body>
<header className="kopf">
<div className="kopf-inhalt">
<a className="marke" href="/">
Courier
</a>
<nav className="nav" aria-label="Hauptnavigation">
<a href="/">Übersicht</a>
<a href="/messages">Nachrichten</a>
<a href="/keys">API-Keys</a>
</nav>
</div>
</header>
<main className="inhalt">{children}</main>
</body>
</html>
);
}
+109
View File
@@ -0,0 +1,109 @@
import { notFound } from "next/navigation";
import { datum } from "@/lib/format";
import { messageDetail } from "@/lib/queries";
export const dynamic = "force-dynamic";
export default async function Nachricht({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const detail = await messageDetail(id).catch(() => null);
if (!detail) notFound();
const { message, events } = detail;
return (
<>
<p>
<a href="/messages">← Nachrichten</a>
</p>
<h1>{message.subject}</h1>
<p className="lead">
<span className={`status status-${message.status}`}>{message.status}</span>{" "}
<span className="mono">{message.id}</span>
</p>
<section className="abschnitt">
<h2>Kopf</h2>
<table className="tabelle">
<tbody>
<tr>
<th>App</th>
<td>{message.app}</td>
</tr>
<tr>
<th>Von</th>
<td>{message.from_name ? `${message.from_name} <${message.from_email}>` : message.from_email}</td>
</tr>
<tr>
<th>An</th>
<td>{message.to_emails.join(", ")}</td>
</tr>
<tr>
<th>CC / BCC</th>
<td>
{message.cc_emails.join(", ") || "–"} / {message.bcc_emails.join(", ") || "–"}
</td>
</tr>
<tr>
<th>SES-ID</th>
<td className="mono">{message.provider_message_id || "–"}</td>
</tr>
<tr>
<th>Erstellt</th>
<td className="mono">{datum(message.created_at)}</td>
</tr>
<tr>
<th>Gesendet</th>
<td className="mono">{datum(message.sent_at)}</td>
</tr>
<tr>
<th>Abgeschlossen</th>
<td className="mono">{datum(message.completed_at)}</td>
</tr>
<tr>
<th>Versuche</th>
<td className="mono">{message.attempts}</td>
</tr>
{message.error ? (
<tr>
<th>Fehler</th>
<td className="fehler">{message.error}</td>
</tr>
) : null}
</tbody>
</table>
</section>
<section className="abschnitt">
<h2>Events</h2>
{events.length ? (
<table className="tabelle">
<thead>
<tr>
<th>Zeit</th>
<th>Typ</th>
<th>Details</th>
</tr>
</thead>
<tbody>
{events.map((event) => (
<tr key={event.id}>
<td className="mono">{datum(event.created_at)}</td>
<td>{event.type}</td>
<td>
<details>
<summary>JSON</summary>
<pre className="mono">{JSON.stringify(event.payload, null, 2)}</pre>
</details>
</td>
</tr>
))}
</tbody>
</table>
) : (
<p className="leer">Noch keine Zustellereignisse.</p>
)}
</section>
</>
);
}
+77
View File
@@ -0,0 +1,77 @@
import { datum, kurz } from "@/lib/format";
import { listMessages } from "@/lib/queries";
export const dynamic = "force-dynamic";
const STATUS = ["queued", "sending", "sent", "delivered", "bounced", "complained", "failed"];
export default async function Nachrichten({
searchParams,
}: {
searchParams: Promise<{ status?: string }>;
}) {
const { status } = await searchParams;
let messages: Awaited<ReturnType<typeof listMessages>> = [];
let error = "";
try {
messages = await listMessages(status);
} catch (cause) {
error = cause instanceof Error ? cause.message : "Datenbank nicht erreichbar";
}
return (
<>
<h1>Nachrichten</h1>
<p className="lead">Die letzten 100 Mails, neueste zuerst.</p>
<div className="zeile" style={{ marginBottom: 20 }}>
<a className="knopf knopf-sekundaer" href="/messages">
Alle
</a>
{STATUS.map((value) => (
<a key={value} className="knopf knopf-sekundaer" href={`/messages?status=${value}`}>
{value}
</a>
))}
</div>
{error ? (
<p className="fehler">Datenbank nicht erreichbar: {error}</p>
) : messages.length ? (
<section className="abschnitt">
<table className="tabelle">
<thead>
<tr>
<th>Zeit</th>
<th>App</th>
<th>Empfänger</th>
<th>Betreff</th>
<th>Versuche</th>
<th>Status</th>
</tr>
</thead>
<tbody>
{messages.map((message) => (
<tr key={message.id}>
<td className="mono">{datum(message.created_at)}</td>
<td>{message.app}</td>
<td>{message.to_emails.join(", ")}</td>
<td>
<a href={`/messages/${message.id}`}>{kurz(message.subject, 70)}</a>
{message.error ? <div className="fehler mono">{kurz(message.error, 80)}</div> : null}
</td>
<td className="mono">{message.attempts}</td>
<td>
<span className={`status status-${message.status}`}>{message.status}</span>
</td>
</tr>
))}
</tbody>
</table>
</section>
) : (
<p className="leer">Keine Nachrichten in dieser Ansicht.</p>
)}
</>
);
}
+167
View File
@@ -0,0 +1,167 @@
.page {
--gray-rgb: 0, 0, 0;
--gray-alpha-200: rgba(var(--gray-rgb), 0.08);
--gray-alpha-100: rgba(var(--gray-rgb), 0.05);
--button-primary-hover: #383838;
--button-secondary-hover: #f2f2f2;
display: grid;
grid-template-rows: 20px 1fr 20px;
align-items: center;
justify-items: center;
min-height: 100svh;
padding: 80px;
gap: 64px;
font-family: var(--font-geist-sans);
}
@media (prefers-color-scheme: dark) {
.page {
--gray-rgb: 255, 255, 255;
--gray-alpha-200: rgba(var(--gray-rgb), 0.145);
--gray-alpha-100: rgba(var(--gray-rgb), 0.06);
--button-primary-hover: #ccc;
--button-secondary-hover: #1a1a1a;
}
}
.main {
display: flex;
flex-direction: column;
gap: 32px;
grid-row-start: 2;
}
.main ol {
font-family: var(--font-geist-mono);
padding-left: 0;
margin: 0;
font-size: 14px;
line-height: 24px;
letter-spacing: -0.01em;
list-style-position: inside;
}
.main li:not(:last-of-type) {
margin-bottom: 8px;
}
.main code {
font-family: inherit;
background: var(--gray-alpha-100);
padding: 2px 4px;
border-radius: 4px;
font-weight: 600;
}
.ctas {
display: flex;
gap: 16px;
}
.ctas a {
appearance: none;
border-radius: 128px;
height: 48px;
padding: 0 20px;
border: 1px solid transparent;
transition:
background 0.2s,
color 0.2s,
border-color 0.2s;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
font-size: 16px;
line-height: 20px;
font-weight: 500;
}
a.primary {
background: var(--foreground);
color: var(--background);
gap: 8px;
}
a.secondary {
border-color: var(--gray-alpha-200);
min-width: 158px;
}
.footer {
grid-row-start: 3;
display: flex;
gap: 24px;
}
.footer a {
display: flex;
align-items: center;
gap: 8px;
}
.footer img {
flex-shrink: 0;
}
/* Enable hover only on non-touch devices */
@media (hover: hover) and (pointer: fine) {
a.primary:hover {
background: var(--button-primary-hover);
border-color: transparent;
}
a.secondary:hover {
background: var(--button-secondary-hover);
border-color: transparent;
}
.footer a:hover {
text-decoration: underline;
text-underline-offset: 4px;
}
}
@media (max-width: 600px) {
.page {
padding: 32px;
padding-bottom: 80px;
}
.main {
align-items: center;
}
.main ol {
text-align: center;
}
.ctas {
flex-direction: column;
}
.ctas a {
font-size: 14px;
height: 40px;
padding: 0 16px;
}
a.secondary {
min-width: auto;
}
.footer {
flex-wrap: wrap;
align-items: center;
justify-content: center;
}
}
@media (prefers-color-scheme: dark) {
.logo {
filter: invert();
}
}
+99
View File
@@ -0,0 +1,99 @@
import { config } from "@/lib/config";
import { datum, kurz } from "@/lib/format";
import { dashboardStats } from "@/lib/queries";
export const dynamic = "force-dynamic";
export default async function Startseite() {
let stats: Awaited<ReturnType<typeof dashboardStats>> | null = null;
let error = "";
try {
stats = await dashboardStats();
} catch (cause) {
error = cause instanceof Error ? cause.message : "Datenbank nicht erreichbar";
}
return (
<>
<h1>Übersicht</h1>
<p className="lead">
Courier nimmt Mails von deinen Apps an, legt sie in eine Warteschlange und übergibt sie an
Amazon SES. Absenderdomain: <strong>{config.fromDomain}</strong>, Transport:{" "}
<strong>{config.transport}</strong>.
</p>
{error ? (
<section className="abschnitt">
<h2>Einrichtung fehlt</h2>
<p className="fehler">Datenbank nicht erreichbar: {error}</p>
<p>
Migration ausführen: <code>npm run db:migrate</code>, danach einen Key erzeugen:{" "}
<code>npm run db:key -- --app plan --name Plan</code>.
</p>
</section>
) : (
<>
<div className="karten">
<div className="karte">
<span className="zahl">{stats?.counts.queued ?? 0}</span>
<span className="label">in Warteschlange</span>
</div>
<div className="karte">
<span className="zahl">{(stats?.counts.sent ?? 0) + (stats?.counts.delivered ?? 0)}</span>
<span className="label">gesendet / zugestellt (24 h)</span>
</div>
<div className="karte">
<span className="zahl">
{(stats?.counts.failed ?? 0) + (stats?.counts.bounced ?? 0) + (stats?.counts.complained ?? 0)}
</span>
<span className="label">Fehler (24 h)</span>
</div>
<div className="karte">
<span className="zahl">{stats?.suppressed ?? 0}</span>
<span className="label">gesperrte Empfänger</span>
</div>
</div>
<section className="abschnitt">
<div className="abschnitt-kopf">
<h2>Letzte Nachrichten</h2>
<a className="knopf knopf-sekundaer" href="/messages">
Alle ansehen
</a>
</div>
{stats?.recent.length ? (
<table className="tabelle">
<thead>
<tr>
<th>Zeit</th>
<th>App</th>
<th>Empfänger</th>
<th>Betreff</th>
<th>Status</th>
</tr>
</thead>
<tbody>
{stats.recent.map((message) => (
<tr key={message.id}>
<td className="mono">{datum(message.created_at)}</td>
<td>{message.app}</td>
<td>{message.to_emails.join(", ")}</td>
<td>
<a href={`/messages/${message.id}`}>{kurz(message.subject, 60)}</a>
</td>
<td>
<span className={`status status-${message.status}`}>{message.status}</span>
</td>
</tr>
))}
</tbody>
</table>
) : (
<p className="leer">Noch keine Nachrichten.</p>
)}
</section>
</>
)}
</>
);
}
+66
View File
@@ -0,0 +1,66 @@
create extension if not exists pgcrypto;
create table if not exists api_keys (
id uuid primary key default gen_random_uuid(),
app text not null,
name text not null,
prefix text not null,
key_hash text not null unique,
from_domain text not null default 'hubsport.club',
allowed_from text[],
daily_limit integer not null default 500,
monthly_limit integer not null default 15000,
revoked_at timestamptz,
last_used_at timestamptz,
created_at timestamptz not null default now()
);
create table if not exists messages (
id uuid primary key default gen_random_uuid(),
api_key_id uuid references api_keys(id) on delete set null,
app text not null,
provider_message_id text,
from_email text not null,
from_name text,
to_emails text[] not null default '{}',
cc_emails text[] not null default '{}',
bcc_emails text[] not null default '{}',
reply_to text[] not null default '{}',
subject text not null,
status text not null default 'queued',
error text,
payload jsonb not null,
idempotency_key text,
attempts integer not null default 0,
next_attempt_at timestamptz not null default now(),
created_at timestamptz not null default now(),
sent_at timestamptz,
completed_at timestamptz
);
create index if not exists messages_queue_idx
on messages (next_attempt_at)
where status = 'queued';
create index if not exists messages_created_idx on messages (created_at desc);
create index if not exists messages_key_created_idx on messages (api_key_id, created_at desc);
create index if not exists messages_provider_idx on messages (provider_message_id);
create unique index if not exists messages_idempotency_idx
on messages (api_key_id, idempotency_key);
create table if not exists message_events (
id bigserial primary key,
message_id uuid references messages(id) on delete cascade,
sns_message_id text unique,
type text not null,
payload jsonb not null,
created_at timestamptz not null default now()
);
create index if not exists message_events_message_idx on message_events (message_id, created_at);
create table if not exists suppressions (
email text primary key,
reason text not null,
created_at timestamptz not null default now()
);
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

+7
View File
@@ -0,0 +1,7 @@
<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512">
<rect width="512" height="512" fill="#051729"/>
<rect x="80" y="80" width="72" height="10" fill="#caa960"/>
<rect x="96" y="152" width="320" height="216" rx="10" fill="none" stroke="#caa960" stroke-width="12"/>
<path d="M104 164 L256 286 L408 164" fill="none" stroke="#caa960" stroke-width="12" stroke-linecap="square"/>
<path d="M104 356 L208 256 M408 356 L304 256" fill="none" stroke="#caa960" stroke-width="8" opacity="0.55"/>
</svg>

After

Width:  |  Height:  |  Size: 535 B

+50
View File
@@ -0,0 +1,50 @@
import addressparser from "nodemailer/lib/addressparser";
export type Mailbox = { address: string; name?: string };
const EMAIL = /^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/;
export function validEmail(value: string): boolean {
return EMAIL.test(value.trim());
}
export function parseMailbox(input: string): Mailbox | null {
const parsed = addressparser(input.trim());
if (parsed.length !== 1) return null;
const address = parsed[0]?.address?.trim().toLowerCase();
if (!address || !validEmail(address)) return null;
const name = parsed[0]?.name?.replace(/[\r\n]+/g, " ").trim();
return name ? { address, name } : { address };
}
export function parseMailboxList(input: string | string[] | undefined): Mailbox[] {
if (!input) return [];
const values = Array.isArray(input) ? input : [input];
const result: Mailbox[] = [];
for (const value of values) {
const parsed = addressparser(value);
for (const item of parsed) {
const address = item.address?.trim().toLowerCase();
if (!address || !validEmail(address)) {
throw new Error(`Ungültige E-Mail-Adresse: ${item.address || value}`);
}
const name = item.name?.replace(/[\r\n]+/g, " ").trim();
result.push(name ? { address, name } : { address });
}
}
return result;
}
export function domainOf(address: string): string {
return address.split("@")[1]?.toLowerCase() ?? "";
}
export function formatMailbox(mailbox: Mailbox): string {
if (!mailbox.name) return mailbox.address;
const name = mailbox.name.replace(/["\\]/g, "").replace(/[\r\n]+/g, " ");
return `"${name}" <${mailbox.address}>`;
}
export function addressesOf(list: Mailbox[]): string[] {
return list.map((item) => item.address);
}
+72
View File
@@ -0,0 +1,72 @@
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
import { config } from "./config";
import { query } from "./db";
export type ApiKey = {
id: string;
app: string;
fromDomain: string;
allowedFrom: string[] | null;
dailyLimit: number;
monthlyLimit: number;
};
type KeyRow = {
id: string;
app: string;
from_domain: string;
allowed_from: string[] | null;
daily_limit: number;
monthly_limit: number;
};
export function hashKey(key: string): string {
return createHmac("sha256", config.apiKeyPepper).update(key).digest("hex");
}
export function generateKey(): string {
return `ck_live_${randomBytes(24).toString("base64url")}`;
}
export function keyPrefix(key: string): string {
return key.slice(0, 16);
}
export function safeEqual(a: string, b: string): boolean {
const left = Buffer.from(a);
const right = Buffer.from(b);
return left.length === right.length && timingSafeEqual(left, right);
}
export async function authenticate(request: Request): Promise<ApiKey | null> {
const header = request.headers.get("authorization") ?? "";
if (!header.toLowerCase().startsWith("bearer ")) return null;
const token = header.slice(7).trim();
if (!token.startsWith("ck_live_")) return null;
const { rows } = await query<KeyRow>(
`select id, app, from_domain, allowed_from, daily_limit, monthly_limit
from api_keys
where key_hash = $1 and revoked_at is null`,
[hashKey(token)],
);
const row = rows[0];
if (!row) return null;
await query(`update api_keys set last_used_at = now() where id = $1`, [row.id]).catch(() => {});
return {
id: row.id,
app: row.app,
fromDomain: row.from_domain,
allowedFrom: row.allowed_from,
dailyLimit: row.daily_limit,
monthlyLimit: row.monthly_limit,
};
}
export function fromAllowed(key: ApiKey, address: string): boolean {
if (!key.allowedFrom?.length) return true;
return key.allowedFrom.map((value) => value.toLowerCase()).includes(address.toLowerCase());
}
+18
View File
@@ -0,0 +1,18 @@
export const config = {
fromDomain: process.env.MAIL_FROM_DOMAIN || "hubsport.club",
transport: (process.env.MAIL_TRANSPORT || "dry-run") as "dry-run" | "ses" | "resend",
databaseUrl:
process.env.DATABASE_URL ||
`postgresql://courier@127.0.0.1:${process.env.DB_PORT || "55432"}/courier`,
apiKeyPepper: process.env.API_KEY_PEPPER || "dev-only-pepper",
globalDailyLimit: Number(process.env.GLOBAL_DAILY_LIMIT || 1000),
snsTopicArn: process.env.SNS_TOPIC_ARN || "",
snsWebhookToken: process.env.SNS_WEBHOOK_TOKEN || "",
awsRegion: process.env.AWS_REGION || "eu-west-1",
sesConfigurationSet: process.env.SES_CONFIGURATION_SET || "courier-transactional",
resendApiKey: process.env.RESEND_API_KEY || "",
publicBaseUrl: process.env.PUBLIC_BASE_URL || "",
};
export type TransportName = typeof config.transport;
+50
View File
@@ -0,0 +1,50 @@
import { Pool, type PoolClient, type QueryResultRow } from "pg";
import { config } from "./config";
function connectionString(): string {
if (process.env.DATABASE_URL) return process.env.DATABASE_URL;
const host = process.env.DB_HOST;
if (host) {
const user = encodeURIComponent(process.env.DB_USER ?? "");
const password = encodeURIComponent(process.env.DB_PASSWORD ?? "");
const name = process.env.DB_NAME ?? "courier";
const port = process.env.DB_PORT ?? "5432";
return `postgresql://${user}:${password}@${host}:${port}/${name}`;
}
return config.databaseUrl;
}
const globalForPg = globalThis as unknown as { courierPool?: Pool };
export const pool =
globalForPg.courierPool ??
new Pool({ connectionString: connectionString(), max: 10 });
if (process.env.NODE_ENV !== "production") {
globalForPg.courierPool = pool;
}
export async function query<T extends QueryResultRow = QueryResultRow>(
text: string,
params: unknown[] = [],
) {
return pool.query<T>(text, params as never[]);
}
export async function transaction<T>(
fn: (client: PoolClient) => Promise<T>,
): Promise<T> {
const client = await pool.connect();
try {
await client.query("begin");
const result = await fn(client);
await client.query("commit");
return result;
} catch (error) {
await client.query("rollback");
throw error;
} finally {
client.release();
}
}
+85
View File
@@ -0,0 +1,85 @@
import { query } from "./db";
type Recipient = { emailAddress?: string; email_address?: string };
export type SesEvent = {
eventType: string;
mail?: { messageId?: string; destination?: string[] };
bounce?: { bounceType?: string; bouncedRecipients?: Recipient[] };
complaint?: { complainedRecipients?: Recipient[] };
};
function recipientsOf(event: SesEvent): string[] {
const list = event.bounce?.bouncedRecipients ?? event.complaint?.complainedRecipients ?? [];
const fromEvent = list
.map((item) => item.emailAddress ?? item.email_address ?? "")
.filter(Boolean)
.map((value) => value.toLowerCase());
if (fromEvent.length) return fromEvent;
return (event.mail?.destination ?? []).map((value) => value.toLowerCase());
}
export async function handleSesNotification(message: string, snsMessageId: string): Promise<void> {
let event: SesEvent;
try {
event = JSON.parse(message) as SesEvent;
} catch {
return;
}
const providerId = event.mail?.messageId;
if (!providerId) return;
const { rows } = await query<{ id: string; status: string }>(
`select id, status from messages where provider_message_id = $1 limit 1`,
[providerId],
);
const messageId = rows[0]?.id ?? null;
const inserted = await query(
`insert into message_events (message_id, sns_message_id, type, payload)
values ($1,$2,$3,$4)
on conflict (sns_message_id) do nothing
returning id`,
[messageId, snsMessageId, event.eventType, event],
);
if (!inserted.rows[0] || !messageId) return;
let next: string | null = null;
if (event.eventType === "Delivery") next = "delivered";
if (event.eventType === "Bounce") next = "bounced";
if (event.eventType === "Complaint") next = "complained";
if (event.eventType === "Reject") next = "failed";
if (!next) return;
await query(
`update messages
set status = case
when status in ('complained','bounced') then status
when $2 = 'complained' then 'complained'
when $2 = 'bounced' then 'bounced'
when $2 = 'delivered' then 'delivered'
when $2 = 'failed' and status <> 'delivered' then 'failed'
else status
end,
completed_at = case
when $2 in ('delivered','bounced','complained','failed') then now()
else completed_at
end
where id = $1`,
[messageId, next],
);
const permanent = event.eventType === "Complaint" || event.bounce?.bounceType === "Permanent";
if (permanent) {
const recipients = recipientsOf(event);
if (recipients.length) {
await query(
`insert into suppressions (email, reason)
select unnest($1::text[]), $2
on conflict (email) do update set reason = excluded.reason`,
[recipients, event.eventType === "Complaint" ? "complaint" : "hard_bounce"],
);
}
}
}
+12
View File
@@ -0,0 +1,12 @@
export function datum(value: string | Date | null | undefined): string {
if (!value) return "–";
return new Intl.DateTimeFormat("de-DE", {
dateStyle: "short",
timeStyle: "medium",
timeZone: "Europe/Berlin",
}).format(new Date(value));
}
export function kurz(value: string, max = 42): string {
return value.length > max ? `${value.slice(0, max - 1)}…` : value;
}
+17
View File
@@ -0,0 +1,17 @@
import { NextResponse } from "next/server";
export function apiError(statusCode: number, name: string, message: string) {
return NextResponse.json({ statusCode, name, message }, { status: statusCode });
}
export function unauthorized(message = "API key is invalid") {
return apiError(401, "validation_error", message);
}
export function validationError(message: string) {
return apiError(422, "validation_error", message);
}
export function serverError(message = "Interner Fehler") {
return apiError(500, "internal_server_error", message);
}
+25
View File
@@ -0,0 +1,25 @@
import { query } from "./db";
export type QuotaState = {
keyDaily: number;
keyMonthly: number;
globalDaily: number;
};
export async function quotaState(keyId: string): Promise<QuotaState> {
const { rows } = await query<{ key_daily: string; key_monthly: string; global_daily: string }>(
`select
count(*) filter (where api_key_id = $1 and created_at >= date_trunc('day', now())) as key_daily,
count(*) filter (where api_key_id = $1 and created_at >= date_trunc('month', now())) as key_monthly,
count(*) filter (where created_at >= date_trunc('day', now())) as global_daily
from messages`,
[keyId],
);
const row = rows[0];
return {
keyDaily: Number(row?.key_daily ?? 0),
keyMonthly: Number(row?.key_monthly ?? 0),
globalDaily: Number(row?.global_daily ?? 0),
};
}
+112
View File
@@ -0,0 +1,112 @@
import { query } from "./db";
export type StatusCount = { status: string; count: string };
export async function dashboardStats() {
const { rows } = await query<StatusCount>(
`select status, count(*)::text as count
from messages
where created_at >= now() - interval '24 hours'
group by status`,
);
const counts = Object.fromEntries(rows.map((row) => [row.status, Number(row.count)]));
const recent = await query<{
id: string;
app: string;
subject: string;
to_emails: string[];
status: string;
created_at: string;
}>(
`select id, app, subject, to_emails, status, created_at
from messages
order by created_at desc
limit 8`,
);
const suppressed = await query<{ count: string }>(`select count(*)::text as count from suppressions`);
return { counts, recent: recent.rows, suppressed: Number(suppressed.rows[0]?.count ?? 0) };
}
export async function listMessages(status: string | undefined, limit = 100) {
const params: unknown[] = [];
let where = "";
if (status) {
params.push(status);
where = `where status = $${params.length}`;
}
params.push(limit);
const { rows } = await query<{
id: string;
app: string;
subject: string;
to_emails: string[];
status: string;
attempts: number;
created_at: string;
completed_at: string | null;
error: string | null;
}>(
`select id, app, subject, to_emails, status, attempts, created_at, completed_at, error
from messages
${where}
order by created_at desc
limit $${params.length}`,
params,
);
return rows;
}
export async function messageDetail(id: string) {
const { rows } = await query<{
id: string;
app: string;
provider_message_id: string | null;
from_email: string;
from_name: string | null;
to_emails: string[];
cc_emails: string[];
bcc_emails: string[];
reply_to: string[];
subject: string;
status: string;
error: string | null;
attempts: number;
created_at: string;
sent_at: string | null;
completed_at: string | null;
payload: unknown;
}>(`select * from messages where id = $1`, [id]);
const message = rows[0];
if (!message) return null;
const events = await query<{ id: string; type: string; payload: unknown; created_at: string }>(
`select id, type, payload, created_at from message_events where message_id = $1 order by created_at`,
[id],
);
return { message, events: events.rows };
}
export async function listApiKeys() {
const { rows } = await query<{
id: string;
app: string;
name: string;
prefix: string;
from_domain: string;
allowed_from: string[] | null;
daily_limit: number;
monthly_limit: number;
revoked_at: string | null;
last_used_at: string | null;
created_at: string;
}>(`select * from api_keys order by created_at desc`);
return rows;
}
export async function listSuppressions(limit = 100) {
const { rows } = await query<{ email: string; reason: string; created_at: string }>(
`select email, reason, created_at from suppressions order by created_at desc limit $1`,
[limit],
);
return rows;
}
+144
View File
@@ -0,0 +1,144 @@
import { randomUUID } from "node:crypto";
import type { ApiKey } from "./api-key";
import { addressesOf } from "./address";
import { config } from "./config";
import { query, transaction } from "./db";
import type { NormalizedMail } from "./schema";
export class QuotaExceededError extends Error {
constructor(message = "Tageslimit erreicht") {
super(message);
this.name = "QuotaExceededError";
}
}
export class SuppressedError extends Error {
recipients: string[];
constructor(recipients: string[]) {
super(`Empfänger gesperrt: ${recipients.join(", ")}`);
this.name = "SuppressedError";
this.recipients = recipients;
}
}
export type StoredPayload = {
from: ReturnType<typeof payloadFrom>;
to: ReturnType<typeof payloadFrom>[];
cc: ReturnType<typeof payloadFrom>[];
bcc: ReturnType<typeof payloadFrom>[];
reply_to: ReturnType<typeof payloadFrom>[];
subject: string;
html?: string;
text?: string;
headers: Record<string, string>;
attachments: { filename: string; content: string; content_type?: string }[];
tags: { name: string; value: string }[];
};
function payloadFrom(mailbox: { address: string; name?: string }) {
return mailbox.name ? { address: mailbox.address, name: mailbox.name } : { address: mailbox.address };
}
export function storedPayload(mail: NormalizedMail): StoredPayload {
return {
from: payloadFrom(mail.from),
to: mail.to.map(payloadFrom),
cc: mail.cc.map(payloadFrom),
bcc: mail.bcc.map(payloadFrom),
reply_to: mail.replyTo.map(payloadFrom),
subject: mail.subject,
html: mail.html,
text: mail.text,
headers: mail.headers,
attachments: mail.attachments.map((item) => ({
filename: item.filename,
content: item.content.toString("base64"),
content_type: item.contentType,
})),
tags: mail.tags,
};
}
export async function enqueue(
apiKey: ApiKey,
mail: NormalizedMail,
idempotencyKey?: string | null,
): Promise<{ id: string; duplicate: boolean }> {
const recipients = addressesOf([...mail.to, ...mail.cc, ...mail.bcc]);
const { rows: suppressed } = await query<{ email: string }>(
`select email from suppressions where email = any($1::text[])`,
[recipients],
);
if (suppressed.length) throw new SuppressedError(suppressed.map((row) => row.email));
const payload = storedPayload(mail);
return transaction(async (client) => {
await client.query(`select pg_advisory_xact_lock(hashtext($1))`, [apiKey.id]);
if (idempotencyKey) {
const existing = await client.query<{ id: string }>(
`select id from messages where api_key_id = $1 and idempotency_key = $2`,
[apiKey.id, idempotencyKey],
);
if (existing.rows[0]) return { id: existing.rows[0].id, duplicate: true };
}
const usage = await client.query<{ key_daily: string; key_monthly: string; global_daily: string }>(
`select
count(*) filter (where api_key_id = $1 and created_at >= date_trunc('day', now())) as key_daily,
count(*) filter (where api_key_id = $1 and created_at >= date_trunc('month', now())) as key_monthly,
count(*) filter (where created_at >= date_trunc('day', now())) as global_daily
from messages`,
[apiKey.id],
);
const row = usage.rows[0];
if (Number(row?.key_daily ?? 0) >= apiKey.dailyLimit) {
throw new QuotaExceededError(`Tageslimit für ${apiKey.app} erreicht`);
}
if (Number(row?.key_monthly ?? 0) >= apiKey.monthlyLimit) {
throw new QuotaExceededError(`Monatslimit für ${apiKey.app} erreicht`);
}
if (Number(row?.global_daily ?? 0) >= config.globalDailyLimit) {
throw new QuotaExceededError("Globales Tageslimit erreicht");
}
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,
reply_to, subject, status, payload, idempotency_key
) values ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,'queued',$11,$12)
on conflict (api_key_id, idempotency_key) do nothing
returning id`,
[
id,
apiKey.id,
apiKey.app,
mail.from.address,
mail.from.name ?? null,
addressesOf(mail.to),
addressesOf(mail.cc),
addressesOf(mail.bcc),
addressesOf(mail.replyTo),
mail.subject,
payload,
idempotencyKey || null,
],
);
if (!inserted.rows[0] && idempotencyKey) {
const existing = await client.query<{ id: string }>(
`select id from messages where api_key_id = $1 and idempotency_key = $2`,
[apiKey.id, idempotencyKey],
);
return { id: existing.rows[0]?.id ?? id, duplicate: true };
}
await client.query(`select pg_notify('courier_queue', $1)`, [id]);
return { id: inserted.rows[0]?.id ?? id, duplicate: false };
});
}
+143
View File
@@ -0,0 +1,143 @@
import { z } from "zod";
import {
domainOf,
formatMailbox,
parseMailbox,
parseMailboxList,
type Mailbox,
} from "./address";
const addressInput = z.union([z.string().min(3), z.array(z.string().min(3)).min(1).max(50)]);
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(),
});
export const sendSchema = z
.object({
from: z.string().min(3),
to: addressInput,
cc: addressInput.optional(),
bcc: addressInput.optional(),
reply_to: addressInput.optional(),
subject: z.string().min(1).max(998),
html: z.string().max(2_000_000).optional(),
text: z.string().max(2_000_000).optional(),
headers: z.record(z.string(), z.string()).optional(),
attachments: z.array(attachmentInput).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(),
})
.refine((value) => Boolean(value.html || value.text), {
message: "html oder text ist erforderlich",
path: ["html"],
});
export const batchSchema = z.array(sendSchema).min(1).max(100);
export type SendInput = z.infer<typeof sendSchema>;
export type NormalizedMail = {
from: Mailbox;
to: Mailbox[];
cc: Mailbox[];
bcc: Mailbox[];
replyTo: Mailbox[];
subject: string;
html?: string;
text?: string;
headers: Record<string, string>;
attachments: { filename: string; content: Buffer; contentType?: string }[];
tags: { name: string; value: string }[];
};
const RESERVED_HEADERS = new Set([
"from",
"to",
"cc",
"bcc",
"reply-to",
"subject",
"date",
"message-id",
"mime-version",
"content-type",
"content-transfer-encoding",
"return-path",
]);
export class MailValidationError extends Error {
constructor(message: string) {
super(message);
this.name = "MailValidationError";
}
}
export function normalizeMail(input: SendInput, fromDomain: string): NormalizedMail {
const from = parseMailbox(input.from);
if (!from) throw new MailValidationError("Ungültige from-Adresse");
const domain = domainOf(from.address);
if (domain !== fromDomain && !domain.endsWith(`.${fromDomain}`)) {
throw new MailValidationError(`Absenderdomain ${domain} ist nicht erlaubt`);
}
const to = parseMailboxList(input.to);
const cc = parseMailboxList(input.cc);
const bcc = parseMailboxList(input.bcc);
if (to.length + cc.length + bcc.length === 0) {
throw new MailValidationError("Mindestens ein Empfänger ist erforderlich");
}
const headers: Record<string, string> = {};
for (const [name, value] of Object.entries(input.headers ?? {})) {
const lower = name.toLowerCase();
if (RESERVED_HEADERS.has(lower)) continue;
if (!/^[A-Za-z0-9-]+$/.test(name)) continue;
if (/[\r\n]/.test(value)) throw new MailValidationError(`Ungültiger Header: ${name}`);
headers[name] = value;
}
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 };
});
const total = attachments.reduce((sum, item) => sum + item.content.length, 0);
if (total > 10 * 1024 * 1024) {
throw new MailValidationError("Anhänge sind zusammen größer als 10 MB");
}
return {
from,
to,
cc,
bcc,
replyTo: parseMailboxList(input.reply_to),
subject: input.subject.replace(/[\r\n]+/g, " "),
html: input.html,
text: input.text,
headers,
attachments,
tags: input.tags ?? [],
};
}
export function mailPreview(mail: NormalizedMail) {
return {
from: formatMailbox(mail.from),
to: mail.to.map(formatMailbox),
cc: mail.cc.map(formatMailbox),
bcc: mail.bcc.map(formatMailbox),
reply_to: mail.replyTo.map(formatMailbox),
subject: mail.subject,
html: mail.html,
text: mail.text,
headers: mail.headers,
tags: mail.tags,
};
}
+94
View File
@@ -0,0 +1,94 @@
import { createVerify } from "node:crypto";
import { config } from "./config";
type SnsEnvelope = {
Type: string;
MessageId: string;
TopicArn: string;
Message: string;
Timestamp: string;
Signature: string;
SignatureVersion?: string;
SigningCertURL: string;
Subject?: string;
SubscribeURL?: string;
Token?: string;
};
const certCache = new Map<string, string>();
function allowedCertUrl(value: string): boolean {
try {
const url = new URL(value);
return (
url.protocol === "https:" &&
/^sns\.[a-z0-9-]+\.amazonaws\.com$/.test(url.hostname) &&
url.pathname.endsWith(".pem")
);
} catch {
return false;
}
}
function allowedSubscribeUrl(value: string): boolean {
try {
const url = new URL(value);
return url.protocol === "https:" && /^sns\.[a-z0-9-]+\.amazonaws\.com$/.test(url.hostname);
} catch {
return false;
}
}
async function signingCert(url: string): Promise<string> {
const cached = certCache.get(url);
if (cached) return cached;
const response = await fetch(url);
if (!response.ok) throw new Error(`SNS-Zertifikat ${response.status}`);
const pem = await response.text();
if (!pem.includes("BEGIN CERTIFICATE")) throw new Error("SNS-Zertifikat ungültig");
certCache.set(url, pem);
return pem;
}
function canonical(envelope: SnsEnvelope): string {
if (envelope.Type === "SubscriptionConfirmation" || envelope.Type === "UnsubscribeConfirmation") {
const parts = [
"Message", envelope.Message,
"MessageId", envelope.MessageId,
"SubscribeURL", envelope.SubscribeURL ?? "",
"Timestamp", envelope.Timestamp,
"Token", envelope.Token ?? "",
"TopicArn", envelope.TopicArn,
"Type", envelope.Type,
];
return `${parts.join("\n")}\n`;
}
const parts = ["Message", envelope.Message, "MessageId", envelope.MessageId];
if (envelope.Subject) parts.push("Subject", envelope.Subject);
parts.push("Timestamp", envelope.Timestamp, "TopicArn", envelope.TopicArn, "Type", envelope.Type);
return `${parts.join("\n")}\n`;
}
export async function verifySns(envelope: SnsEnvelope): Promise<void> {
if (envelope.TopicArn !== config.snsTopicArn) throw new Error("SNS-Topic unbekannt");
if (!allowedCertUrl(envelope.SigningCertURL)) throw new Error("SNS-Zertifikats-URL ungültig");
const cert = await signingCert(envelope.SigningCertURL);
const verifier = createVerify(envelope.SignatureVersion === "2" ? "RSA-SHA256" : "RSA-SHA1");
verifier.update(canonical(envelope), "utf8");
verifier.end();
if (!verifier.verify(cert, envelope.Signature, "base64")) {
throw new Error("SNS-Signatur ungültig");
}
}
export async function confirmSubscription(envelope: SnsEnvelope): Promise<void> {
if (!envelope.SubscribeURL || !allowedSubscribeUrl(envelope.SubscribeURL)) {
throw new Error("SNS-Subscribe-URL ungültig");
}
const response = await fetch(envelope.SubscribeURL);
if (!response.ok) throw new Error(`SNS-Bestätigung ${response.status}`);
}
export type { SnsEnvelope };
+119
View File
@@ -0,0 +1,119 @@
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 type { StoredPayload } from "./queue";
export type SendResult = { providerMessageId: string };
export type SendFailure = Error & { retryable?: boolean; statusCode?: number };
function mimeOptions(payload: StoredPayload) {
return {
from: formatMailbox(payload.from),
to: payload.to.map(formatMailbox),
cc: payload.cc.map(formatMailbox),
bcc: payload.bcc.map(formatMailbox),
replyTo: payload.reply_to.map(formatMailbox),
subject: payload.subject,
text: payload.text,
html: payload.html,
headers: payload.headers,
attachments: payload.attachments.map((item) => ({
filename: item.filename,
content: Buffer.from(item.content, "base64"),
contentType: item.content_type,
})),
};
}
function buildRaw(payload: StoredPayload): Promise<Buffer> {
return new Promise((resolve, reject) => {
new MailComposer(mimeOptions(payload))
.compile()
.build((error, message) => {
if (error) reject(error);
else resolve(message);
});
});
}
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()}` };
}
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", {
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,
})),
tags: payload.tags,
}),
});
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 };
}
const raw = await buildRaw(payload);
const client = new SESv2Client({ region: config.awsRegion });
try {
const result = await client.send(
new SendEmailCommand({
FromEmailAddress: formatMailbox(payload.from),
Destination: {
ToAddresses: addressesOf(payload.to),
CcAddresses: addressesOf(payload.cc),
BccAddresses: addressesOf(payload.bcc),
},
ReplyToAddresses: addressesOf(payload.reply_to),
Content: { Raw: { Data: raw } },
ConfigurationSetName: config.sesConfigurationSet,
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 });
return { providerMessageId: result.MessageId };
} catch (error) {
const status = (error as { $metadata?: { httpStatusCode?: number } }).$metadata?.httpStatusCode;
const name = (error as Error).name || "";
const retryable =
status === 429 ||
(status !== undefined && status >= 500) ||
/throttl|timeout|temporar|slow down|service unavailable/i.test(name) ||
/throttl|timeout|temporar|slow down|service unavailable/i.test((error as Error).message || "");
throw Object.assign(error as Error, { retryable, statusCode: status });
}
}
+14
View File
@@ -0,0 +1,14 @@
import type { NextConfig } from "next";
const config: NextConfig = {
distDir: process.env.NEXT_DIST_DIR || ".next",
experimental: {
serverActions: {
allowedOrigins: ["courier.hubsport.club", "courier.kaivostudio.olares.de"],
},
},
basePath: process.env.NEXT_BASE_PATH || undefined,
trailingSlash: true,
};
export default config;
+8
View File
@@ -0,0 +1,8 @@
apiVersion: v2
name: courier
description: Transaktionsmail-Gateway für hubsport.club über Amazon SES.
type: application
version: 26.11.1
appVersion: "26.11.1"
icon: https://git.aimighty.olares.de/aimighty/courier/raw/branch/main/icon.png
home: https://git.aimighty.olares.de/aimighty/courier
+167
View File
@@ -0,0 +1,167 @@
olaresManifest.version: '0.12.0'
olaresManifest.type: app
apiVersion: 'v3'
workloadReplicas:
courier: 1
courier-worker: 1
metadata:
name: courier
appid: courier
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.1
categories:
- Applications
entrances:
- name: courier
host: courier
port: 3000
title: Courier
icon: https://git.aimighty.olares.de/aimighty/courier/raw/branch/main/icon.png
authLevel: internal
invisible: false
openMethod: window
middleware:
postgres:
username: courier
databases:
- name: courier
envs:
- envName: AWS_ACCESS_KEY_ID
required: true
type: password
editable: false
applyOnChange: false
default: ""
description: "IAM-Zugang courier-ses (nur SES senden)."
- envName: AWS_SECRET_ACCESS_KEY
required: true
type: password
editable: false
applyOnChange: false
default: ""
description: "Secret zum IAM-Zugang courier-ses."
- envName: AWS_REGION
required: true
type: string
editable: false
applyOnChange: false
default: "eu-west-1"
- envName: API_KEY_PEPPER
required: true
type: password
editable: false
applyOnChange: false
default: ""
description: "Pepper für die Hashes der Courier-API-Keys."
- envName: SNS_WEBHOOK_TOKEN
required: true
type: password
editable: false
applyOnChange: false
default: ""
description: "Zufälliger Token im SNS-Webhook-Pfad."
- envName: SES_CONFIGURATION_SET
required: true
type: string
editable: false
applyOnChange: false
default: "courier-transactional"
- envName: SNS_TOPIC_ARN
required: true
type: string
editable: false
applyOnChange: false
default: "arn:aws:sns:eu-west-1:945831802901:courier-ses-events"
- envName: MAIL_FROM_DOMAIN
required: true
type: string
editable: true
applyOnChange: true
default: "hubsport.club"
- envName: MAIL_TRANSPORT
required: true
type: string
editable: true
applyOnChange: true
default: "ses"
options:
- title: Amazon SES
value: ses
- title: Resend (Übergang)
value: resend
- title: Dry-Run
value: dry-run
- envName: GLOBAL_DAILY_LIMIT
required: false
type: int
editable: true
applyOnChange: true
default: "1000"
spec:
versionName: '26.11.1'
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.
**Funktionen**
- `POST /api/emails` und `/api/emails/batch` (Resend-kompatibel)
- API-Keys pro App mit Domain- und Absenderbeschränkung
- Tages- und Monatslimits, Idempotency-Key
- Queue mit Retry und Backoff
- Bounce-/Complaint-Verarbeitung über SNS, Suppression-Liste
- Übersicht und Nachrichten-Detail im Web
**Technik**
Next.js 15, PostgreSQL (Olares-Middleware), Amazon SES (eu-west-1).
developer: AImighty
website: https://git.aimighty.olares.de/aimighty/courier
sourceCode: https://git.aimighty.olares.de/aimighty/courier
submitter: AImighty
locale:
- de-DE
doc: https://git.aimighty.olares.de/aimighty/courier#readme
license:
- text: Proprietary
supportArch:
- amd64
requiredCpu: 250m
requiredMemory: 512Mi
requiredDisk: 1Gi
limitedCpu: 1000m
limitedMemory: 1Gi
limitedDisk: 5Gi
options:
policies:
- entranceName: courier
description: Mail-API für Apps
uriRegex: ^/api/(emails|health)(/.*)?(\?.*)?$
level: public
oneTime: false
validDuration: 0s
- entranceName: courier
description: SES-Ereignisse von SNS
uriRegex: ^/api/webhooks/ses(/.*)?(\?.*)?$
level: public
oneTime: false
validDuration: 0s
dependencies:
- name: olares
type: system
version: '>=1.12.6-0 <2.0.0'
allowMultipleInstall: false
allowedOutboundPorts:
- 443
runAsUser: "1000"
appScope:
clusterScoped: false
apiTimeout: 30
+98
View File
@@ -0,0 +1,98 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: courier
labels:
app: courier
spec:
replicas: {{ .Values.workloads.courier.replicaCount }}
selector:
matchLabels:
app: courier
template:
metadata:
labels:
app: courier
spec:
containers:
- name: courier
image: "{{ .Values.images.registry }}/courier:{{ .Values.images.tag | default .Chart.AppVersion }}"
imagePullPolicy: {{ .Values.images.pullPolicy }}
ports:
- name: http
containerPort: 3000
env:
- name: DB_HOST
value: {{ .Values.postgres.host | quote }}
- name: DB_PORT
value: {{ .Values.postgres.port | quote }}
- name: DB_USER
value: {{ .Values.postgres.username | quote }}
- name: DB_PASSWORD
value: {{ .Values.postgres.password | quote }}
- name: DB_NAME
value: {{ .Values.postgres.databases.courier | quote }}
- name: MAIL_TRANSPORT
value: {{ .Values.olaresEnv.MAIL_TRANSPORT | quote }}
- name: MAIL_FROM_DOMAIN
value: {{ .Values.olaresEnv.MAIL_FROM_DOMAIN | quote }}
- name: GLOBAL_DAILY_LIMIT
value: {{ .Values.olaresEnv.GLOBAL_DAILY_LIMIT | quote }}
- name: PUBLIC_BASE_URL
value: {{ .Values.app.publicBaseUrl | default (printf "https://courier.%s" .Values.user.zone) | quote }}
- name: AWS_REGION
value: {{ .Values.olaresEnv.AWS_REGION | quote }}
- name: SES_CONFIGURATION_SET
value: {{ .Values.olaresEnv.SES_CONFIGURATION_SET | quote }}
- name: SNS_TOPIC_ARN
value: {{ .Values.olaresEnv.SNS_TOPIC_ARN | quote }}
- name: TZ
value: {{ .Values.app.timezone | quote }}
- name: PORT
value: "3000"
- name: HOSTNAME
value: "0.0.0.0"
- name: AWS_ACCESS_KEY_ID
valueFrom:
secretKeyRef:
name: courier-secrets
key: AWS_ACCESS_KEY_ID
- name: AWS_SECRET_ACCESS_KEY
valueFrom:
secretKeyRef:
name: courier-secrets
key: AWS_SECRET_ACCESS_KEY
- name: API_KEY_PEPPER
valueFrom:
secretKeyRef:
name: courier-secrets
key: API_KEY_PEPPER
- name: SNS_WEBHOOK_TOKEN
valueFrom:
secretKeyRef:
name: courier-secrets
key: SNS_WEBHOOK_TOKEN
readinessProbe:
httpGet:
path: /api/health/
port: http
initialDelaySeconds: 10
periodSeconds: 10
livenessProbe:
httpGet:
path: /api/health/
port: http
initialDelaySeconds: 30
periodSeconds: 20
resources:
requests:
cpu: 100m
memory: 256Mi
limits:
cpu: 500m
memory: 512Mi
securityContext:
allowPrivilegeEscalation: false
capabilities:
drop:
- ALL
+78
View File
@@ -0,0 +1,78 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: courier-worker
labels:
app: courier-worker
spec:
replicas: {{ (index .Values.workloads "courier-worker").replicaCount }}
selector:
matchLabels:
app: courier-worker
template:
metadata:
labels:
app: courier-worker
spec:
containers:
- name: courier-worker
image: "{{ .Values.images.registry }}/courier:{{ .Values.images.tag | default .Chart.AppVersion }}"
imagePullPolicy: {{ .Values.images.pullPolicy }}
command:
- ./node_modules/.bin/tsx
- scripts/worker.ts
env:
- name: DB_HOST
value: {{ .Values.postgres.host | quote }}
- name: DB_PORT
value: {{ .Values.postgres.port | quote }}
- name: DB_USER
value: {{ .Values.postgres.username | quote }}
- name: DB_PASSWORD
value: {{ .Values.postgres.password | quote }}
- name: DB_NAME
value: {{ .Values.postgres.databases.courier | quote }}
- name: MAIL_TRANSPORT
value: {{ .Values.olaresEnv.MAIL_TRANSPORT | quote }}
- name: MAIL_FROM_DOMAIN
value: {{ .Values.olaresEnv.MAIL_FROM_DOMAIN | quote }}
- name: AWS_REGION
value: {{ .Values.olaresEnv.AWS_REGION | quote }}
- name: SES_CONFIGURATION_SET
value: {{ .Values.olaresEnv.SES_CONFIGURATION_SET | quote }}
- name: SNS_TOPIC_ARN
value: {{ .Values.olaresEnv.SNS_TOPIC_ARN | quote }}
- name: TZ
value: {{ .Values.app.timezone | quote }}
- name: AWS_ACCESS_KEY_ID
valueFrom:
secretKeyRef:
name: courier-secrets
key: AWS_ACCESS_KEY_ID
- name: AWS_SECRET_ACCESS_KEY
valueFrom:
secretKeyRef:
name: courier-secrets
key: AWS_SECRET_ACCESS_KEY
- name: API_KEY_PEPPER
valueFrom:
secretKeyRef:
name: courier-secrets
key: API_KEY_PEPPER
- name: SNS_WEBHOOK_TOKEN
valueFrom:
secretKeyRef:
name: courier-secrets
key: SNS_WEBHOOK_TOKEN
resources:
requests:
cpu: 50m
memory: 128Mi
limits:
cpu: 250m
memory: 512Mi
securityContext:
allowPrivilegeEscalation: false
capabilities:
drop:
- ALL
+12
View File
@@ -0,0 +1,12 @@
apiVersion: v1
kind: Secret
metadata:
name: courier-secrets
labels:
app: courier
type: Opaque
stringData:
AWS_ACCESS_KEY_ID: {{ .Values.olaresEnv.AWS_ACCESS_KEY_ID | quote }}
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 }}
+14
View File
@@ -0,0 +1,14 @@
apiVersion: v1
kind: Service
metadata:
name: courier
labels:
app: courier
spec:
type: ClusterIP
selector:
app: courier
ports:
- name: http
port: 3000
targetPort: 3000
+13
View File
@@ -0,0 +1,13 @@
# Nur zum Prüfen mit `helm lint` und `helm template`. Die echten Werte
# injiziert Olares zur Laufzeit.
postgres:
host: postgres-cluster.os-platform
port: "5432"
username: courier
password: nur-zum-pruefen
databases:
courier: courier-db
bfl:
username: pruefer
user:
zone: pruefer.olares.com
+28
View File
@@ -0,0 +1,28 @@
workloads:
courier:
replicaCount: 1
courier-worker:
replicaCount: 1
images:
registry: git.aimighty.olares.de/aimighty
tag: ""
pullPolicy: IfNotPresent
app:
timezone: Europe/Berlin
publicBaseUrl: ""
# Olares überschreibt diese Map beim Install mit den envs aus dem Manifest.
# Die Schlüssel müssen hier stehen, sonst rendert ein nacktes helm template nicht.
olaresEnv:
AWS_ACCESS_KEY_ID: ""
AWS_SECRET_ACCESS_KEY: ""
AWS_REGION: "eu-west-1"
API_KEY_PEPPER: ""
SNS_WEBHOOK_TOKEN: ""
SES_CONFIGURATION_SET: "courier-transactional"
SNS_TOPIC_ARN: "arn:aws:sns:eu-west-1:945831802901:courier-ses-events"
MAIL_FROM_DOMAIN: "hubsport.club"
MAIL_TRANSPORT: "ses"
GLOBAL_DAILY_LIMIT: "1000"
+2122
View File
File diff suppressed because it is too large. Load diff
+35
View File
@@ -0,0 +1,35 @@
{
"name": "courier",
"version": "26.11.1",
"private": true,
"scripts": {
"dev": "next dev -H 0.0.0.0 -p 3400",
"build": "next build",
"start": "next start -H 0.0.0.0 -p 3400",
"typecheck": "tsc --noEmit",
"db:migrate": "node scripts/migrate.mjs",
"db:key": "node scripts/create-key.mjs",
"worker": "tsx scripts/worker.ts",
"ses:records": "node scripts/ses-records.mjs"
},
"dependencies": {
"@aws-sdk/client-sesv2": "^3.1175.0",
"geist": "^1.9.2",
"next": "15.5.29",
"nodemailer": "^10.6.1",
"pg": "^8.23.1",
"react": "19.1.0",
"react-dom": "19.1.0",
"server-only": "^0.0.1",
"tsx": "^4.23.15",
"zod": "^4.6.7"
},
"devDependencies": {
"@types/node": "^20",
"@types/nodemailer": "^8.0.2",
"@types/pg": "^8.23.1",
"@types/react": "^19",
"@types/react-dom": "^19",
"typescript": "^5"
}
}
+1
View File
@@ -0,0 +1 @@
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>

After

Width:  |  Height:  |  Size: 391 B

+1
View File
@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

+1
View File
@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>

After

Width:  |  Height:  |  Size: 128 B

+1
View File
@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>

After

Width:  |  Height:  |  Size: 385 B

+40
View File
@@ -0,0 +1,40 @@
import { createHmac, randomBytes } from "node:crypto";
import pg from "pg";
const args = process.argv.slice(2);
const get = (name, fallback) => {
const index = args.indexOf(`--${name}`);
return index >= 0 ? args[index + 1] : fallback;
};
const app = get("app");
if (!app) {
console.error("Aufruf: npm run db:key -- --app plan --name 'Plan' [--daily 400] [--monthly 12000] [--from plan@hubsport.club]");
process.exit(1);
}
const name = get("name", app);
const domain = get("domain", process.env.MAIL_FROM_DOMAIN || "hubsport.club");
const daily = Number(get("daily", 500));
const monthly = Number(get("monthly", 15000));
const from = get("from");
const pepper = process.env.API_KEY_PEPPER || "dev-only-pepper";
const key = `ck_live_${randomBytes(24).toString("base64url")}`;
const hash = createHmac("sha256", pepper).update(key).digest("hex");
const prefix = key.slice(0, 16);
const url =
process.env.DATABASE_URL ||
`postgresql://courier@127.0.0.1:${process.env.DB_PORT || "55432"}/courier`;
const client = new pg.Client({ connectionString: url });
await client.connect();
const { rows } = await client.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)
returning id, app, created_at`,
[app, name, prefix, hash, domain, from ? [from] : null, daily, monthly],
);
await client.end();
console.log(JSON.stringify(rows[0], null, 2));
console.log(`\nAPI-Key (nur jetzt sichtbar):\n${key}\n`);
+15
View File
@@ -0,0 +1,15 @@
#!/bin/sh
set -e
i=0
until node scripts/migrate.mjs; do
i=$((i + 1))
if [ "$i" -ge 30 ]; then
echo "Datenbank nicht erreichbar, Migration abgebrochen." >&2
exit 1
fi
echo "Migration erneut in 2s (Versuch $i)…" >&2
sleep 2
done
exec ./node_modules/.bin/next start -H 0.0.0.0 -p "${PORT:-3000}"
+47
View File
@@ -0,0 +1,47 @@
import { createHash } from "node:crypto";
import { readdir, readFile } from "node:fs/promises";
import path from "node:path";
import pg from "pg";
const url =
process.env.DATABASE_URL ||
`postgresql://courier@127.0.0.1:${process.env.DB_PORT || "55432"}/courier`;
const client = new pg.Client({ connectionString: url });
await client.connect();
await client.query(`
create table if not exists schema_migrations (
name text primary key,
checksum text not null,
applied_at timestamptz not null default now()
)
`);
const dir = path.join(process.cwd(), "db", "migrations");
const files = (await readdir(dir)).filter((file) => file.endsWith(".sql")).sort();
for (const file of files) {
const sql = await readFile(path.join(dir, file), "utf8");
const checksum = createHash("sha256").update(sql).digest("hex");
const { rows } = await client.query(`select checksum from schema_migrations where name = $1`, [file]);
if (rows[0]) {
if (rows[0].checksum !== checksum) {
throw new Error(`${file} wurde nach dem Anwenden geändert`);
}
continue;
}
console.log(`migrate ${file}`);
await client.query("begin");
try {
await client.query(sql);
await client.query(`insert into schema_migrations (name, checksum) values ($1, $2)`, [file, checksum]);
await client.query("commit");
} catch (error) {
await client.query("rollback");
throw error;
}
}
await client.end();
console.log("Datenbank aktuell.");
+25
View File
@@ -0,0 +1,25 @@
import { SESv2Client, GetEmailIdentityCommand } from "@aws-sdk/client-sesv2";
const domain = process.env.MAIL_FROM_DOMAIN || "hubsport.club";
const region = process.env.AWS_REGION || "eu-west-1";
const client = new SESv2Client({ region });
const identity = await client.send(new GetEmailIdentityCommand({ EmailIdentity: domain }));
const status = identity.DkimAttributes?.Status ?? "UNKNOWN";
const tokens = identity.DkimAttributes?.Tokens ?? [];
const mailFrom = identity.MailFromAttributes?.MailFromDomain ?? `bounce.${domain}`;
console.log(`SES-Identity: ${domain} (${region})`);
console.log(`DKIM: ${status}`);
console.log(`Sending aktiv: ${identity.VerifiedForSendingStatus ? "ja" : "nein"}\n`);
console.log("Cloudflare-Records (Proxy aus):\n");
for (const token of tokens) {
console.log(`CNAME ${token}._domainkey.${domain} -> ${token}.dkim.amazonses.com`);
}
console.log(`MX ${mailFrom} -> 10 feedback-smtp.${region}.amazonses.com`);
console.log(`TXT ${mailFrom} -> "v=spf1 include:amazonses.com ~all"`);
console.log(`TXT _dmarc.${domain} -> "v=DMARC1; p=none;"\n`);
if (tokens.length === 0) {
console.log("Keine DKIM-Tokens gefunden. Ist die Identity im richtigen Account/Region angelegt?");
}
+81
View File
@@ -0,0 +1,81 @@
import { query } from "../lib/db";
import { sendStored, type SendFailure } from "../lib/transport";
import type { StoredPayload } from "../lib/queue";
const MAX_ATTEMPTS = 5;
const POLL_MS = 1000;
type Claimed = {
id: string;
attempts: number;
payload: StoredPayload;
};
let running = true;
process.on("SIGTERM", () => {
running = false;
});
process.on("SIGINT", () => {
running = false;
});
function sleep(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function claim(): Promise<Claimed | null> {
const { rows } = await query<Claimed>(
`update messages
set status = 'sending', attempts = attempts + 1
where id = (
select id from messages
where status = 'queued' and next_attempt_at <= now()
order by next_attempt_at
limit 1
for update skip locked
)
returning id, attempts, payload`,
);
return rows[0] ?? null;
}
async function run() {
console.log(`[courier-worker] gestartet, Transport ${process.env.MAIL_TRANSPORT || "dry-run"}`);
while (running) {
const job = await claim();
if (!job) {
await sleep(POLL_MS);
continue;
}
try {
const result = await sendStored(job.payload);
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})`);
} catch (error) {
const failure = error as SendFailure;
const retry = failure.retryable !== false && job.attempts < MAX_ATTEMPTS;
const delay = Math.min(3600, 30 * 2 ** Math.max(0, job.attempts - 1));
await query(
`update messages
set status = $2,
error = $3,
next_attempt_at = case when $2 = 'queued' then now() + ($4 || ' seconds')::interval else next_attempt_at end
where id = $1`,
[job.id, retry ? "queued" : "failed", String(failure.message || failure).slice(0, 2000), String(delay)],
);
console.error(`[courier-worker] ${job.id} ${retry ? `erneut in ${delay}s` : "endgültig fehlgeschlagen"}:`, failure.message);
}
}
console.log("[courier-worker] beendet");
}
run().catch((error) => {
console.error("[courier-worker] Absturz:", error);
process.exit(1);
});
+27
View File
@@ -0,0 +1,27 @@
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}
+12
View File
@@ -0,0 +1,12 @@
declare module "nodemailer/lib/addressparser" {
export type ParsedAddress = { address: string; name: string };
export default function addressparser(address: string): ParsedAddress[];
}
declare module "nodemailer/lib/mail-composer" {
import type { Options } from "nodemailer/lib/mailer";
export default class MailComposer {
constructor(mail: Options);
compile(): { build(callback: (error: Error | null, message: Buffer) => void): void };
}
}