+ The iOS and Android apps keep your recent rooms and member tokens on the phone in the same way,
+ and your phone’s own backup may include them.
+
Split itself sets four cookies. Each one is needed for the product to work. None of them
measures you or advertises to you.
@@ -198,6 +207,7 @@ export default function PrivacyPage() {
Advertising
+
The Google Ads and X Ads tags described here load on the website only, never in the apps.
Since 24 August 2026, peanutsplit.com carries a Google Ads tag (
{GOOGLE_ADS_ID}). It runs on this site only, and it has one
@@ -266,11 +276,12 @@ export default function PrivacyPage() {
Photographs of receipts
- If you photograph a receipt to fill in an expense, the image is sent once to a language-model
- provider to be read, and the answer comes back as text. Split does not keep the photograph:
- there is no column, bucket or temporary file for it, and neither the image nor anything read off
- it is written to a log. The provider is required to be one that retains nothing and trains on
- nothing. The feature is off entirely unless the operator has configured it.
+ If you photograph a receipt to fill in an expense, the image is sent once to Google Gemini,
+ through OpenRouter, to be read, and the answer comes back as text. Split does not keep the
+ photograph: there is no column, bucket or temporary file for it, and neither the image nor
+ anything read off it is written to a log. The provider is required to be one that retains
+ nothing and trains on nothing. The feature is off entirely unless the operator has configured
+ it.
@@ -288,12 +299,18 @@ export default function PrivacyPage() {
PostHog — product analytics;
Sentry — error reports;
- a language-model provider — receipt photographs, held for the length of one request;
+ Google Gemini, through OpenRouter — receipt photographs, held for the length of one
+ request;
your browser vendor’s push service — it delivers a notification you asked for,
and it necessarily sees that a message was sent to your device;
+
+ Apple Push Notification service and Google Firebase Cloud Messaging — they deliver the
+ notifications you turn on in the iOS and Android apps, and they can read each
+ notification’s title and text, including names and amounts;
+
our hosting provider — ordinary web-server request logs, including IP addresses.
diff --git a/apps/web/src/app/api/rooms/[slug]/push-subscriptions/route.ts b/apps/web/src/app/api/rooms/[slug]/push-subscriptions/route.ts
index 699ef967..e68510ea 100644
--- a/apps/web/src/app/api/rooms/[slug]/push-subscriptions/route.ts
+++ b/apps/web/src/app/api/rooms/[slug]/push-subscriptions/route.ts
@@ -6,10 +6,15 @@
* channel to it needs proof of membership, because a bare link-holder who never
* joined should not be able to make somebody's phone buzz on a schedule they
* chose. The proof is the member token the server minted at join time.
+ *
+ * Two body shapes: a browser's Web Push subscription (`endpoint` + `keys`) and
+ * an app install's device token (`transport` + `token`), stored as
+ * `:`. `server/validation.ts` turns both into one channel.
*/
import { prisma } from '@/server/db'
import { ApiError, readJson, respond } from '@/server/http'
import { isAllowedPushEndpoint } from '@/server/pushHosts'
+import { assertNativePushAvailable } from '@/server/push-native/config'
import { assertProvenMember, loadRoom } from '@/server/roomState'
import { enforceRateLimit, meterRoomLookup, WRITE_LIMIT } from '@/server/rateLimit'
import { pushSubscribeSchema, pushUnsubscribeSchema } from '@/server/validation'
@@ -28,13 +33,14 @@ export const POST = (request: Request, ctx: Ctx) =>
enforceRateLimit(request, WRITE_LIMIT, 'push-subscribe')
const { slug } = await ctx.params
const body = pushSubscribeSchema.parse(await readJson(request))
+ assertNativePushAvailable(body.transport)
// A guessed slug 404s here and a real slug with a bad token 403s, so the
// miss goes on the shared budget — same as the DELETE below and the
// status route beside it. All three paths meter it the same way.
const room = await meterRoomLookup(request, () => loadRoom(slug))
assertProvenMember(room, body.memberId, body.memberToken)
- if (!isAllowedPushEndpoint(body.endpoint)) {
+ if (body.transport === 'webpush' && !isAllowedPushEndpoint(body.endpoint)) {
throw new ApiError(400, 'UNSUPPORTED_PUSH_HOST', 'that is not a push service we can deliver to')
}
@@ -65,17 +71,18 @@ export const POST = (request: Request, ctx: Ctx) =>
create: {
roomId: room.id,
memberId: body.memberId,
+ transport: body.transport,
endpoint: body.endpoint,
- p256dh: body.keys.p256dh,
- auth: body.keys.auth,
+ p256dh: body.keys?.p256dh ?? null,
+ auth: body.keys?.auth ?? null,
userAgent: body.userAgent ?? null,
},
update: {
// memberId too: one phone can be passed to whoever is paying,
// and the channel should follow whoever it last proved it was.
memberId: body.memberId,
- p256dh: body.keys.p256dh,
- auth: body.keys.auth,
+ p256dh: body.keys?.p256dh ?? null,
+ auth: body.keys?.auth ?? null,
userAgent: body.userAgent ?? null,
lastSeenAt: new Date(),
},
diff --git a/apps/web/src/app/api/rooms/[slug]/push-subscriptions/status/route.ts b/apps/web/src/app/api/rooms/[slug]/push-subscriptions/status/route.ts
index 67693a1c..914abc19 100644
--- a/apps/web/src/app/api/rooms/[slug]/push-subscriptions/status/route.ts
+++ b/apps/web/src/app/api/rooms/[slug]/push-subscriptions/status/route.ts
@@ -7,13 +7,19 @@
*
* POST, and the endpoint is never a query parameter: an FCM or WNS endpoint
* embeds the device's registration token, and a URL would copy it into every
- * access log, proxy trace and Referer header on the way.
+ * access log, proxy trace and Referer header on the way. An app sends its
+ * `transport` and device token instead, for the same reason in the body.
+ *
+ * An app asks this before it shows its notification row, so a transport with
+ * no server credentials answers 503 NATIVE_PUSH_UNAVAILABLE here too, and the
+ * row stays hidden.
*/
import { prisma } from '@/server/db'
import { readJson, respond } from '@/server/http'
import { assertProvenMember, loadRoom } from '@/server/roomState'
import { enforceRateLimit, meterRoomLookup, WRITE_LIMIT } from '@/server/rateLimit'
import { pushStatusSchema } from '@/server/validation'
+import { assertNativePushAvailable } from '@/server/push-native/config'
export const dynamic = 'force-dynamic'
@@ -24,6 +30,7 @@ export const POST = (request: Request, ctx: Ctx) =>
enforceRateLimit(request, WRITE_LIMIT, 'push-status')
const { slug } = await ctx.params
const body = pushStatusSchema.parse(await readJson(request))
+ assertNativePushAvailable(body.transport)
// A guessed slug 404s here and a real slug with a bad token 403s, which is
// a room-existence oracle. Its own 120/hour bucket would have widened the
// 30/hour the miss limiter exists to enforce, so the miss goes there.
diff --git a/apps/web/src/components/room/JoinGate.tsx b/apps/web/src/components/room/JoinGate.tsx
index 8567f616..f6587747 100644
--- a/apps/web/src/components/room/JoinGate.tsx
+++ b/apps/web/src/components/room/JoinGate.tsx
@@ -6,6 +6,7 @@ import { useTranslations } from 'next-intl'
import { BaseInput } from '@/components/ui/BaseInput'
import { Button } from '@/components/ui/Button'
import { Card } from '@/components/ui/Card'
+import { roomProps, track } from '@/lib/analytics'
import { isApiError } from '@/lib/api'
import type { ApiMember, RoomState } from '@/lib/api-types'
import type { MemberIdentity } from '@/lib/identity'
@@ -56,6 +57,7 @@ export function JoinGate({ slug, state, onJoined, previousIdentity = null }: Joi
const [reactivation, setReactivation] = useState(null)
useEffect(() => {
+ track('join_gate_shown', roomProps(slug))
const previouslyFocused = document.activeElement instanceof HTMLElement ? document.activeElement : null
const gateRoot = gateRootRef.current
const background = gateRoot?.parentElement
@@ -123,6 +125,7 @@ export function JoinGate({ slug, state, onJoined, previousIdentity = null }: Joi
try {
const next = await claimMember.mutateAsync({ memberId })
feedback('pop')
+ track('join_gate_completed', { ...roomProps(slug), via: 'claim' })
onJoined({ memberId: next.memberId, token: next.memberToken, name: memberName })
} catch (err) {
feedback('error', { haptic: 'error' })
@@ -145,6 +148,7 @@ export function JoinGate({ slug, state, onJoined, previousIdentity = null }: Joi
try {
const next = await joinRoom.mutateAsync({ name: trimmed })
feedback('pop')
+ track('join_gate_completed', { ...roomProps(slug), via: 'new' })
onJoined({ memberId: next.memberId, token: next.memberToken, name: trimmed })
} catch (err) {
// The card is the whole screen here; shaking it is the only motion
@@ -175,6 +179,7 @@ export function JoinGate({ slug, state, onJoined, previousIdentity = null }: Joi
try {
const next = await reactivateMember.mutateAsync(reactivation.id)
feedback('pop')
+ track('join_gate_completed', { ...roomProps(slug), via: 'new' })
onJoined({ memberId: next.memberId, token: next.memberToken, name: reactivation.name })
} catch (err) {
feedback('error', { haptic: 'error' })
diff --git a/apps/web/src/i18n/messages/de.json b/apps/web/src/i18n/messages/de.json
index 72d4d03b..3ab25195 100644
--- a/apps/web/src/i18n/messages/de.json
+++ b/apps/web/src/i18n/messages/de.json
@@ -1229,7 +1229,8 @@
"NO_RATE": "Für diese Währung gibt es keinen Wechselkurs zur Gruppenwährung. Verwende stattdessen die Gruppenwährung.",
"MANUAL_FX_RATE_REQUIRED": "Gib für diese benutzerdefinierte Währung einen manuellen Kurs ein.",
"MANUAL_FX_RATE_INVALID": "Dieser Kurs ist ungültig oder rundet den umgerechneten Betrag auf null.",
- "MANUAL_FX_RATE_NOT_ALLOWED": "Manuelle Kurse sind nur bei benutzerdefinierten Ausgabenwährungen möglich."
+ "MANUAL_FX_RATE_NOT_ALLOWED": "Manuelle Kurse sind nur bei benutzerdefinierten Ausgabenwährungen möglich.",
+ "NATIVE_PUSH_UNAVAILABLE": "Benachrichtigungen sind noch nicht verfügbar."
},
"derivation": {
"title": "So kommt dieser Betrag zustande",
diff --git a/apps/web/src/i18n/messages/en.json b/apps/web/src/i18n/messages/en.json
index 13c79b06..7031c15e 100644
--- a/apps/web/src/i18n/messages/en.json
+++ b/apps/web/src/i18n/messages/en.json
@@ -1229,7 +1229,8 @@
"NO_RATE": "There is no rate between that currency and the room’s, so it cannot be converted. Use the room currency.",
"MANUAL_FX_RATE_REQUIRED": "Enter a manual rate for this custom currency.",
"MANUAL_FX_RATE_INVALID": "That manual rate is invalid or makes the converted amount round to zero.",
- "MANUAL_FX_RATE_NOT_ALLOWED": "Manual rates are only available for custom expense currencies."
+ "MANUAL_FX_RATE_NOT_ALLOWED": "Manual rates are only available for custom expense currencies.",
+ "NATIVE_PUSH_UNAVAILABLE": "Notifications aren’t available yet."
},
"derivation": {
"title": "How this adds up",
diff --git a/apps/web/src/i18n/messages/es-419.json b/apps/web/src/i18n/messages/es-419.json
index 7a913a2c..f2176009 100644
--- a/apps/web/src/i18n/messages/es-419.json
+++ b/apps/web/src/i18n/messages/es-419.json
@@ -1229,7 +1229,8 @@
"NO_RATE": "No hay cotización entre esa moneda y la de la sala, así que no se puede convertir. Usá la moneda de la sala.",
"MANUAL_FX_RATE_REQUIRED": "Ingresa una cotización manual para esta moneda personalizada.",
"MANUAL_FX_RATE_INVALID": "Esa cotización manual no es válida o hace que el monto convertido se redondee a cero.",
- "MANUAL_FX_RATE_NOT_ALLOWED": "Las cotizaciones manuales solo están disponibles para monedas personalizadas del gasto."
+ "MANUAL_FX_RATE_NOT_ALLOWED": "Las cotizaciones manuales solo están disponibles para monedas personalizadas del gasto.",
+ "NATIVE_PUSH_UNAVAILABLE": "Las notificaciones aún no están disponibles."
},
"derivation": {
"title": "Cómo sale este número",
diff --git a/apps/web/src/i18n/messages/fr.json b/apps/web/src/i18n/messages/fr.json
index d696cda7..529321fd 100644
--- a/apps/web/src/i18n/messages/fr.json
+++ b/apps/web/src/i18n/messages/fr.json
@@ -1229,7 +1229,8 @@
"NO_RATE": "Il n’existe aucun taux de change entre cette devise et celle du groupe. Utilise la devise du groupe.",
"MANUAL_FX_RATE_REQUIRED": "Saisis un taux manuel pour cette devise personnalisée.",
"MANUAL_FX_RATE_INVALID": "Ce taux manuel est invalide ou arrondit le montant converti à zéro.",
- "MANUAL_FX_RATE_NOT_ALLOWED": "Les taux manuels sont disponibles uniquement pour les devises de dépense personnalisées."
+ "MANUAL_FX_RATE_NOT_ALLOWED": "Les taux manuels sont disponibles uniquement pour les devises de dépense personnalisées.",
+ "NATIVE_PUSH_UNAVAILABLE": "Les notifications ne sont pas encore disponibles."
},
"derivation": {
"title": "Comment ce solde est calculé",
diff --git a/apps/web/src/i18n/messages/pl.json b/apps/web/src/i18n/messages/pl.json
index ef1b9616..437e1899 100644
--- a/apps/web/src/i18n/messages/pl.json
+++ b/apps/web/src/i18n/messages/pl.json
@@ -1229,7 +1229,8 @@
"NO_RATE": "Nie ma kursu między tą walutą a walutą pokoju, więc nie można jej przeliczyć. Użyj waluty pokoju.",
"MANUAL_FX_RATE_REQUIRED": "Wpisz własny kurs tej niestandardowej waluty.",
"MANUAL_FX_RATE_INVALID": "Wpisany kurs jest nieprawidłowy albo sprawia, że przeliczona kwota zaokrągla się do zera.",
- "MANUAL_FX_RATE_NOT_ALLOWED": "Własne kursy są dostępne tylko dla niestandardowych walut wydatków."
+ "MANUAL_FX_RATE_NOT_ALLOWED": "Własne kursy są dostępne tylko dla niestandardowych walut wydatków.",
+ "NATIVE_PUSH_UNAVAILABLE": "Powiadomienia nie są jeszcze dostępne."
},
"derivation": {
"title": "Skąd ta suma",
diff --git a/apps/web/src/i18n/messages/pt-br.json b/apps/web/src/i18n/messages/pt-br.json
index ad227fb4..07726b6f 100644
--- a/apps/web/src/i18n/messages/pt-br.json
+++ b/apps/web/src/i18n/messages/pt-br.json
@@ -1229,7 +1229,8 @@
"NO_RATE": "Não há cotação entre essa moeda e a da sala, então não dá para converter. Use a moeda da sala.",
"MANUAL_FX_RATE_REQUIRED": "Insira uma cotação manual para esta moeda personalizada.",
"MANUAL_FX_RATE_INVALID": "Essa cotação manual é inválida ou faz o valor convertido arredondar para zero.",
- "MANUAL_FX_RATE_NOT_ALLOWED": "As cotações manuais só estão disponíveis para moedas personalizadas do gasto."
+ "MANUAL_FX_RATE_NOT_ALLOWED": "As cotações manuais só estão disponíveis para moedas personalizadas do gasto.",
+ "NATIVE_PUSH_UNAVAILABLE": "As notificações ainda não estão disponíveis."
},
"derivation": {
"title": "De onde vem esse número",
diff --git a/apps/web/src/i18n/messages/uk.json b/apps/web/src/i18n/messages/uk.json
index 8c316c6b..5efa76a0 100644
--- a/apps/web/src/i18n/messages/uk.json
+++ b/apps/web/src/i18n/messages/uk.json
@@ -1229,7 +1229,8 @@
"NO_RATE": "Між цією валютою й валютою кімнати немає курсу, тому конвертація неможлива. Використай валюту кімнати.",
"MANUAL_FX_RATE_REQUIRED": "Укажи власний курс цієї нестандартної валюти.",
"MANUAL_FX_RATE_INVALID": "Власний курс недійсний або округлює конвертовану суму до нуля.",
- "MANUAL_FX_RATE_NOT_ALLOWED": "Власні курси доступні лише для нестандартних валют витрат."
+ "MANUAL_FX_RATE_NOT_ALLOWED": "Власні курси доступні лише для нестандартних валют витрат.",
+ "NATIVE_PUSH_UNAVAILABLE": "Сповіщення поки недоступні."
},
"derivation": {
"title": "Звідки ця сума",
diff --git a/apps/web/src/lib/analytics.ts b/apps/web/src/lib/analytics.ts
index ec8cc3c3..68695c9e 100644
--- a/apps/web/src/lib/analytics.ts
+++ b/apps/web/src/lib/analytics.ts
@@ -125,6 +125,15 @@ export type AnalyticsEvent =
// A content CTA click through to `/new`. `source` is the page's own public slug — the same
// value its URL shows every reader — so it names the PAGE, never the person who clicked.
| 'content_cta_clicked'
+ // Native apps. `store_link_clicked` carries `platform: 'ios'` and the closed `source` of the web
+ // surface that showed the store link; `app_room_opened` carries only how the app reached the room
+ // (`link`, `push`, `paste` or `launch`). The join-gate pair measures whether a store banner costs
+ // web joins: `join_gate_completed` says only whether the person joined as someone new or claimed
+ // a name already on the roster. All four carry `roomProps(slug)` at most, never a slug or a name.
+ | 'store_link_clicked'
+ | 'app_room_opened'
+ | 'join_gate_shown'
+ | 'join_gate_completed'
let ready = false
diff --git a/apps/web/src/lib/api-types.ts b/apps/web/src/lib/api-types.ts
index c8e3cec0..7fff9392 100644
--- a/apps/web/src/lib/api-types.ts
+++ b/apps/web/src/lib/api-types.ts
@@ -304,22 +304,34 @@ export interface SettlementInput {
// ─── push ───────────────────────────────────────────────────────────────────
-export interface PushSubscribeInput {
- endpoint: string
- keys: { p256dh: string; auth: string }
+/** The native app's delivery service. iOS builds pick `apns` or `apns-sandbox`
+ * from the build's APNs environment; Android uses `fcm`. */
+export type NativePushTransport = 'apns' | 'apns-sandbox' | 'fcm'
+
+interface PushMemberProof {
memberId: string
/** Proof of membership. Unlike every other write, push registration is not
* satisfied by holding the room link. */
memberToken: string
- userAgent?: string | null
}
-export interface PushUnsubscribeInput {
+/** A browser's Web Push subscription. */
+export interface WebPushChannel {
endpoint: string
- memberId: string
- memberToken: string
}
+/** An app install's device token. The server stores it as `:`. */
+export interface NativePushChannel {
+ transport: NativePushTransport
+ token: string
+}
+
+export type PushSubscribeInput =
+ | (WebPushChannel & PushMemberProof & { keys: { p256dh: string; auth: string }; userAgent?: string | null })
+ | (NativePushChannel & PushMemberProof & { userAgent?: string | null })
+
+export type PushUnsubscribeInput = (WebPushChannel | NativePushChannel) & PushMemberProof
+
// ─── receipt scan ───────────────────────────────────────────────────────────
// A scan is a DRAFT, not a write. Nothing here is stored anywhere: the image is
// forwarded once and dropped, and the reviewed result leaves as an ordinary
diff --git a/apps/web/src/lib/cors.test.ts b/apps/web/src/lib/cors.test.ts
new file mode 100644
index 00000000..655738e4
--- /dev/null
+++ b/apps/web/src/lib/cors.test.ts
@@ -0,0 +1,115 @@
+import { describe, expect, it } from 'vitest'
+import { APP_ORIGINS, corsFor } from './cors'
+
+const PREFLIGHT_HEADERS = (origin: string) => ({
+ 'Access-Control-Allow-Origin': origin,
+ 'Access-Control-Allow-Methods': 'GET, POST, PATCH, DELETE',
+ 'Access-Control-Allow-Headers': 'Content-Type, X-Member-Token',
+ 'Access-Control-Max-Age': '600',
+ Vary: 'Origin',
+})
+
+const RESPONSE_HEADERS = (origin: string) => ({
+ 'Access-Control-Allow-Origin': origin,
+ 'Access-Control-Expose-Headers': 'Content-Disposition',
+ Vary: 'Origin',
+})
+
+const SLUG = 'ski-trip-kunc-syrup-drum'
+
+describe('corsFor', () => {
+ it('allows exactly the two Capacitor WebView origins', () => {
+ expect(APP_ORIGINS).toEqual(['capacitor://localhost', 'https://localhost'])
+ })
+
+ it('answers a preflight from each app origin with the exact headers', () => {
+ for (const origin of APP_ORIGINS) {
+ expect(corsFor(origin, '/api/currencies', 'OPTIONS', undefined), origin).toEqual({
+ kind: 'preflight',
+ headers: PREFLIGHT_HEADERS(origin),
+ })
+ }
+ })
+
+ it('reflects the origin on every other method', () => {
+ for (const origin of APP_ORIGINS) {
+ for (const method of ['GET', 'POST', 'PATCH', 'DELETE', 'get']) {
+ expect(corsFor(origin, `/api/rooms/${SLUG}`, method, undefined), `${origin} ${method}`).toEqual({
+ kind: 'response',
+ headers: RESPONSE_HEADERS(origin),
+ })
+ }
+ }
+ })
+
+ it('covers the room card images outside /api', () => {
+ for (const path of [`/r/${SLUG}/card/settled`, `/r/${SLUG}/recap/card`]) {
+ expect(corsFor('capacitor://localhost', path, 'GET', undefined)?.kind, path).toBe('response')
+ }
+ })
+
+ it('leaves pages and other room paths alone', () => {
+ for (const path of [
+ `/r/${SLUG}`,
+ `/r/${SLUG}/recap`,
+ `/r/${SLUG}/card`,
+ `/r/${SLUG}/card/Settled`,
+ `/r/${SLUG}/card/settled/extra`,
+ `/r/${SLUG}/opengraph-image`,
+ '/app',
+ '/',
+ '/apiary',
+ ]) {
+ expect(corsFor('capacitor://localhost', path, 'GET', undefined), path).toBeNull()
+ }
+ })
+
+ it('keeps the cookie-bound install handoff same-origin only', () => {
+ for (const path of ['/api/install-handoff', `/api/rooms/${SLUG}/install-handoff`]) {
+ for (const method of ['OPTIONS', 'POST', 'GET']) {
+ expect(corsFor('capacitor://localhost', path, method, undefined), `${method} ${path}`).toBeNull()
+ }
+ }
+ })
+
+ it('gives an unknown, missing or look-alike origin nothing', () => {
+ for (const origin of [
+ 'https://evil.example',
+ 'http://localhost',
+ 'capacitor://localhost.evil.example',
+ 'https://localhost:8443',
+ 'https://peanutsplit.com',
+ 'null',
+ '*',
+ '',
+ null,
+ ]) {
+ expect(corsFor(origin, '/api/currencies', 'OPTIONS', undefined), String(origin)).toBeNull()
+ expect(corsFor(origin, '/api/currencies', 'GET', undefined), String(origin)).toBeNull()
+ }
+ })
+
+ it('adds the e2e harness origins, trimmed, but never a wildcard or null', () => {
+ const extra = ' http://localhost:8779 , http://127.0.0.1:8779,*,null,'
+ expect(corsFor('http://localhost:8779', '/api/currencies', 'OPTIONS', extra)).toEqual({
+ kind: 'preflight',
+ headers: PREFLIGHT_HEADERS('http://localhost:8779'),
+ })
+ expect(corsFor('http://127.0.0.1:8779', '/api/currencies', 'GET', extra)?.kind).toBe('response')
+ expect(corsFor('*', '/api/currencies', 'GET', extra)).toBeNull()
+ expect(corsFor('null', '/api/currencies', 'GET', extra)).toBeNull()
+ expect(corsFor('http://localhost:8780', '/api/currencies', 'GET', extra)).toBeNull()
+ })
+
+ it('never allows credentials and never answers with a wildcard', () => {
+ const origins = [...APP_ORIGINS, 'http://localhost:8779']
+ for (const origin of origins) {
+ for (const method of ['OPTIONS', 'GET']) {
+ const headers = corsFor(origin, '/api/currencies', method, 'http://localhost:8779')?.headers ?? {}
+ const names = Object.keys(headers).map((name) => name.toLowerCase())
+ expect(names).not.toContain('access-control-allow-credentials')
+ expect(Object.values(headers)).not.toContain('*')
+ }
+ }
+ })
+})
diff --git a/apps/web/src/lib/cors.ts b/apps/web/src/lib/cors.ts
new file mode 100644
index 00000000..d09da533
--- /dev/null
+++ b/apps/web/src/lib/cors.ts
@@ -0,0 +1,80 @@
+/**
+ * Cross-origin access for the store apps. The App Store and Google Play builds load the app from
+ * `capacitor://localhost` (iOS) and `https://localhost` (Android) and call the API on
+ * `https://peanutsplit.com`, so the server must answer CORS for exactly those two origins.
+ *
+ * No API route accepts an ambient credential: the room slug in the path is the capability, and a
+ * member token travels in a header or the body. Allowing two fixed origins without credentials
+ * therefore grants nothing that `curl` with the slug cannot already do. That is why this never sends
+ * `Access-Control-Allow-Credentials` and never `*`.
+ *
+ * The install handoff is the exception: it is bound to a `__Host-` cookie and checks the exact
+ * request Origin itself (`src/server/installHandoff.ts`), so it stays same-origin only.
+ *
+ * Applied in `src/proxy.ts` rather than per route handler, so preflights never reach a handler or a
+ * rate-limit bucket, and error responses (429, 403, 500) carry the header too. Without it the app
+ * would read a rate limit as an opaque network error.
+ */
+
+/** The WebView origins Capacitor 8 uses, the same set peanut-ui allows. */
+export const APP_ORIGINS: readonly string[] = ['capacitor://localhost', 'https://localhost']
+
+const CORS_PATH = /^\/api\/|^\/r\/[^/]+\/(?:card\/[a-z]+|recap\/card)$/
+const SAME_ORIGIN_ONLY_PATH = /^\/api\/(?:rooms\/[^/]+\/)?install-handoff(?:\/|$)/
+
+export const PREFLIGHT_STATUS = 204
+
+/**
+ * The extra origins only the cross-origin e2e harness sets (`SPLIT_CORS_TEST_ORIGINS`, comma
+ * separated). Production never sets it. `*` and `null` are dropped so a careless value cannot open
+ * the API to every page.
+ */
+function testOrigins(value: string | undefined): string[] {
+ if (!value) return []
+ return value
+ .split(',')
+ .map((origin) => origin.trim())
+ .filter((origin) => origin.length > 0 && origin !== '*' && origin !== 'null')
+}
+
+export type CorsResult = { kind: 'preflight' | 'response'; headers: Record }
+
+/**
+ * Decides the CORS answer for one request. `null` means "no CORS headers, behave exactly as before":
+ * an unknown or missing Origin, a path the apps do not call, or a same-origin-only path.
+ */
+export function corsFor(
+ origin: string | null,
+ pathname: string,
+ method: string,
+ extraOrigins: string | undefined = process.env.SPLIT_CORS_TEST_ORIGINS
+): CorsResult | null {
+ if (!origin) return null
+ if (!APP_ORIGINS.includes(origin) && !testOrigins(extraOrigins).includes(origin)) return null
+ if (!CORS_PATH.test(pathname) || SAME_ORIGIN_ONLY_PATH.test(pathname)) return null
+
+ if (method.toUpperCase() === 'OPTIONS') {
+ return {
+ kind: 'preflight',
+ headers: {
+ 'Access-Control-Allow-Origin': origin,
+ 'Access-Control-Allow-Methods': 'GET, POST, PATCH, DELETE',
+ 'Access-Control-Allow-Headers': 'Content-Type, X-Member-Token',
+ // WebKit caps the preflight cache at 600 s; a longer value buys nothing.
+ 'Access-Control-Max-Age': '600',
+ Vary: 'Origin',
+ },
+ }
+ }
+
+ return {
+ kind: 'response',
+ headers: {
+ 'Access-Control-Allow-Origin': origin,
+ // Export downloads name their file in this header; the app reads it to save the file.
+ 'Access-Control-Expose-Headers': 'Content-Disposition',
+ // A shared cache must not serve one origin's answer to another (`/api/currencies` is public).
+ Vary: 'Origin',
+ },
+ }
+}
diff --git a/apps/web/src/lib/error-messages.ts b/apps/web/src/lib/error-messages.ts
index f2a31140..c62a36b2 100644
--- a/apps/web/src/lib/error-messages.ts
+++ b/apps/web/src/lib/error-messages.ts
@@ -89,6 +89,7 @@ export const KNOWN_ERROR_CODES = [
'IMPORT_CURRENCY_CONVERSION_UNSUPPORTED',
'UNSUPPORTED_PUSH_HOST',
'PUSH_SUBSCRIPTION_LIMIT',
+ 'NATIVE_PUSH_UNAVAILABLE',
'RATE_LIMITED',
] as const
diff --git a/apps/web/src/lib/redact.test.ts b/apps/web/src/lib/redact.test.ts
index ecffc090..2df94198 100644
--- a/apps/web/src/lib/redact.test.ts
+++ b/apps/web/src/lib/redact.test.ts
@@ -30,6 +30,26 @@ describe('redactRoomSlugs', () => {
)
})
+ it('scrubs the slug query parameter the native app’s room pages use', () => {
+ expect(redactRoomSlugs('capacitor://localhost/room/?slug=ski-trip-kunc-syrup-drum&add=1')).toBe(
+ 'capacitor://localhost/room/?slug=[slug]&add=1'
+ )
+ expect(redactRoomSlugs('https://localhost/room/import/?slug=ski-trip-kunc-syrup-drum')).toBe(
+ 'https://localhost/room/import/?slug=[slug]'
+ )
+ expect(redactRoomSlugs('https://localhost/room/?add=1&slug=ski-trip-kunc-syrup-drum#expenses')).toBe(
+ 'https://localhost/room/?add=1&slug=[slug]#expenses'
+ )
+ })
+
+ it('scrubs any slug parameter, on purpose, even outside a room path', () => {
+ // Over-redacting an unrelated `slug=` loses a little debugging detail; a narrower rule
+ // would leak a room credential the first time a new page passes one.
+ expect(redactRoomSlugs('https://peanutsplit.com/blog/?slug=splitwise-alternative')).toBe(
+ 'https://peanutsplit.com/blog/?slug=[slug]'
+ )
+ })
+
it('leaves slug-free strings alone', () => {
expect(redactRoomSlugs('/new')).toBe('/new')
expect(redactRoomSlugs('/api/currencies')).toBe('/api/currencies')
@@ -79,4 +99,38 @@ describe('redactTelemetryEvent', () => {
breadcrumbs: [{ message: 'Navigated from /r/[slug]' }],
})
})
+
+ it('scrubs the native app’s slug query from breadcrumbs and exception text', () => {
+ const capability = 'ski-trip-kunc-syrup-drum'
+ const event = redactTelemetryEvent({
+ exception: {
+ values: [{ value: `Failed to load capacitor://localhost/room/?slug=${capability}&add=1` }],
+ },
+ breadcrumbs: [
+ {
+ message: `Navigated to /room/?slug=${capability}`,
+ data: {
+ from: 'capacitor://localhost/app/',
+ to: `capacitor://localhost/room/?slug=${capability}&add=1`,
+ url: `https://localhost/room/import/?slug=${capability}`,
+ },
+ },
+ ],
+ })
+
+ expect(JSON.stringify(event)).not.toContain(capability)
+ expect(event).toEqual({
+ exception: { values: [{ value: 'Failed to load capacitor://localhost/room/?slug=[slug]&add=1' }] },
+ breadcrumbs: [
+ {
+ message: 'Navigated to /room/?slug=[slug]',
+ data: {
+ from: 'capacitor://localhost/app/',
+ to: 'capacitor://localhost/room/?slug=[slug]&add=1',
+ url: 'https://localhost/room/import/?slug=[slug]',
+ },
+ },
+ ],
+ })
+ })
})
diff --git a/apps/web/src/lib/redact.ts b/apps/web/src/lib/redact.ts
index 5a528b0e..dff1a65b 100644
--- a/apps/web/src/lib/redact.ts
+++ b/apps/web/src/lib/redact.ts
@@ -8,9 +8,17 @@
*/
/** `/r/ski-trip-x7k2m9` and `/api/rooms/ski-trip-x7k2m9/expenses` — the two
- * shapes a slug ever appears in. */
+ * path shapes a slug appears in. The native app adds a query shape, below. */
const SLUG_PATHS = [/(\/r)\/[^/?#]+/g, /(\/api\/rooms)\/[^/?#]+/g]
+/**
+ * The native app's static export cannot have a dynamic `/r/` route, so its room pages carry the
+ * slug as a query parameter instead: `capacitor://localhost/room/?slug=&add=1`. Every `slug=`
+ * parameter is redacted, on any path, because a stray non-room `slug=` costing a little debugging
+ * detail is cheaper than a room credential reaching Sentry.
+ */
+const SLUG_QUERY = /([?&]slug=)[^\s"']+/g
+
/**
* The card query string, dropped whole.
*
@@ -25,6 +33,7 @@ const CARD_QUERY = /(\/card\/[a-z]+)\?[^#\s"']*/g
export function redactRoomSlugs(value: string): string {
let out = value
for (const pattern of SLUG_PATHS) out = out.replace(pattern, '$1/[slug]')
+ out = out.replace(SLUG_QUERY, '$1[slug]')
return out.replace(CARD_QUERY, '$1')
}
diff --git a/apps/web/src/lib/splash.test.ts b/apps/web/src/lib/splash.test.ts
index 6d2d4cc0..81d30c0b 100644
--- a/apps/web/src/lib/splash.test.ts
+++ b/apps/web/src/lib/splash.test.ts
@@ -36,16 +36,16 @@ describe('iOS launch screens', () => {
* include list stops covering a folder that did not exist when it was written, and the symptom
* — an asset silently missing offline — is invisible until someone is on a train. So the shape
* of `public/` is pinned here: add a folder, and this fails until it is either added to the
- * patterns or deliberately recorded as online-only. `dev/` and `press/` are the latter: an
- * internal static quiz and downloadable distribution assets are not part of the installable
- * app shell.
+ * patterns or deliberately recorded as online-only. `.well-known/`, `dev/` and `press/` are
+ * the latter: the app-link association files, an internal static quiz and downloadable
+ * distribution assets are not part of the installable app shell.
*/
it('keeps every public folder either precached or explicitly online-only', () => {
const folders = readdirSync(path.join(WEB, 'public'), { withFileTypes: true })
.filter((entry) => entry.isDirectory())
.map((entry) => entry.name)
.sort()
- expect(folders).toEqual(['dev', 'doodles', 'fonts', 'icons', 'install', 'press'])
+ expect(folders).toEqual(['.well-known', 'dev', 'doodles', 'fonts', 'icons', 'install', 'press'])
expect(readFileSync(path.join(WEB, 'next.config.js'), 'utf8')).toContain("'install/*.svg'")
})
})
diff --git a/apps/web/src/proxy.test.ts b/apps/web/src/proxy.test.ts
index db1fd72c..1f358efb 100644
--- a/apps/web/src/proxy.test.ts
+++ b/apps/web/src/proxy.test.ts
@@ -7,7 +7,7 @@ import { MARKETING_CACHE_CONTROL } from '@/lib/marketing-cache'
import { siteUrl } from '@/lib/site'
import { splitGuidePaths } from '@/lib/split-content/artifact'
import { SPLIT_CONTENT_INDEX_RELEASED_PATHS } from '@/lib/split-content/index-release'
-import { config, proxy } from './proxy'
+import { config, proxy, ROOM_SLUG_HEADER } from './proxy'
describe('proxy /new locale handoff', () => {
it('matches identity-bearing files and APIs for alias canonicalisation', () => {
@@ -253,3 +253,172 @@ describe('proxy released and parked guide headers on the indexed deployment', ()
}
})
})
+
+describe('proxy CORS for the store apps', () => {
+ const APP_ORIGINS = ['capacitor://localhost', 'https://localhost']
+ const slug = 'ski-trip-kunc-syrup-drum'
+ const canonicalHost = new URL(siteUrl).host
+ const request = (path: string, init: { method?: string; origin?: string; host?: string } = {}) =>
+ new NextRequest(`https://renderer.internal${path}`, {
+ method: init.method ?? 'GET',
+ headers: {
+ 'x-forwarded-host': init.host ?? canonicalHost,
+ ...(init.origin ? { origin: init.origin } : {}),
+ },
+ })
+ const corsHeaderNames = (response: Response) =>
+ [...response.headers.keys()].filter((name) => name.startsWith('access-control-'))
+
+ afterEach(() => {
+ vi.unstubAllEnvs()
+ })
+
+ it('answers a preflight from each app origin with 204 and exactly the agreed headers', () => {
+ for (const origin of APP_ORIGINS) {
+ const response = proxy(request('/api/currencies', { method: 'OPTIONS', origin }))
+
+ expect(response.status, origin).toBe(204)
+ expect(response.headers.get('access-control-allow-origin'), origin).toBe(origin)
+ expect(response.headers.get('access-control-allow-methods'), origin).toBe('GET, POST, PATCH, DELETE')
+ expect(response.headers.get('access-control-allow-headers'), origin).toBe('Content-Type, X-Member-Token')
+ expect(response.headers.get('access-control-max-age'), origin).toBe('600')
+ expect(response.headers.get('vary'), origin).toBe('Origin')
+ expect(corsHeaderNames(response).sort(), origin).toEqual([
+ 'access-control-allow-headers',
+ 'access-control-allow-methods',
+ 'access-control-allow-origin',
+ 'access-control-max-age',
+ ])
+ // A preflight is answered here; it must never reach a handler or a rate-limit bucket.
+ expect(response.headers.get('x-middleware-next'), origin).toBeNull()
+ }
+ })
+
+ it('lets a GET from an app origin through to the handler with the origin reflected', () => {
+ for (const origin of APP_ORIGINS) {
+ const response = proxy(request('/api/currencies', { origin }))
+
+ expect(response.status, origin).toBe(200)
+ expect(response.headers.get('x-middleware-next'), origin).toBe('1')
+ expect(response.headers.get('access-control-allow-origin'), origin).toBe(origin)
+ expect(response.headers.get('access-control-expose-headers'), origin).toBe('Content-Disposition')
+ expect(response.headers.get('vary'), origin).toBe('Origin')
+ }
+ })
+
+ it('includes the room card routes, which live outside /api', () => {
+ for (const path of [`/r/${slug}/card/settled`, `/r/${slug}/recap/card`]) {
+ const preflight = proxy(request(path, { method: 'OPTIONS', origin: 'capacitor://localhost' }))
+ expect(preflight.status, path).toBe(204)
+ expect(preflight.headers.get('access-control-allow-origin'), path).toBe('capacitor://localhost')
+
+ const get = proxy(request(path, { origin: 'https://localhost' }))
+ expect(get.status, path).toBe(200)
+ expect(get.headers.get('access-control-allow-origin'), path).toBe('https://localhost')
+ }
+ })
+
+ it("gives an unknown origin no CORS headers and today's behaviour", () => {
+ for (const method of ['OPTIONS', 'GET']) {
+ const response = proxy(request('/api/currencies', { method, origin: 'https://evil.example' }))
+
+ expect(response.status, method).toBe(200)
+ expect(response.headers.get('x-middleware-next'), method).toBe('1')
+ expect(corsHeaderNames(response), method).toEqual([])
+ expect(response.headers.get('vary'), method).toBeNull()
+ }
+ })
+
+ it('adds the e2e harness origin only while SPLIT_CORS_TEST_ORIGINS names it', () => {
+ expect(corsHeaderNames(proxy(request('/api/currencies', { origin: 'http://localhost:8779' })))).toEqual([])
+
+ vi.stubEnv('SPLIT_CORS_TEST_ORIGINS', 'http://localhost:8779')
+ const response = proxy(request('/api/currencies', { method: 'OPTIONS', origin: 'http://localhost:8779' }))
+ expect(response.status).toBe(204)
+ expect(response.headers.get('access-control-allow-origin')).toBe('http://localhost:8779')
+ })
+
+ it('keeps both install-handoff routes same-origin only', () => {
+ for (const path of ['/api/install-handoff', `/api/rooms/${slug}/install-handoff`]) {
+ for (const method of ['OPTIONS', 'POST']) {
+ const response = proxy(request(path, { method, origin: 'capacitor://localhost' }))
+ expect(response.status, `${method} ${path}`).toBe(200)
+ expect(corsHeaderNames(response), `${method} ${path}`).toEqual([])
+ }
+ }
+ })
+
+ it('still answers an alias host with only the 308, even from an app origin', () => {
+ for (const method of ['OPTIONS', 'GET']) {
+ const response = proxy(
+ request('/api/currencies', { method, origin: 'capacitor://localhost', host: 'split.peanut.me' })
+ )
+ expect(response.status, method).toBe(308)
+ expect(response.headers.get('location'), method).toBe(`${siteUrl}/api/currencies`)
+ expect(corsHeaderNames(response), method).toEqual([])
+ }
+ })
+
+ it('never allows credentials and never answers with a wildcard', () => {
+ for (const origin of APP_ORIGINS) {
+ for (const method of ['OPTIONS', 'GET', 'POST', 'PATCH', 'DELETE']) {
+ for (const path of ['/api/currencies', `/api/rooms/${slug}/expenses`, `/r/${slug}/recap/card`]) {
+ const response = proxy(request(path, { method, origin }))
+ expect(response.headers.get('access-control-allow-credentials'), `${method} ${path}`).toBeNull()
+ expect(response.headers.get('access-control-allow-origin'), `${method} ${path}`).not.toBe('*')
+ }
+ }
+ }
+ })
+})
+
+describe('proxy room-slug header for the Smart App Banner', () => {
+ const slug = 'ski-trip-kunc-syrup-drum'
+ const forwardedSlug = (response: Response) => response.headers.get(`x-middleware-request-${ROOM_SLUG_HEADER}`)
+
+ it('names the room on the room page and its recap', () => {
+ for (const path of [`/r/${slug}`, `/r/${slug}/recap`]) {
+ const response = proxy(new NextRequest(`https://renderer.internal${path}`))
+ expect(response.status, path).toBe(200)
+ expect(forwardedSlug(response), path).toBe(slug)
+ }
+ })
+
+ it('is absent everywhere else, including other room paths and invalid slugs', () => {
+ for (const path of [
+ '/app',
+ '/new',
+ '/',
+ '/blog',
+ `/r/${slug}/import`,
+ `/r/${slug}/card/settled`,
+ `/r/${slug}/recap/card`,
+ '/r/not_a_valid_slug',
+ '/r/Ski-Trip-kunc-syrup-drum',
+ ]) {
+ const response = proxy(new NextRequest(`https://renderer.internal${path}`))
+ expect(forwardedSlug(response), path).toBeNull()
+ }
+ })
+
+ it('replaces a spoofed header on room pages and strips it everywhere else, APIs included', () => {
+ const spoofed = 'evil-room-kunc-syrup-drum'
+ const cases = [
+ [`/r/${slug}`, slug],
+ [`/r/${slug}/recap`, slug],
+ ['/app', null],
+ ['/guides/synthetic-guide', null],
+ [`/api/rooms/${slug}`, null],
+ ] as const
+
+ for (const [path, expected] of cases) {
+ const response = proxy(
+ new NextRequest(`https://renderer.internal${path}`, { headers: { [ROOM_SLUG_HEADER]: spoofed } })
+ )
+ expect(response.status, path).toBe(200)
+ // An overridden request header list that lacks the name is how Next drops it.
+ expect(response.headers.get('x-middleware-override-headers'), path).not.toBeNull()
+ expect(forwardedSlug(response), path).toBe(expected)
+ }
+ })
+})
diff --git a/apps/web/src/proxy.ts b/apps/web/src/proxy.ts
index 8c58449a..09966f07 100644
--- a/apps/web/src/proxy.ts
+++ b/apps/web/src/proxy.ts
@@ -2,12 +2,29 @@ import { NextResponse, type NextRequest } from 'next/server'
import { LOCALE_COOKIE, LOCALE_COOKIE_MAX_AGE_SECONDS } from '@/i18n/locales'
import { LOCALE_HEADER, localeFromPathname } from '@/i18n/paths'
import { canonicalRedirect } from '@/lib/canonical-redirect'
+import { corsFor, PREFLIGHT_STATUS } from '@/lib/cors'
import { localeFromNewRoomHandoff } from '@/lib/locale-handoff'
import { MARKETING_CACHE_CONTROL, marketingCacheable } from '@/lib/marketing-cache'
+import { roomSlugFromLink } from '@/lib/recent-rooms'
import { siteUrl } from '@/lib/site'
import { splitContentIndexable } from '@/lib/split-content/indexability'
import { splitGuideLocale } from '@/lib/split-content/urls'
+/**
+ * Internal request header naming the room on `/r/` and `/r//recap`. The product-shell
+ * layout reads it to put the Smart App Banner `` in the ``, which the Metadata API
+ * cannot do on a streamed dynamic route. Only this proxy may set it.
+ */
+export const ROOM_SLUG_HEADER = 'x-split-room-slug'
+
+const ROOM_PAGE_PATH = /^\/r\/([^/]+)(?:\/recap)?$/
+
+/** The room slug of a room or recap page, validated against the room-slug contract. */
+function roomPageSlug(pathname: string): string | null {
+ const segment = pathname.match(ROOM_PAGE_PATH)?.[1]
+ return segment ? roomSlugFromLink(`/r/${segment}`, siteUrl) : null
+}
+
/**
* Tells the server what language a URL is in. It does not route or rewrite anything.
* (The configured-origin redirect runs first, and `/new?locale=…` persists a guide CTA's locale.)
@@ -27,6 +44,19 @@ import { splitGuideLocale } from '@/lib/split-content/urls'
* cookie-localized public marketing.
*/
export function proxy(request: NextRequest) {
+ const response = routeRequest(request)
+ // Redirects stay as they were: the apps only call canonical paths on the configured host.
+ if (response.status >= 300 && response.status < 400) return response
+
+ // CORS for the store apps comes after the canonical redirect, so an alias host still answers
+ // 308 and nothing else. See `src/lib/cors.ts` for why the proxy owns it.
+ const cors = corsFor(request.headers.get('origin'), request.nextUrl.pathname, request.method)
+ if (cors?.kind === 'preflight') return new NextResponse(null, { status: PREFLIGHT_STATUS, headers: cors.headers })
+ if (cors) for (const [name, value] of Object.entries(cors.headers)) response.headers.set(name, value)
+ return response
+}
+
+function routeRequest(request: NextRequest): NextResponse {
// The trailing-slash strip Next no longer applies (`skipTrailingSlashRedirect` in
// next.config.js). First, where Next's built-in ran, so `/guides/` and friends have
// already been retired in one hop by the config redirects before reaching here. A
@@ -47,15 +77,24 @@ export function proxy(request: NextRequest) {
// from the ordinary `localeFromPathname` path below — a guide URL states its language.
const isGuide = splitGuideLocale(request.nextUrl.pathname) !== null
- // API requests are matched only so requests to an alias can be canonicalised above.
- // On the configured host they must remain untouched: creation locale and request-origin
- // checks belong to the API handlers themselves.
- if (request.nextUrl.pathname.startsWith('/api/')) return NextResponse.next()
+ // API requests are matched so requests to an alias can be canonicalised above and the store
+ // apps get CORS headers in `proxy`. On the configured host the request itself stays untouched:
+ // creation locale and request-origin checks belong to the API handlers themselves.
+ if (request.nextUrl.pathname.startsWith('/api/')) {
+ // The room-slug header is internal; a caller must not be able to hand one to any route.
+ if (!request.headers.has(ROOM_SLUG_HEADER)) return NextResponse.next()
+ const stripped = new Headers(request.headers)
+ stripped.delete(ROOM_SLUG_HEADER)
+ return NextResponse.next({ request: { headers: stripped } })
+ }
// The locale header is internal state derived here. A caller-supplied value must never
// survive into the request React sees.
const forwarded = new Headers(request.headers)
forwarded.delete(LOCALE_HEADER)
+ forwarded.delete(ROOM_SLUG_HEADER)
+ const roomSlug = roomPageSlug(request.nextUrl.pathname)
+ if (roomSlug) forwarded.set(ROOM_SLUG_HEADER, roomSlug)
const handoffLocale = localeFromNewRoomHandoff(request.nextUrl.pathname, request.nextUrl.searchParams)
const locale = handoffLocale ?? localeFromPathname(request.nextUrl.pathname)
if (!locale) return NextResponse.next({ request: { headers: forwarded } })
diff --git a/apps/web/src/server/notifyCopy.ts b/apps/web/src/server/notifyCopy.ts
index a4abdb3c..340a3415 100644
--- a/apps/web/src/server/notifyCopy.ts
+++ b/apps/web/src/server/notifyCopy.ts
@@ -5,11 +5,16 @@
* and nowhere else — that is the whole reason the copy is not inlined at the
* three call sites that produce it.
*
- * Amounts and member names ARE allowed in a payload: it is encrypted end-to-end
- * to a device that already holds the room link and can read all of it in the
- * app anyway. The room SLUG is the thing to be careful with — it is the room's
- * access control, so it appears only in the click-through `url`, never in a log
- * line or an analytics property.
+ * Amounts and member names ARE allowed in a Web Push payload: it is encrypted
+ * end-to-end to a device that already holds the room link and can read all of
+ * it in the app anyway. The room SLUG is the thing to be careful with — it is
+ * the room's access control, so it appears only in the click-through `url`,
+ * never in a log line or an analytics property.
+ *
+ * App notifications (APNs and FCM) are readable by Apple and Google, so they
+ * never carry the slug at all: `server/push-native/payload.ts` builds them from
+ * the title and body here plus the room's `analyticsKey`, using the three
+ * constants at the end of this file.
*/
import { formatMoney } from '@/lib/money'
@@ -109,3 +114,16 @@ export function allSettledPayload(input: { room: RoomRef; roomId: string; sendId
sendId: input.sendId,
}
}
+
+/**
+ * The body of every app notification. `null` sends the same text as Web Push,
+ * names and amounts included (the decided default; Apple and Google can read
+ * it). Set it to `NATIVE_GENERIC_BODY` to keep names and amounts off their
+ * servers — a one-line change, nothing else reads the body.
+ */
+export const NATIVE_PUSH_BODY: string | null = null
+
+/** Replaces an app notification's title or body that would contain the slug,
+ * for instance a room named exactly like its own link. */
+export const NATIVE_GENERIC_TITLE = 'Split'
+export const NATIVE_GENERIC_BODY = 'New activity in your room.'
diff --git a/apps/web/src/server/push-native/apns.test.ts b/apps/web/src/server/push-native/apns.test.ts
new file mode 100644
index 00000000..04f22347
--- /dev/null
+++ b/apps/web/src/server/push-native/apns.test.ts
@@ -0,0 +1,55 @@
+import { describe, expect, it } from 'vitest'
+import { generateKeyPairSync, verify } from 'node:crypto'
+import { isDeadApnsToken, signApnsToken } from '@/server/push-native/apns'
+
+const decode = (part: string) => JSON.parse(Buffer.from(part, 'base64url').toString('utf8'))
+
+describe('APNs provider token', () => {
+ it('is an ES256 JWT that verifies against the key pair it was signed with', () => {
+ // Apple's .p8 is a PKCS#8 P-256 key; a fresh one stands in for it.
+ const { privateKey, publicKey } = generateKeyPairSync('ec', { namedCurve: 'prime256v1' })
+ const keyP8 = privateKey.export({ type: 'pkcs8', format: 'pem' }).toString()
+ const now = Date.UTC(2026, 10, 14, 2, 0, 0)
+
+ const token = signApnsToken({ keyP8, keyId: 'ABC123DEFG', teamId: 'TEAM123456' }, now)
+ const [header, claims, signature] = token.split('.')
+
+ expect(decode(header)).toEqual({ alg: 'ES256', kid: 'ABC123DEFG' })
+ expect(decode(claims)).toEqual({ iss: 'TEAM123456', iat: now / 1000 })
+ const signatureBytes = Buffer.from(signature, 'base64url')
+ // JOSE ES256 is the raw 64-byte r||s form, not DER.
+ expect(signatureBytes).toHaveLength(64)
+ expect(
+ verify(
+ 'sha256',
+ Buffer.from(`${header}.${claims}`),
+ { key: publicKey, dsaEncoding: 'ieee-p1363' },
+ signatureBytes
+ )
+ ).toBe(true)
+
+ const other = generateKeyPairSync('ec', { namedCurve: 'prime256v1' }).publicKey
+ expect(
+ verify(
+ 'sha256',
+ Buffer.from(`${header}.${claims}`),
+ { key: other, dsaEncoding: 'ieee-p1363' },
+ signatureBytes
+ )
+ ).toBe(false)
+ })
+})
+
+describe('APNs dead-token classification', () => {
+ it.each([
+ [410, 'Unregistered', true],
+ [400, 'BadDeviceToken', true],
+ [400, 'BadCollapseId', false],
+ [403, 'InvalidProviderToken', false],
+ [429, 'TooManyRequests', false],
+ [500, 'InternalServerError', false],
+ [200, undefined, false],
+ ])('status %i with reason %s → dead %s', (status, reason, dead) => {
+ expect(isDeadApnsToken(status, reason)).toBe(dead)
+ })
+})
diff --git a/apps/web/src/server/push-native/apns.ts b/apps/web/src/server/push-native/apns.ts
new file mode 100644
index 00000000..21b85e42
--- /dev/null
+++ b/apps/web/src/server/push-native/apns.ts
@@ -0,0 +1,166 @@
+/**
+ * Apple Push Notification service sender: token-based auth over HTTP/2.
+ *
+ * No SDK: the provider token is an ES256 JWT signed with `node:crypto`, and the
+ * request is one `http2` POST per device. A row's transport picks the host:
+ * `apns` goes to production, `apns-sandbox` to Apple's development service
+ * (debug and TestFlight-less device builds).
+ */
+import { sign } from 'node:crypto'
+import http2 from 'node:http2'
+import tls from 'node:tls'
+import type { ApnsCredentials } from '@/server/push-native/config'
+import {
+ apnsPayload,
+ NATIVE_TTL_SECONDS,
+ type NativeDelivery,
+ type NativeNotification,
+} from '@/server/push-native/payload'
+import { openTunnel } from '@/server/push-native/tunnel'
+
+const HOSTS = { production: 'api.push.apple.com', sandbox: 'api.sandbox.push.apple.com' } as const
+const REQUEST_TIMEOUT_MS = 10_000
+/** Apple rejects a provider token older than an hour and throttles one renewed
+ * more often than every 20 minutes. */
+const TOKEN_LIFETIME_MS = 50 * 60_000
+
+const base64url = (value: string | Buffer) => Buffer.from(value).toString('base64url')
+
+/** The provider JWT: `{ alg: ES256, kid }` over `{ iss: teamId, iat }`. */
+export function signApnsToken(credentials: Pick, nowMs: number): string {
+ const header = base64url(JSON.stringify({ alg: 'ES256', kid: credentials.keyId }))
+ const claims = base64url(JSON.stringify({ iss: credentials.teamId, iat: Math.floor(nowMs / 1000) }))
+ const input = `${header}.${claims}`
+ // JOSE wants the raw r||s signature, not Node's default DER encoding.
+ const signature = sign('sha256', Buffer.from(input), { key: credentials.keyP8, dsaEncoding: 'ieee-p1363' })
+ return `${input}.${base64url(signature)}`
+}
+
+let cachedToken: { value: string; keyId: string; issuedAt: number } | null = null
+
+function providerToken(credentials: ApnsCredentials): string {
+ const now = Date.now()
+ if (!cachedToken || cachedToken.keyId !== credentials.keyId || now - cachedToken.issuedAt > TOKEN_LIFETIME_MS) {
+ cachedToken = { value: signApnsToken(credentials, now), keyId: credentials.keyId, issuedAt: now }
+ }
+ return cachedToken.value
+}
+
+/** Test seam: drops the cached provider token. */
+export function resetApnsToken(): void {
+ cachedToken = null
+}
+
+/**
+ * Apple says the token is gone: 410 (Unregistered, the app was removed) or 400
+ * BadDeviceToken (a token from the other environment, or garbage). Retrying it
+ * on every future event would only add noise, so the row is deleted.
+ */
+export function isDeadApnsToken(status: number, reason: string | undefined): boolean {
+ return status === 410 || (status === 400 && reason === 'BadDeviceToken')
+}
+
+async function openSession(host: string): Promise {
+ const authority = `https://${host}:443`
+ const proxyUrl = process.env.SPLIT_PUSH_PROXY_URL
+ if (!proxyUrl) return http2.connect(authority)
+ const socket = await openTunnel(proxyUrl, host, 443)
+ const secure = tls.connect({ socket, servername: host, ALPNProtocols: ['h2'] })
+ return http2.connect(authority, { createConnection: () => secure })
+}
+
+function post(
+ session: http2.ClientHttp2Session,
+ headers: http2.OutgoingHttpHeaders,
+ body: string
+): Promise<{ status: number; reason?: string }> {
+ return new Promise((resolve, reject) => {
+ const request = session.request(headers)
+ let status = 0
+ let text = ''
+ request.setEncoding('utf8')
+ request.setTimeout(REQUEST_TIMEOUT_MS, () => request.close(http2.constants.NGHTTP2_CANCEL))
+ request.on('response', (response) => {
+ status = Number(response[':status'])
+ })
+ request.on('data', (chunk: string) => {
+ text += chunk
+ })
+ request.on('end', () => {
+ let reason: string | undefined
+ try {
+ reason = text ? (JSON.parse(text) as { reason?: string }).reason : undefined
+ } catch {
+ reason = undefined
+ }
+ resolve({ status, reason })
+ })
+ request.on('error', reject)
+ // A cancelled (timed-out) stream closes without 'end'; status 0 then
+ // reads as a failed send that keeps its row.
+ request.on('close', () => resolve({ status, reason: undefined }))
+ request.end(body)
+ })
+}
+
+/**
+ * Sends one notification to every token, one HTTP/2 session per Apple host for
+ * the whole batch. Results come back in the order of `targets`. A connection
+ * failure fails the batch's sends but never marks a token dead.
+ */
+export async function sendApns(
+ credentials: ApnsCredentials,
+ targets: readonly { token: string; sandbox: boolean }[],
+ notification: NativeNotification
+): Promise {
+ const body = JSON.stringify(apnsPayload(notification))
+ const results: NativeDelivery[] = targets.map(() => ({ ok: false, dead: false }))
+ for (const sandbox of [false, true]) {
+ const indexes = targets.flatMap((target, index) => (target.sandbox === sandbox ? [index] : []))
+ if (indexes.length === 0) continue
+ let session: http2.ClientHttp2Session | null = null
+ try {
+ session = await openSession(sandbox ? HOSTS.sandbox : HOSTS.production)
+ // An idle session error must not crash the process; requests on it
+ // fail through their own error events.
+ session.on('error', () => {})
+ const open = session
+ await Promise.all(
+ indexes.map(async (index) => {
+ try {
+ const { status, reason } = await post(
+ open,
+ {
+ ':method': 'POST',
+ ':path': `/3/device/${targets[index].token}`,
+ authorization: `bearer ${providerToken(credentials)}`,
+ 'apns-topic': credentials.bundleId,
+ 'apns-push-type': 'alert',
+ 'apns-priority': '10',
+ 'apns-expiration': String(Math.floor(Date.now() / 1000) + NATIVE_TTL_SECONDS),
+ // Same coalescing as the Web Push tag: a newer
+ // notification for the room replaces the older one.
+ 'apns-collapse-id': notification.room,
+ 'content-type': 'application/json',
+ },
+ body
+ )
+ results[index] = {
+ ok: status === 200,
+ dead: isDeadApnsToken(status, reason),
+ statusCode: status,
+ }
+ if (status !== 200) console.warn('[split] apns delivery failed', { status, reason })
+ } catch {
+ console.warn('[split] apns delivery failed', { status: 'request-error' })
+ }
+ })
+ )
+ } catch {
+ console.warn('[split] apns connection failed')
+ } finally {
+ session?.close()
+ }
+ }
+ return results
+}
diff --git a/apps/web/src/server/push-native/channel.test.ts b/apps/web/src/server/push-native/channel.test.ts
new file mode 100644
index 00000000..ca25d928
--- /dev/null
+++ b/apps/web/src/server/push-native/channel.test.ts
@@ -0,0 +1,130 @@
+/**
+ * The request shapes and the credentials gate, without a database. The route
+ * handler tests in `server/test/push.test.ts` cover the same paths end to end.
+ */
+import { afterEach, describe, expect, it } from 'vitest'
+import { ApiError } from '@/server/http'
+import { assertNativePushAvailable, fcmCredentials } from '@/server/push-native/config'
+import { pushStatusSchema, pushSubscribeSchema, pushUnsubscribeSchema } from '@/server/validation'
+
+const member = { memberId: 'member-1', memberToken: 'token-1' }
+const APNS_TOKEN = 'a1b2c3d4'.repeat(8)
+const FCM_TOKEN = 'dGVzdA:APA91bH-xyz_123'
+const WEB = 'https://fcm.googleapis.com/fcm/send/abc'
+const KEYS = { p256dh: 'BPk3p256dhKeyMaterial', auth: 'authKeyMaterial' }
+
+describe('push subscribe body', () => {
+ it('keeps a web body a web channel with its keys', () => {
+ expect(pushSubscribeSchema.parse({ endpoint: WEB, keys: KEYS, ...member })).toMatchObject({
+ transport: 'webpush',
+ endpoint: WEB,
+ keys: KEYS,
+ })
+ })
+
+ it('still rejects a web body without keys', () => {
+ expect(pushSubscribeSchema.safeParse({ endpoint: WEB, ...member }).success).toBe(false)
+ })
+
+ it.each([
+ ['apns', APNS_TOKEN],
+ ['apns-sandbox', APNS_TOKEN],
+ ['fcm', FCM_TOKEN],
+ ])('stores a %s token as a prefixed endpoint without keys', (transport, token) => {
+ expect(pushSubscribeSchema.parse({ transport, token, ...member })).toEqual({
+ transport,
+ endpoint: `${transport}:${token}`,
+ keys: null,
+ ...member,
+ })
+ })
+
+ it.each([
+ ['an unknown transport', { transport: 'webpush', token: APNS_TOKEN }],
+ ['a path in an APNs token', { transport: 'apns', token: 'abcd/../x' }],
+ ['a non-hex APNs token', { transport: 'apns', token: FCM_TOKEN }],
+ ['a query in an FCM token', { transport: 'fcm', token: 'abc?x=1' }],
+ ['an empty token', { transport: 'fcm', token: '' }],
+ ])('rejects %s', (_label, body) => {
+ expect(pushSubscribeSchema.safeParse({ ...member, ...body }).success).toBe(false)
+ })
+
+ it('rejects a native body without the member token', () => {
+ expect(
+ pushSubscribeSchema.safeParse({ transport: 'fcm', token: FCM_TOKEN, memberId: 'member-1' }).success
+ ).toBe(false)
+ })
+})
+
+describe('push unsubscribe and status bodies', () => {
+ it.each([
+ ['unsubscribe', pushUnsubscribeSchema],
+ ['status', pushStatusSchema],
+ ])('%s accepts a web endpoint or a native token', (_label, schema) => {
+ expect(schema.parse({ endpoint: WEB, ...member })).toEqual({ transport: 'webpush', endpoint: WEB, ...member })
+ expect(schema.parse({ transport: 'fcm', token: FCM_TOKEN, ...member })).toEqual({
+ transport: 'fcm',
+ endpoint: `fcm:${FCM_TOKEN}`,
+ ...member,
+ })
+ expect(schema.safeParse({ ...member }).success).toBe(false)
+ })
+})
+
+describe('native push credentials gate', () => {
+ const names = [
+ 'SPLIT_APNS_KEY_P8',
+ 'SPLIT_APNS_KEY_ID',
+ 'SPLIT_APNS_TEAM_ID',
+ 'SPLIT_APNS_BUNDLE_ID',
+ 'SPLIT_FCM_SERVICE_ACCOUNT_JSON',
+ ] as const
+ const saved = Object.fromEntries(names.map((name) => [name, process.env[name]]))
+
+ afterEach(() => {
+ for (const name of names) {
+ if (saved[name] === undefined) delete process.env[name]
+ else process.env[name] = saved[name]
+ }
+ })
+
+ const codeOf = (transport: Parameters[0]) => {
+ try {
+ assertNativePushAvailable(transport)
+ return 'ok'
+ } catch (err) {
+ return err instanceof ApiError ? `${err.status} ${err.code}` : 'other'
+ }
+ }
+
+ it('answers 503 NATIVE_PUSH_UNAVAILABLE for a native transport without credentials, never for web', () => {
+ for (const name of names) delete process.env[name]
+ expect(codeOf('apns')).toBe('503 NATIVE_PUSH_UNAVAILABLE')
+ expect(codeOf('apns-sandbox')).toBe('503 NATIVE_PUSH_UNAVAILABLE')
+ expect(codeOf('fcm')).toBe('503 NATIVE_PUSH_UNAVAILABLE')
+ expect(codeOf('webpush')).toBe('ok')
+ })
+
+ it('opens each transport only with its own complete credentials', () => {
+ for (const name of names) delete process.env[name]
+ process.env.SPLIT_APNS_KEY_P8 = 'key'
+ process.env.SPLIT_APNS_KEY_ID = 'id'
+ process.env.SPLIT_APNS_TEAM_ID = 'team'
+ expect(codeOf('apns')).toBe('503 NATIVE_PUSH_UNAVAILABLE')
+ process.env.SPLIT_APNS_BUNDLE_ID = 'com.peanutsplit.app'
+ expect(codeOf('apns')).toBe('ok')
+ expect(codeOf('apns-sandbox')).toBe('ok')
+ expect(codeOf('fcm')).toBe('503 NATIVE_PUSH_UNAVAILABLE')
+
+ process.env.SPLIT_FCM_SERVICE_ACCOUNT_JSON = '{not json'
+ expect(codeOf('fcm')).toBe('503 NATIVE_PUSH_UNAVAILABLE')
+ process.env.SPLIT_FCM_SERVICE_ACCOUNT_JSON = JSON.stringify({
+ project_id: 'split-test',
+ client_email: 'push@split-test.iam.gserviceaccount.com',
+ // Any escaped multi-line string proves the unescape; a PEM-shaped literal trips the secret hook.
+ private_key: 'line-one\\nline-two\\n',
+ })
+ expect(codeOf('fcm')).toBe('ok')
+ expect(fcmCredentials()?.privateKey).toBe('line-one\nline-two\n')
+ })
+})
diff --git a/apps/web/src/server/push-native/config.ts b/apps/web/src/server/push-native/config.ts
new file mode 100644
index 00000000..38e77125
--- /dev/null
+++ b/apps/web/src/server/push-native/config.ts
@@ -0,0 +1,71 @@
+/**
+ * Which app push services this server can deliver to, read from the runtime
+ * environment.
+ *
+ * Every value is optional. Without them the subscribe and status routes answer
+ * 503 NATIVE_PUSH_UNAVAILABLE, the app hides its notification row, and the
+ * fan-out skips native rows. Setting them on the server turns app push on with
+ * no store release. Like the VAPID pair, the APNs key and the FCM service
+ * account are never rotated in place without a plan for the stored tokens.
+ */
+import type { NativePushTransport } from '@/lib/api-types'
+import { ApiError } from '@/server/http'
+
+export const NATIVE_PUSH_TRANSPORTS = ['apns', 'apns-sandbox', 'fcm'] as const satisfies readonly NativePushTransport[]
+
+export interface ApnsCredentials {
+ /** PEM text of the `.p8` key. */
+ keyP8: string
+ keyId: string
+ teamId: string
+ /** The app's bundle ID, sent as `apns-topic`. */
+ bundleId: string
+}
+
+export interface FcmCredentials {
+ projectId: string
+ clientEmail: string
+ privateKey: string
+}
+
+export function apnsCredentials(): ApnsCredentials | null {
+ const keyP8 = process.env.SPLIT_APNS_KEY_P8
+ const keyId = process.env.SPLIT_APNS_KEY_ID
+ const teamId = process.env.SPLIT_APNS_TEAM_ID
+ const bundleId = process.env.SPLIT_APNS_BUNDLE_ID
+ if (!keyP8 || !keyId || !teamId || !bundleId) return null
+ // Secret stores often keep a multi-line PEM as one line with literal \n.
+ return { keyP8: keyP8.replace(/\\n/g, '\n'), keyId, teamId, bundleId }
+}
+
+export function fcmCredentials(): FcmCredentials | null {
+ const raw = process.env.SPLIT_FCM_SERVICE_ACCOUNT_JSON
+ if (!raw) return null
+ try {
+ const json = JSON.parse(raw) as { project_id?: unknown; client_email?: unknown; private_key?: unknown }
+ const { project_id: projectId, client_email: clientEmail, private_key: privateKey } = json
+ if (typeof projectId !== 'string' || typeof clientEmail !== 'string' || typeof privateKey !== 'string') {
+ return null
+ }
+ return { projectId, clientEmail, privateKey: privateKey.replace(/\\n/g, '\n') }
+ } catch {
+ // A malformed value is treated as unset: the routes answer 503 instead
+ // of storing tokens that every send would then fail on.
+ return null
+ }
+}
+
+export function isNativePushAvailable(transport: NativePushTransport): boolean {
+ return transport === 'fcm' ? fcmCredentials() !== null : apnsCredentials() !== null
+}
+
+/**
+ * The routes' gate for app tokens. It runs before the room lookup, so it says
+ * nothing about whether a room exists. The app hides its notification row on
+ * this code, so a store build never shows a button the server cannot serve.
+ */
+export function assertNativePushAvailable(transport: NativePushTransport | 'webpush'): void {
+ if (transport !== 'webpush' && !isNativePushAvailable(transport)) {
+ throw new ApiError(503, 'NATIVE_PUSH_UNAVAILABLE', 'app notifications are not configured on this server')
+ }
+}
diff --git a/apps/web/src/server/push-native/fcm.test.ts b/apps/web/src/server/push-native/fcm.test.ts
new file mode 100644
index 00000000..6756c3da
--- /dev/null
+++ b/apps/web/src/server/push-native/fcm.test.ts
@@ -0,0 +1,120 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { generateKeyPairSync, verify } from 'node:crypto'
+import { isDeadFcmToken, resetFcmToken, sendFcm, signFcmAssertion } from '@/server/push-native/fcm'
+import type { NativeNotification } from '@/server/push-native/payload'
+
+const decode = (part: string) => JSON.parse(Buffer.from(part, 'base64url').toString('utf8'))
+
+const { privateKey, publicKey } = generateKeyPairSync('rsa', { modulusLength: 2048 })
+const credentials = {
+ projectId: 'split-test',
+ clientEmail: 'push@split-test.iam.gserviceaccount.com',
+ privateKey: privateKey.export({ type: 'pkcs8', format: 'pem' }).toString(),
+}
+
+describe('FCM OAuth assertion', () => {
+ it('is an RS256 JWT for the messaging scope that verifies against the service account key', () => {
+ const now = Date.UTC(2026, 10, 14, 2, 0, 0)
+ const [header, claims, signature] = signFcmAssertion(credentials, now).split('.')
+
+ expect(decode(header)).toEqual({ alg: 'RS256', typ: 'JWT' })
+ expect(decode(claims)).toEqual({
+ iss: credentials.clientEmail,
+ scope: 'https://www.googleapis.com/auth/firebase.messaging',
+ aud: 'https://oauth2.googleapis.com/token',
+ iat: now / 1000,
+ exp: now / 1000 + 3600,
+ })
+ expect(
+ verify('sha256', Buffer.from(`${header}.${claims}`), publicKey, Buffer.from(signature, 'base64url'))
+ ).toBe(true)
+ })
+})
+
+describe('FCM dead-token classification', () => {
+ const unregistered = {
+ error: {
+ status: 'NOT_FOUND',
+ details: [{ '@type': 'type.googleapis.com/google.firebase.fcm.v1.FcmError', errorCode: 'UNREGISTERED' }],
+ },
+ }
+ const invalidArgument = {
+ error: { status: 'INVALID_ARGUMENT', details: [{ errorCode: 'INVALID_ARGUMENT' }] },
+ }
+
+ it.each([
+ [404, unregistered, true],
+ [404, null, true],
+ [400, { error: { details: [{ errorCode: 'UNREGISTERED' }] } }, true],
+ [400, invalidArgument, false],
+ [401, null, false],
+ [429, { error: { details: [{ errorCode: 'QUOTA_EXCEEDED' }] } }, false],
+ [503, 'not json', false],
+ ])('status %i → dead %s', (status, body, dead) => {
+ expect(isDeadFcmToken(status, body)).toBe(dead)
+ })
+})
+
+describe('sendFcm', () => {
+ const notification: NativeNotification = {
+ title: 'Ski Trip',
+ body: 'Ana added Lift passes — €120.00',
+ room: '0123456789abcdef0123456789abcdef',
+ sendId: '00000000-0000-4000-8000-000000000001',
+ }
+ const fetchMock = vi.fn()
+
+ beforeEach(() => {
+ resetFcmToken()
+ fetchMock.mockReset()
+ vi.stubGlobal('fetch', fetchMock)
+ vi.spyOn(console, 'warn').mockImplementation(() => {})
+ // No proxy: egressFetch uses the global fetch, which is the stub.
+ delete process.env.SPLIT_PUSH_PROXY_URL
+ })
+
+ afterEach(() => {
+ vi.unstubAllGlobals()
+ vi.restoreAllMocks()
+ })
+
+ it('gets one access token, sends to each device and marks only the unregistered one dead', async () => {
+ fetchMock.mockImplementation(async (input, init) => {
+ const url = String(input)
+ if (url === 'https://oauth2.googleapis.com/token') {
+ return Response.json({ access_token: 'access-1', expires_in: 3600 })
+ }
+ const sent = JSON.parse(String(init?.body)) as { message: { token: string } }
+ if (sent.message.token === 'gone-token')
+ return Response.json({ error: { status: 'NOT_FOUND' } }, { status: 404 })
+ if (sent.message.token === 'busy-token') return Response.json({ error: {} }, { status: 503 })
+ return Response.json({ name: 'projects/split-test/messages/1' })
+ })
+
+ const results = await sendFcm(credentials, ['live-token', 'gone-token', 'busy-token'], notification)
+
+ expect(results).toEqual([
+ { ok: true, dead: false, statusCode: 200 },
+ { ok: false, dead: true, statusCode: 404 },
+ { ok: false, dead: false, statusCode: 503 },
+ ])
+ const urls = fetchMock.mock.calls.map(([input]) => String(input))
+ expect(urls.filter((url) => url.endsWith('/token'))).toHaveLength(1)
+ expect(
+ urls.filter((url) => url === 'https://fcm.googleapis.com/v1/projects/split-test/messages:send')
+ ).toHaveLength(3)
+
+ // The cached token is reused for the next event.
+ await sendFcm(credentials, ['live-token'], notification)
+ expect(fetchMock.mock.calls.filter(([input]) => String(input).endsWith('/token'))).toHaveLength(1)
+ })
+
+ it('fails every send without marking a token dead when the token call fails', async () => {
+ fetchMock.mockResolvedValue(Response.json({ error: 'invalid_grant' }, { status: 400 }))
+
+ expect(await sendFcm(credentials, ['a', 'b'], notification)).toEqual([
+ { ok: false, dead: false },
+ { ok: false, dead: false },
+ ])
+ })
+})
diff --git a/apps/web/src/server/push-native/fcm.ts b/apps/web/src/server/push-native/fcm.ts
new file mode 100644
index 00000000..fc79be6f
--- /dev/null
+++ b/apps/web/src/server/push-native/fcm.ts
@@ -0,0 +1,116 @@
+/**
+ * Firebase Cloud Messaging sender (HTTP v1) for the Android app.
+ *
+ * No SDK: the service account signs an RS256 JWT with `node:crypto`, Google's
+ * token endpoint swaps it for an hour-long access token, and each device gets
+ * one `messages:send` POST. Both calls go through `egressFetch` with
+ * `SPLIT_PUSH_PROXY_URL`, the same way out of the container as every other
+ * runtime request.
+ */
+import { sign } from 'node:crypto'
+import type { FcmCredentials } from '@/server/push-native/config'
+import { fcmMessage, type NativeDelivery, type NativeNotification } from '@/server/push-native/payload'
+import { egressFetch } from '@/server/egress'
+
+const TOKEN_URL = 'https://oauth2.googleapis.com/token'
+const SCOPE = 'https://www.googleapis.com/auth/firebase.messaging'
+const TOKEN_LIFETIME_S = 3600
+/** Renew a minute early so a token never expires between check and send. */
+const RENEW_MARGIN_MS = 60_000
+const REQUEST_TIMEOUT_MS = 10_000
+
+const base64url = (value: string | Buffer) => Buffer.from(value).toString('base64url')
+
+/** The OAuth assertion Google's token endpoint takes for a service account. */
+export function signFcmAssertion(
+ credentials: Pick,
+ nowMs: number
+): string {
+ const iat = Math.floor(nowMs / 1000)
+ const header = base64url(JSON.stringify({ alg: 'RS256', typ: 'JWT' }))
+ const claims = base64url(
+ JSON.stringify({ iss: credentials.clientEmail, scope: SCOPE, aud: TOKEN_URL, iat, exp: iat + TOKEN_LIFETIME_S })
+ )
+ const input = `${header}.${claims}`
+ return `${input}.${base64url(sign('sha256', Buffer.from(input), credentials.privateKey))}`
+}
+
+/**
+ * FCM says the token is gone: the app was uninstalled or the token rotated
+ * (`UNREGISTERED`, usually with 404). Anything else, including 400
+ * INVALID_ARGUMENT, keeps the row: that code also covers a bad payload.
+ */
+export function isDeadFcmToken(status: number, body: unknown): boolean {
+ if (status === 404) return true
+ const details = (body as { error?: { details?: { errorCode?: unknown }[] } } | null)?.error?.details
+ return Array.isArray(details) && details.some((detail) => detail?.errorCode === 'UNREGISTERED')
+}
+
+let cachedToken: { value: string; clientEmail: string; expiresAt: number } | null = null
+
+/** Test seam: drops the cached access token. */
+export function resetFcmToken(): void {
+ cachedToken = null
+}
+
+async function accessToken(credentials: FcmCredentials, proxyUrl: string | undefined): Promise {
+ const now = Date.now()
+ if (cachedToken && cachedToken.clientEmail === credentials.clientEmail && now < cachedToken.expiresAt) {
+ return cachedToken.value
+ }
+ const response = await egressFetch(proxyUrl, TOKEN_URL, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
+ body: new URLSearchParams({
+ grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
+ assertion: signFcmAssertion(credentials, now),
+ }).toString(),
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
+ })
+ if (!response.ok) throw new Error(`fcm token request failed: ${response.status}`)
+ const json = (await response.json()) as { access_token?: unknown; expires_in?: unknown }
+ if (typeof json.access_token !== 'string') throw new Error('fcm token response had no access_token')
+ const lifetimeS = typeof json.expires_in === 'number' ? json.expires_in : TOKEN_LIFETIME_S
+ cachedToken = {
+ value: json.access_token,
+ clientEmail: credentials.clientEmail,
+ expiresAt: now + lifetimeS * 1000 - RENEW_MARGIN_MS,
+ }
+ return cachedToken.value
+}
+
+/** Sends one notification to every token. Results come back in token order. */
+export async function sendFcm(
+ credentials: FcmCredentials,
+ tokens: readonly string[],
+ notification: NativeNotification
+): Promise {
+ const proxyUrl = process.env.SPLIT_PUSH_PROXY_URL
+ let bearer: string
+ try {
+ bearer = await accessToken(credentials, proxyUrl)
+ } catch {
+ console.warn('[split] fcm auth failed')
+ return tokens.map(() => ({ ok: false, dead: false }))
+ }
+ const url = `https://fcm.googleapis.com/v1/projects/${encodeURIComponent(credentials.projectId)}/messages:send`
+ return Promise.all(
+ tokens.map(async (token): Promise => {
+ try {
+ const response = await egressFetch(proxyUrl, url, {
+ method: 'POST',
+ headers: { Authorization: `Bearer ${bearer}`, 'Content-Type': 'application/json' },
+ body: JSON.stringify(fcmMessage(token, notification)),
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
+ })
+ if (response.ok) return { ok: true, dead: false, statusCode: response.status }
+ const body = await response.json().catch(() => null)
+ console.warn('[split] fcm delivery failed', { status: response.status })
+ return { ok: false, dead: isDeadFcmToken(response.status, body), statusCode: response.status }
+ } catch {
+ console.warn('[split] fcm delivery failed', { status: 'request-error' })
+ return { ok: false, dead: false }
+ }
+ })
+ )
+}
diff --git a/apps/web/src/server/push-native/payload.test.ts b/apps/web/src/server/push-native/payload.test.ts
new file mode 100644
index 00000000..bdbd5c7a
--- /dev/null
+++ b/apps/web/src/server/push-native/payload.test.ts
@@ -0,0 +1,77 @@
+import { describe, expect, it } from 'vitest'
+import { allSettledPayload, expenseAddedPayload, NATIVE_GENERIC_BODY, NATIVE_GENERIC_TITLE } from '@/server/notifyCopy'
+import { apnsPayload, fcmMessage, toNativeNotification } from '@/server/push-native/payload'
+
+const SLUG = 'ski-trip-kunc-syrup-drum'
+const ANALYTICS_KEY = '0123456789abcdef0123456789abcdef'
+const SEND_ID = '00000000-0000-4000-8000-000000000001'
+
+const room = (name: string) => ({ slug: SLUG, name, emoji: null, currency: 'EUR' })
+
+const serialized = (name: string, description = 'Lift passes') => {
+ const web = expenseAddedPayload({
+ room: room(name),
+ roomId: 'room-uuid',
+ sendId: SEND_ID,
+ actorName: 'Ana',
+ description,
+ amountMinor: '12000',
+ currency: 'EUR',
+ })
+ const notification = toNativeNotification(web, { slug: SLUG, analyticsKey: ANALYTICS_KEY })
+ return {
+ notification,
+ apns: JSON.stringify(apnsPayload(notification)),
+ fcm: JSON.stringify(fcmMessage('device-token', notification)),
+ }
+}
+
+describe('app notification payloads', () => {
+ it('carry the web title and body, the analytics key and the send id', () => {
+ const { notification, apns, fcm } = serialized('Ski Trip')
+ expect(notification).toEqual({
+ title: 'Ski Trip',
+ body: 'Ana added Lift passes — €120.00',
+ room: ANALYTICS_KEY,
+ sendId: SEND_ID,
+ })
+ expect(JSON.parse(apns)).toEqual({
+ aps: { alert: { title: 'Ski Trip', body: 'Ana added Lift passes — €120.00' }, 'thread-id': ANALYTICS_KEY },
+ room: ANALYTICS_KEY,
+ sendId: SEND_ID,
+ })
+ expect(JSON.parse(fcm)).toEqual({
+ message: {
+ token: 'device-token',
+ notification: { title: 'Ski Trip', body: 'Ana added Lift passes — €120.00' },
+ android: { ttl: '86400s', notification: { tag: ANALYTICS_KEY, icon: 'ic_stat_split' } },
+ data: { room: ANALYTICS_KEY, sendId: SEND_ID },
+ },
+ })
+ })
+
+ it('never contain the slug, while the web payload does', () => {
+ const web = allSettledPayload({ room: room('Ski Trip'), roomId: 'room-uuid', sendId: SEND_ID })
+ expect(JSON.stringify(web)).toContain(SLUG)
+
+ const { apns, fcm } = serialized('Ski Trip')
+ expect(apns).not.toContain(SLUG)
+ expect(fcm).not.toContain(SLUG)
+ expect(apns).not.toContain('/r/')
+ expect(fcm).not.toContain('/r/')
+ })
+
+ it('replace a title that is the slug, as when a room is named after its own link', () => {
+ const { notification, apns, fcm } = serialized(SLUG)
+ expect(notification.title).toBe(NATIVE_GENERIC_TITLE)
+ expect(apns).not.toContain(SLUG)
+ expect(fcm).not.toContain(SLUG)
+ })
+
+ it('replace a body that mentions the slug, in any letter case', () => {
+ const { notification, apns, fcm } = serialized('Ski Trip', `Paid via ${SLUG.toUpperCase()}`)
+ expect(notification.body).toBe(NATIVE_GENERIC_BODY)
+ expect(apns.toLowerCase()).not.toContain(SLUG)
+ expect(fcm.toLowerCase()).not.toContain(SLUG)
+ })
+})
diff --git a/apps/web/src/server/push-native/payload.ts b/apps/web/src/server/push-native/payload.ts
new file mode 100644
index 00000000..28c0f0ff
--- /dev/null
+++ b/apps/web/src/server/push-native/payload.ts
@@ -0,0 +1,73 @@
+/**
+ * App notification bodies for APNs and FCM. Pure, so the "no slug" rule is a
+ * unit test rather than a promise.
+ *
+ * Apple and Google can read these payloads (Web Push is end-to-end encrypted;
+ * these are not), and the slug is the room's credential. So the only room id
+ * here is the `analyticsKey`, a one-way digest the app maps back to a room it
+ * already knows, and any title or body that would contain the slug is replaced
+ * with generic copy.
+ */
+import { NATIVE_GENERIC_BODY, NATIVE_GENERIC_TITLE, NATIVE_PUSH_BODY, type PushPayload } from '@/server/notifyCopy'
+
+/** Web Push drops a message it could not deliver within a day; so do these. */
+export const NATIVE_TTL_SECONDS = 86_400
+
+/** What an app notification may carry. No slug, no URL. */
+export interface NativeNotification {
+ title: string
+ body: string
+ /** The room's `analyticsKey`. */
+ room: string
+ /** Ledger row id, echoed back by the app's opened beacon. */
+ sendId: string
+}
+
+/** One device's outcome. `dead` means the service says the token is gone for
+ * good and the row should be deleted. */
+export interface NativeDelivery {
+ ok: boolean
+ dead: boolean
+ statusCode?: number
+}
+
+const mentions = (text: string, slug: string) => text.toLowerCase().includes(slug.toLowerCase())
+
+export function toNativeNotification(
+ payload: PushPayload,
+ room: { slug: string; analyticsKey: string }
+): NativeNotification {
+ const body = NATIVE_PUSH_BODY ?? payload.body
+ return {
+ title: mentions(payload.title, room.slug) ? NATIVE_GENERIC_TITLE : payload.title,
+ body: mentions(body, room.slug) ? NATIVE_GENERIC_BODY : body,
+ room: room.analyticsKey,
+ sendId: payload.sendId,
+ }
+}
+
+/** The JSON body of one APNs request. `thread-id` groups a room's notifications. */
+export function apnsPayload(n: NativeNotification) {
+ return {
+ aps: { alert: { title: n.title, body: n.body }, 'thread-id': n.room },
+ room: n.room,
+ sendId: n.sendId,
+ }
+}
+
+/** The JSON body of one FCM HTTP v1 `messages:send` request. */
+export function fcmMessage(token: string, n: NativeNotification) {
+ return {
+ message: {
+ token,
+ notification: { title: n.title, body: n.body },
+ android: {
+ ttl: `${NATIVE_TTL_SECONDS}s`,
+ // One tag per room: a newer notification replaces the older one
+ // on the device, as the Web Push tag does.
+ notification: { tag: n.room, icon: 'ic_stat_split' },
+ },
+ data: { room: n.room, sendId: n.sendId },
+ },
+ }
+}
diff --git a/apps/web/src/server/push-native/tunnel.test.ts b/apps/web/src/server/push-native/tunnel.test.ts
new file mode 100644
index 00000000..78405088
--- /dev/null
+++ b/apps/web/src/server/push-native/tunnel.test.ts
@@ -0,0 +1,84 @@
+import { afterEach, describe, expect, it } from 'vitest'
+import http from 'node:http'
+import net, { type AddressInfo } from 'node:net'
+import { openTunnel } from '@/server/push-native/tunnel'
+
+/** Local stand-ins: a TCP echo server as the "push service" and a CONNECT proxy
+ * in front of it. No request leaves the machine. */
+const servers: { close(): unknown }[] = []
+
+afterEach(async () => {
+ for (const server of servers.splice(0)) server.close()
+})
+
+const listen = async (server: T): Promise => {
+ servers.push(server)
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
+ return (server.address() as AddressInfo).port
+}
+
+const echoServer = () => listen(net.createServer((socket) => socket.pipe(socket)))
+
+function connectProxy(options: { refuse?: boolean } = {}) {
+ const seen: { url?: string; auth?: string } = {}
+ const server = http.createServer((_req, res) => res.writeHead(405).end())
+ server.on('connect', (req, client: net.Socket) => {
+ seen.url = req.url
+ seen.auth = req.headers['proxy-authorization']
+ if (options.refuse) {
+ client.end('HTTP/1.1 403 Forbidden\r\n\r\n')
+ return
+ }
+ const [host, port] = (req.url ?? '').split(':')
+ const upstream = net.connect(Number(port), host, () => {
+ client.write('HTTP/1.1 200 Connection Established\r\n\r\n')
+ upstream.pipe(client)
+ client.pipe(upstream)
+ })
+ upstream.on('error', () => client.destroy())
+ })
+ return { seen, port: listen(server) }
+}
+
+const roundTrip = (socket: net.Socket, text: string) =>
+ new Promise((resolve) => {
+ socket.once('data', (chunk) => resolve(chunk.toString('utf8')))
+ socket.write(text)
+ })
+
+describe('openTunnel', () => {
+ it('asks the proxy for the target host and port, then carries bytes both ways', async () => {
+ const target = await echoServer()
+ const proxy = connectProxy()
+ const socket = await openTunnel(`http://127.0.0.1:${await proxy.port}`, '127.0.0.1', target)
+
+ expect(proxy.seen.url).toBe(`127.0.0.1:${target}`)
+ expect(proxy.seen.auth).toBeUndefined()
+ expect(await roundTrip(socket, 'hello through the tunnel')).toBe('hello through the tunnel')
+ socket.destroy()
+ })
+
+ it('sends basic proxy credentials from the proxy URL', async () => {
+ const target = await echoServer()
+ const proxy = connectProxy()
+ const socket = await openTunnel(`http://split%40box:p%3Ass@127.0.0.1:${await proxy.port}`, '127.0.0.1', target)
+
+ expect(proxy.seen.auth).toBe(`Basic ${Buffer.from('split@box:p:ss').toString('base64')}`)
+ socket.destroy()
+ })
+
+ it('rejects when the proxy refuses the CONNECT', async () => {
+ const proxy = connectProxy({ refuse: true })
+ await expect(openTunnel(`http://127.0.0.1:${await proxy.port}`, 'api.push.apple.com', 443)).rejects.toThrow(
+ 'proxy refused CONNECT: 403'
+ )
+ expect(proxy.seen.url).toBe('api.push.apple.com:443')
+ })
+
+ it('rejects when the proxy is not there', async () => {
+ const closed = net.createServer()
+ const port = await listen(closed)
+ closed.close()
+ await expect(openTunnel(`http://127.0.0.1:${port}`, 'api.push.apple.com', 443)).rejects.toThrow()
+ })
+})
diff --git a/apps/web/src/server/push-native/tunnel.ts b/apps/web/src/server/push-native/tunnel.ts
new file mode 100644
index 00000000..ae40b101
--- /dev/null
+++ b/apps/web/src/server/push-native/tunnel.ts
@@ -0,0 +1,45 @@
+/**
+ * A TCP tunnel through the egress proxy, for APNs.
+ *
+ * Production has no egress except the pinned proxy in `SPLIT_PUSH_PROXY_URL`.
+ * Web Push and FCM are HTTP/1.1 and go through `egressFetch`; APNs needs
+ * HTTP/2, and Node's `http2.connect` has no proxy option. So this opens an
+ * HTTP CONNECT tunnel and returns the raw socket; the caller wraps it in TLS
+ * and hands it to `http2.connect({ createConnection })`.
+ */
+import http from 'node:http'
+import type { Socket } from 'node:net'
+
+const CONNECT_TIMEOUT_MS = 10_000
+
+export function openTunnel(proxyUrl: string, host: string, port: number): Promise {
+ const proxy = new URL(proxyUrl)
+ const headers: Record = { Host: `${host}:${port}` }
+ if (proxy.username) {
+ const credentials = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`
+ headers['Proxy-Authorization'] = `Basic ${Buffer.from(credentials).toString('base64')}`
+ }
+ return new Promise((resolve, reject) => {
+ const request = http.request({
+ host: proxy.hostname,
+ port: proxy.port || 80,
+ method: 'CONNECT',
+ path: `${host}:${port}`,
+ headers,
+ timeout: CONNECT_TIMEOUT_MS,
+ })
+ request.once('connect', (response, socket) => {
+ if (response.statusCode === 200) {
+ // The connect timeout must not outlive the handshake: an idle
+ // HTTP/2 session on this socket is normal.
+ socket.setTimeout(0)
+ return resolve(socket)
+ }
+ socket.destroy()
+ reject(new Error(`proxy refused CONNECT: ${response.statusCode}`))
+ })
+ request.once('timeout', () => request.destroy(new Error('proxy CONNECT timed out')))
+ request.once('error', reject)
+ request.end()
+ })
+}
diff --git a/apps/web/src/server/push.ts b/apps/web/src/server/push.ts
index bc621f13..68b8b7ee 100644
--- a/apps/web/src/server/push.ts
+++ b/apps/web/src/server/push.ts
@@ -1,5 +1,6 @@
/**
- * Web-push fan-out for room events.
+ * Push fan-out for room events: Web Push for browsers, APNs and FCM for the
+ * store apps (`server/push-native/`).
*
* The product rule is one line: you get a notification when SOMEBODY ELSE in a
* room you opted into writes something. Everything below exists to make that
@@ -13,8 +14,11 @@
* entering a trip's worth of receipts in one sitting is one session, not
* twenty events.
*
- * With no VAPID keys configured the whole module is inert — it warns once and
- * every send returns `disabled`. That is the local-dev and self-hoster default.
+ * Each transport turns on with its own credentials: VAPID keys for Web Push,
+ * the APNs key for iOS, the FCM service account for Android. Rows of a
+ * transport without credentials are skipped. With none configured the whole
+ * module is inert — it warns once and every send returns `disabled`. That is
+ * the local-dev and self-hoster default.
*/
import { Prisma, type PushSubscription as PushSubscriptionRow } from '@prisma/client'
import webpush, { type RequestOptions, WebPushError } from 'web-push'
@@ -29,6 +33,10 @@ import {
} from '@/server/notifyCopy'
import type { RoomWithRelations } from '@/server/roomState'
import type { RoomState } from '@/lib/api-types'
+import { sendApns } from '@/server/push-native/apns'
+import { apnsCredentials, fcmCredentials, type ApnsCredentials, type FcmCredentials } from '@/server/push-native/config'
+import { sendFcm } from '@/server/push-native/fcm'
+import { toNativeNotification, type NativeNotification } from '@/server/push-native/payload'
/** A 20-expense entry session must not fire 20 pushes. Post-delivery coalescing
* (one tag per room) would collapse them on the device, but they would still
@@ -130,6 +138,8 @@ export async function claimSend(
interface SendRoomEventInput {
room: RoomWithRelations
+ /** The room id app notifications carry instead of the slug. */
+ analyticsKey: string
template: NotificationTemplate
/** Whoever caused the event — excluded from delivery. Null when the writer
* sent no member token, in which case everyone subscribed gets it. */
@@ -139,13 +149,36 @@ interface SendRoomEventInput {
buildPayload: (sendId: string) => PushPayload
}
+interface Senders {
+ webPush: boolean
+ apns: ApnsCredentials | null
+ fcm: FcmCredentials | null
+}
+
+function configuredSenders(): Senders {
+ return { webPush: vapidReady(), apns: apnsCredentials(), fcm: fcmCredentials() }
+}
+
+function deliverableTransports(senders: Senders): string[] {
+ return [
+ ...(senders.webPush ? ['webpush'] : []),
+ ...(senders.apns ? ['apns', 'apns-sandbox'] : []),
+ ...(senders.fcm ? ['fcm'] : []),
+ ]
+}
+
export async function sendRoomEvent(input: SendRoomEventInput): Promise {
- if (!vapidReady()) return { status: 'disabled' }
+ const senders = configuredSenders()
+ const transports = deliverableTransports(senders)
+ if (transports.length === 0) return { status: 'disabled' }
const { room, template, actorMemberId } = input
const targets = await prisma.pushSubscription.findMany({
where: {
roomId: room.id,
+ // A row nobody here can deliver to is not a target: counting it
+ // would burn the dedupe slot on a send that cannot happen.
+ transport: { in: transports },
// Removal deletes subscriptions transactionally; this relation
// filter is defense in depth for legacy/orphaned rows.
member: { removedAt: null },
@@ -185,12 +218,17 @@ export async function sendRoomEvent(input: SendRoomEventInput): Promise deliver(target, payload, options)))
+ const payload = input.buildPayload(claim.id)
+ const results = await deliverAll(
+ targets,
+ payload,
+ toNativeNotification(payload, { slug: room.slug, analyticsKey: input.analyticsKey }),
+ senders
+ )
const dead = results.filter((r) => r.dead).map((r) => r.id)
- // A 404/410 is the push service saying the browser threw this endpoint away.
+ // A 404/410 (or APNs BadDeviceToken, FCM UNREGISTERED) is the push service
+ // saying the browser or app threw this endpoint away.
// Keeping it means retrying a corpse on every future event, forever.
if (dead.length > 0) await prisma.pushSubscription.deleteMany({ where: { id: { in: dead } } })
@@ -216,7 +254,44 @@ interface DeliveryResult {
statusCode?: number
}
-async function deliver(target: PushSubscriptionRow, payload: string, options: RequestOptions): Promise {
+type WebPushRow = PushSubscriptionRow & { transport: 'webpush'; p256dh: string; auth: string }
+
+const isWebPushRow = (row: PushSubscriptionRow): row is WebPushRow =>
+ row.transport === 'webpush' && row.p256dh !== null && row.auth !== null
+
+/** A native row's endpoint is `:`. */
+const nativeToken = (row: PushSubscriptionRow) => row.endpoint.slice(row.transport.length + 1)
+
+async function deliverAll(
+ targets: PushSubscriptionRow[],
+ payload: PushPayload,
+ notification: NativeNotification,
+ senders: Senders
+): Promise {
+ const web = targets.filter(isWebPushRow)
+ const apple = targets.filter((row) => row.transport === 'apns' || row.transport === 'apns-sandbox')
+ const google = targets.filter((row) => row.transport === 'fcm')
+ const webPayload = JSON.stringify(payload)
+ const options = requestOptions()
+ const [webResults, appleResults, googleResults] = await Promise.all([
+ Promise.all(web.map((target) => deliverWebPush(target, webPayload, options))),
+ senders.apns && apple.length > 0
+ ? sendApns(
+ senders.apns,
+ apple.map((row) => ({ token: nativeToken(row), sandbox: row.transport === 'apns-sandbox' })),
+ notification
+ )
+ : [],
+ senders.fcm && google.length > 0 ? sendFcm(senders.fcm, google.map(nativeToken), notification) : [],
+ ])
+ return [
+ ...webResults,
+ ...appleResults.map((result, index) => ({ id: apple[index].id, ...result })),
+ ...googleResults.map((result, index) => ({ id: google[index].id, ...result })),
+ ]
+}
+
+async function deliverWebPush(target: WebPushRow, payload: string, options: RequestOptions): Promise {
try {
await webpush.sendNotification(
{ endpoint: target.endpoint, keys: { p256dh: target.p256dh, auth: target.auth } },
@@ -255,6 +330,10 @@ export function notifyRoomWrite(input: {
const { room, state, actorMemberId, event } = input
const nameOf = (id: string | null | undefined) => room.members.find((m) => m.id === id)?.name ?? null
const roomRef = { slug: room.slug, name: room.name, emoji: room.emoji, currency: room.currency }
+ // `toRoomState` always sets the key; the wire type is optional only so old
+ // cached client state parses. An empty key would open the app's home, never
+ // a wrong room.
+ const analyticsKey = state.room.analyticsKey ?? ''
if (event.kind === 'expense_added') {
const expense = room.expenses.find((e) => e.id === event.expenseId)
@@ -262,6 +341,7 @@ export function notifyRoomWrite(input: {
fireAndForget(
sendRoomEvent({
room,
+ analyticsKey,
template: 'expense_added',
actorMemberId,
eventId: expense.id,
@@ -284,6 +364,7 @@ export function notifyRoomWrite(input: {
fireAndForget(
sendRoomEvent({
room,
+ analyticsKey,
template: 'settlement_recorded',
actorMemberId,
eventId: settlement.id,
@@ -308,6 +389,7 @@ export function notifyRoomWrite(input: {
fireAndForget(
sendRoomEvent({
room,
+ analyticsKey,
template: 'all_settled',
actorMemberId,
buildPayload: (sendId) => allSettledPayload({ room: roomRef, roomId: room.id, sendId }),
diff --git a/apps/web/src/server/test/push.test.ts b/apps/web/src/server/test/push.test.ts
index 0e6d3db3..0ad965d0 100644
--- a/apps/web/src/server/test/push.test.ts
+++ b/apps/web/src/server/test/push.test.ts
@@ -4,7 +4,8 @@
* regression uses real web-push and stubs only the HTTPS request. Prisma stays
* real so dedupe claims, daily caps, and endpoint pruning exercise database rules.
*/
-import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
+import { generateKeyPairSync } from 'node:crypto'
import { EventEmitter } from 'node:events'
import type { ClientRequest, IncomingMessage } from 'node:http'
import https from 'node:https'
@@ -20,6 +21,7 @@ import { DELETE as deleteSubscription, POST as postSubscription } from '@/app/ap
import { POST as postSubscriptionStatus } from '@/app/api/rooms/[slug]/push-subscriptions/status/route'
import { POST as postOpened } from '@/app/api/push/opened/route'
import { POST as postDismissed } from '@/app/api/push/dismissed/route'
+import { resetFcmToken } from '@/server/push-native/fcm'
import type { RoomStateWithMember } from '@/lib/api-types'
const { sendNotification } = vi.hoisted(() => ({ sendNotification: vi.fn() }))
@@ -240,6 +242,143 @@ describe('subscribe endpoint', () => {
})
})
+const APNS_TOKEN = 'a1b2c3d4'.repeat(8)
+const FCM_TOKEN = 'dGVzdA:APA91bH-native_device'
+const NATIVE_ENV = [
+ 'SPLIT_APNS_KEY_P8',
+ 'SPLIT_APNS_KEY_ID',
+ 'SPLIT_APNS_TEAM_ID',
+ 'SPLIT_APNS_BUNDLE_ID',
+ 'SPLIT_FCM_SERVICE_ACCOUNT_JSON',
+] as const
+
+/** Fake but well-formed credentials: nothing here reaches Apple or Google. */
+function setNativeCredentials(): void {
+ const ec = generateKeyPairSync('ec', { namedCurve: 'prime256v1' }).privateKey
+ const rsa = generateKeyPairSync('rsa', { modulusLength: 2048 }).privateKey
+ process.env.SPLIT_APNS_KEY_P8 = ec.export({ type: 'pkcs8', format: 'pem' }).toString()
+ process.env.SPLIT_APNS_KEY_ID = 'ABC123DEFG'
+ process.env.SPLIT_APNS_TEAM_ID = 'TEAM123456'
+ process.env.SPLIT_APNS_BUNDLE_ID = 'com.peanutsplit.app'
+ process.env.SPLIT_FCM_SERVICE_ACCOUNT_JSON = JSON.stringify({
+ project_id: 'split-test',
+ client_email: 'push@split-test.iam.gserviceaccount.com',
+ private_key: rsa.export({ type: 'pkcs8', format: 'pem' }).toString(),
+ })
+}
+
+function clearNativeCredentials(): void {
+ for (const name of NATIVE_ENV) delete process.env[name]
+}
+
+const nativeBody = (member: { id: string; token: string }, transport: string, token: string) => ({
+ transport,
+ token,
+ memberId: member.id,
+ memberToken: member.token,
+})
+
+const subscribeNative = (fixture: Fixture, member: { id: string; token: string }, transport: string, token: string) =>
+ call<{ subscribed: boolean } | { error: { code: string } }>(postSubscription as Handler, {
+ path: `/api/rooms/${fixture.slug}/push-subscriptions`,
+ method: 'POST',
+ params: { slug: fixture.slug },
+ body: nativeBody(member, transport, token),
+ })
+
+const askNativeStatus = (fixture: Fixture, member: { id: string; token: string }, transport: string, token: string) =>
+ call<{ subscribed: boolean } | { error: { code: string } }>(postSubscriptionStatus as Handler, {
+ path: `/api/rooms/${fixture.slug}/push-subscriptions/status`,
+ method: 'POST',
+ params: { slug: fixture.slug },
+ body: nativeBody(member, transport, token),
+ })
+
+describe('native app subscriptions', () => {
+ afterEach(clearNativeCredentials)
+
+ it('still rejects a web body without keys', async () => {
+ const fixture = await makeRoom()
+ const { status, body } = await call<{ error: { code: string } }>(postSubscription as Handler, {
+ path: `/api/rooms/${fixture.slug}/push-subscriptions`,
+ method: 'POST',
+ params: { slug: fixture.slug },
+ body: { endpoint: FCM('no-keys'), memberId: fixture.owner.id, memberToken: fixture.owner.token },
+ })
+ expect(status).toBe(400)
+ expect(body).toMatchObject({ error: { code: 'VALIDATION_ERROR' } })
+ expect(await prisma.pushSubscription.count()).toBe(0)
+ })
+
+ it('stores an app token under its prefixed endpoint, without keys', async () => {
+ setNativeCredentials()
+ const fixture = await makeRoom()
+ expect((await subscribeNative(fixture, fixture.owner, 'apns', APNS_TOKEN)).status).toBe(201)
+ expect((await subscribeNative(fixture, fixture.friend, 'fcm', FCM_TOKEN)).status).toBe(201)
+
+ const rows = await prisma.pushSubscription.findMany({ orderBy: { transport: 'asc' } })
+ expect(rows).toMatchObject([
+ { transport: 'apns', endpoint: `apns:${APNS_TOKEN}`, p256dh: null, auth: null, memberId: fixture.owner.id },
+ { transport: 'fcm', endpoint: `fcm:${FCM_TOKEN}`, p256dh: null, auth: null, memberId: fixture.friend.id },
+ ])
+ })
+
+ it('keeps web rows on the webpush transport', async () => {
+ const fixture = await makeRoom()
+ await subscribe(fixture, fixture.owner, FCM('a'))
+ expect(await prisma.pushSubscription.findFirst()).toMatchObject({ transport: 'webpush', endpoint: FCM('a') })
+ })
+
+ it('answers 503 NATIVE_PUSH_UNAVAILABLE on subscribe and status when the server has no credentials', async () => {
+ clearNativeCredentials()
+ const fixture = await makeRoom()
+
+ const subscribed = await subscribeNative(fixture, fixture.owner, 'fcm', FCM_TOKEN)
+ expect(subscribed.status).toBe(503)
+ expect(subscribed.body).toMatchObject({ error: { code: 'NATIVE_PUSH_UNAVAILABLE' } })
+ const status = await askNativeStatus(fixture, fixture.owner, 'apns-sandbox', APNS_TOKEN)
+ expect(status.status).toBe(503)
+ expect(status.body).toMatchObject({ error: { code: 'NATIVE_PUSH_UNAVAILABLE' } })
+ expect(await prisma.pushSubscription.count()).toBe(0)
+
+ // Web push is not gated on app credentials.
+ expect((await subscribe(fixture, fixture.owner, FCM('a'))).status).toBe(201)
+ })
+
+ it('answers status for a native token per room, and drops it on DELETE', async () => {
+ setNativeCredentials()
+ const first = await makeRoom()
+ const second = await makeRoom()
+ await subscribeNative(first, first.owner, 'apns-sandbox', APNS_TOKEN)
+
+ expect((await askNativeStatus(first, first.owner, 'apns-sandbox', APNS_TOKEN)).body).toEqual({
+ subscribed: true,
+ })
+ expect((await askNativeStatus(second, second.owner, 'apns-sandbox', APNS_TOKEN)).body).toEqual({
+ subscribed: false,
+ })
+ // The same token on the other APNs environment is a different channel.
+ expect((await askNativeStatus(first, first.owner, 'apns', APNS_TOKEN)).body).toEqual({ subscribed: false })
+
+ const removed = await call<{ subscribed: false; endpointStillUsed: boolean }>(deleteSubscription as Handler, {
+ path: `/api/rooms/${first.slug}/push-subscriptions`,
+ method: 'DELETE',
+ params: { slug: first.slug },
+ body: nativeBody(first.owner, 'apns-sandbox', APNS_TOKEN),
+ })
+ expect(removed.body).toEqual({ subscribed: false, endpointStillUsed: false })
+ expect(await prisma.pushSubscription.count()).toBe(0)
+ })
+
+ it('rejects a web body whose endpoint looks like a native channel', async () => {
+ const fixture = await makeRoom()
+ const { status, body } = await subscribe(fixture, fixture.owner, `fcm:${FCM_TOKEN}`)
+ expect(status).toBe(400)
+ expect(body).toMatchObject({ error: { code: 'UNSUPPORTED_PUSH_HOST' } })
+ expect(await prisma.pushSubscription.count()).toBe(0)
+ })
+})
+
describe('unsubscribe endpoint', () => {
it('preserves a channel rebound to another member when the previous member finishes cleanup', async () => {
const fixture = await makeRoom()
@@ -391,6 +530,7 @@ describe('send pipeline', () => {
const room = await loadRoom(fixture.slug)
return sendRoomEvent({
room,
+ analyticsKey: toRoomState(room).room.analyticsKey as string,
template: 'expense_added',
actorMemberId: fixture.owner.id,
eventId,
@@ -582,6 +722,7 @@ describe('send pipeline', () => {
const settled = () =>
sendRoomEvent({
room,
+ analyticsKey: toRoomState(room).room.analyticsKey as string,
template: 'all_settled',
actorMemberId: fixture.owner.id,
buildPayload: (sendId) => allSettledPayload({ room, roomId: room.id, sendId }),
@@ -592,6 +733,102 @@ describe('send pipeline', () => {
})
})
+describe('native fan-out', () => {
+ const fetchMock = vi.fn()
+
+ beforeEach(() => {
+ setNativeCredentials()
+ resetFcmToken()
+ fetchMock.mockReset()
+ vi.stubGlobal('fetch', fetchMock)
+ delete process.env.SPLIT_PUSH_PROXY_URL
+ })
+
+ afterEach(() => {
+ clearNativeCredentials()
+ vi.unstubAllGlobals()
+ vi.restoreAllMocks()
+ })
+
+ const seedNative = (roomId: string, memberId: string, transport: string, token: string) =>
+ prisma.pushSubscription.create({ data: { roomId, memberId, transport, endpoint: `${transport}:${token}` } })
+
+ it('sends FCM without the slug, keeps web push, and prunes an unregistered app token', async () => {
+ vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const fixture = await makeRoom()
+ await seedSubscription(fixture.roomId, fixture.friend.id, FCM('friend-browser'))
+ await seedNative(fixture.roomId, fixture.friend.id, 'fcm', 'live-android')
+ await seedNative(fixture.roomId, fixture.friend.id, 'fcm', 'gone-android')
+
+ const sent: unknown[] = []
+ fetchMock.mockImplementation(async (input, init) => {
+ if (String(input) === 'https://oauth2.googleapis.com/token') {
+ return Response.json({ access_token: 'access-1', expires_in: 3600 })
+ }
+ const message = JSON.parse(String(init?.body)) as { message: { token: string } }
+ sent.push(message)
+ return message.message.token === 'gone-android'
+ ? Response.json({ error: { details: [{ errorCode: 'UNREGISTERED' }] } }, { status: 404 })
+ : Response.json({ name: 'projects/split-test/messages/1' })
+ })
+
+ const room = await loadRoom(fixture.slug)
+ const analyticsKey = toRoomState(room).room.analyticsKey as string
+ const outcome = await sendRoomEvent({
+ room,
+ analyticsKey,
+ template: 'expense_added',
+ actorMemberId: fixture.owner.id,
+ eventId: 'native-1',
+ buildPayload: (sendId) =>
+ expenseAddedPayload({
+ room,
+ roomId: room.id,
+ sendId,
+ actorName: 'Ana',
+ description: 'Lift passes',
+ amountMinor: '12000',
+ currency: 'EUR',
+ }),
+ })
+
+ expect(outcome).toEqual({ status: 'sent', delivered: 2, pruned: 1 })
+ expect(sendNotification).toHaveBeenCalledTimes(1)
+ expect(sent).toHaveLength(2)
+ for (const message of sent) {
+ expect(JSON.stringify(message)).not.toContain(fixture.slug)
+ expect(message).toMatchObject({
+ message: {
+ notification: { title: 'Ski Trip', body: 'Ana added Lift passes — €120.00' },
+ data: { room: analyticsKey },
+ },
+ })
+ }
+ const left = await prisma.pushSubscription.findMany({ orderBy: { endpoint: 'asc' } })
+ expect(left.map((row) => row.endpoint)).toEqual(['fcm:live-android', FCM('friend-browser')])
+ })
+
+ it('skips app rows whose transport has no credentials, without burning the dedupe slot', async () => {
+ clearNativeCredentials()
+ const fixture = await makeRoom()
+ await seedNative(fixture.roomId, fixture.friend.id, 'fcm', 'android-without-server-key')
+ const room = await loadRoom(fixture.slug)
+
+ const outcome = await sendRoomEvent({
+ room,
+ analyticsKey: toRoomState(room).room.analyticsKey as string,
+ template: 'all_settled',
+ actorMemberId: fixture.owner.id,
+ buildPayload: (sendId) => allSettledPayload({ room, roomId: room.id, sendId }),
+ })
+
+ expect(outcome).toEqual({ status: 'skipped', reason: 'no-targets' })
+ expect(fetchMock).not.toHaveBeenCalled()
+ expect(await prisma.notificationSend.count()).toBe(0)
+ expect(await prisma.pushSubscription.count()).toBe(1)
+ })
+})
+
describe('all-settled detection', () => {
it('is false for an empty room and true once every balance is zero', async () => {
const fixture = await makeRoom()
diff --git a/apps/web/src/server/validation.ts b/apps/web/src/server/validation.ts
index 2226bfba..8fca1071 100644
--- a/apps/web/src/server/validation.ts
+++ b/apps/web/src/server/validation.ts
@@ -15,6 +15,8 @@ import {
MAX_MEMBERS,
MAX_NAME_CHARS,
} from '@/lib/splitwise-csv'
+import type { NativePushTransport } from '@/lib/api-types'
+import { NATIVE_PUSH_TRANSPORTS } from '@/server/push-native/config'
/**
* A currency code — one of the 162 real ones, or a ticker somebody invented.
@@ -274,28 +276,72 @@ const pushKey = z
.regex(/^[A-Za-z0-9_\-=]+$/, 'must be base64')
const memberSecret = z.string().min(1).max(200)
-export const pushSubscribeSchema = z.object({
- endpoint: pushEndpoint,
- keys: z.object({ p256dh: pushKey, auth: pushKey }),
- memberId: id,
- memberToken: memberSecret,
- userAgent: z.string().trim().max(512).nullish(),
-})
-
-export const pushUnsubscribeSchema = z.object({
- endpoint: pushEndpoint,
- memberId: id,
- memberToken: memberSecret,
-})
+const nativeTransport = z.enum(NATIVE_PUSH_TRANSPORTS)
+/**
+ * An APNs device token is hex; an FCM registration token is URL-safe base64
+ * with colons. The charset matters beyond tidiness: the APNs token becomes part
+ * of the HTTP/2 `:path`, so a slash or a question mark must never get through.
+ */
+const nativeToken = z
+ .string()
+ .trim()
+ .min(1)
+ .max(1024)
+ .regex(/^[A-Za-z0-9_:-]+$/, 'must be a device token')
+const isTokenShapeFor = (body: { transport: NativePushTransport; token: string }) =>
+ body.transport === 'fcm' || /^[0-9A-Fa-f]+$/.test(body.token)
+const nativeEndpoint = (body: { transport: NativePushTransport; token: string }) => `${body.transport}:${body.token}`
-/** Asking whether THIS room is on for this endpoint. Same three fields as the
- * unsubscribe, and deliberately its own schema: the question is a read, and it
- * must stay free to gain a field without widening what a delete accepts. */
-export const pushStatusSchema = z.object({
- endpoint: pushEndpoint,
- memberId: id,
- memberToken: memberSecret,
-})
+/**
+ * Both bodies normalise to one channel shape: `transport` plus the `endpoint`
+ * that is stored and looked up. A native token is stored as
+ * `:`, so `(endpoint, roomId)` uniqueness, the per-room cap
+ * and the status lookup work the same for every transport. A web body can never
+ * produce that shape: its URL must pass the https allowlist in the route.
+ */
+const webChannel = { endpoint: pushEndpoint }
+const nativeChannel = { transport: nativeTransport, token: nativeToken }
+const membership = { memberId: id, memberToken: memberSecret }
+const tokenShapeError = { message: 'must be an APNs device token', path: ['token'] }
+
+export const pushSubscribeSchema = z.union([
+ z
+ .object({
+ ...webChannel,
+ keys: z.object({ p256dh: pushKey, auth: pushKey }),
+ ...membership,
+ userAgent: z.string().trim().max(512).nullish(),
+ })
+ // A web body without keys fails here and then fails the native branch
+ // too (no transport), so it is still a 400.
+ .transform((body) => ({ ...body, transport: 'webpush' as const })),
+ z
+ .object({ ...nativeChannel, ...membership, userAgent: z.string().trim().max(512).nullish() })
+ .refine(isTokenShapeFor, tokenShapeError)
+ .transform(({ token, ...body }) => ({
+ ...body,
+ endpoint: nativeEndpoint({ transport: body.transport, token }),
+ keys: null,
+ })),
+])
+
+const pushChannelSchema = z.union([
+ z.object({ ...webChannel, ...membership }).transform((body) => ({ ...body, transport: 'webpush' as const })),
+ z
+ .object({ ...nativeChannel, ...membership })
+ .refine(isTokenShapeFor, tokenShapeError)
+ .transform(({ token, ...body }) => ({
+ ...body,
+ endpoint: nativeEndpoint({ transport: body.transport, token }),
+ })),
+])
+
+export const pushUnsubscribeSchema = pushChannelSchema
+
+/** Asking whether THIS room is on for this channel. Same fields as the
+ * unsubscribe today, under its own name: the question is a read, and it must
+ * stay free to gain a field without widening what a delete accepts. */
+export const pushStatusSchema = pushChannelSchema
/** What the service worker beacons back on a tap or a swipe-away. Every field is
* optional-ish because the worker is fire-and-forget and must never be the
diff --git a/docs/current/generated/API-ROUTES.md b/docs/current/generated/API-ROUTES.md
index e7a22d2b..da006f45 100644
--- a/docs/current/generated/API-ROUTES.md
+++ b/docs/current/generated/API-ROUTES.md
@@ -3,7 +3,7 @@
Source: `apps/web/src/app/**/route.ts`
-Input SHA-256: `406d4b2f3ea942224210b20d80c726b798a4453632dca910c3080d2d2df6f66f`
+Input SHA-256: `b8b1c068f080a5d25dd3fe5abcec4e449719b7ce68d65f6e4b57607aada9854d`
Exported operations: 43
diff --git a/docs/current/generated/DATA-MODEL-INVENTORY.md b/docs/current/generated/DATA-MODEL-INVENTORY.md
index de9da57c..4339de07 100644
--- a/docs/current/generated/DATA-MODEL-INVENTORY.md
+++ b/docs/current/generated/DATA-MODEL-INVENTORY.md
@@ -3,7 +3,7 @@
Source: `apps/web/prisma/schema.prisma`
-Input SHA-256: `a486551b2365dab7eb7a451ee4c0ccb8944a51f9e163bac5fddc0eb8bd7dd4b1`
+Input SHA-256: `bc2551cdab23f0df1ed0eb246f33278628f3bc137acf01bf5de44d82091d3d6b`
PostgreSQL namespace: `split`
Models: 15
@@ -206,19 +206,20 @@ Split modes: `EQUAL`, `EXACT`, `PERCENTAGE`, `SHARES`
## PushSubscription
-| Field | Prisma type | Attributes |
-| ------------ | ----------- | ------------------------------------------------------------------ |
-| `id` | `String` | @id @default(uuid()) |
-| `roomId` | `String` | — |
-| `memberId` | `String` | — |
-| `endpoint` | `String` | // push-service URL; the host is allowlisted at write time |
-| `p256dh` | `String` | — |
-| `auth` | `String` | — |
-| `userAgent` | `String?` | — |
-| `createdAt` | `DateTime` | @default(now()) |
-| `lastSeenAt` | `DateTime` | @default(now()) |
-| `room` | `Room` | @relation(fields: [roomId], references: [id], onDelete: Cascade) |
-| `member` | `Member` | @relation(fields: [memberId], references: [id], onDelete: Cascade) |
+| Field | Prisma type | Attributes |
+| ------------ | ----------- | ----------------------------------------------------------------------- |
+| `id` | `String` | @id @default(uuid()) |
+| `roomId` | `String` | — |
+| `memberId` | `String` | — |
+| `transport` | `String` | @default("webpush") |
+| `endpoint` | `String` | // webpush: allowlisted push-service URL; native: ":" |
+| `p256dh` | `String?` | // webpush only |
+| `auth` | `String?` | // webpush only |
+| `userAgent` | `String?` | — |
+| `createdAt` | `DateTime` | @default(now()) |
+| `lastSeenAt` | `DateTime` | @default(now()) |
+| `room` | `Room` | @relation(fields: [roomId], references: [id], onDelete: Cascade) |
+| `member` | `Member` | @relation(fields: [memberId], references: [id], onDelete: Cascade) |
## NotificationSend