commit
Meow
diff --git a/app/app/build.gradle.kts b/app/app/build.gradle.kts
index 9e11881..8c130e8 100644
--- a/app/app/build.gradle.kts
+++ b/app/app/build.gradle.kts
@@ -7,6 +7,11 @@ plugins {
id("org.jetbrains.kotlin.plugin.serialization")
}
+// Firebase (notifications) is switched on by dropping the project's
+// google-services.json next to this file. Without it the app builds and runs,
+// just without notifications.
+if (file("google-services.json").exists()) apply(plugin = "com.google.gms.google-services")
+
// Signing details live in keystore.properties (not committed). Without it the
// release build is left unsigned.
val keystoreProps = Properties().apply {
@@ -81,6 +86,10 @@ dependencies {
implementation("androidx.lifecycle:lifecycle-process:2.8.7")
implementation("androidx.browser:browser:1.8.0")
+ implementation(platform("com.google.firebase:firebase-bom:33.7.0"))
+ implementation("com.google.firebase:firebase-messaging")
+ implementation("org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.9.0")
+
implementation("com.squareup.okhttp3:okhttp:4.12.0")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.3")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.9.0")
diff --git a/app/app/src/main/AndroidManifest.xml b/app/app/src/main/AndroidManifest.xml
index d453b7e..9ac92fe 100644
--- a/app/app/src/main/AndroidManifest.xml
+++ b/app/app/src/main/AndroidManifest.xml
@@ -2,6 +2,7 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
+ <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<!-- Custom Tabs for signing in: lets us find a browser that supports them. -->
<queries>
@@ -50,5 +51,14 @@
<data android:pathPrefix="/bin" />
</intent-filter>
</activity>
+
+ <!-- New-mail notifications from the Worker, through Firebase. -->
+ <service
+ android:name=".PushService"
+ android:exported="false">
+ <intent-filter>
+ <action android:name="com.google.firebase.MESSAGING_EVENT" />
+ </intent-filter>
+ </service>
</application>
</manifest>
diff --git a/app/app/src/main/java/gay/doughmination/mail/Push.kt b/app/app/src/main/java/gay/doughmination/mail/Push.kt
new file mode 100644
index 0000000..5e5bb23
--- /dev/null
+++ b/app/app/src/main/java/gay/doughmination/mail/Push.kt
@@ -0,0 +1,102 @@
+package gay.doughmination.mail
+
+import android.Manifest
+import android.app.NotificationChannel
+import android.app.NotificationManager
+import android.app.PendingIntent
+import android.content.Context
+import android.content.Intent
+import android.content.pm.PackageManager
+import android.net.Uri
+import android.os.Build
+import android.util.Log
+import androidx.core.app.NotificationCompat
+import androidx.core.app.NotificationManagerCompat
+import androidx.core.content.ContextCompat
+import com.google.firebase.FirebaseApp
+import com.google.firebase.messaging.FirebaseMessaging
+import com.google.firebase.messaging.FirebaseMessagingService
+import com.google.firebase.messaging.RemoteMessage
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.tasks.await
+
+/**
+ * New-mail notifications. When Resend's webhook delivers an email, the Worker
+ * sends a data message through Firebase to every install's FCM token; this
+ * turns it into a notification that opens the thread.
+ */
+object Push {
+ private const val CHANNEL = "mail"
+ private const val TAG = "Push"
+
+ /** False when the build has no google-services.json. */
+ fun available(context: Context): Boolean = FirebaseApp.getApps(context).isNotEmpty()
+
+ /** Tells the server where to reach this install. Called after sign-in. */
+ suspend fun register(app: InboxApp) {
+ if (!available(app)) return
+ runCatching { app.api.registerFcm(FirebaseMessaging.getInstance().token.await()) }
+ .onFailure { Log.w(TAG, "couldn't register for notifications", it) }
+ }
+
+ /** Before signing out: stop this install getting the account's mail. */
+ suspend fun unregister(app: InboxApp) {
+ if (!available(app)) return
+ runCatching {
+ val messaging = FirebaseMessaging.getInstance()
+ app.api.unregisterFcm(messaging.token.await())
+ // A fresh token next time, so nothing old can still point here.
+ messaging.deleteToken().await()
+ }.onFailure { Log.w(TAG, "couldn't unregister from notifications", it) }
+ }
+
+ fun show(context: Context, data: Map<String, String>) {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
+ ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED
+ ) return
+
+ val manager = context.getSystemService(NotificationManager::class.java)
+ if (manager.getNotificationChannel(CHANNEL) == null) {
+ manager.createNotificationChannel(NotificationChannel(CHANNEL, "New mail", NotificationManager.IMPORTANCE_HIGH))
+ }
+
+ val tag = data["tag"] ?: data.hashCode().toString()
+ // Same URLs as the site's, which MainActivity already knows how to open.
+ val open = Intent(Intent.ACTION_VIEW, Uri.parse(BuildConfig.INBOX_URL + (data["url"] ?: "/inbox")), context, MainActivity::class.java)
+ val tap = PendingIntent.getActivity(
+ context,
+ tag.hashCode(),
+ open,
+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
+ )
+ val notification = NotificationCompat.Builder(context, CHANNEL)
+ .setSmallIcon(R.drawable.ic_notification)
+ .setColor(0xFFEB459E.toInt())
+ .setContentTitle(data["title"] ?: "New email")
+ .setContentText(data["body"].orEmpty())
+ .setStyle(NotificationCompat.BigTextStyle().bigText(data["body"].orEmpty()))
+ .setCategory(NotificationCompat.CATEGORY_EMAIL)
+ .setContentIntent(tap)
+ .setAutoCancel(true)
+ .build()
+ NotificationManagerCompat.from(context).notify(tag, 0, notification)
+ }
+}
+
+class PushService : FirebaseMessagingService() {
+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
+
+ override fun onMessageReceived(message: RemoteMessage) {
+ if (message.data.isNotEmpty()) Push.show(this, message.data)
+ }
+
+ /** Firebase rotated this install's token; the server needs the new one. */
+ override fun onNewToken(token: String) {
+ val app = application as InboxApp
+ if (!app.signedIn.value) return
+ scope.launch { runCatching { app.api.registerFcm(token) } }
+ }
+}
diff --git a/app/app/src/main/java/gay/doughmination/mail/data/Api.kt b/app/app/src/main/java/gay/doughmination/mail/data/Api.kt
index a6d5143..653c89b 100644
--- a/app/app/src/main/java/gay/doughmination/mail/data/Api.kt
+++ b/app/app/src/main/java/gay/doughmination/mail/data/Api.kt
@@ -93,6 +93,8 @@ class Api(val baseUrl: String, private val tokens: TokenStore, private val onSig
@Serializable private data class Read(val read: Boolean)
@Serializable private data class Star(val starred: Boolean)
@Serializable private data class Name(val name: String)
+ @Serializable data class PushResult(val sent: Int, val pruned: Int = 0)
+ @Serializable private data class FcmToken(val token: String)
@Serializable private data class CodeSwap(val code: String, val verifier: String)
@Serializable private data class Token(val token: String)
@@ -127,6 +129,11 @@ class Api(val baseUrl: String, private val tokens: TokenStore, private val onSig
suspend fun updateDraft(id: String, input: SendRequest): String = call<Id, SendRequest>("PUT", "/api/drafts/$id", input).id
suspend fun send(input: SendRequest): Sent = call("POST", "/api/send", input)
+ suspend fun registerFcm(token: String) { call<JsonObject, FcmToken>("POST", "/api/push/fcm", FcmToken(token)) }
+ suspend fun unregisterFcm(token: String) { call<JsonObject, FcmToken>("POST", "/api/push/fcm/unregister", FcmToken(token)) }
+ /** Sends a test notification to every device; returns how many it reached. */
+ suspend fun pushTest(): Int = call<PushResult>("POST", "/api/push/test").sent
+
fun attachmentUrl(id: String, inline: Boolean = false): String =
"$baseUrl/api/attachments/$id${if (inline) "?inline=1" else ""}"
diff --git a/app/app/src/main/java/gay/doughmination/mail/ui/AppRoot.kt b/app/app/src/main/java/gay/doughmination/mail/ui/AppRoot.kt
index bada636..03659f1 100644
--- a/app/app/src/main/java/gay/doughmination/mail/ui/AppRoot.kt
+++ b/app/app/src/main/java/gay/doughmination/mail/ui/AppRoot.kt
@@ -1,6 +1,13 @@
package gay.doughmination.mail.ui
+import android.Manifest
+import android.content.pm.PackageManager
+import android.os.Build
import androidx.activity.compose.BackHandler
+import androidx.activity.compose.rememberLauncherForActivityResult
+import androidx.activity.result.contract.ActivityResultContracts
+import androidx.core.content.ContextCompat
+import gay.doughmination.mail.Push
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
@@ -59,6 +66,7 @@ fun AppRoot(vm: MailViewModel) {
LoginScreen(vm)
return@Surface
}
+ AskForNotifications()
BackHandler(enabled = vm.stack.size > 1) { vm.back() }
AnimatedContent(
targetState = vm.screen,
@@ -76,6 +84,20 @@ fun AppRoot(vm: MailViewModel) {
}
}
+/** Android 13+ needs permission before any notification shows; asked once signed in. */
+@Composable
+private fun AskForNotifications() {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return
+ val context = LocalContext.current
+ if (!Push.available(context)) return
+ val ask = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) {}
+ LaunchedEffect(Unit) {
+ val granted = ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) ==
+ PackageManager.PERMISSION_GRANTED
+ if (!granted) ask.launch(Manifest.permission.POST_NOTIFICATIONS)
+ }
+}
+
@Composable
private fun LoginScreen(vm: MailViewModel) {
val context = LocalContext.current
diff --git a/app/app/src/main/java/gay/doughmination/mail/ui/MailViewModel.kt b/app/app/src/main/java/gay/doughmination/mail/ui/MailViewModel.kt
index f0902bc..6391cae 100644
--- a/app/app/src/main/java/gay/doughmination/mail/ui/MailViewModel.kt
+++ b/app/app/src/main/java/gay/doughmination/mail/ui/MailViewModel.kt
@@ -11,6 +11,7 @@ import androidx.compose.runtime.setValue
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import gay.doughmination.mail.InboxApp
+import gay.doughmination.mail.Push
import gay.doughmination.mail.data.ApiException
import gay.doughmination.mail.data.AttachmentInfo
import gay.doughmination.mail.data.ListFolder
@@ -161,6 +162,7 @@ class MailViewModel(application: Application) : AndroidViewModel(application) {
}
fun signOut() = viewModelScope.launch {
+ Push.unregister(inbox)
api.logout()
inbox.setSignedIn(false)
}
@@ -185,6 +187,7 @@ class MailViewModel(application: Application) : AndroidViewModel(application) {
fail(e)
}
reload()
+ Push.register(inbox)
}
private suspend fun refreshUnread() {
@@ -602,6 +605,15 @@ class MailViewModel(application: Application) : AndroidViewModel(application) {
}
}
+ fun testPush() = viewModelScope.launch {
+ try {
+ val n = api.pushTest()
+ say(if (n == 0) "No devices have notifications on yet." else "Sent to $n device(s).")
+ } catch (e: Exception) {
+ fail(e)
+ }
+ }
+
/** Returns false when there's nowhere to go back to. */
fun back(): Boolean {
when {
diff --git a/app/app/src/main/java/gay/doughmination/mail/ui/SettingsScreen.kt b/app/app/src/main/java/gay/doughmination/mail/ui/SettingsScreen.kt
index d976eb7..dbc32cd 100644
--- a/app/app/src/main/java/gay/doughmination/mail/ui/SettingsScreen.kt
+++ b/app/app/src/main/java/gay/doughmination/mail/ui/SettingsScreen.kt
@@ -1,6 +1,8 @@
package gay.doughmination.mail.ui
+import android.content.Intent
import android.net.Uri
+import android.provider.Settings
import androidx.browser.customtabs.CustomTabsIntent
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
@@ -15,6 +17,9 @@ import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.outlined.ArrowBack
import androidx.compose.material.icons.automirrored.outlined.Logout
import androidx.compose.material.icons.outlined.Description
+import androidx.compose.material.icons.outlined.Notifications
+import androidx.compose.material.icons.outlined.NotificationsActive
+import androidx.compose.material.icons.outlined.NotificationsOff
import androidx.compose.material.icons.outlined.PrivacyTip
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
@@ -37,6 +42,7 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import gay.doughmination.mail.BuildConfig
+import gay.doughmination.mail.Push
@OptIn(ExperimentalMaterial3Api::class)
@Composable
@@ -85,6 +91,31 @@ fun SettingsScreen(vm: MailViewModel) {
if (me?.addresses.isNullOrEmpty()) Text("None yet. Ask an admin to switch on a domain.", color = Muted)
}
HorizontalDivider()
+ if (Push.available(context)) {
+ ListItem(
+ headlineContent = { Text("Notification settings") },
+ supportingContent = { Text("Turn new-mail notifications on or off") },
+ leadingContent = { Icon(Icons.Outlined.Notifications, null) },
+ modifier = Modifier.clickable {
+ context.startActivity(
+ Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS)
+ .putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName),
+ )
+ },
+ )
+ ListItem(
+ headlineContent = { Text("Send a test notification") },
+ leadingContent = { Icon(Icons.Outlined.NotificationsActive, null) },
+ modifier = Modifier.clickable { vm.testPush() },
+ )
+ } else {
+ ListItem(
+ headlineContent = { Text("Notifications") },
+ supportingContent = { Text("This build has no Firebase setup, so notifications are off.") },
+ leadingContent = { Icon(Icons.Outlined.NotificationsOff, null) },
+ )
+ }
+ HorizontalDivider()
ListItem(
headlineContent = { Text("Privacy policy") },
leadingContent = { Icon(Icons.Outlined.PrivacyTip, null) },
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index 70dfb63..5beb9b9 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -3,4 +3,5 @@ plugins {
id("org.jetbrains.kotlin.android") version "2.0.21" apply false
id("org.jetbrains.kotlin.plugin.compose") version "2.0.21" apply false
id("org.jetbrains.kotlin.plugin.serialization") version "2.0.21" apply false
+ id("com.google.gms.google-services") version "4.4.2" apply false
}
diff --git a/email/.dev.vars.example b/email/.dev.vars.example
index ac4d5fc..6f163f2 100644
--- a/email/.dev.vars.example
+++ b/email/.dev.vars.example
@@ -5,3 +5,4 @@ VAPID_PRIVATE_KEY=
COOKIE_SECURE=false
OIDC_REDIRECT_URI=http://localhost:5173/auth/callback
OIDC_POST_LOGOUT_REDIRECT_URI=http://localhost:5173
+FCM_SERVICE_ACCOUNT=
diff --git a/email/migrations/0007_fcm_tokens.sql b/email/migrations/0007_fcm_tokens.sql
new file mode 100644
index 0000000..2898b2f
--- /dev/null
+++ b/email/migrations/0007_fcm_tokens.sql
@@ -0,0 +1,8 @@
+-- Devices running the Android app, which get notifications through Firebase
+-- Cloud Messaging rather than Web Push. One row per app install's FCM token.
+CREATE TABLE fcm_tokens (
+ token TEXT PRIMARY KEY,
+ username TEXT NOT NULL COLLATE NOCASE REFERENCES users (username) ON DELETE CASCADE,
+ created_at INTEGER NOT NULL
+);
+CREATE INDEX fcm_user ON fcm_tokens (username);
diff --git a/email/src/worker/routes/mail.ts b/email/src/worker/routes/mail.ts
index 4802bc6..a0c70a0 100644
--- a/email/src/worker/routes/mail.ts
+++ b/email/src/worker/routes/mail.ts
@@ -20,6 +20,7 @@ import {
unreadByMailbox,
} from "../services/messages";
import { ComposeError, saveDraft, sendDraft } from "../services/outbound";
+import { addFcmToken, removeFcmToken } from "../services/fcm";
import { addSubscription, notifyUser, pushPublicKey, removeSubscription } from "../services/push";
const address = z.string().max(320).refine(isAddress, "Not an email address");
@@ -208,6 +209,17 @@ export const mail = new Hono<AppEnv>()
return c.json({ ok: true });
})
+ /** The Android app's FCM token, registered after sign-in and whenever Firebase rotates it. */
+ .post("/push/fcm", zValidator("json", z.object({ token: z.string().min(1).max(4096) })), async (c) => {
+ const added = await addFcmToken(c.env, c.get("user").username, c.req.valid("json").token);
+ return added ? c.json({ ok: true }) : c.json({ error: "Too many devices have notifications on." }, 400);
+ })
+
+ .post("/push/fcm/unregister", zValidator("json", z.object({ token: z.string().max(4096) })), async (c) => {
+ await removeFcmToken(c.env, c.get("user").username, c.req.valid("json").token);
+ return c.json({ ok: true });
+ })
+
.post("/push/test", async (c) =>
c.json(
await notifyUser(c.env, c.get("user").username, {
diff --git a/email/src/worker/services/fcm.ts b/email/src/worker/services/fcm.ts
new file mode 100644
index 0000000..0969de9
--- /dev/null
+++ b/email/src/worker/services/fcm.ts
@@ -0,0 +1,110 @@
+import { SignJWT, importPKCS8 } from "jose";
+
+/**
+ * Notifications for the Android app, through Firebase Cloud Messaging's HTTP
+ * v1 API. FCM_SERVICE_ACCOUNT holds the Firebase service account's JSON key;
+ * without it, FCM is simply off.
+ */
+interface ServiceAccount {
+ project_id: string;
+ client_email: string;
+ private_key: string;
+}
+
+export type FcmMessage = { title: string; body: string; url?: string; tag?: string };
+
+function account(env: Env): ServiceAccount | null {
+ if (!env.FCM_SERVICE_ACCOUNT) return null;
+ const parsed = JSON.parse(env.FCM_SERVICE_ACCOUNT) as Partial<ServiceAccount>;
+ if (!parsed.project_id || !parsed.client_email || !parsed.private_key) {
+ throw new Error("FCM_SERVICE_ACCOUNT is missing project_id, client_email or private_key");
+ }
+ return parsed as ServiceAccount;
+}
+
+// Google's access tokens last an hour; one per isolate is reused until close to that.
+let cached: { email: string; token: string; expiresAt: number } | null = null;
+
+async function accessToken(sa: ServiceAccount): Promise<string> {
+ const now = Math.floor(Date.now() / 1000);
+ if (cached && cached.email === sa.client_email && cached.expiresAt - 60 > now) return cached.token;
+
+ const assertion = await new SignJWT({ scope: "https://www.googleapis.com/auth/firebase.messaging" })
+ .setProtectedHeader({ alg: "RS256", typ: "JWT" })
+ .setIssuer(sa.client_email)
+ .setAudience("https://oauth2.googleapis.com/token")
+ .setIssuedAt(now)
+ .setExpirationTime(now + 3600)
+ .sign(await importPKCS8(sa.private_key, "RS256"));
+
+ const res = await fetch("https://oauth2.googleapis.com/token", {
+ method: "POST",
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
+ body: new URLSearchParams({ grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer", assertion }),
+ });
+ if (!res.ok) throw new Error(`Google token request failed (${res.status}): ${await res.text()}`);
+ const { access_token, expires_in } = (await res.json()) as { access_token: string; expires_in: number };
+ cached = { email: sa.client_email, token: access_token, expiresAt: now + expires_in };
+ return access_token;
+}
+
+// Every new email fans out one request per device, so cap them, as for Web Push.
+export const MAX_FCM_TOKENS = 20;
+
+/** Returns false when the user already has MAX_FCM_TOKENS other devices. */
+export async function addFcmToken(env: Env, username: string, token: string): Promise<boolean> {
+ // A token re-registered by someone else (the phone changed hands) moves to them.
+ const res = await env.DB.prepare(
+ "INSERT INTO fcm_tokens (token, username, created_at) SELECT ?1, ?2, ?3 " +
+ "WHERE (SELECT COUNT(*) FROM fcm_tokens WHERE username = ?2 AND token != ?1) < ?4 " +
+ "ON CONFLICT (token) DO UPDATE SET username = excluded.username",
+ )
+ .bind(token, username, Date.now(), MAX_FCM_TOKENS)
+ .run();
+ return res.meta.changes > 0;
+}
+
+export async function removeFcmToken(env: Env, username: string, token: string): Promise<void> {
+ await env.DB.prepare("DELETE FROM fcm_tokens WHERE token = ? AND username = ?").bind(token, username).run();
+}
+
+/** Sends to every app install `username` has; drops tokens FCM says are gone. */
+export async function notifyFcm(env: Env, username: string, msg: FcmMessage): Promise<{ sent: number; pruned: number }> {
+ const sa = account(env);
+ if (!sa) return { sent: 0, pruned: 0 };
+ const { results } = await env.DB.prepare("SELECT token FROM fcm_tokens WHERE username = ?")
+ .bind(username)
+ .all<{ token: string }>();
+ if (!results.length) return { sent: 0, pruned: 0 };
+
+ const bearer = await accessToken(sa);
+ const url = `https://fcm.googleapis.com/v1/projects/${sa.project_id}/messages:send`;
+ // Data-only, so the app builds the notification itself and a tap opens the thread.
+ const data = Object.fromEntries(Object.entries(msg).filter(([, v]) => v !== undefined)) as Record<string, string>;
+ const dead: string[] = [];
+ let sent = 0;
+
+ await Promise.all(
+ results.map(async ({ token }) => {
+ try {
+ const res = await fetch(url, {
+ method: "POST",
+ headers: { Authorization: `Bearer ${bearer}`, "Content-Type": "application/json" },
+ body: JSON.stringify({ message: { token, data, android: { priority: "HIGH", ttl: "86400s" } } }),
+ });
+ if (res.ok) return void sent++;
+ const text = await res.text();
+ // UNREGISTERED: the app was uninstalled or its token rotated.
+ if (res.status === 404 || text.includes("UNREGISTERED")) dead.push(token);
+ else console.error("FCM send failed", res.status, text);
+ } catch (err) {
+ console.error("FCM send error", err);
+ }
+ }),
+ );
+
+ if (dead.length) {
+ await env.DB.batch(dead.map((t) => env.DB.prepare("DELETE FROM fcm_tokens WHERE token = ?").bind(t)));
+ }
+ return { sent, pruned: dead.length };
+}
diff --git a/email/src/worker/services/push.ts b/email/src/worker/services/push.ts
index 761a161..fdc9245 100644
--- a/email/src/worker/services/push.ts
+++ b/email/src/worker/services/push.ts
@@ -1,3 +1,4 @@
+import { notifyFcm } from "./fcm";
import { sendWebPush, type PushSubscription, type VapidKeys } from "./webpush";
function vapid(env: Env): VapidKeys | null {
@@ -37,12 +38,27 @@ export async function removeSubscription(env: Env, username: string, endpoint: s
.run();
}
-/** Notifies every device `username` has subscribed; drops ones the push service says are gone. */
+/**
+ * Notifies every device `username` has: browsers through Web Push, the
+ * Android app through FCM. Drops ones the push service says are gone.
+ */
export async function notifyUser(
env: Env,
username: string,
payload: PushPayload,
): Promise<{ sent: number; pruned: number }> {
+ const [web, app] = await Promise.all([
+ notifyWebPush(env, username, payload),
+ // A broken FCM setup mustn't stop browsers getting theirs.
+ notifyFcm(env, username, payload).catch((err) => {
+ console.error("FCM notify failed", err);
+ return { sent: 0, pruned: 0 };
+ }),
+ ]);
+ return { sent: web.sent + app.sent, pruned: web.pruned + app.pruned };
+}
+
+async function notifyWebPush(env: Env, username: string, payload: PushPayload): Promise<{ sent: number; pruned: number }> {
const keys = vapid(env);
if (!keys) return { sent: 0, pruned: 0 };
diff --git a/email/src/worker/worker-configuration.d.ts b/email/src/worker/worker-configuration.d.ts
index 36a1208..80c1721 100644
--- a/email/src/worker/worker-configuration.d.ts
+++ b/email/src/worker/worker-configuration.d.ts
@@ -1,5 +1,5 @@
/* eslint-disable */
-// Generated by Wrangler by running `wrangler types --env-file=.dev.vars.example src/worker/worker-configuration.d.ts` (hash: 6d0c47eb9c2dd92f118cd97ff14ec68e)
+// Generated by Wrangler by running `wrangler types --env-file=.dev.vars.example src/worker/worker-configuration.d.ts` (hash: 4429817345404049eed4a2ccc0e35b88)
// Runtime types generated with [email protected] 2026-10-01 nodejs_compat
interface __BaseEnv_Env {
BUCKET: R2Bucket;
@@ -17,6 +17,7 @@ interface __BaseEnv_Env {
COOKIE_SECURE: string;
OIDC_REDIRECT_URI: string;
OIDC_POST_LOGOUT_REDIRECT_URI: string;
+ FCM_SERVICE_ACCOUNT: string;
LIVE: DurableObjectNamespace<import("./index").LiveHub>;
}
declare namespace Cloudflare {
@@ -31,7 +32,7 @@ type StringifyValues<EnvType extends Record<string, unknown>> = {
[Binding in keyof EnvType]: EnvType[Binding] extends string ? EnvType[Binding] : string;
};
declare namespace NodeJS {
- interface ProcessEnv extends StringifyValues<Pick<Cloudflare.Env, "ADMIN_USERS" | "OIDC_ISSUER" | "OIDC_CLIENT_ID" | "OIDC_SCOPE" | "VAPID_SUBJECT" | "VAPID_PUBLIC_KEY" | "RESEND_API_KEY" | "RESEND_WEBHOOK_SECRET" | "OIDC_CLIENT_SECRET" | "VAPID_PRIVATE_KEY" | "COOKIE_SECURE" | "OIDC_REDIRECT_URI" | "OIDC_POST_LOGOUT_REDIRECT_URI">> {}
+ interface ProcessEnv extends StringifyValues<Pick<Cloudflare.Env, "ADMIN_USERS" | "OIDC_ISSUER" | "OIDC_CLIENT_ID" | "OIDC_SCOPE" | "VAPID_SUBJECT" | "VAPID_PUBLIC_KEY" | "RESEND_API_KEY" | "RESEND_WEBHOOK_SECRET" | "OIDC_CLIENT_SECRET" | "VAPID_PRIVATE_KEY" | "COOKIE_SECURE" | "OIDC_REDIRECT_URI" | "OIDC_POST_LOGOUT_REDIRECT_URI" | "FCM_SERVICE_ACCOUNT">> {}
}
declare module "*.txt" {
const value: string;
diff --git a/email/test/fcm.test.ts b/email/test/fcm.test.ts
new file mode 100644
index 0000000..512220f
--- /dev/null
+++ b/email/test/fcm.test.ts
@@ -0,0 +1,94 @@
+import { env, exports } from "cloudflare:workers";
+import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
+import { addFcmToken, notifyFcm } from "../src/worker/services/fcm";
+import { createSession } from "../src/worker/services/sessions";
+
+const ORIGIN = "https://mail.test";
+
+async function serviceAccount(): Promise<string> {
+ const pair = (await crypto.subtle.generateKey(
+ { name: "RSASSA-PKCS1-v1_5", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" },
+ true,
+ ["sign", "verify"],
+ )) as CryptoKeyPair;
+ const der = new Uint8Array((await crypto.subtle.exportKey("pkcs8", pair.privateKey)) as ArrayBuffer);
+ const b64 = btoa(String.fromCharCode(...der)).replace(/(.{64})/g, "$1\n");
+ return JSON.stringify({
+ project_id: "inbox-test",
+ client_email: "[email protected]",
+ private_key: `-----BEGIN PRIVATE KEY-----\n${b64}\n-----END PRIVATE KEY-----\n`,
+ });
+}
+
+/** env with FCM switched on; everything else is inherited. */
+let fcmEnv: Env;
+
+beforeAll(async () => {
+ // defineProperty, not assignment: assigning would go through env's proxy and change it for every test.
+ fcmEnv = Object.defineProperty(Object.create(env) as Env, "FCM_SERVICE_ACCOUNT", { value: await serviceAccount() });
+ await env.DB.prepare(
+ "INSERT INTO users (username, sub, is_admin, created_at, last_login_at) VALUES ('noor', 'sub-noor', 0, 0, 0)",
+ ).run();
+});
+
+afterEach(() => vi.restoreAllMocks());
+
+describe("notifyFcm", () => {
+ it("does nothing without a service account", async () => {
+ const fetch = vi.spyOn(globalThis, "fetch");
+ await addFcmToken(env, "noor", "token-off");
+ expect(await notifyFcm(env, "noor", { title: "t", body: "b" })).toEqual({ sent: 0, pruned: 0 });
+ expect(fetch).not.toHaveBeenCalled();
+ });
+
+ it("sends a data message to each device and drops unregistered ones", async () => {
+ await addFcmToken(env, "noor", "token-live");
+ await addFcmToken(env, "noor", "token-gone");
+ const sends: { url: string; auth: string | null; body: { message: Record<string, unknown> } }[] = [];
+ vi.spyOn(globalThis, "fetch").mockImplementation(async (input, init) => {
+ const url = String(input);
+ if (url === "https://oauth2.googleapis.com/token") {
+ const form = new URLSearchParams(String(init?.body));
+ expect(form.get("grant_type")).toBe("urn:ietf:params:oauth:grant-type:jwt-bearer");
+ return Response.json({ access_token: "google-token", expires_in: 3600 });
+ }
+ const body = JSON.parse(String(init?.body)) as { message: { token: string } };
+ sends.push({ url, auth: new Headers(init?.headers).get("authorization"), body });
+ if (body.message.token === "token-gone") {
+ return Response.json({ error: { status: "NOT_FOUND", details: [{ errorCode: "UNREGISTERED" }] } }, { status: 404 });
+ }
+ return Response.json({ name: "projects/inbox-test/messages/1" });
+ });
+
+ const result = await notifyFcm(fcmEnv, "noor", { title: "New email", body: "Hi", url: "/inbox/t1", tag: "m1" });
+
+ expect(result.pruned).toBe(1);
+ expect(result.sent).toBe(2); // token-off and token-live
+ expect(sends.every((s) => s.url === "https://fcm.googleapis.com/v1/projects/inbox-test/messages:send")).toBe(true);
+ expect(sends.every((s) => s.auth === "Bearer google-token")).toBe(true);
+ expect(sends[0]!.body.message).toMatchObject({
+ data: { title: "New email", body: "Hi", url: "/inbox/t1", tag: "m1" },
+ android: { priority: "HIGH" },
+ });
+ const left = await env.DB.prepare("SELECT token FROM fcm_tokens WHERE username = 'noor' ORDER BY token").all();
+ expect(left.results.map((r) => r.token)).toEqual(["token-live", "token-off"]);
+ });
+});
+
+describe("FCM token registration", () => {
+ it("registers through the API, at most 20 devices", async () => {
+ const token = await createSession(env, { username: "noor", sub: "sub-noor", refreshToken: null, idToken: "x" });
+ const register = (t: string) =>
+ exports.default.fetch(
+ new Request(`${ORIGIN}/api/push/fcm`, {
+ method: "POST",
+ headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
+ body: JSON.stringify({ token: t }),
+ }),
+ );
+ await env.DB.prepare("DELETE FROM fcm_tokens").run();
+ for (let i = 0; i < 20; i++) expect((await register(`device-${i}`)).status).toBe(200);
+ expect((await register("device-20")).status).toBe(400);
+ expect((await register("device-5")).status).toBe(200);
+ });
+});