Email for professionals and teams
feat: add PWA and Web Push notifications
Arnabebc552f5a017
diff --git a/docs/deployment.md b/docs/deployment.mdindex 859b396..bad9956 100644--- a/docs/deployment.md+++ b/docs/deployment.md@@ -30,6 +30,14 @@ Mailflare requires this runtime value:Paste only the token secret into `CF_TOKEN`. Do not include the word `Bearer` and do not use the token ID. The token must belong to the same Cloudflare account as the domains you connect.+### Optional Web Push configuration++To enable background new-mail notifications, run `npm run push:keys` once and+store `VAPID_PRIVATE_KEY` as a Worker secret. Configure `VAPID_PUBLIC_KEY` and+`VAPID_SUBJECT` as Worker variables; the subject must be a `mailto:` URI or the+public HTTPS URL of the installation. The same VAPID key pair should be kept+across deployments so existing browser subscriptions remain valid.+## Step 2: Complete mailflare setup1. Open the URL of the deployed `mailflare` Worker.diff --git a/docs/self-hosting.md b/docs/self-hosting.mdindex 651580b..ac4b660 100644--- a/docs/self-hosting.md+++ b/docs/self-hosting.md@@ -21,6 +21,21 @@ Behind a reverse proxy, set `APP_URL=https://mail.example.com` so links inpassword-reset mail and the JMAP session point at the public address, andforward WebSocket upgrades for `/api/realtime`.+### PWA and push notifications++Mailflare can be installed as a PWA and can deliver new-mail notifications+after the browser is closed. Generate one VAPID key pair for the installation:++```bash+npm run push:keys+```++Set the printed `VAPID_PUBLIC_KEY` and `VAPID_PRIVATE_KEY` values in the+runtime environment, plus `VAPID_SUBJECT` as either a `mailto:` contact or the+public HTTPS URL of the installation. Keep the private key secret. Browsers+require HTTPS for service workers and Web Push (localhost is the development+exception). Users can then enable push under **Settings → Inbox → Notifications**.+## Receiving mailPick one; both can be on at once.@@ -79,6 +94,9 @@ and the DNS page shows what to set by hand.| `CF_ACCOUNT_ID`, `CF_TOKEN` | unset | Cloudflare Email Sending, and zone management if the token allows || `INBOUND_WEBHOOK_SECRET` | unset | Enables `/api/inbound` for the relay Worker || `TURNSTILE_SECRET_KEY` | unset | Bot protection on login and reset forms (`NEXT_PUBLIC_TURNSTILE_SITE_KEY` at build time) |+| `VAPID_PUBLIC_KEY` | unset | Public Web Push application-server key |+| `VAPID_PRIVATE_KEY` | unset | Secret Web Push application-server key |+| `VAPID_SUBJECT` | unset | Web Push contact URI (`mailto:` or HTTPS) |## Operationsdiff --git a/drizzle/migrations/0032_add_push_subscriptions.sql b/drizzle/migrations/0032_add_push_subscriptions.sqlnew file mode 100644index 0000000..7924906--- /dev/null+++ b/drizzle/migrations/0032_add_push_subscriptions.sql@@ -0,0 +1,18 @@+CREATE TABLE `push_subscriptions` (+ `id` text PRIMARY KEY NOT NULL,+ `user_id` text NOT NULL,+ `session_id` text NOT NULL,+ `endpoint` text NOT NULL,+ `p256dh` text NOT NULL,+ `auth` text NOT NULL,+ `created_at` integer NOT NULL,+ `updated_at` integer NOT NULL,+ FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade,+ FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE cascade+);+--> statement-breakpoint+CREATE UNIQUE INDEX `push_subscriptions_endpoint_idx` ON `push_subscriptions` (`endpoint`);+--> statement-breakpoint+CREATE INDEX `push_subscriptions_user_idx` ON `push_subscriptions` (`user_id`);+--> statement-breakpoint+CREATE INDEX `push_subscriptions_session_idx` ON `push_subscriptions` (`session_id`);diff --git a/env.d.ts b/env.d.tsindex fbbe42d..e46efbb 100644--- a/env.d.ts+++ b/env.d.ts@@ -30,4 +30,10 @@ interface CloudflareEnv {CF_ACCOUNT_ID?: string;/** Public origin of this install (https://mail.example.com) when it sits behind a proxy. */APP_URL?: string;+ /** VAPID public key (uncompressed P-256 point, URL-safe base64) for Web Push. */+ VAPID_PUBLIC_KEY?: string;+ /** VAPID private scalar (URL-safe base64). Keep this secret. */+ VAPID_PRIVATE_KEY?: string;+ /** Contact URI for VAPID, e.g. mailto:[email protected] or https://mail.example.com. */+ VAPID_SUBJECT?: string;}diff --git a/package.json b/package.jsonindex 32b5a0b..8610d48 100644--- a/package.json+++ b/package.json@@ -14,6 +14,7 @@"upload": "npm run db:bundle && opennextjs-cloudflare build && OPEN_NEXT_DEPLOY=true wrangler versions upload","preview": "npm run db:bundle && opennextjs-cloudflare build && opennextjs-cloudflare preview","cf-typegen": "wrangler types --env-interface CloudflareEnv ./cloudflare-env.d.ts",+ "push:keys": "node scripts/generate-vapid-keys.mjs","db:bundle": "node scripts/generate-migration-bundle.mjs","db:generate": "drizzle-kit generate","db:migrate:local": "wrangler d1 migrations apply DB --local",diff --git a/public/icon-192.png b/public/icon-192.pngnew file mode 100644index 0000000..54af9b2Binary files /dev/null and b/public/icon-192.png differdiff --git a/public/icon-512.png b/public/icon-512.pngnew file mode 100644index 0000000..6122eb7Binary files /dev/null and b/public/icon-512.png differdiff --git a/public/sw.js b/public/sw.jsnew file mode 100644index 0000000..6c918fb--- /dev/null+++ b/public/sw.js@@ -0,0 +1,49 @@+const DEFAULT_NOTIFICATION = {+ title: "New email",+ body: "You have a new message",+ icon: "/icon-192.png",+ badge: "/icon-96.png",+ url: "/inbox",+};++self.addEventListener("push", (event) => {+ event.waitUntil(+ (async () => {+ const windows = await self.clients.matchAll({ type: "window", includeUncontrolled: true });+ if (windows.some((client) => client.visibilityState === "visible")) return;++ let payload = DEFAULT_NOTIFICATION;+ try {+ payload = { ...DEFAULT_NOTIFICATION, ...(event.data?.json() ?? {}) };+ } catch {+ // Keep the generic notification if a provider delivers an empty or malformed payload.+ }++ await self.registration.showNotification(payload.title, {+ body: payload.body,+ icon: payload.icon,+ badge: payload.badge,+ tag: payload.tag,+ data: { url: payload.url },+ });+ })(),+ );+});++self.addEventListener("notificationclick", (event) => {+ event.notification.close();+ const target = new URL(event.notification.data?.url || "/inbox", self.location.origin).href;+ event.waitUntil(+ (async () => {+ const windows = await self.clients.matchAll({ type: "window", includeUncontrolled: true });+ for (const client of windows) {+ if (client.url.startsWith(self.location.origin)) {+ await client.focus();+ await client.navigate(target);+ return;+ }+ }+ await self.clients.openWindow(target);+ })(),+ );+});diff --git a/scripts/generate-vapid-keys.mjs b/scripts/generate-vapid-keys.mjsnew file mode 100644index 0000000..330f2ea--- /dev/null+++ b/scripts/generate-vapid-keys.mjs@@ -0,0 +1,19 @@+import { webcrypto } from "node:crypto";++function base64Url(bytes) {+ return Buffer.from(bytes).toString("base64url");+}++const pair = await webcrypto.subtle.generateKey(+ { name: "ECDSA", namedCurve: "P-256" },+ true,+ ["sign", "verify"],+);+const publicKey = new Uint8Array(await webcrypto.subtle.exportKey("raw", pair.publicKey));+const privateJwk = await webcrypto.subtle.exportKey("jwk", pair.privateKey);++if (!privateJwk.d) throw new Error("Generated VAPID private key is missing its scalar");++console.log(`VAPID_PUBLIC_KEY=${base64Url(publicKey)}`);+console.log(`VAPID_PRIVATE_KEY=${privateJwk.d}`);+console.log("VAPID_SUBJECT=mailto:[email protected]");diff --git a/server/runtime/env.ts b/server/runtime/env.tsindex c3d3de3..7b66714 100644--- a/server/runtime/env.ts+++ b/server/runtime/env.ts@@ -61,6 +61,9 @@ export function createNodeRuntime(): NodeRuntime {MAILFLARE_RUNTIME: "node",APP_URL: optional("APP_URL")?.replace(/\/$/, ""),INBOUND_WEBHOOK_SECRET: optional("INBOUND_WEBHOOK_SECRET"),+ VAPID_PUBLIC_KEY: optional("VAPID_PUBLIC_KEY"),+ VAPID_PRIVATE_KEY: optional("VAPID_PRIVATE_KEY"),+ VAPID_SUBJECT: optional("VAPID_SUBJECT"),} as unknown as CloudflareEnv;return {diff --git a/src/app/(settings)/settings/inbox/page.tsx b/src/app/(settings)/settings/inbox/page.tsxindex 097200f..7573f3a 100644--- a/src/app/(settings)/settings/inbox/page.tsx+++ b/src/app/(settings)/settings/inbox/page.tsx@@ -2,10 +2,20 @@ import { InboxThreadingSettings } from "@/components/settings/inbox-threading-seimport { InboxShortcutsSettings } from "@/components/settings/inbox-shortcuts-settings";import { MailboxAutoReplyForm } from "@/components/settings/mailbox-auto-reply-form";import { SpamFilterSettings } from "@/components/settings/spam-filter-settings";+import { PushNotificationSettings } from "@/components/settings/push-notification-settings";export default function SettingsInboxPage() {return (<div className="space-y-8 py-4">+ <section className="space-y-4">+ <div>+ <h2 className="text-xl font-semibold text-neutral-900">Notifications</h2>+ <p className="mt-1 text-sm text-neutral-500">Choose how Mailflare alerts you about new messages.</p>+ </div>+ <div className="rounded-3xl bg-white p-6">+ <PushNotificationSettings />+ </div>+ </section><section className="space-y-4"><div><h2 className="text-xl font-semibold text-neutral-900">Spam protection</h2>diff --git a/src/app/api/push/config/route.ts b/src/app/api/push/config/route.tsnew file mode 100644index 0000000..af788b7--- /dev/null+++ b/src/app/api/push/config/route.ts@@ -0,0 +1,13 @@+import { NextResponse } from "next/server";+import { getEnv } from "@/lib/cloudflare";+import { requireSessionUser } from "@/lib/api/auth";+import { getVapidPublicKey } from "@/lib/push/server";++export async function GET(request: Request) {+ const env = getEnv();+ const auth = await requireSessionUser(env, request);+ if (auth.error) return auth.error;++ const publicKey = getVapidPublicKey(env);+ return NextResponse.json({ enabled: !!publicKey, publicKey });+}diff --git a/src/app/api/push/subscriptions/route.ts b/src/app/api/push/subscriptions/route.tsnew file mode 100644index 0000000..d9ad7eb--- /dev/null+++ b/src/app/api/push/subscriptions/route.ts@@ -0,0 +1,93 @@+import { and, eq } from "drizzle-orm";+import { NextResponse } from "next/server";+import { z } from "zod";+import { getDb } from "@/db";+import { pushSubscriptions } from "@/db/schema";+import { requireSessionUser } from "@/lib/api/auth";+import {+ getSessionFromToken,+ getSessionTokenFromRequestHeaders,+} from "@/lib/auth/session";+import { getEnv } from "@/lib/cloudflare";+import { newId } from "@/lib/ids";+import {+ getVapidPublicKey,+ hasValidPushKeys,+ isSupportedPushEndpoint,+} from "@/lib/push/server";++const subscriptionSchema = z.object({+ endpoint: z.string().url().max(4096),+ keys: z.object({+ p256dh: z.string().min(1).max(512),+ auth: z.string().min(1).max(256),+ }),+});++const deleteSchema = z.object({+ endpoint: z.string().url().max(4096),+});++export async function POST(request: Request) {+ const env = getEnv();+ const auth = await requireSessionUser(env, request);+ if (auth.error) return auth.error;+ if (!getVapidPublicKey(env)) {+ return NextResponse.json({ error: "Push notifications are not configured" }, { status: 503 });+ }++ const parsed = subscriptionSchema.safeParse(await request.json().catch(() => null));+ if (!parsed.success) return NextResponse.json({ error: "Invalid push subscription" }, { status: 400 });+ if (!isSupportedPushEndpoint(parsed.data.endpoint) || !hasValidPushKeys(parsed.data.keys)) {+ return NextResponse.json({ error: "Unsupported push subscription" }, { status: 400 });+ }++ const session = await getSessionFromToken(env, getSessionTokenFromRequestHeaders(request));+ if (!session || session.userId !== auth.user.id) {+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });+ }++ const now = new Date();+ await getDb(env)+ .insert(pushSubscriptions)+ .values({+ id: newId(),+ userId: auth.user.id,+ sessionId: session.id,+ endpoint: parsed.data.endpoint,+ p256dh: parsed.data.keys.p256dh,+ auth: parsed.data.keys.auth,+ createdAt: now,+ updatedAt: now,+ })+ .onConflictDoUpdate({+ target: pushSubscriptions.endpoint,+ set: {+ userId: auth.user.id,+ sessionId: session.id,+ p256dh: parsed.data.keys.p256dh,+ auth: parsed.data.keys.auth,+ updatedAt: now,+ },+ });++ return NextResponse.json({ ok: true });+}++export async function DELETE(request: Request) {+ const env = getEnv();+ const auth = await requireSessionUser(env, request);+ if (auth.error) return auth.error;+ const parsed = deleteSchema.safeParse(await request.json().catch(() => null));+ if (!parsed.success) return NextResponse.json({ error: "Invalid push subscription" }, { status: 400 });++ await getDb(env)+ .delete(pushSubscriptions)+ .where(+ and(+ eq(pushSubscriptions.userId, auth.user.id),+ eq(pushSubscriptions.endpoint, parsed.data.endpoint),+ ),+ );+ return NextResponse.json({ ok: true });+}diff --git a/src/app/layout.tsx b/src/app/layout.tsxindex 83e32b8..89f3bf0 100644--- a/src/app/layout.tsx+++ b/src/app/layout.tsx@@ -16,7 +16,12 @@ const geistMono = Geist_Mono({export const metadata: Metadata = {title: "Mailflare",description: "Multi-tenant email on Cloudflare",- icons: { icon: "/api/branding/icon" },+ icons: { icon: "/api/branding/icon", apple: "/icon-192.png" },+ appleWebApp: {+ capable: true,+ title: "Mailflare",+ statusBarStyle: "default",+ },robots: {index: false,follow: false,diff --git a/src/app/manifest.ts b/src/app/manifest.tsnew file mode 100644index 0000000..4387497--- /dev/null+++ b/src/app/manifest.ts@@ -0,0 +1,17 @@+import type { MetadataRoute } from "next";++export default function manifest(): MetadataRoute.Manifest {+ return {+ name: "Mailflare",+ short_name: "Mailflare",+ description: "Email, anywhere.",+ start_url: "/inbox",+ display: "standalone",+ background_color: "#ffffff",+ theme_color: "#ffffff",+ icons: [+ { src: "/icon-192.png", sizes: "192x192", type: "image/png" },+ { src: "/icon-512.png", sizes: "512x512", type: "image/png" },+ ],+ };+}diff --git a/src/components/providers.tsx b/src/components/providers.tsxindex 47f24d6..ca30a0d 100644--- a/src/components/providers.tsx+++ b/src/components/providers.tsx@@ -5,6 +5,7 @@ import { useEffect, useState } from "react";import { clearMailboxClientState } from "@/components/mailbox-provider-utils";import { BrandingProvider } from "@/components/branding-provider";import { NewMessagePopup } from "@/components/new-message-popup";+import { PwaServiceWorker } from "@/components/pwa-service-worker";import { useMessagePolling } from "@/hooks/use-message-polling";import { clearMessageClientState } from "@/hooks/utils";import { clearMessageDetailCache } from "@/lib/messages/detail-cache";@@ -42,6 +43,7 @@ export function Providers({ children }: { children: React.ReactNode }) {return (<QueryClientProvider client={client}><BrandingProvider>+ <PwaServiceWorker />{children}{realtime.notification && (<NewMessagePopupdiff --git a/src/components/pwa-service-worker.tsx b/src/components/pwa-service-worker.tsxnew file mode 100644index 0000000..d01e428--- /dev/null+++ b/src/components/pwa-service-worker.tsx@@ -0,0 +1,15 @@+"use client";++import { useEffect } from "react";+import { registerMailflareServiceWorker } from "@/lib/push/client";++export function PwaServiceWorker() {+ useEffect(() => {+ if (!("serviceWorker" in navigator)) return;+ void registerMailflareServiceWorker().catch((error) => {+ console.warn("Mailflare service worker registration failed", error);+ });+ }, []);++ return null;+}diff --git a/src/components/settings/push-notification-settings.tsx b/src/components/settings/push-notification-settings.tsxnew file mode 100644index 0000000..11b2f23--- /dev/null+++ b/src/components/settings/push-notification-settings.tsx@@ -0,0 +1,91 @@+"use client";++import { useEffect, useState } from "react";+import { Switch } from "@/components/ui/switch";+import {+ disablePushNotifications,+ enablePushNotifications,+ getPushState,+} from "@/lib/push/client";++type State = {+ loading: boolean;+ supported: boolean;+ configured: boolean;+ permission: NotificationPermission | "unsupported";+ subscribed: boolean;+ error: string | null;+};++const initialState: State = {+ loading: true,+ supported: false,+ configured: false,+ permission: "unsupported",+ subscribed: false,+ error: null,+};++export function PushNotificationSettings() {+ const [state, setState] = useState<State>(initialState);++ useEffect(() => {+ let cancelled = false;+ getPushState()+ .then((next) => {+ if (!cancelled) setState({ ...next, loading: false, error: null });+ })+ .catch((error) => {+ if (!cancelled) {+ setState((current) => ({+ ...current,+ loading: false,+ error: error instanceof Error ? error.message : "Failed to load notification settings",+ }));+ }+ });+ return () => {+ cancelled = true;+ };+ }, []);++ const disabled =+ state.loading ||+ !state.supported ||+ (!state.configured && !state.subscribed) ||+ (state.permission === "denied" && !state.subscribed);+ let description = "Get new mail alerts even when Mailflare is closed.";+ if (!state.supported) description = "This browser does not support Web Push for Mailflare.";+ else if (!state.configured) description = "Web Push has not been configured on this Mailflare server.";+ else if (state.permission === "denied") description = "Notifications are blocked in your browser settings.";++ return (+ <div>+ <label className="flex items-start gap-3 rounded-xl bg-neutral-50 p-4">+ <span className="flex-1">+ <span className="block text-sm font-medium text-neutral-900">Browser push notifications</span>+ <span className="mt-1 block text-sm text-neutral-500">{description}</span>+ </span>+ <Switch+ checked={state.subscribed}+ disabled={disabled}+ onCheckedChange={(enabled) => {+ setState((current) => ({ ...current, loading: true, error: null }));+ void (enabled ? enablePushNotifications() : disablePushNotifications())+ .then(() => getPushState())+ .then((next) => setState({ ...next, loading: false, error: null }))+ .catch((error) => {+ setState((current) => ({+ ...current,+ loading: false,+ error: error instanceof Error ? error.message : "Failed to update notifications",+ }));+ });+ }}+ aria-label="Enable browser push notifications"+ />+ </label>+ {state.error && <p className="mt-2 px-4 text-sm text-red-600">{state.error}</p>}+ </div>+ );+}diff --git a/src/db/schema/index.ts b/src/db/schema/index.tsindex ab39902..28cd1ec 100644--- a/src/db/schema/index.ts+++ b/src/db/schema/index.ts@@ -476,6 +476,33 @@ export const sessions = sqliteTable("sessions", {.$defaultFn(() => new Date()),});+export const pushSubscriptions = sqliteTable(+ "push_subscriptions",+ {+ id: text("id").primaryKey(),+ userId: text("user_id")+ .notNull()+ .references(() => users.id, { onDelete: "cascade" }),+ sessionId: text("session_id")+ .notNull()+ .references(() => sessions.id, { onDelete: "cascade" }),+ endpoint: text("endpoint").notNull(),+ p256dh: text("p256dh").notNull(),+ auth: text("auth").notNull(),+ createdAt: integer("created_at", { mode: "timestamp" })+ .notNull()+ .$defaultFn(() => new Date()),+ updatedAt: integer("updated_at", { mode: "timestamp" })+ .notNull()+ .$defaultFn(() => new Date()),+ },+ (t) => [+ uniqueIndex("push_subscriptions_endpoint_idx").on(t.endpoint),+ index("push_subscriptions_user_idx").on(t.userId),+ index("push_subscriptions_session_idx").on(t.sessionId),+ ],+);+/** Single-use links mailed to a user's recovery address. Only the hash is stored. */export const passwordResetTokens = sqliteTable("password_reset_tokens",@@ -636,6 +663,7 @@ export const schema = {webhooks,webhookDeliveries,sessions,+ pushSubscriptions,auditLogs,backupSettings,backups,diff --git a/src/hooks/message-realtime-utils.ts b/src/hooks/message-realtime-utils.tsindex 4c774ab..77b68bc 100644--- a/src/hooks/message-realtime-utils.ts+++ b/src/hooks/message-realtime-utils.ts@@ -1,4 +1,5 @@import type { NewMessageEvent } from "./message-realtime-types";+import { hasActivePushSubscription } from "@/lib/push/client";export const REALTIME_FALLBACK_INTERVAL_MS = 60_000;export const REALTIME_HEARTBEAT_INTERVAL_MS = 25_000;@@ -38,7 +39,7 @@ export function parseNewMessageEvent(value: string): NewMessageEvent | null {}}-export function showBrowserNewMessageNotification(event: NewMessageEvent): void {+export async function showBrowserNewMessageNotification(event: NewMessageEvent): Promise<void> {if (typeof Notification === "undefined" ||Notification.permission !== "granted" ||@@ -46,6 +47,7 @@ export function showBrowserNewMessageNotification(event: NewMessageEvent): void) {return;}+ if (await hasActivePushSubscription().catch(() => false)) return;const notification = new Notification(event.subject || "New email", {body: `From ${event.fromName ?? event.from}`,diff --git a/src/hooks/use-message-polling.ts b/src/hooks/use-message-polling.tsindex 43c3289..b93fa6d 100644--- a/src/hooks/use-message-polling.ts+++ b/src/hooks/use-message-polling.ts@@ -74,7 +74,7 @@ export function useMessagePolling(): MessageRealtimeState {if (!event) return;dispatchMessagesChanged();setNotification(event);- showBrowserNewMessageNotification(event);+ void showBrowserNewMessageNotification(event);};socket.onerror = () => socket?.close();socket.onclose = scheduleReconnect;diff --git a/src/lib/auth/session.ts b/src/lib/auth/session.tsindex 722b8aa..8e8ff9b 100644--- a/src/lib/auth/session.ts+++ b/src/lib/auth/session.ts@@ -38,6 +38,17 @@ export async function getUserFromSession(env: CloudflareEnv,token: string | undefined,): Promise<typeof users.$inferSelect | null> {+ const session = await getSessionFromToken(env, token);+ if (!session) return null;+ const db = getDb(env);+ const [user] = await db.select().from(users).where(eq(users.id, session.userId)).limit(1);+ return user ?? null;+}++export async function getSessionFromToken(+ env: CloudflareEnv,+ token: string | undefined,+): Promise<typeof sessions.$inferSelect | null> {if (!token) return null;const db = getDb(env);const tokenHash = await hashSessionToken(token);@@ -46,9 +57,7 @@ export async function getUserFromSession(.from(sessions).where(and(eq(sessions.tokenHash, tokenHash), gt(sessions.expiresAt, new Date()))).limit(1);- if (!session) return null;- const [user] = await db.select().from(users).where(eq(users.id, session.userId)).limit(1);- return user ?? null;+ return session ?? null;}export async function deleteSession(env: CloudflareEnv, token: string): Promise<void> {diff --git a/src/lib/push/client.ts b/src/lib/push/client.tsnew file mode 100644index 0000000..69fea32--- /dev/null+++ b/src/lib/push/client.ts@@ -0,0 +1,139 @@+"use client";++import { authFetch } from "@/lib/auth/client";++type PushConfigResponse = {+ enabled: boolean;+ publicKey: string | null;+};++function toArrayBuffer(bytes: Uint8Array): ArrayBuffer {+ const buffer = new ArrayBuffer(bytes.byteLength);+ new Uint8Array(buffer).set(bytes);+ return buffer;+}++function decodeBase64Url(value: string): Uint8Array {+ const normalized = value.replace(/-/g, "+").replace(/_/g, "/");+ const padded = normalized + "=".repeat((4 - (normalized.length % 4)) % 4);+ const binary = atob(padded);+ return Uint8Array.from(binary, (char) => char.charCodeAt(0));+}++export function browserSupportsPush(): boolean {+ return (+ typeof window !== "undefined" &&+ window.isSecureContext &&+ "serviceWorker" in navigator &&+ "PushManager" in window &&+ "Notification" in window+ );+}++export async function registerMailflareServiceWorker(): Promise<ServiceWorkerRegistration> {+ if (!("serviceWorker" in navigator)) throw new Error("Service workers are not supported by this browser");+ const registration = await navigator.serviceWorker.register("/sw.js", { scope: "/" });+ return registration;+}++async function loadPushConfig(): Promise<PushConfigResponse> {+ const response = await authFetch("/api/push/config", { redirectOnUnauthorized: false });+ if (!response.ok) throw new Error("Failed to load push notification settings");+ return (await response.json()) as PushConfigResponse;+}++async function saveSubscription(subscription: PushSubscription): Promise<void> {+ const json = subscription.toJSON();+ if (!json.endpoint || !json.keys?.p256dh || !json.keys?.auth) {+ throw new Error("Browser returned an incomplete push subscription");+ }+ const response = await authFetch("/api/push/subscriptions", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ endpoint: json.endpoint,+ keys: { p256dh: json.keys.p256dh, auth: json.keys.auth },+ }),+ redirectOnUnauthorized: false,+ });+ if (!response.ok) {+ const data = (await response.json().catch(() => null)) as { error?: string } | null;+ throw new Error(data?.error || "Failed to save push subscription");+ }+}++export async function getPushState(): Promise<{+ supported: boolean;+ configured: boolean;+ permission: NotificationPermission | "unsupported";+ subscribed: boolean;+}> {+ if (!browserSupportsPush()) {+ return { supported: false, configured: false, permission: "unsupported", subscribed: false };+ }+ const [config, registration] = await Promise.all([+ loadPushConfig(),+ registerMailflareServiceWorker(),+ ]);+ const subscription = await registration.pushManager.getSubscription();+ if (subscription && config.enabled && Notification.permission === "granted") {+ await saveSubscription(subscription);+ }+ return {+ supported: true,+ configured: config.enabled && !!config.publicKey,+ permission: Notification.permission,+ subscribed: !!subscription && Notification.permission === "granted",+ };+}++export async function enablePushNotifications(): Promise<void> {+ if (!browserSupportsPush()) throw new Error("Push notifications are not supported by this browser");+ const permission = await Notification.requestPermission();+ if (permission !== "granted") throw new Error("Notification permission was not granted");++ const config = await loadPushConfig();+ if (!config.enabled || !config.publicKey) throw new Error("Push notifications are not configured on this server");++ const registration = await registerMailflareServiceWorker();+ let subscription = await registration.pushManager.getSubscription();+ if (!subscription) {+ subscription = await registration.pushManager.subscribe({+ userVisibleOnly: true,+ applicationServerKey: toArrayBuffer(decodeBase64Url(config.publicKey)),+ });+ }++ try {+ await saveSubscription(subscription);+ } catch (error) {+ await subscription.unsubscribe().catch(() => false);+ throw error;+ }+}++export async function disablePushNotifications(): Promise<void> {+ if (!("serviceWorker" in navigator)) return;+ const registration = await navigator.serviceWorker.getRegistration("/");+ const subscription = await registration?.pushManager.getSubscription();+ if (!subscription) return;++ const response = await authFetch("/api/push/subscriptions", {+ method: "DELETE",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ endpoint: subscription.endpoint }),+ redirectOnUnauthorized: false,+ });+ if (!response.ok) throw new Error("Failed to disable push notifications");+ await subscription.unsubscribe();+}++export async function hasActivePushSubscription(): Promise<boolean> {+ if (!("serviceWorker" in navigator) || Notification.permission !== "granted") return false;+ const [registration, config] = await Promise.all([+ navigator.serviceWorker.getRegistration("/"),+ loadPushConfig(),+ ]);+ if (!config.enabled) return false;+ return !!(await registration?.pushManager.getSubscription());+}diff --git a/src/lib/push/server.ts b/src/lib/push/server.tsnew file mode 100644index 0000000..0c74810--- /dev/null+++ b/src/lib/push/server.ts@@ -0,0 +1,297 @@+import { and, eq, gt, inArray } from "drizzle-orm";+import { getDb } from "@/db";+import { pushSubscriptions, sessions } from "@/db/schema";+import type { NewMessageNotification } from "@/lib/realtime/types";++type VapidConfig = {+ publicKey: string;+ privateKey: string;+ subject: string;+};++type PushSubscriptionKeys = {+ p256dh: string;+ auth: string;+};++const encoder = new TextEncoder();+const PUSH_ENDPOINT_HOSTS = new Set([+ "fcm.googleapis.com",+ "push.services.mozilla.com",+ "updates.push.services.mozilla.com",+ "web.push.apple.com",+]);++function toArrayBuffer(bytes: Uint8Array): ArrayBuffer {+ const buffer = new ArrayBuffer(bytes.byteLength);+ new Uint8Array(buffer).set(bytes);+ return buffer;+}++function concatBytes(...chunks: Uint8Array[]): Uint8Array {+ const output = new Uint8Array(chunks.reduce((total, chunk) => total + chunk.length, 0));+ let offset = 0;+ for (const chunk of chunks) {+ output.set(chunk, offset);+ offset += chunk.length;+ }+ return output;+}++function decodeBase64Url(value: string): Uint8Array {+ const normalized = value.replace(/-/g, "+").replace(/_/g, "/");+ const padded = normalized + "=".repeat((4 - (normalized.length % 4)) % 4);+ const binary = atob(padded);+ return Uint8Array.from(binary, (char) => char.charCodeAt(0));+}++function encodeBase64Url(value: Uint8Array): string {+ let binary = "";+ for (const byte of value) binary += String.fromCharCode(byte);+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");+}++function encodeJson(value: unknown): string {+ return encodeBase64Url(encoder.encode(JSON.stringify(value)));+}++async function hmacSha256(keyBytes: Uint8Array, data: Uint8Array): Promise<Uint8Array> {+ const key = await crypto.subtle.importKey(+ "raw",+ toArrayBuffer(keyBytes),+ { name: "HMAC", hash: "SHA-256" },+ false,+ ["sign"],+ );+ return new Uint8Array(await crypto.subtle.sign("HMAC", key, toArrayBuffer(data)));+}++async function hkdf(+ salt: Uint8Array,+ inputKeyMaterial: Uint8Array,+ info: Uint8Array,+ length: number,+): Promise<Uint8Array> {+ if (length > 32) throw new Error("Web Push HKDF output is too long");+ const prk = await hmacSha256(salt, inputKeyMaterial);+ const block = await hmacSha256(prk, concatBytes(info, new Uint8Array([1])));+ return block.slice(0, length);+}++function parseVapidConfig(env: CloudflareEnv): VapidConfig | null {+ const publicKey = env.VAPID_PUBLIC_KEY?.trim();+ const privateKey = env.VAPID_PRIVATE_KEY?.trim();+ const subject = env.VAPID_SUBJECT?.trim();+ if (!publicKey || !privateKey || !subject) return null;++ try {+ const publicBytes = decodeBase64Url(publicKey);+ const privateBytes = decodeBase64Url(privateKey);+ const subjectUrl = new URL(subject);+ if (+ publicBytes.length !== 65 ||+ publicBytes[0] !== 4 ||+ privateBytes.length !== 32 ||+ !(["mailto:", "https:"] as string[]).includes(subjectUrl.protocol)+ ) {+ return null;+ }+ } catch {+ return null;+ }++ return { publicKey, privateKey, subject };+}++export function getVapidPublicKey(env: CloudflareEnv): string | null {+ return parseVapidConfig(env)?.publicKey ?? null;+}++export function isSupportedPushEndpoint(endpoint: string): boolean {+ try {+ const url = new URL(endpoint);+ if (url.protocol !== "https:") return false;+ return PUSH_ENDPOINT_HOSTS.has(url.hostname) || url.hostname.endsWith(".notify.windows.com");+ } catch {+ return false;+ }+}++export function hasValidPushKeys(keys: PushSubscriptionKeys): boolean {+ try {+ return decodeBase64Url(keys.p256dh).length === 65 && decodeBase64Url(keys.auth).length === 16;+ } catch {+ return false;+ }+}++async function createVapidAuthorization(config: VapidConfig, endpoint: string): Promise<string> {+ const audience = new URL(endpoint).origin;+ const publicBytes = decodeBase64Url(config.publicKey);+ const privateBytes = decodeBase64Url(config.privateKey);+ const signingKey = await crypto.subtle.importKey(+ "jwk",+ {+ kty: "EC",+ crv: "P-256",+ x: encodeBase64Url(publicBytes.slice(1, 33)),+ y: encodeBase64Url(publicBytes.slice(33, 65)),+ d: encodeBase64Url(privateBytes),+ ext: true,+ },+ { name: "ECDSA", namedCurve: "P-256" },+ false,+ ["sign"],+ );+ const unsignedToken = `${encodeJson({ typ: "JWT", alg: "ES256" })}.${encodeJson({+ aud: audience,+ exp: Math.floor(Date.now() / 1000) + 12 * 60 * 60,+ sub: config.subject,+ })}`;+ const signature = new Uint8Array(+ await crypto.subtle.sign(+ { name: "ECDSA", hash: "SHA-256" },+ signingKey,+ encoder.encode(unsignedToken),+ ),+ );+ return `vapid t=${unsignedToken}.${encodeBase64Url(signature)}, k=${config.publicKey}`;+}++async function encryptPushPayload(keys: PushSubscriptionKeys, payload: string): Promise<Uint8Array> {+ const clientPublicBytes = decodeBase64Url(keys.p256dh);+ const authSecret = decodeBase64Url(keys.auth);+ const clientPublicKey = await crypto.subtle.importKey(+ "raw",+ toArrayBuffer(clientPublicBytes),+ { name: "ECDH", namedCurve: "P-256" },+ false,+ [],+ );+ const serverKeys = await crypto.subtle.generateKey(+ { name: "ECDH", namedCurve: "P-256" },+ true,+ ["deriveBits"],+ );+ const serverPublicBytes = new Uint8Array(await crypto.subtle.exportKey("raw", serverKeys.publicKey));+ const sharedSecret = new Uint8Array(+ await crypto.subtle.deriveBits(+ { name: "ECDH", public: clientPublicKey },+ serverKeys.privateKey,+ 256,+ ),+ );+ const keyInfo = concatBytes(+ encoder.encode("WebPush: info\0"),+ clientPublicBytes,+ serverPublicBytes,+ );+ const inputKeyMaterial = await hkdf(authSecret, sharedSecret, keyInfo, 32);+ const salt = crypto.getRandomValues(new Uint8Array(16));+ const contentEncryptionKey = await hkdf(+ salt,+ inputKeyMaterial,+ encoder.encode("Content-Encoding: aes128gcm\0"),+ 16,+ );+ const nonce = await hkdf(+ salt,+ inputKeyMaterial,+ encoder.encode("Content-Encoding: nonce\0"),+ 12,+ );+ const aesKey = await crypto.subtle.importKey(+ "raw",+ toArrayBuffer(contentEncryptionKey),+ "AES-GCM",+ false,+ ["encrypt"],+ );+ const plaintext = concatBytes(encoder.encode(payload), new Uint8Array([2]));+ const ciphertext = new Uint8Array(+ await crypto.subtle.encrypt(+ { name: "AES-GCM", iv: toArrayBuffer(nonce) },+ aesKey,+ toArrayBuffer(plaintext),+ ),+ );+ const header = new Uint8Array(21 + serverPublicBytes.length);+ header.set(salt, 0);+ new DataView(header.buffer).setUint32(16, 4096);+ header[20] = serverPublicBytes.length;+ header.set(serverPublicBytes, 21);+ return concatBytes(header, ciphertext);+}++async function sendSubscriptionPush(+ config: VapidConfig,+ subscription: { endpoint: string; p256dh: string; auth: string },+ payload: string,+): Promise<Response> {+ const body = await encryptPushPayload(subscription, payload);+ return fetch(subscription.endpoint, {+ method: "POST",+ headers: {+ Authorization: await createVapidAuthorization(config, subscription.endpoint),+ "Content-Encoding": "aes128gcm",+ "Content-Type": "application/octet-stream",+ TTL: "86400",+ Urgency: "normal",+ },+ body: toArrayBuffer(body),+ });+}++export async function sendPushNotifications(+ env: CloudflareEnv,+ userIds: string[],+ payload: NewMessageNotification,+): Promise<void> {+ const config = parseVapidConfig(env);+ const uniqueUserIds = [...new Set(userIds)];+ if (!config || uniqueUserIds.length === 0) return;++ const db = getDb(env);+ const subscriptions = await db+ .select({+ id: pushSubscriptions.id,+ endpoint: pushSubscriptions.endpoint,+ p256dh: pushSubscriptions.p256dh,+ auth: pushSubscriptions.auth,+ })+ .from(pushSubscriptions)+ .innerJoin(sessions, eq(pushSubscriptions.sessionId, sessions.id))+ .where(+ and(+ inArray(pushSubscriptions.userId, uniqueUserIds),+ gt(sessions.expiresAt, new Date()),+ ),+ );++ const title = (payload.subject || "New email").slice(0, 180);+ const sender = (payload.fromName ?? payload.from).slice(0, 240);+ const notificationPayload = JSON.stringify({+ title,+ body: `From ${sender}`,+ icon: "/icon-192.png",+ badge: "/icon-96.png",+ tag: payload.messageId,+ url: `/inbox/${payload.messageId}`,+ });++ await Promise.allSettled(+ subscriptions.map(async (subscription) => {+ if (!isSupportedPushEndpoint(subscription.endpoint)) return;+ try {+ const response = await sendSubscriptionPush(config, subscription, notificationPayload);+ if (response.status === 404 || response.status === 410) {+ await db.delete(pushSubscriptions).where(eq(pushSubscriptions.id, subscription.id));+ } else if (!response.ok) {+ console.warn(`Web Push delivery failed (${response.status}) for subscription ${subscription.id}`);+ }+ } catch (error) {+ console.warn(`Web Push delivery failed for subscription ${subscription.id}`, error);+ }+ }),+ );+}diff --git a/src/lib/realtime/utils.ts b/src/lib/realtime/utils.tsindex 732acdc..23994f8 100644--- a/src/lib/realtime/utils.ts+++ b/src/lib/realtime/utils.ts@@ -3,6 +3,7 @@ import { getDb } from "@/db";import { domains, mailboxAccess, mailboxes } from "@/db/schema";import { isTeamMailboxSharingEnabled } from "@/lib/mailboxes/access-utils";import type { NewMessageNotification } from "./types";+import { sendPushNotifications } from "@/lib/push/server";export function getSessionTokenFromRequest(request: Request): string | undefined {const cookie = request.headers.get("Cookie");@@ -53,8 +54,8 @@ export async function notifyUsersOfNewMessage(userIds: string[],payload: NewMessageNotification,): Promise<void> {- await Promise.allSettled(- userIds.map((userId) => {+ await Promise.allSettled([+ ...userIds.map((userId) => {const hub = env.REALTIME.getByName(userId);return hub.fetch("https://mailflare-realtime/notify", {method: "POST",@@ -62,5 +63,6 @@ export async function notifyUsersOfNewMessage(body: JSON.stringify(payload),});}),- );+ sendPushNotifications(env, userIds, payload),+ ]);}