nomadro/lib/ntfy.ts
eric 9f8fec1723 Ship portal PC/H5 acceptance, VIP ScrollReader, admin analytics and ops anchors.
Adds /api/health, ntfy notify on config save, /admin/analytics charts, and deploy smoke for miniprogram config/API.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-28 23:52:00 -05:00

54 lines
1.7 KiB
TypeScript

/**
* Publish to self-hosted ntfy (https://ntfy.nomadro.cn).
* Env: NTFY_BASE_URL, NTFY_TOPIC, NTFY_TOKEN (optional Bearer).
*/
export type NtfyPublishInput = {
title: string;
message: string;
priority?: "min" | "low" | "default" | "high" | "urgent" | number;
tags?: string;
topic?: string;
};
export function ntfyConfigured(): boolean {
const base = (process.env.NTFY_BASE_URL || "https://ntfy.nomadro.cn").trim();
const topic = (process.env.NTFY_TOPIC || "nomadro").trim();
return Boolean(base && topic);
}
export async function publishNtfy(input: NtfyPublishInput): Promise<{
ok: boolean;
skipped?: boolean;
status?: number;
error?: string;
}> {
const base = (process.env.NTFY_BASE_URL || "https://ntfy.nomadro.cn").replace(/\/$/, "");
const topic = (input.topic || process.env.NTFY_TOPIC || "nomadro").replace(/^\/+|\/+$/g, "");
if (!base || !topic) {
return { ok: false, skipped: true, error: "ntfy not configured" };
}
const headers: Record<string, string> = {
Title: input.title.slice(0, 200),
Priority: String(input.priority ?? "default"),
};
if (input.tags) headers.Tags = input.tags;
const token = (process.env.NTFY_TOKEN || "").trim();
if (token) headers.Authorization = `Bearer ${token}`;
try {
const res = await fetch(`${base}/${topic}`, {
method: "POST",
headers,
body: input.message.slice(0, 4000),
cache: "no-store",
});
if (!res.ok) {
return { ok: false, status: res.status, error: await res.text().then((t) => t.slice(0, 200)) };
}
return { ok: true, status: res.status };
} catch (e) {
return { ok: false, error: e instanceof Error ? e.message : String(e) };
}
}