Files
2026-11-23 09:08:21 +00:00

133 lines
4.3 KiB
TypeScript

import {
CreateEmailIdentityCommand,
GetAccountCommand,
GetEmailIdentityCommand,
ListEmailIdentitiesCommand,
PutEmailIdentityMailFromAttributesCommand,
SESv2Client,
} from "@aws-sdk/client-sesv2";
import { config } from "./config";
import { query } from "./db";
const client = new SESv2Client({ region: config.awsRegion });
export type DomainRow = {
domain: string;
status: string;
dkim_tokens: string[] | null;
mail_from_domain: string | null;
mail_from_status: string | null;
last_checked_at: string | null;
created_at: string;
};
const DOMAIN = /^(?=.{1,253}$)([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/;
export function normalizeDomain(value: string): string {
return value.trim().toLowerCase().replace(/\.$/, "");
}
export function validDomain(value: string): boolean {
return DOMAIN.test(normalizeDomain(value));
}
async function upsertDomain(domain: string, detail: Awaited<ReturnType<typeof getIdentity>>) {
const status = detail.VerifiedForSendingStatus ? "verified" : "pending";
const tokens = detail.DkimAttributes?.Tokens ?? null;
const mailFrom = detail.MailFromAttributes?.MailFromDomain ?? null;
const mailFromStatus = detail.MailFromAttributes?.MailFromDomainStatus ?? null;
await query(
`insert into domains (domain, status, dkim_tokens, mail_from_domain, mail_from_status, last_checked_at)
values ($1,$2,$3,$4,$5,now())
on conflict (domain) do update set
status = excluded.status,
dkim_tokens = excluded.dkim_tokens,
mail_from_domain = excluded.mail_from_domain,
mail_from_status = excluded.mail_from_status,
last_checked_at = now()`,
[domain, status, JSON.stringify(tokens), mailFrom, mailFromStatus],
);
}
async function getIdentity(domain: string) {
return client.send(new GetEmailIdentityCommand({ EmailIdentity: domain }));
}
export async function syncDomains(): Promise<DomainRow[]> {
const list = await client.send(new ListEmailIdentitiesCommand({ PageSize: 100 }));
for (const identity of list.EmailIdentities ?? []) {
if (identity.IdentityType !== "DOMAIN" || !identity.IdentityName) continue;
try {
const detail = await getIdentity(identity.IdentityName);
await upsertDomain(identity.IdentityName, detail);
} catch {
// Einzelne Identities dürfen die Übersicht nicht blockieren.
}
}
return listDomainRows();
}
export async function listDomainRows(): Promise<DomainRow[]> {
const { rows } = await query<DomainRow>(`select * from domains order by domain`);
return rows;
}
export async function getDomainRow(domain: string): Promise<DomainRow | null> {
const { rows } = await query<DomainRow>(`select * from domains where domain = $1`, [domain]);
return rows[0] ?? null;
}
export async function verifyDomain(domain: string): Promise<DomainRow | null> {
try {
const detail = await getIdentity(domain);
await upsertDomain(domain, detail);
} catch {
return getDomainRow(domain);
}
return getDomainRow(domain);
}
export async function createDomainIdentity(domain: string): Promise<DomainRow> {
const normalized = normalizeDomain(domain);
let detail: Awaited<ReturnType<typeof getIdentity>>;
try {
await client.send(new CreateEmailIdentityCommand({ EmailIdentity: normalized }));
detail = await getIdentity(normalized);
} catch (error) {
if ((error as Error).name !== "AlreadyExistsException") throw error;
detail = await getIdentity(normalized);
}
try {
await client.send(
new PutEmailIdentityMailFromAttributesCommand({
EmailIdentity: normalized,
MailFromDomain: `bounce.${normalized}`,
BehaviorOnMxFailure: "USE_DEFAULT_VALUE",
}),
);
detail = await getIdentity(normalized);
} catch {
// MAIL FROM ist optional; die Identity bleibt nutzbar.
}
await upsertDomain(normalized, detail);
const row = await getDomainRow(normalized);
if (!row) throw new Error("Domain konnte nicht gespeichert werden");
return row;
}
export async function sesAccountStatus() {
try {
const account = await client.send(new GetAccountCommand({}));
return {
production: account.ProductionAccessEnabled ?? false,
max24h: account.SendQuota?.Max24HourSend ?? 0,
rate: account.SendQuota?.MaxSendRate ?? 0,
};
} catch {
return { production: false, max24h: 0, rate: 0 };
}
}