peppa/packages/core/src/webpush.ts
2026-11-18 00:51:15 +05:00

208 lines
10 KiB
TypeScript

// Web Push (PEP-55) on node:crypto: VAPID (RFC 8292) + aes128gcm payload encryption
// (RFC 8291 / RFC 8188), a durable outbox delivered by the bot, and the subscriptions table.
import { m as tr } from "@peppa/shared/i18n";
import { createECDH, createPrivateKey, generateKeyPairSync, hkdfSync, randomBytes, createCipheriv, sign } from "node:crypto";
import { pushOutbox, pushSubscriptions, type Db } from "@peppa/db";
import { loadEnv } from "@peppa/shared";
import { and, asc, eq, lte } from "drizzle-orm";
import { getSetting, setSetting } from "./settings.ts";
import { inNightQuiet } from "./night-quiet.ts";
export type PushSubscriptionRow = typeof pushSubscriptions.$inferSelect;
export type PushOutboxRow = typeof pushOutbox.$inferSelect;
/** What the service worker shows (apps/web/public/sw.js). */
export interface PushPayload {
title: string;
body: string;
/** Opened on click (path on the Peppa web). */
url: string;
/** Same tag replaces the previous notification. */
tag?: string;
/** Play the system sound (user preference «звук»). */
sound?: boolean;
/** Waiting items for the app badge. */
count?: number;
}
const VAPID = "push.vapid";
const b64u = (b: Buffer) => b.toString("base64url");
const fromB64u = (s: string) => Buffer.from(s, "base64url");
interface VapidKeys {
/** Uncompressed P-256 point, base64url (applicationServerKey in the browser). */
publicKey: string;
/** PKCS#8 PEM. */
privateKey: string;
}
/** VAPID key pair of this Peppa: created on first use, kept in settings. */
export async function vapidKeys(db: Db): Promise<VapidKeys> {
const saved = await getSetting<VapidKeys>(db, VAPID);
if (saved) return saved;
const { publicKey, privateKey } = generateKeyPairSync("ec", { namedCurve: "prime256v1" });
const jwk = publicKey.export({ format: "jwk" });
const raw = Buffer.concat([Buffer.from([4]), fromB64u(jwk.x!), fromB64u(jwk.y!)]);
const keys = { publicKey: b64u(raw), privateKey: privateKey.export({ format: "pem", type: "pkcs8" }).toString() };
await setSetting(db, VAPID, keys);
// Another process may have raced us: whoever wrote last wins, read it back.
return (await getSetting<VapidKeys>(db, VAPID))!;
}
export const vapidPublicKey = async (db: Db) => (await vapidKeys(db)).publicKey;
/** `Authorization: vapid t=<JWT>, k=<public key>` for the push service at `endpoint`. */
export function vapidAuthorization(keys: VapidKeys, endpoint: string, subject: string, now = Date.now()): string {
const header = b64u(Buffer.from(JSON.stringify({ typ: "JWT", alg: "ES256" })));
const claims = b64u(Buffer.from(JSON.stringify({ aud: new URL(endpoint).origin, exp: Math.floor(now / 1000) + 12 * 3600, sub: subject })));
const data = `${header}.${claims}`;
const sig = sign("sha256", Buffer.from(data), { key: createPrivateKey(keys.privateKey), dsaEncoding: "ieee-p1363" });
return `vapid t=${data}.${b64u(sig)}, k=${keys.publicKey}`;
}
/** RFC 8291 aes128gcm body for the subscription's keys (one record). */
export function encryptPayload(plaintext: Buffer, p256dh: string, auth: string): Buffer {
const uaPublic = fromB64u(p256dh);
const authSecret = fromB64u(auth);
const ecdh = createECDH("prime256v1");
const asPublic = ecdh.generateKeys();
const shared = ecdh.computeSecret(uaPublic);
const keyInfo = Buffer.concat([Buffer.from("WebPush: info\0"), uaPublic, asPublic]);
const ikm = Buffer.from(hkdfSync("sha256", shared, authSecret, keyInfo, 32));
const salt = randomBytes(16);
const cek = Buffer.from(hkdfSync("sha256", ikm, salt, Buffer.from("Content-Encoding: aes128gcm\0"), 16));
const nonce = Buffer.from(hkdfSync("sha256", ikm, salt, Buffer.from("Content-Encoding: nonce\0"), 12));
const cipher = createCipheriv("aes-128-gcm", cek, nonce);
// 0x02 = padding delimiter of the last (only) record.
const body = Buffer.concat([cipher.update(Buffer.concat([plaintext, Buffer.from([2])])), cipher.final(), cipher.getAuthTag()]);
const rs = Buffer.alloc(4);
rs.writeUInt32BE(4096);
return Buffer.concat([salt, rs, Buffer.from([asPublic.length]), asPublic, body]);
}
export type PushResult = { ok: true } | { ok: false; gone: boolean; retryAfterSec?: number; status: number; error: string };
/** One push to one subscription. `gone` = the subscription no longer exists (404/410). */
export async function sendWebPush(
db: Db,
sub: Pick<PushSubscriptionRow, "endpoint" | "p256dh" | "auth">,
payload: PushPayload,
o: { urgency?: "normal" | "high"; ttlSec?: number } = {},
): Promise<PushResult> {
const keys = await vapidKeys(db);
const body = encryptPayload(Buffer.from(JSON.stringify(payload)), sub.p256dh, sub.auth);
try {
const res = await fetch(sub.endpoint, {
method: "POST",
headers: {
Authorization: vapidAuthorization(keys, sub.endpoint, loadEnv().PEPPA_WEB_URL),
"Content-Encoding": "aes128gcm",
"Content-Type": "application/octet-stream",
TTL: String(o.ttlSec ?? 24 * 3600),
Urgency: o.urgency ?? "normal",
},
body: new Uint8Array(body),
signal: AbortSignal.timeout(15_000),
});
if (res.ok) return { ok: true };
const text = (await res.text().catch(() => "")).slice(0, 300);
const retryAfter = Number(res.headers.get("retry-after"));
return {
ok: false,
gone: res.status === 404 || res.status === 410,
status: res.status,
retryAfterSec: Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter : undefined,
error: `${res.status} ${text}`.trim(),
};
} catch (e) {
return { ok: false, gone: false, status: 0, error: (e as Error).message };
}
}
// ── subscriptions ───────────────────────────────────────────────────────────────────
export async function savePushSubscription(
db: Db,
userId: number,
s: { endpoint: string; keys: { p256dh: string; auth: string }; userAgent?: string | null },
): Promise<PushSubscriptionRow> {
if (!/^https:\/\//.test(s.endpoint) && !/^http:\/\/(127\.0\.0\.1|localhost)[:/]/.test(s.endpoint)) throw new Error(tr("Неверный адрес push-подписки"));
if (fromB64u(s.keys.p256dh).length !== 65 || fromB64u(s.keys.auth).length < 16) throw new Error(tr("Неверные ключи push-подписки"));
const values = { userId, endpoint: s.endpoint, p256dh: s.keys.p256dh, auth: s.keys.auth, userAgent: s.userAgent?.slice(0, 300) ?? null };
const [row] = await db
.insert(pushSubscriptions)
.values(values)
// The same browser re-subscribing (or another user on it) takes the endpoint over.
.onConflictDoUpdate({ target: pushSubscriptions.endpoint, set: values })
.returning();
return row!;
}
export async function deletePushSubscription(db: Db, userId: number, endpoint: string): Promise<void> {
await db.delete(pushSubscriptions).where(and(eq(pushSubscriptions.userId, userId), eq(pushSubscriptions.endpoint, endpoint)));
}
export async function userPushSubscriptions(db: Db, userId: number): Promise<PushSubscriptionRow[]> {
return db.select().from(pushSubscriptions).where(eq(pushSubscriptions.userId, userId)).orderBy(asc(pushSubscriptions.id));
}
// ── outbox ──────────────────────────────────────────────────────────────────────────
/** Queues a push for every subscription of the user. Returns the number queued. */
export async function enqueuePush(db: Db, userId: number, m: { dedupeKey: string; payload: PushPayload; urgency?: "normal" | "high" }): Promise<number> {
let queued = 0;
for (const s of await userPushSubscriptions(db, userId)) {
const rows = await db
.insert(pushOutbox)
.values({ dedupeKey: `${m.dedupeKey}:push:${s.id}`, subscriptionId: s.id, payload: { ...m.payload }, urgency: m.urgency ?? "normal" })
.onConflictDoNothing()
.returning();
queued += rows.length;
}
return queued;
}
const MAX_ATTEMPTS = 6;
/** Delivers due pushes; called from the bot's outbox loop. Returns the number delivered. */
export async function flushPushOutbox(db: Db, o: { log?: (m: string) => void; limit?: number; now?: Date } = {}): Promise<number> {
// PEP-208: no pushes in the night silence — they wait for the morning.
if (inNightQuiet(o.now)) return 0;
const due = await db
.select({ row: pushOutbox, sub: pushSubscriptions })
.from(pushOutbox)
.leftJoin(pushSubscriptions, eq(pushOutbox.subscriptionId, pushSubscriptions.id))
.where(and(eq(pushOutbox.status, "pending"), lte(pushOutbox.nextAttemptAt, new Date())))
.orderBy(asc(pushOutbox.id))
.limit(o.limit ?? 20);
let sent = 0;
for (const { row, sub } of due) {
if (!sub) {
await db.update(pushOutbox).set({ status: "failed", error: "subscription removed" }).where(eq(pushOutbox.id, row.id));
continue;
}
const r = await sendWebPush(db, sub, row.payload as unknown as PushPayload, { urgency: row.urgency });
const attempts = row.attempts + 1;
if (r.ok) {
sent++;
await db.update(pushOutbox).set({ status: "sent", sentAt: new Date(), attempts, error: null }).where(eq(pushOutbox.id, row.id));
await db.update(pushSubscriptions).set({ lastOkAt: new Date() }).where(eq(pushSubscriptions.id, sub.id));
continue;
}
o.log?.(`push #${row.id}: ${r.error}`);
if (r.gone) {
// The browser unsubscribed or the subscription expired: forget it (and its queue).
await db.update(pushOutbox).set({ status: "failed", attempts, error: r.error }).where(eq(pushOutbox.subscriptionId, sub.id));
await db.delete(pushSubscriptions).where(eq(pushSubscriptions.id, sub.id));
continue;
}
const permanent = r.status >= 400 && r.status < 500 && r.status !== 429;
const delayMs = r.retryAfterSec != null ? r.retryAfterSec * 1000 : Math.min(10 * 60_000, 2000 * 2 ** attempts);
await db
.update(pushOutbox)
.set({ attempts, error: r.error, status: permanent || attempts >= MAX_ATTEMPTS ? "failed" : "pending", nextAttemptAt: new Date(Date.now() + delayMs) })
.where(eq(pushOutbox.id, row.id));
}
return sent;
}