Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

feat(native): push notifications on Android through the relay

Maurice3c4c880c315f
diff --git a/.github/workflows/native.yml b/.github/workflows/native.yml
index 8ee1272f2..bb2fe5a13 100644
--- a/.github/workflows/native.yml
+++ b/.github/workflows/native.yml
@@ -80,7 +80,7 @@ jobs:
# unsigned: the upload key only exists in native-release.yml.
- name: Assemble debug and release APKs
working-directory: client/android
- run: ./gradlew assembleDebug assembleRelease lintDebug --no-daemon
+ run: ./gradlew assembleDebug assembleRelease lintDebug testDebugUnitTest --no-daemon
- uses: actions/upload-artifact@v6
with:
diff --git a/client/android/app/build.gradle b/client/android/app/build.gradle
index d936d41a0..aca4e544e 100644
--- a/client/android/app/build.gradle
+++ b/client/android/app/build.gradle
@@ -57,6 +57,9 @@ dependencies {
implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion"
implementation "androidx.browser:browser:$androidxBrowserVersion"
implementation "androidx.biometric:biometric:1.1.0"
+ // Push through liketrek's relay. No google-services plugin: Firebase reads
+ // its project from res/values/firebase.xml, the strings the plugin would generate.
+ implementation "com.google.firebase:firebase-messaging:24.1.2"
implementation project(':capacitor-android')
testImplementation "junit:junit:$junitVersion"
androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion"
diff --git a/client/android/app/src/main/AndroidManifest.xml b/client/android/app/src/main/AndroidManifest.xml
index e395c86a0..56b0297cd 100644
--- a/client/android/app/src/main/AndroidManifest.xml
+++ b/client/android/app/src/main/AndroidManifest.xml
@@ -60,6 +60,15 @@
</activity>
+ <!-- Push: the relay's data messages, decrypted and shown here. -->
+ <service
+ android:name=".TrekPushService"
+ android:exported="false">
+ <intent-filter>
+ <action android:name="com.google.firebase.MESSAGING_EVENT" />
+ </intent-filter>
+ </service>
+
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
@@ -86,5 +95,7 @@
Play hide the app from tablets and other GPS-less devices. -->
<uses-feature android:name="android.hardware.location.gps" android:required="false" />
<uses-permission android:name="android.permission.CAMERA" />
+ <!-- Android 13 and later ask before an app may show notifications. -->
+ <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-feature android:name="android.hardware.camera" android:required="false" />
</manifest>
diff --git a/client/android/app/src/main/java/com/liketrek/trek/TrekPushKeys.java b/client/android/app/src/main/java/com/liketrek/trek/TrekPushKeys.java
new file mode 100644
index 000000000..6882da9ec
--- /dev/null
+++ b/client/android/app/src/main/java/com/liketrek/trek/TrekPushKeys.java
@@ -0,0 +1,139 @@
+package com.liketrek.trek;
+
+import android.content.Context;
+import android.content.SharedPreferences;
+import android.security.keystore.KeyGenParameterSpec;
+import android.security.keystore.KeyProperties;
+import android.util.Base64;
+import java.math.BigInteger;
+import java.security.KeyFactory;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.KeyStore;
+import java.security.interfaces.ECPrivateKey;
+import java.security.interfaces.ECPublicKey;
+import java.security.spec.ECGenParameterSpec;
+import java.security.spec.PKCS8EncodedKeySpec;
+import java.security.SecureRandom;
+import javax.crypto.Cipher;
+import javax.crypto.KeyGenerator;
+import javax.crypto.SecretKey;
+import javax.crypto.spec.GCMParameterSpec;
+
+/**
+ * The device's Web Push key pair (P-256) and auth secret (RFC 8291). The server
+ * encrypts every notification for these, and TrekPushService decrypts with
+ * them. They are kept in the app's preferences, sealed with an AES key that
+ * never leaves the Android Keystore, so a copy of the preferences alone opens
+ * nothing.
+ */
+final class TrekPushKeys {
+
+ private static final String PREFS = "trek_push";
+ private static final String WRAP_ALIAS = "trek_push_wrap";
+ private static final String PRIVATE = "private";
+ private static final String PUBLIC = "public";
+ private static final String AUTH = "auth";
+
+ final ECPrivateKey privateKey;
+ /** Uncompressed point, 65 bytes, as the server reads p256dh. */
+ final byte[] publicKey;
+ final byte[] auth;
+
+ TrekPushKeys(ECPrivateKey privateKey, byte[] publicKey, byte[] auth) {
+ this.privateKey = privateKey;
+ this.publicKey = publicKey;
+ this.auth = auth;
+ }
+
+ /** The stored keys, or null when the app never subscribed. */
+ static synchronized TrekPushKeys load(Context context) throws Exception {
+ SharedPreferences prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE);
+ String sealedPrivate = prefs.getString(PRIVATE, null);
+ String publicKey = prefs.getString(PUBLIC, null);
+ String sealedAuth = prefs.getString(AUTH, null);
+ if (sealedPrivate == null || publicKey == null || sealedAuth == null) return null;
+ byte[] pkcs8 = unseal(sealedPrivate);
+ ECPrivateKey key = (ECPrivateKey) KeyFactory.getInstance("EC").generatePrivate(new PKCS8EncodedKeySpec(pkcs8));
+ return new TrekPushKeys(key, Base64.decode(publicKey, Base64.NO_WRAP), unseal(sealedAuth));
+ }
+
+ static synchronized TrekPushKeys loadOrCreate(Context context) throws Exception {
+ TrekPushKeys existing;
+ try {
+ existing = load(context);
+ } catch (Exception unreadable) {
+ // The Keystore key is gone (backup restored to another device, data
+ // cleared): start over, the next subscription carries the new keys.
+ existing = null;
+ }
+ if (existing != null) return existing;
+
+ KeyPairGenerator generator = KeyPairGenerator.getInstance("EC");
+ generator.initialize(new ECGenParameterSpec("secp256r1"));
+ KeyPair pair = generator.generateKeyPair();
+ byte[] publicKey = uncompressed((ECPublicKey) pair.getPublic());
+ byte[] auth = new byte[16];
+ new SecureRandom().nextBytes(auth);
+ context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
+ .edit()
+ .putString(PRIVATE, seal(pair.getPrivate().getEncoded()))
+ .putString(PUBLIC, Base64.encodeToString(publicKey, Base64.NO_WRAP))
+ .putString(AUTH, seal(auth))
+ .apply();
+ return new TrekPushKeys((ECPrivateKey) pair.getPrivate(), publicKey, auth);
+ }
+
+ static String base64url(byte[] data) {
+ return Base64.encodeToString(data, Base64.URL_SAFE | Base64.NO_WRAP | Base64.NO_PADDING);
+ }
+
+ static byte[] uncompressed(ECPublicKey key) {
+ byte[] out = new byte[65];
+ out[0] = 0x04;
+ copyFixed(key.getW().getAffineX(), out, 1);
+ copyFixed(key.getW().getAffineY(), out, 33);
+ return out;
+ }
+
+ /** A coordinate as exactly 32 bytes: BigInteger adds a sign byte or drops leading zeros. */
+ private static void copyFixed(BigInteger value, byte[] out, int offset) {
+ byte[] raw = value.toByteArray();
+ int start = Math.max(0, raw.length - 32);
+ int length = raw.length - start;
+ System.arraycopy(raw, start, out, offset + 32 - length, length);
+ }
+
+ private static SecretKey wrapKey() throws Exception {
+ KeyStore store = KeyStore.getInstance("AndroidKeyStore");
+ store.load(null);
+ if (store.containsAlias(WRAP_ALIAS)) return ((KeyStore.SecretKeyEntry) store.getEntry(WRAP_ALIAS, null)).getSecretKey();
+ KeyGenerator generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
+ generator.init(
+ new KeyGenParameterSpec.Builder(WRAP_ALIAS, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
+ .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
+ .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
+ .setKeySize(256)
+ .build()
+ );
+ return generator.generateKey();
+ }
+
+ private static String seal(byte[] plain) throws Exception {
+ Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
+ cipher.init(Cipher.ENCRYPT_MODE, wrapKey());
+ byte[] iv = cipher.getIV();
+ byte[] sealed = cipher.doFinal(plain);
+ byte[] out = new byte[iv.length + sealed.length];
+ System.arraycopy(iv, 0, out, 0, iv.length);
+ System.arraycopy(sealed, 0, out, iv.length, sealed.length);
+ return Base64.encodeToString(out, Base64.NO_WRAP);
+ }
+
+ private static byte[] unseal(String value) throws Exception {
+ byte[] in = Base64.decode(value, Base64.NO_WRAP);
+ Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
+ cipher.init(Cipher.DECRYPT_MODE, wrapKey(), new GCMParameterSpec(128, in, 0, 12));
+ return cipher.doFinal(in, 12, in.length - 12);
+ }
+}
diff --git a/client/android/app/src/main/java/com/liketrek/trek/TrekPushService.java b/client/android/app/src/main/java/com/liketrek/trek/TrekPushService.java
new file mode 100644
index 000000000..8724aa750
--- /dev/null
+++ b/client/android/app/src/main/java/com/liketrek/trek/TrekPushService.java
@@ -0,0 +1,101 @@
+package com.liketrek.trek;
+
+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.os.Build;
+import android.util.Base64;
+import androidx.annotation.NonNull;
+import androidx.core.app.NotificationCompat;
+import androidx.core.app.NotificationManagerCompat;
+import androidx.core.content.ContextCompat;
+import com.google.firebase.messaging.FirebaseMessagingService;
+import com.google.firebase.messaging.RemoteMessage;
+import java.nio.charset.StandardCharsets;
+import org.json.JSONObject;
+
+/**
+ * Receives the relay's data messages ({enc}: the server's encrypted Web Push
+ * record), decrypts them with the device's keys and shows the notification.
+ * Without the keys, or when the record does not open, it shows the same
+ * neutral text the iOS extension falls back to, never the ciphertext.
+ */
+public class TrekPushService extends FirebaseMessagingService {
+
+ static final String CHANNEL = "trek";
+ static final String EXTRA_URL = "trek.pushUrl";
+
+ @Override
+ public void onMessageReceived(@NonNull RemoteMessage message) {
+ String enc = message.getData().get("enc");
+ if (enc == null) return;
+ String title = getString(R.string.push_fallback_title);
+ String body = getString(R.string.push_fallback_body);
+ String url = null;
+ String tag = null;
+ try {
+ TrekPushKeys keys = TrekPushKeys.load(this);
+ if (keys != null) {
+ byte[] plain = TrekWebPush.decrypt(Base64.decode(enc, Base64.DEFAULT), keys);
+ JSONObject payload = new JSONObject(new String(plain, StandardCharsets.UTF_8));
+ if (!payload.optString("title").isEmpty()) title = payload.optString("title");
+ body = payload.optString("body", body);
+ url = payload.optString("url", null);
+ tag = payload.optString("tag", null);
+ }
+ } catch (Exception unreadable) {
+ // Shown with the neutral text: the tap still opens the app.
+ }
+ show(this, title, body, url, tag);
+ }
+
+ /** A new token means a new endpoint; the UI re-registers on its next start (resyncPushSubscription). */
+ @Override
+ public void onNewToken(@NonNull String token) {}
+
+ static void ensureChannel(Context context) {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return;
+ NotificationManager manager = context.getSystemService(NotificationManager.class);
+ if (manager == null || manager.getNotificationChannel(CHANNEL) != null) return;
+ NotificationChannel channel = new NotificationChannel(
+ CHANNEL,
+ context.getString(R.string.push_channel_name),
+ NotificationManager.IMPORTANCE_DEFAULT
+ );
+ manager.createNotificationChannel(channel);
+ }
+
+ private static void show(Context context, String title, String body, String url, String tag) {
+ ensureChannel(context);
+ Intent open = new Intent(context, MainActivity.class)
+ .setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
+ if (url != null) open.putExtra(EXTRA_URL, url);
+ int id = tag != null ? tag.hashCode() : (int) (System.currentTimeMillis() & 0x7fffffff);
+ PendingIntent tap = PendingIntent.getActivity(
+ context,
+ id,
+ open,
+ PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
+ );
+ NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL)
+ .setSmallIcon(R.drawable.ic_stat_trek)
+ .setContentTitle(title)
+ .setContentText(body)
+ .setStyle(new NotificationCompat.BigTextStyle().bigText(body))
+ .setAutoCancel(true)
+ .setContentIntent(tap);
+ if (Build.VERSION.SDK_INT >= 33
+ && ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
+ return;
+ }
+ try {
+ NotificationManagerCompat.from(context).notify(tag, id, builder.build());
+ } catch (SecurityException notAllowed) {
+ // Notifications switched off for the app since it subscribed.
+ }
+ }
+}
diff --git a/client/android/app/src/main/java/com/liketrek/trek/TrekShellPlugin.java b/client/android/app/src/main/java/com/liketrek/trek/TrekShellPlugin.java
index c365cecdf..8c3ff7840 100644
--- a/client/android/app/src/main/java/com/liketrek/trek/TrekShellPlugin.java
+++ b/client/android/app/src/main/java/com/liketrek/trek/TrekShellPlugin.java
@@ -1,19 +1,29 @@
package com.liketrek.trek;
+import android.Manifest;
import android.content.Intent;
import android.net.Uri;
+import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import androidx.browser.customtabs.CustomTabsIntent;
+import androidx.core.app.NotificationManagerCompat;
import com.getcapacitor.JSObject;
+import com.getcapacitor.PermissionState;
import com.getcapacitor.Plugin;
import com.getcapacitor.PluginCall;
import com.getcapacitor.PluginMethod;
import com.getcapacitor.annotation.CapacitorPlugin;
+import com.getcapacitor.annotation.Permission;
+import com.getcapacitor.annotation.PermissionCallback;
+import com.google.firebase.messaging.FirebaseMessaging;
import org.json.JSONObject;
/** The native half of client/src/native/trekShell.ts. */
-@CapacitorPlugin(name = "TrekShell")
+@CapacitorPlugin(
+ name = "TrekShell",
+ permissions = { @Permission(strings = { Manifest.permission.POST_NOTIFICATIONS }, alias = "notifications") }
+)
public class TrekShellPlugin extends Plugin {
/** How long to wait after returning from the browser for the redirect to land. */
@@ -31,7 +41,13 @@ public class TrekShellPlugin extends Plugin {
*/
static final int SHELL_API = 2;
/** The native features by name, so the UI can turn each on by itself. */
- static final String[] FEATURES = { "capabilities", "biometricLock", "sharedFiles" };
+ static final String[] FEATURES = { "capabilities", "biometricLock", "sharedFiles", "nativePush" };
+
+ /** liketrek's push relay: the endpoint for this device's FCM token (trek-hosted push-relay.ts). */
+ static final String PUSH_RELAY = "https://push.liketrek.com/v1/fcm/";
+
+ /** The notification the app was started from, until the UI asks for it. */
+ private String openedPushUrl;
@PluginMethod
public void getCapabilities(PluginCall call) {
@@ -60,6 +76,71 @@ public class TrekShellPlugin extends Plugin {
@Override
public void load() {
TrekSharedFiles.setListener(file -> notifyListeners("sharedFile", file));
+ if (getActivity() != null && getActivity().getIntent() != null) {
+ openedPushUrl = getActivity().getIntent().getStringExtra(TrekPushService.EXTRA_URL);
+ getActivity().getIntent().removeExtra(TrekPushService.EXTRA_URL);
+ }
+ }
+
+ // ---- Push ----
+
+ /**
+ * Permission, the FCM token and the device keys, as the Web Push subscription
+ * the server stores (native/push.ts). Rejects with DENIED when the user
+ * refuses notifications, as on iOS.
+ */
+ @PluginMethod
+ public void registerPush(PluginCall call) {
+ if (Build.VERSION.SDK_INT >= 33 && getPermissionState("notifications") != PermissionState.GRANTED) {
+ requestPermissionForAlias("notifications", call, "pushPermissionAnswered");
+ return;
+ }
+ subscribePush(call);
+ }
+
+ @PermissionCallback
+ private void pushPermissionAnswered(PluginCall call) {
+ if (getPermissionState("notifications") != PermissionState.GRANTED) {
+ call.reject("Notifications are not allowed", "DENIED");
+ return;
+ }
+ subscribePush(call);
+ }
+
+ private void subscribePush(PluginCall call) {
+ if (!NotificationManagerCompat.from(getContext()).areNotificationsEnabled()) {
+ call.reject("Notifications are not allowed", "DENIED");
+ return;
+ }
+ TrekPushService.ensureChannel(getContext());
+ final TrekPushKeys keys;
+ try {
+ keys = TrekPushKeys.loadOrCreate(getContext());
+ } catch (Exception e) {
+ call.reject("Could not create the push keys", e);
+ return;
+ }
+ FirebaseMessaging.getInstance().getToken().addOnCompleteListener(task -> {
+ if (!task.isSuccessful() || task.getResult() == null) {
+ call.reject("Could not get a push token", task.getException());
+ return;
+ }
+ JSObject subscription = new JSObject();
+ subscription.put("endpoint", PUSH_RELAY + task.getResult());
+ JSObject keyObject = new JSObject();
+ keyObject.put("p256dh", TrekPushKeys.base64url(keys.publicKey));
+ keyObject.put("auth", TrekPushKeys.base64url(keys.auth));
+ subscription.put("keys", keyObject);
+ call.resolve(subscription);
+ });
+ }
+
+ @PluginMethod
+ public void takeOpenedPush(PluginCall call) {
+ JSObject result = new JSObject();
+ result.put("url", openedPushUrl == null ? JSONObject.NULL : openedPushUrl);
+ openedPushUrl = null;
+ call.resolve(result);
}
/** The document shared to TREK before the UI was there to hear of it. */
@@ -200,6 +281,14 @@ public class TrekShellPlugin extends Plugin {
@Override
protected void handleOnNewIntent(Intent intent) {
super.handleOnNewIntent(intent);
+ String pushUrl = intent.getStringExtra(TrekPushService.EXTRA_URL);
+ if (pushUrl != null) {
+ intent.removeExtra(TrekPushService.EXTRA_URL);
+ JSObject opened = new JSObject();
+ opened.put("url", pushUrl);
+ notifyListeners("pushOpened", opened);
+ return;
+ }
Uri data = intent.getData();
PluginCall call = pendingAuthCall();
if (call == null || data == null || !authScheme.equals(data.getScheme())) return;
diff --git a/client/android/app/src/main/java/com/liketrek/trek/TrekWebPush.java b/client/android/app/src/main/java/com/liketrek/trek/TrekWebPush.java
new file mode 100644
index 000000000..759231eaa
--- /dev/null
+++ b/client/android/app/src/main/java/com/liketrek/trek/TrekWebPush.java
@@ -0,0 +1,84 @@
+package com.liketrek.trek;
+
+import java.math.BigInteger;
+import java.nio.charset.StandardCharsets;
+import java.security.KeyFactory;
+import java.security.interfaces.ECPrivateKey;
+import java.security.interfaces.ECPublicKey;
+import java.security.spec.ECPoint;
+import java.security.spec.ECPublicKeySpec;
+import java.util.Arrays;
+import javax.crypto.Cipher;
+import javax.crypto.KeyAgreement;
+import javax.crypto.Mac;
+import javax.crypto.spec.GCMParameterSpec;
+import javax.crypto.spec.SecretKeySpec;
+
+/**
+ * Decrypts a Web Push record (RFC 8291, aes128gcm content coding of RFC 8188):
+ * the same thing a browser does, and the counterpart of the iOS notification
+ * extension's WebPushRecord. One record, as TREK's server always sends.
+ */
+final class TrekWebPush {
+
+ private TrekWebPush() {}
+
+ static byte[] decrypt(byte[] record, TrekPushKeys keys) throws Exception {
+ if (record.length < 21) throw new IllegalArgumentException("record too short");
+ byte[] salt = Arrays.copyOfRange(record, 0, 16);
+ int idLength = record[20] & 0xff;
+ if (idLength != 65 || record.length < 21 + idLength + 17) throw new IllegalArgumentException("unexpected header");
+ byte[] senderKey = Arrays.copyOfRange(record, 21, 21 + idLength);
+ byte[] ciphertext = Arrays.copyOfRange(record, 21 + idLength, record.length);
+
+ KeyAgreement agreement = KeyAgreement.getInstance("ECDH");
+ agreement.init(keys.privateKey);
+ agreement.doPhase(publicKeyFrom(senderKey, keys.privateKey), true);
+ byte[] shared = agreement.generateSecret();
+
+ byte[] keyInfo = concat("WebPush: info\0".getBytes(StandardCharsets.US_ASCII), keys.publicKey, senderKey);
+ byte[] ikm = hkdf(keys.auth, shared, keyInfo, 32);
+ byte[] cek = hkdf(salt, ikm, "Content-Encoding: aes128gcm\0".getBytes(StandardCharsets.US_ASCII), 16);
+ byte[] nonce = hkdf(salt, ikm, "Content-Encoding: nonce\0".getBytes(StandardCharsets.US_ASCII), 12);
+
+ Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
+ cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(cek, "AES"), new GCMParameterSpec(128, nonce));
+ byte[] padded = cipher.doFinal(ciphertext);
+
+ // Padding: the content, one delimiter (2 for the last record), then zeros.
+ int end = padded.length - 1;
+ while (end >= 0 && padded[end] == 0) end--;
+ if (end < 0 || padded[end] != 2) throw new IllegalArgumentException("bad padding");
+ return Arrays.copyOf(padded, end);
+ }
+
+ private static ECPublicKey publicKeyFrom(byte[] point, ECPrivateKey onCurve) throws Exception {
+ if (point[0] != 0x04) throw new IllegalArgumentException("compressed key");
+ BigInteger x = new BigInteger(1, Arrays.copyOfRange(point, 1, 33));
+ BigInteger y = new BigInteger(1, Arrays.copyOfRange(point, 33, 65));
+ return (ECPublicKey) KeyFactory.getInstance("EC").generatePublic(new ECPublicKeySpec(new ECPoint(x, y), onCurve.getParams()));
+ }
+
+ /** HKDF-SHA256 (RFC 5869) for outputs of at most one block. */
+ private static byte[] hkdf(byte[] salt, byte[] ikm, byte[] info, int length) throws Exception {
+ Mac mac = Mac.getInstance("HmacSHA256");
+ mac.init(new SecretKeySpec(salt, "HmacSHA256"));
+ byte[] prk = mac.doFinal(ikm);
+ mac.init(new SecretKeySpec(prk, "HmacSHA256"));
+ mac.update(info);
+ mac.update((byte) 1);
+ return Arrays.copyOf(mac.doFinal(), length);
+ }
+
+ private static byte[] concat(byte[]... parts) {
+ int length = 0;
+ for (byte[] part : parts) length += part.length;
+ byte[] out = new byte[length];
+ int offset = 0;
+ for (byte[] part : parts) {
+ System.arraycopy(part, 0, out, offset, part.length);
+ offset += part.length;
+ }
+ return out;
+ }
+}
diff --git a/client/android/app/src/main/res/drawable/ic_stat_trek.xml b/client/android/app/src/main/res/drawable/ic_stat_trek.xml
new file mode 100644
index 000000000..3f7b9155f
--- /dev/null
+++ b/client/android/app/src/main/res/drawable/ic_stat_trek.xml
@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Status bar icon for notifications: a single-colour map pin, as Android
+ tints it and shows only its shape. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24"
+ android:tint="#FFFFFF">
+ <path
+ android:fillColor="#FFFFFF"
+ android:pathData="M12,2C8.13,2 5,5.13 5,9c0,5.25 7,13 7,13s7,-7.75 7,-13c0,-3.87 -3.13,-7 -7,-7zM12,11.5c-1.38,0 -2.5,-1.12 -2.5,-2.5s1.12,-2.5 2.5,-2.5 2.5,1.12 2.5,2.5 -1.12,2.5 -2.5,2.5z" />
+</vector>
diff --git a/client/android/app/src/main/res/values/firebase.xml b/client/android/app/src/main/res/values/firebase.xml
new file mode 100644
index 000000000..9615c5484
--- /dev/null
+++ b/client/android/app/src/main/res/values/firebase.xml
@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- The Firebase project the app receives push through (liketrek push relay).
+ These are the strings the google-services Gradle plugin would generate from
+ google-services.json; Firebase reads them at start. None of them is a secret:
+ they identify the project, sending needs the relay's service account. -->
+<resources>
+ <string name="google_app_id" translatable="false">1:1074454522965:android:3ff2fe270a27a73051b8dc</string>
+ <string name="gcm_defaultSenderId" translatable="false">1074454522965</string>
+ <string name="google_api_key" translatable="false">AIzaSyB2VYXmZ90BZuksHhHR_n2W8naNE_vJAJA</string>
+ <string name="google_crash_reporting_api_key" translatable="false">AIzaSyB2VYXmZ90BZuksHhHR_n2W8naNE_vJAJA</string>
+ <string name="project_id" translatable="false">trek-9392e</string>
+ <string name="google_storage_bucket" translatable="false">trek-9392e.firebasestorage.app</string>
+</resources>
diff --git a/client/android/app/src/main/res/values/strings.xml b/client/android/app/src/main/res/values/strings.xml
index 768fe05ff..e66821104 100644
--- a/client/android/app/src/main/res/values/strings.xml
+++ b/client/android/app/src/main/res/values/strings.xml
@@ -4,4 +4,7 @@
<string name="title_activity_main">TREK</string>
<string name="package_name">com.liketrek.trek</string>
<string name="custom_url_scheme">com.liketrek.trek</string>
+ <string name="push_channel_name">Notifications</string>
+ <string name="push_fallback_title">TREK</string>
+ <string name="push_fallback_body">New notification</string>
</resources>
diff --git a/client/android/app/src/test/java/com/liketrek/trek/TrekWebPushTest.java b/client/android/app/src/test/java/com/liketrek/trek/TrekWebPushTest.java
new file mode 100644
index 000000000..de31a29e1
--- /dev/null
+++ b/client/android/app/src/test/java/com/liketrek/trek/TrekWebPushTest.java
@@ -0,0 +1,63 @@
+package com.liketrek.trek;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThrows;
+
+import java.math.BigInteger;
+import java.nio.charset.StandardCharsets;
+import java.security.KeyFactory;
+import java.security.KeyPairGenerator;
+import java.security.interfaces.ECPrivateKey;
+import java.security.interfaces.ECPublicKey;
+import java.security.spec.ECGenParameterSpec;
+import java.security.spec.ECPrivateKeySpec;
+import java.util.Base64;
+import org.junit.Test;
+
+/** The decryption against the worked example in RFC 8291, section 5. */
+public class TrekWebPushTest {
+
+ private static byte[] b64(String value) {
+ return Base64.getUrlDecoder().decode(value);
+ }
+
+ private static TrekPushKeys rfcKeys() throws Exception {
+ KeyPairGenerator generator = KeyPairGenerator.getInstance("EC");
+ generator.initialize(new ECGenParameterSpec("secp256r1"));
+ ECPublicKey anyKey = (ECPublicKey) generator.generateKeyPair().getPublic();
+ BigInteger d = new BigInteger(1, b64("q1dXpw3UpT5VOmu_cf_v6ih07Aems3njxI-JWgLcM94"));
+ ECPrivateKey privateKey = (ECPrivateKey) KeyFactory.getInstance("EC").generatePrivate(new ECPrivateKeySpec(d, anyKey.getParams()));
+ return new TrekPushKeys(
+ privateKey,
+ b64("BCVxsr7N_eNgVRqvHtD0zTZsEc6-VV-JvLexhqUzORcxaOzi6-AYWXvTBHm4bjyPjs7Vd8pZGH6SRpkNtoIAiw4"),
+ b64("BTBZMqHH6r4Tts7J_aSIgg")
+ );
+ }
+
+ private static final String RECORD =
+ "DGv6ra1nlYgDCS1FRnbzlwAAEABBBP4z9KsN6nGRTbVYI_c7VJSPQTBtkgcy27mlmlMoZIIgDll6e3vCYLocInmYWAmS6TlzAC8wEqKK6PBru3jl7A_yl95bQpu6cVPTpK4Mqgkf1CXztLVBSt2Ks3oZwbuwXPXLWyouBWLVWGNWQexSgSxsj_Qulcy4a-fN";
+
+ @Test
+ public void decryptsTheRfcExample() throws Exception {
+ byte[] plain = TrekWebPush.decrypt(b64(RECORD), rfcKeys());
+ assertEquals("When I grow up, I want to be a watermelon", new String(plain, StandardCharsets.UTF_8));
+ }
+
+ @Test
+ public void refusesATamperedRecord() throws Exception {
+ byte[] record = b64(RECORD);
+ record[record.length - 1] ^= 1;
+ assertThrows(Exception.class, () -> TrekWebPush.decrypt(record, rfcKeys()));
+ }
+
+ @Test
+ public void writesThePublicKeyAsAFixedLengthPoint() throws Exception {
+ KeyPairGenerator generator = KeyPairGenerator.getInstance("EC");
+ generator.initialize(new ECGenParameterSpec("secp256r1"));
+ for (int i = 0; i < 20; i++) {
+ byte[] point = TrekPushKeys.uncompressed((ECPublicKey) generator.generateKeyPair().getPublic());
+ assertEquals(65, point.length);
+ assertEquals(4, point[0]);
+ }
+ }
+}
diff --git a/client/src/native/push.test.ts b/client/src/native/push.test.ts
index ff903e8a0..4c2add3e0 100644
--- a/client/src/native/push.test.ts
+++ b/client/src/native/push.test.ts
@@ -1,6 +1,6 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { hasNativeFeature } from './capabilities';
-import { isNativeIos } from './platform';
+import { isNativeApp } from './platform';
import {
NativePushDenied,
forgetNativePush,
@@ -12,7 +12,7 @@ import {
} from './push';
import { TrekShell } from './trekShell';
-vi.mock('./platform', () => ({ isNativeIos: vi.fn() }));
+vi.mock('./platform', () => ({ isNativeApp: vi.fn() }));
vi.mock('./capabilities', () => ({ hasNativeFeature: vi.fn() }));
vi.mock('./trekShell', () => ({
TrekShell: {
@@ -29,7 +29,7 @@ const SUB = {
beforeEach(() => {
window.localStorage.clear();
- vi.mocked(isNativeIos).mockReturnValue(true);
+ vi.mocked(isNativeApp).mockReturnValue(true);
vi.mocked(hasNativeFeature).mockReturnValue(true);
vi.mocked(TrekShell.registerPush).mockReset().mockResolvedValue(SUB);
vi.mocked(TrekShell.takeOpenedPush).mockReset().mockResolvedValue({ url: null });
diff --git a/client/src/native/push.ts b/client/src/native/push.ts
index 628d125df..056b0183b 100644
--- a/client/src/native/push.ts
+++ b/client/src/native/push.ts
@@ -1,15 +1,16 @@
import type { PushSubscriptionInput } from '@trek/shared';
import { hasNativeFeature } from './capabilities';
-import { isNativeIos } from './platform';
+import { isNativeApp } from './platform';
import { reportNativeFailure } from './reportFailure';
import { TrekShell } from './trekShell';
/**
* Push inside the app: the same Web Push subscription a browser makes, only
* the app makes it (TrekShell.registerPush). Its endpoint is liketrek's relay
- * for this device's APNs token and its keys live on the device, so the server
- * encrypts exactly as for a browser and the relay hands on ciphertext that the
- * app's notification extension decrypts. push/webPush.ts takes this path
+ * for this device's APNs or FCM token and its keys live on the device, so the
+ * server encrypts exactly as for a browser and the relay hands on ciphertext
+ * that the app decrypts (iOS: the notification extension, Android:
+ * TrekPushService). push/webPush.ts takes this path
* wherever the binary reports the nativePush feature; the settings card, the
* test push and the logout teardown stay what they are.
*
@@ -19,7 +20,7 @@ import { TrekShell } from './trekShell';
const KEY = 'trek.nativePushEndpoint';
export function nativePushActive(): boolean {
- return isNativeIos() && hasNativeFeature('nativePush');
+ return isNativeApp() && hasNativeFeature('nativePush');
}
export function nativePushEndpoint(): string | null {