ai-chatbot/lib/notifications/notification-center.ts

84 lines
2.6 KiB
TypeScript

import "server-only";
import { createHash, createHmac, randomBytes } from "node:crypto";
export type NotificationPayload = {
idempotencyKey: string;
recipientAlias: string;
title: string;
content: string;
actionTitle: string;
actionUrl: string;
};
export type NotificationDelivery = { id: string; status: string; lastErrorCode?: string | null };
export class NotificationCenterError extends Error {
code: string;
retryable: boolean;
constructor(code: string, retryable: boolean) {
super(code);
this.code = code;
this.retryable = retryable;
}
}
export function notificationCenterConfigured() {
return Boolean(
process.env.YYD_NOTIFICATION_CENTER_URL &&
process.env.YYD_NOTIFICATION_CENTER_PROJECT_CODE &&
process.env.YYD_NOTIFICATION_CENTER_PROJECT_SECRET,
);
}
export async function notificationCenterRequest(
method: "GET" | "POST",
path: string,
payload?: NotificationPayload,
): Promise<NotificationDelivery> {
if (!notificationCenterConfigured())
throw new NotificationCenterError("NOTIFICATION_CONFIG_MISSING", true);
const body = payload ? JSON.stringify(payload) : "";
const timestamp = String(Math.floor(Date.now() / 1000));
const nonce = randomBytes(18).toString("base64url");
const canonical = [
timestamp,
nonce,
method,
path,
createHash("sha256").update(body).digest("hex"),
].join("\n");
let response: Response;
try {
response = await fetch(
`${process.env.YYD_NOTIFICATION_CENTER_URL!.replace(/\/$/, "")}${path}`,
{
method,
headers: {
"Content-Type": "application/json",
"x-yyd-project-code": process.env.YYD_NOTIFICATION_CENTER_PROJECT_CODE!,
"x-yyd-timestamp": timestamp,
"x-yyd-nonce": nonce,
"x-yyd-signature": createHmac(
"sha256",
process.env.YYD_NOTIFICATION_CENTER_PROJECT_SECRET!,
)
.update(canonical)
.digest("hex"),
},
...(body ? { body } : {}),
cache: "no-store",
signal: AbortSignal.timeout(8000),
},
);
} catch {
throw new NotificationCenterError("NOTIFICATION_CONNECTION_FAILED", true);
}
const data = await response.json().catch(() => null);
if (!response.ok)
throw new NotificationCenterError(
typeof data?.error === "string" ? data.error : "NOTIFICATION_RESPONSE_FAILED",
response.status >= 500 || response.status === 429,
);
if (!data || typeof data.id !== "string" || typeof data.status !== "string")
throw new NotificationCenterError("NOTIFICATION_RESPONSE_INVALID", true);
return data;
}