Skip to content

The open-source AI receptionist for businesses. Answers every call, books the appointment and hands over to a person when needed. You own the code and the data.

Push notifications in the Linedesk app: APNs and FCM next to Web Push (PR 1999)

Tim Gutberlet43a3369abc88
diff --git a/apps/api/src/admin-overview.ts b/apps/api/src/admin-overview.ts
index cfbe5f1a..692c21d7 100644
--- a/apps/api/src/admin-overview.ts
+++ b/apps/api/src/admin-overview.ts
@@ -72,6 +72,8 @@ export const pricePerMinute: Record<ProviderName, number> = {
turnstile: 0,
// Partner addresses cost per custom hostname a month, not per call minute.
cloudflare_saas: 0,
+ apns: 0,
+ fcm: 0,
}
/** After-call transcription, per minute of the recording (only the picked service runs). */
@@ -160,6 +162,7 @@ async function activeRates(tx: Tx): Promise<ActiveRate[]> {
'apps',
'bot_check',
'domains',
+ 'mobile',
...((await realtimeInUse(tx)) ? ['stt', 'llm', 'tts'] : ['realtime']),
]
for (const category of categoryNames.filter(c => !skipped.includes(c))) {
diff --git a/apps/api/src/native-push.test.ts b/apps/api/src/native-push.test.ts
new file mode 100644
index 00000000..0600539b
--- /dev/null
+++ b/apps/api/src/native-push.test.ts
@@ -0,0 +1,111 @@
+import { generateKeyPairSync } from 'node:crypto'
+import { describe, expect, it } from 'vitest'
+import { apnsBody, fcmMessage, probeFcm, readApnsConfig, readFcmConfig, sendFcm } from './native-push.ts'
+
+const payload = {
+ callId: 'call_1',
+ kind: 'urgent' as const,
+ urgent: true,
+ title: 'Urgent: Sarah Whitfield',
+ body: 'Burst pipe',
+}
+const rsa = generateKeyPairSync('rsa', { modulusLength: 2048 })
+ .privateKey.export({ type: 'pkcs8', format: 'pem' })
+ .toString()
+const ec = generateKeyPairSync('ec', { namedCurve: 'P-256' })
+ .privateKey.export({ type: 'pkcs8', format: 'pem' })
+ .toString()
+const serviceAccount = JSON.stringify({
+ project_id: 'linedesk-app',
+ client_email: '[email protected]',
+ private_key: rsa,
+})
+
+describe('readApnsConfig', () => {
+ it('needs all four values; the key may come without line breaks', () => {
+ expect(readApnsConfig({ APNS_KEY_P8: ec, APNS_KEY_ID: 'K', APNS_TEAM_ID: 'T' })).toBeNull()
+ const config = readApnsConfig({
+ APNS_KEY_P8: ec.replace(/\n/g, ' '),
+ APNS_KEY_ID: 'K',
+ APNS_TEAM_ID: 'T',
+ APNS_BUNDLE_ID: 'ai.example.app',
+ })
+ expect(config?.key).toBe(ec)
+ })
+})
+
+describe('readFcmConfig', () => {
+ it('reads the service account file, and nothing from a broken one', () => {
+ expect(readFcmConfig({ FCM_SERVICE_ACCOUNT_JSON: serviceAccount })).toMatchObject({ projectId: 'linedesk-app' })
+ expect(readFcmConfig({ FCM_SERVICE_ACCOUNT_JSON: '{nope' })).toBeNull()
+ expect(readFcmConfig({ FCM_SERVICE_ACCOUNT_JSON: '{"project_id":"x"}' })).toBeNull()
+ })
+})
+
+describe('the notification', () => {
+ it('APNs: alert, one thread per call, time-sensitive when urgent', () => {
+ expect(apnsBody(payload)).toEqual({
+ aps: {
+ alert: { title: 'Urgent: Sarah Whitfield', body: 'Burst pipe' },
+ sound: 'default',
+ 'thread-id': 'call_1',
+ 'interruption-level': 'time-sensitive',
+ },
+ callId: 'call_1',
+ kind: 'urgent',
+ })
+ expect(apnsBody({ ...payload, urgent: false, body: '' }).aps).toMatchObject({
+ alert: { title: payload.title },
+ 'interruption-level': 'active',
+ })
+ })
+
+ it('FCM: the calls channel, newer news about the call replaces older', () => {
+ const { message } = fcmMessage('tok', payload)
+ expect(message.token).toBe('tok')
+ expect(message.data).toEqual({ callId: 'call_1', kind: 'urgent' })
+ expect(message.android).toMatchObject({
+ priority: 'HIGH',
+ collapse_key: 'call_1',
+ notification: { tag: 'call_1', channel_id: 'calls' },
+ })
+ })
+})
+
+describe('sendFcm', () => {
+ const config = readFcmConfig({ FCM_SERVICE_ACCOUNT_JSON: serviceAccount })!
+ const fakeGoogle = (send: Response) => {
+ const calls: string[] = []
+ const doFetch = (async (url: string) => {
+ calls.push(String(url))
+ if (String(url).includes('oauth2')) return Response.json({ access_token: 'at', expires_in: 3600 })
+ return send
+ }) as typeof fetch
+ return { calls, doFetch }
+ }
+
+ it('sends with an access token from the service account', async () => {
+ const google = fakeGoogle(Response.json({ name: 'projects/x/messages/1' }))
+ expect(await sendFcm(config, 'tok', payload, 1000, google.doFetch)).toBe('sent')
+ expect(google.calls.at(-1)).toBe('https://fcm.googleapis.com/v1/projects/linedesk-app/messages:send')
+ })
+
+ it('a removed app is gone, a server error is an error', async () => {
+ const gone = Response.json(
+ { error: { status: 'NOT_FOUND', details: [{ errorCode: 'UNREGISTERED' }] } },
+ { status: 404 },
+ )
+ expect(await sendFcm(config, 'tok', payload, 1000, fakeGoogle(gone).doFetch)).toBe('gone')
+ await expect(
+ sendFcm(config, 'tok', payload, 1000, fakeGoogle(new Response('', { status: 503 })).doFetch),
+ ).rejects.toThrow(/503/)
+ // A refused message is no proof that the phone is gone: an error, the device stays.
+ const refused = Response.json({ error: { status: 'INVALID_ARGUMENT' } }, { status: 400 })
+ await expect(sendFcm(config, 'tok', payload, 1000, fakeGoogle(refused).doFetch)).rejects.toThrow(/INVALID_ARGUMENT/)
+ })
+
+ it('test connection: a made-up token Google refuses means the keys work', async () => {
+ expect(await probeFcm(config, 1000, fakeGoogle(new Response('{}', { status: 400 })).doFetch)).toBe('ok')
+ expect(await probeFcm(config, 1000, fakeGoogle(new Response('{}', { status: 403 })).doFetch)).toBe('project')
+ })
+})
diff --git a/apps/api/src/native-push.ts b/apps/api/src/native-push.ts
new file mode 100644
index 00000000..28825c24
--- /dev/null
+++ b/apps/api/src/native-push.ts
@@ -0,0 +1,399 @@
+// Pushes to the Linedesk app (iOS, Android; apps/mobile): Apple's push service (APNs) for iOS, Google's Firebase Cloud
+// Messaging (FCM) for Android. A device is stored like a browser (push_subscriptions) with the endpoint
+// `apns:<token>` or `fcm:<token>` (packages/actions notifications.ts). The keys come from Server admin › Providers ›
+// Mobile app push (or APNS_*, FCM_SERVICE_ACCOUNT_JSON) and are read at each push (nativePushConfigs), so a change
+// there needs no restart.
+// The payload is the web push's (push.ts): who called and, for members who opted in, one line on what about.
+import { createHash, createPrivateKey, sign } from 'node:crypto'
+import { type ClientHttp2Session, connect } from 'node:http2'
+import type { Tx } from '@linedesk/db'
+import { resolveProvider } from './provider-settings.ts'
+import type { PushPayload } from './push.ts'
+
+type Env = Record<string, string | undefined>
+
+/** How long one push may take (the same as a web push's, push.ts SEND_TIMEOUT_MS; not imported: push.ts imports this). */
+const SEND_TIMEOUT_MS = 5000
+
+/** How long a push may wait for an offline phone: news about a call goes stale (the web push's TTL). */
+const TTL_SECONDS = 12 * 60 * 60
+
+const base64url = (value: string | Buffer) => Buffer.from(value).toString('base64url')
+
+/** A JWT signed with `key` (ES256 for Apple, RS256 for Google). */
+function jwt(header: object, claims: object, key: string, alg: 'ES256' | 'RS256'): string {
+ const body = `${base64url(JSON.stringify(header))}.${base64url(JSON.stringify(claims))}`
+ const signature = sign('sha256', Buffer.from(body), {
+ key: createPrivateKey(key),
+ ...(alg === 'ES256' && { dsaEncoding: 'ieee-p1363' as const }),
+ })
+ return `${body}.${base64url(signature)}`
+}
+
+/** A key pasted without its line breaks (a form field) or with `\n` (an env file), as PEM again. */
+function pem(raw: string): string {
+ const text = raw.replace(/\\n/g, '\n').trim()
+ const armour = /-----BEGIN ([A-Z ]+)-----/.exec(text)?.[1] ?? 'PRIVATE KEY'
+ const body = text.replace(/-----(BEGIN|END) [A-Z ]+-----/g, '').replace(/\s+/g, '')
+ return `-----BEGIN ${armour}-----\n${body.match(/.{1,64}/g)?.join('\n') ?? ''}\n-----END ${armour}-----\n`
+}
+
+export type NativeAnswer = 'sent' | 'gone'
+
+/** A title stays short (a caller's name can be long): the push's size limits are 4 KB. */
+const MAX_TITLE = 120
+
+// --- Apple (APNs) ----------------------------------------------------------------------------------------------------
+
+export type ApnsConfig = { key: string; keyId: string; teamId: string; bundleId: string }
+
+/** All four values, and a key that is a private key (a broken one leaves iOS push off, and Test connection says so). */
+export function readApnsConfig(env: Env = process.env): ApnsConfig | null {
+ const key = env.APNS_KEY_P8?.trim()
+ const keyId = env.APNS_KEY_ID?.trim()
+ const teamId = env.APNS_TEAM_ID?.trim()
+ const bundleId = env.APNS_BUNDLE_ID?.trim()
+ if (!key || !keyId || !teamId || !bundleId) return null
+ try {
+ createPrivateKey(pem(key))
+ } catch {
+ return null
+ }
+ return { key: pem(key), keyId, teamId, bundleId }
+}
+
+/** What a cached token was made from: every field, so another key with the same IDs never reuses it (review of #1999). */
+const fingerprint = (...parts: string[]) => createHash('sha256').update(parts.join('\n')).digest('hex')
+
+const APNS_HOSTS = { production: 'https://api.push.apple.com', sandbox: 'https://api.sandbox.push.apple.com' }
+
+/**
+ * Apple's provider tokens, one per key (fingerprint of key, key ID and team): renewed after 50 minutes. Apple refuses
+ * a token older than an hour and answers 429 TooManyProviderTokenUpdates when a key gets new ones too often, so Test
+ * connection uses the same cache; a token for other values never stands in for the saved key (review of #1999).
+ */
+const apnsTokens = new Map<string, { value: string; at: number }>()
+function apnsProviderToken(config: ApnsConfig, now = Date.now()): string {
+ const signer = fingerprint(config.key, config.keyId, config.teamId)
+ const kept = apnsTokens.get(signer)
+ if (kept && now - kept.at < 50 * 60 * 1000) return kept.value
+ const value = jwt(
+ { alg: 'ES256', kid: config.keyId },
+ { iss: config.teamId, iat: Math.floor(now / 1000) },
+ config.key,
+ 'ES256',
+ )
+ if (apnsTokens.size > 20) apnsTokens.clear()
+ apnsTokens.set(signer, { value, at: now })
+ return value
+}
+
+/** A token Apple refused (InvalidProviderToken, ExpiredProviderToken) is made again at the next push. */
+const forgetApnsToken = (config: ApnsConfig) => apnsTokens.delete(fingerprint(config.key, config.keyId, config.teamId))
+
+/** The notification as APNs takes it: an alert, the call's thread, and time-sensitive for urgent calls. */
+export function apnsBody(payload: PushPayload) {
+ return {
+ aps: {
+ alert: { title: payload.title.slice(0, MAX_TITLE), ...(payload.body && { body: payload.body }) },
+ sound: 'default',
+ 'thread-id': payload.callId,
+ 'interruption-level': payload.urgent ? 'time-sensitive' : 'active',
+ },
+ callId: payload.callId,
+ kind: payload.kind,
+ }
+}
+
+type Http2Answer = { status: number; body: string }
+
+/**
+ * One HTTP/2 connection per APNs host, kept and reused (Apple asks not to open one per push); a closed or failed one
+ * is dropped and the next push connects again.
+ */
+const sessions = new Map<string, ClientHttp2Session>()
+function sessionFor(origin: string): ClientHttp2Session {
+ const open = sessions.get(origin)
+ if (open && !open.closed && !open.destroyed) return open
+ const session = connect(origin)
+ const drop = () => {
+ if (sessions.get(origin) === session) sessions.delete(origin)
+ }
+ session.on('error', drop)
+ session.on('goaway', drop)
+ session.on('close', drop)
+ // Idle connections close after a while; nothing keeps the process alive for them.
+ session.setTimeout(10 * 60 * 1000, () => session.close())
+ session.unref()
+ sessions.set(origin, session)
+ return session
+}
+
+function http2Post(origin: string, path: string, headers: Record<string, string>, body: string, timeoutMs: number) {
+ return new Promise<Http2Answer>((resolve, reject) => {
+ const session = sessionFor(origin)
+ const req = session.request({ ':method': 'POST', ':path': path, ...headers })
+ const timer = setTimeout(() => {
+ req.close()
+ // i18n-ignore: a log line of the push job, never shown to a person
+ reject(new Error(`no answer from ${origin} within ${timeoutMs} ms`))
+ }, timeoutMs)
+ let status = 0
+ let data = ''
+ req.on('response', h => {
+ status = Number(h[':status'])
+ })
+ req.setEncoding('utf8')
+ req.on('data', chunk => {
+ data += chunk
+ })
+ req.on('end', () => {
+ clearTimeout(timer)
+ resolve({ status, body: data })
+ })
+ req.on('error', e => {
+ clearTimeout(timer)
+ reject(e)
+ })
+ req.end(body)
+ })
+}
+
+/**
+ * APNs reasons that mean the token is no device (any more): the row goes. Not DeviceTokenNotForTopic: that is a wrong
+ * bundle ID in Server admin, which must not delete every iOS device (review of #1999).
+ */
+// i18n-ignore: Apple's reason codes, not text
+const APNS_GONE = new Set(['Unregistered', 'BadDeviceToken'])
+/** Reasons that the provider token is refused: it is made again at the next push. */
+const APNS_TOKEN_REFUSED = /ProviderToken/
+
+export async function sendApns(
+ config: ApnsConfig,
+ deviceToken: string,
+ payload: PushPayload,
+ timeoutMs: number,
+): Promise<NativeAnswer> {
+ const headers = {
+ authorization: `bearer ${apnsProviderToken(config)}`,
+ 'apns-topic': config.bundleId,
+ 'apns-push-type': 'alert',
+ 'apns-priority': payload.urgent ? '10' : '5',
+ 'apns-expiration': String(Math.floor(Date.now() / 1000) + TTL_SECONDS),
+ // Newer news about the same call replaces the older one on the phone.
+ 'apns-collapse-id': payload.callId.slice(0, 64),
+ 'content-type': 'application/json',
+ }
+ const body = JSON.stringify(apnsBody(payload))
+ const path = `/3/device/${deviceToken}`
+ // App Store and TestFlight builds use production; a build from Xcode the sandbox, which answers BadDeviceToken
+ // for the other's tokens, so the sandbox is asked second, within the same time.
+ const deadline = Date.now() + timeoutMs
+ for (const env of ['production', 'sandbox'] as const) {
+ const left = deadline - Date.now()
+ if (left <= 0) break
+ const answer = await http2Post(APNS_HOSTS[env], path, headers, body, left)
+ if (answer.status === 200) return 'sent'
+ const reason = (JSON.parse(answer.body || '{}') as { reason?: string }).reason ?? ''
+ if (answer.status === 400 && reason === 'BadDeviceToken' && env === 'production') continue
+ if (answer.status === 410 || APNS_GONE.has(reason)) return 'gone'
+ if (APNS_TOKEN_REFUSED.test(reason) && reason !== 'TooManyProviderTokenUpdates') forgetApnsToken(config)
+ throw new Error(`APNs answered ${answer.status}${reason ? ` (${reason.slice(0, 60)})` : ''}`)
+ }
+ // i18n-ignore: a log line of the push job, never shown to a person
+ throw new Error('APNs did not answer in time')
+}
+
+// --- Google (FCM) ----------------------------------------------------------------------------------------------------
+
+export type FcmConfig = { projectId: string; clientEmail: string; privateKey: string }
+
+/** FCM_SERVICE_ACCOUNT_JSON: the service account key file Firebase gives (Project settings › Service accounts). */
+export function readFcmConfig(env: Env = process.env): FcmConfig | null {
+ const raw = env.FCM_SERVICE_ACCOUNT_JSON?.trim()
+ if (!raw) return null
+ try {
+ const file = JSON.parse(raw) as { project_id?: unknown; client_email?: unknown; private_key?: unknown }
+ if (typeof file.project_id !== 'string' || typeof file.client_email !== 'string') return null
+ if (typeof file.private_key !== 'string') return null
+ return { projectId: file.project_id, clientEmail: file.client_email, privateKey: pem(file.private_key) }
+ } catch {
+ return null
+ }
+}
+
+const fcmAccess = new Map<string, { value: string; until: number }>()
+/**
+ * A Google access token for FCM, from the service account (OAuth 2 JWT bearer), kept until shortly before it ends,
+ * per whole account (key included), so the token of other values never stands in for the saved account.
+ */
+async function fcmAccessToken(config: FcmConfig, doFetch: typeof fetch, timeoutMs: number): Promise<string> {
+ const now = Date.now()
+ const account = fingerprint(config.projectId, config.clientEmail, config.privateKey)
+ const kept = fcmAccess.get(account)
+ if (kept && kept.until > now + 60_000) return kept.value
+ const iat = Math.floor(now / 1000)
+ const assertion = jwt(
+ { alg: 'RS256', typ: 'JWT' },
+ {
+ iss: config.clientEmail,
+ scope: 'https://www.googleapis.com/auth/firebase.messaging',
+ aud: 'https://oauth2.googleapis.com/token',
+ iat,
+ exp: iat + 3600,
+ },
+ config.privateKey,
+ 'RS256',
+ )
+ const res = await doFetch('https://oauth2.googleapis.com/token', {
+ method: 'POST',
+ headers: { 'content-type': 'application/x-www-form-urlencoded' },
+ body: new URLSearchParams({ grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', assertion }),
+ signal: AbortSignal.timeout(timeoutMs),
+ })
+ const body = (await res.json().catch(() => ({}))) as { access_token?: string; expires_in?: number; error?: string }
+ // i18n-ignore: a log line of the push job, never shown to a person
+ const refusedBy = `Google refused the FCM service account (${body.error ?? res.status})`
+ if (!res.ok || !body.access_token) throw new Error(refusedBy)
+ if (fcmAccess.size > 20) fcmAccess.clear()
+ fcmAccess.set(account, { value: body.access_token, until: now + (body.expires_in ?? 3600) * 1000 })
+ return body.access_token
+}
+
+/** The message as FCM HTTP v1 takes it: a notification on the "calls" channel, newer news replacing older. */
+export function fcmMessage(deviceToken: string, payload: PushPayload) {
+ return {
+ message: {
+ token: deviceToken,
+ notification: { title: payload.title.slice(0, MAX_TITLE), ...(payload.body && { body: payload.body }) },
+ data: { callId: payload.callId, kind: payload.kind },
+ android: {
+ priority: payload.urgent ? 'HIGH' : 'NORMAL',
+ ttl: `${TTL_SECONDS}s`,
+ collapse_key: payload.callId,
+ notification: { tag: payload.callId, channel_id: 'calls' },
+ },
+ },
+ }
+}
+
+export async function sendFcm(
+ config: FcmConfig,
+ deviceToken: string,
+ payload: PushPayload,
+ timeoutMs: number,
+ doFetch: typeof fetch = fetch,
+): Promise<NativeAnswer> {
+ const access = await fcmAccessToken(config, doFetch, timeoutMs)
+ const res = await doFetch(
+ `https://fcm.googleapis.com/v1/projects/${encodeURIComponent(config.projectId)}/messages:send`,
+ {
+ method: 'POST',
+ headers: { authorization: `Bearer ${access}`, 'content-type': 'application/json' },
+ body: JSON.stringify(fcmMessage(deviceToken, payload)),
+ signal: AbortSignal.timeout(timeoutMs),
+ },
+ )
+ if (res.ok) return 'sent'
+ const body = (await res.json().catch(() => ({}))) as {
+ error?: { status?: string; details?: { errorCode?: string }[] }
+ }
+ const codes = [body.error?.status, ...(body.error?.details ?? []).map(d => d.errorCode)]
+ // The app was removed, or the token was never one of this app's.
+ // Only these say the phone is gone; INVALID_ARGUMENT or SENDER_ID_MISMATCH can be our message or the project, which
+ // must not delete devices (review of #1999).
+ if (res.status === 404 || codes.includes('UNREGISTERED')) return 'gone'
+ if (res.status === 401) fcmAccess.delete(fingerprint(config.projectId, config.clientEmail, config.privateKey))
+ throw new Error(`FCM answered ${res.status}${body.error?.status ? ` (${body.error.status.slice(0, 40)})` : ''}`)
+}
+
+export type NativePushConfigs = { apns: ApnsConfig | null; fcm: FcmConfig | null }
+
+/** The keys in effect (Server admin, else the server's variables). A key that cannot be read leaves its channel off. */
+export async function nativePushConfigs(tx: Tx): Promise<NativePushConfigs> {
+ const value = async (provider: 'apns' | 'fcm') => {
+ const config = await resolveProvider(tx, provider).catch(() => null)
+ return (field: string) => config?.[field]?.value
+ }
+ const [apns, fcm] = await Promise.all([value('apns'), value('fcm')])
+ return {
+ apns: readApnsConfig({
+ APNS_KEY_P8: apns('key'),
+ APNS_KEY_ID: apns('key_id'),
+ APNS_TEAM_ID: apns('team_id'),
+ APNS_BUNDLE_ID: apns('bundle_id'),
+ }),
+ fcm: readFcmConfig({ FCM_SERVICE_ACCOUNT_JSON: fcm('service_account') }),
+ }
+}
+
+/** Sends to a native device by its endpoint (`apns:…`, `fcm:…`); 'gone' when its channel has no keys any more. */
+export type NativeSender = (configs: NativePushConfigs, endpoint: string, payload: PushPayload) => Promise<NativeAnswer>
+
+export const sendNative: NativeSender = async (configs, endpoint, payload) => {
+ if (endpoint.startsWith('apns:')) {
+ // i18n-ignore: a log line of the push job, never shown to a person
+ if (!configs.apns) throw new Error('APNs keys are not set up')
+ return sendApns(configs.apns, endpoint.slice(5), payload, SEND_TIMEOUT_MS)
+ }
+ if (endpoint.startsWith('fcm:')) {
+ // i18n-ignore: a log line of the push job, never shown to a person
+ if (!configs.fcm) throw new Error('FCM is not set up')
+ return sendFcm(configs.fcm, endpoint.slice(4), payload, SEND_TIMEOUT_MS)
+ }
+ return 'gone'
+}
+
+// --- Test connection (provider-test.ts) ------------------------------------------------------------------------------
+
+/**
+ * APNs with a made-up device token: BadDeviceToken means the key, key ID and team are right (Apple checks them first),
+ * InvalidProviderToken that they are not, a topic reason that the bundle ID is not this team's app. Nothing is shown.
+ */
+export async function probeApns(config: ApnsConfig, timeoutMs: number): Promise<'ok' | 'auth' | 'topic' | string> {
+ const answer = await http2Post(
+ APNS_HOSTS.production,
+ `/3/device/${'0'.repeat(64)}`,
+ {
+ authorization: `bearer ${apnsProviderToken(config)}`,
+ 'apns-topic': config.bundleId,
+ 'apns-push-type': 'alert',
+ 'content-type': 'application/json',
+ },
+ JSON.stringify({ aps: { alert: 'test' } }),
+ timeoutMs,
+ )
+ const reason = (JSON.parse(answer.body || '{}') as { reason?: string }).reason ?? String(answer.status)
+ if (reason === 'BadDeviceToken') return 'ok'
+ if (/ProviderToken|Forbidden/.test(reason) || answer.status === 403) return 'auth'
+ if (/Topic/.test(reason)) return 'topic'
+ return reason.slice(0, 60)
+}
+
+/**
+ * FCM: an access token from the service account, then a message to a made-up token with `validate_only` (nothing is
+ * sent): INVALID_ARGUMENT means the project takes messages from this account.
+ */
+export async function probeFcm(config: FcmConfig, timeoutMs: number, doFetch: typeof fetch = fetch) {
+ let access: string
+ try {
+ access = await fcmAccessToken(config, doFetch, timeoutMs)
+ } catch {
+ return 'auth' as const
+ }
+ const res = await doFetch(
+ `https://fcm.googleapis.com/v1/projects/${encodeURIComponent(config.projectId)}/messages:send`,
+ {
+ method: 'POST',
+ headers: { authorization: `Bearer ${access}`, 'content-type': 'application/json' },
+ body: JSON.stringify({
+ validate_only: true,
+ message: { token: 'linedesk-connection-test', notification: { title: 'test' } },
+ }),
+ signal: AbortSignal.timeout(timeoutMs),
+ },
+ )
+ if (res.status === 400) return 'ok' as const
+ if (res.status === 401 || res.status === 403 || res.status === 404) return 'project' as const
+ return String(res.status)
+}
diff --git a/apps/api/src/provider-test.ts b/apps/api/src/provider-test.ts
index 6a44cb64..990f9395 100644
--- a/apps/api/src/provider-test.ts
+++ b/apps/api/src/provider-test.ts
@@ -23,6 +23,7 @@ import {
import { LIVE_KEYS_REFUSED, liveKeysAllowed, loadBillingProvider, stripeKeyMode } from '@linedesk/billing'
import { JOBBER_API, JOBBER_CLIENT_REFUSED, ZOHO_CLIENT_REFUSED, ZOHO_DATA_CENTERS } from '@linedesk/connectors'
import { msg } from '@linedesk/i18n'
+import { probeApns, probeFcm, readApnsConfig, readFcmConfig } from './native-push.ts'
import { smtpCheck } from './email.ts'
import { ResendError, resendKeyCheck } from './email-resend.ts'
import { isMailService, type MailService, mailConnectionOf } from './email-services.ts'
@@ -544,6 +545,46 @@ const zoho: Check = async (values, http) => {
return warning('unknown', said('server.api.providerTest.answered', { provider: label, status: res.status }))
}
+// The app's push keys (native-push.ts): a push to a made-up device, which Apple and Google refuse only after the keys.
+const apns: Check = async values => {
+ const config = (() => {
+ try {
+ return readApnsConfig({
+ APNS_KEY_P8: values.key,
+ APNS_KEY_ID: values.key_id,
+ APNS_TEAM_ID: values.team_id,
+ APNS_BUNDLE_ID: values.bundle_id,
+ })
+ } catch {
+ return null
+ }
+ })()
+ if (!config) return error('config', said('server.api.providerTest.apns.key'))
+ try {
+ const answer = await probeApns(config, TIMEOUT_MS)
+ if (answer === 'ok') return ok()
+ if (answer === 'auth') return error('auth', said('server.api.providerTest.apns.key'))
+ if (answer === 'topic') return error('config', said('server.api.providerTest.apns.bundle'))
+ return error('unknown', said('server.api.providerTest.apns.answered', { reason: answer }))
+ } catch {
+ return error('network', said('server.api.providerTest.apns.unreachable'))
+ }
+}
+
+const fcm: Check = async values => {
+ const config = readFcmConfig({ FCM_SERVICE_ACCOUNT_JSON: values.service_account })
+ if (!config) return error('config', said('server.api.providerTest.fcm.file'))
+ try {
+ const answer = await probeFcm(config, TIMEOUT_MS)
+ if (answer === 'ok') return ok()
+ if (answer === 'auth') return error('auth', said('server.api.providerTest.fcm.file'))
+ if (answer === 'project') return error('config', said('server.api.providerTest.fcm.project'))
+ return error('unknown', said('server.api.providerTest.fcm.answered', { status: answer }))
+ } catch {
+ return error('network', said('server.api.providerTest.fcm.unreachable'))
+ }
+}
+
// Shopify's token endpoint lives on each shop's own domain, so without a shop nothing can test the client secret: only
// the client ID's form is checked here, the keys themselves when the first business connects.
const shopify: Check = async values => {
@@ -577,6 +618,8 @@ const checks: Record<HttpProvider, Check> = {
zoho,
turnstile,
cloudflare_saas: cloudflareSaas,
+ apns,
+ fcm,
}
// --- Billing ------------------------------------------------------------------------------------
diff --git a/apps/api/src/push.ts b/apps/api/src/push.ts
index 78d70328..01f33918 100644
--- a/apps/api/src/push.ts
+++ b/apps/api/src/push.ts
@@ -5,7 +5,13 @@
// The payload is minimal: who called, and only for members who opted in, one line on what about.
// Never a transcript. VAPID keys are made and stored on the first start (instance-env.ts); VAPID_* on the server win.
import { Agent } from 'node:https'
-import { isPushServiceUrl, type PushSettings, pushDeviceId } from '@linedesk/actions'
+import {
+ isNativePushEndpoint,
+ isPushServiceUrl,
+ nativePushEndpoint,
+ type PushSettings,
+ pushDeviceId,
+} from '@linedesk/actions'
import { calls, contacts, member, member_notification_settings, push_subscriptions, type Tx, user } from '@linedesk/db'
import type { Call } from '@linedesk/db/types'
import { and, desc, eq, inArray, isNull, ne } from 'drizzle-orm'
@@ -17,6 +23,7 @@ import { assignedPushText, callPushTitle } from './emails/push-text.ts'
import type { EmailLocale } from './emails/templates.ts'
import { type Handler, Forbidden, Reject } from './handler-context.ts'
import { createRateLimiter } from './rate-limit.ts'
+import { type NativePushConfigs, type NativeSender, nativePushConfigs, sendNative } from './native-push.ts'
import { publicLookup } from './webhooks.ts'
type Env = Record<string, string | undefined>
@@ -89,6 +96,12 @@ export function pushSenderFromEnv(env: Env = process.env): PushSender {
}
}
+let nativeSender: NativeSender = sendNative
+/** For tests: another sender for the app's devices (null: the real one). */
+export const setNativeSender = (sender: NativeSender | null) => {
+ nativeSender = sender ?? sendNative
+}
+
let defaultSender: PushSender | null = null
/** The install's sender, read from the environment once. */
export const pushSender = () => (defaultSender ??= pushSenderFromEnv())
@@ -184,6 +197,7 @@ type Recipient = Awaited<ReturnType<typeof pushRecipients>>[number]
async function deliver(
tx: Tx,
sender: PushSender,
+ native: NativePushConfigs,
call: Call,
recipients: Recipient[],
payloadFor: (r: Recipient) => PushPayload,
@@ -193,8 +207,12 @@ async function deliver(
const gone: string[] = []
await inParallel(recipients, concurrency, async r => {
const target = { endpoint: r.endpoint, keys: { p256dh: r.p256dh, auth: r.auth } }
+ // The app's phones (APNs, FCM: native-push.ts) by their endpoint; browsers through Web Push.
+ const send = isNativePushEndpoint(r.endpoint)
+ ? nativeSender(native, r.endpoint, payloadFor(r))
+ : sender.send(target, payloadFor(r))
try {
- if ((await withTimeout(sender.send(target, payloadFor(r)), timeoutMs)) === 'sent') result.sent++
+ if ((await withTimeout(send, timeoutMs)) === 'sent') result.sent++
else gone.push(r.endpoint)
} catch (e) {
result.failed++
@@ -206,10 +224,15 @@ async function deliver(
return result
}
-/** The call a push is about, or why none goes out. */
-async function pushableCall(tx: Tx, sender: PushSender, callId: string): Promise<Call | PushResult> {
+/** The call a push is about, or why none goes out (no way to push at all: no Web Push and no app keys). */
+async function pushableCall(
+ tx: Tx,
+ sender: PushSender,
+ native: NativePushConfigs,
+ callId: string,
+): Promise<Call | PushResult> {
const none: PushResult = { sent: 0, gone: 0, failed: 0 }
- if (!sender.publicKey) return { ...none, skipped: 'off' }
+ if (!sender.publicKey && !native.apns && !native.fcm) return { ...none, skipped: 'off' }
const [call] = await tx.select().from(calls).where(eq(calls.id, callId))
if (!call || call.deleted_at) return { ...none, skipped: 'missing' }
if (call.source === 'test') return { ...none, skipped: 'test' }
@@ -228,13 +251,15 @@ export async function notifyCallPush(
kind: PushKind,
options: SendOptions = {},
): Promise<PushResult> {
- const call = await pushableCall(tx, sender, callId)
+ const native = await nativePushConfigs(tx)
+ const call = await pushableCall(tx, sender, native, callId)
if (!('id' in call)) return call
const callerName = await callerNameOf(tx, call)
const recipients = await pushRecipients(tx, call.workspace_id)
return deliver(
tx,
sender,
+ native,
call,
recipients,
r => pushPayload(call, kind, callerName, r.summary === true, localeForUser(r)),
@@ -251,13 +276,15 @@ export async function notifyAssignedPush(
byName: string,
options: SendOptions = {},
): Promise<PushResult> {
- const call = await pushableCall(tx, sender, callId)
+ const native = await nativePushConfigs(tx)
+ const call = await pushableCall(tx, sender, native, callId)
if (!('id' in call)) return call
const callerName = await callerNameOf(tx, call)
const recipients = await pushRecipients(tx, call.workspace_id, userId)
return deliver(
tx,
sender,
+ native,
call,
recipients,
r => assignedPushPayload(call, callerName, byName, r.summary === true, localeForUser(r)),
@@ -289,8 +316,10 @@ export async function pushSettings(
.select({ endpoint: push_subscriptions.endpoint })
.from(push_subscriptions)
.where(and(eq(push_subscriptions.workspace_id, workspaceId), eq(push_subscriptions.user_id, userId)))
+ const native = await nativePushConfigs(tx)
return {
publicKey: pushSender().publicKey,
+ native: { ios: native.apns !== null, android: native.fcm !== null },
devices: await Promise.all(rows.map(r => pushDeviceId(r.endpoint))),
summary: summary === true,
}
@@ -378,6 +407,31 @@ export const pushHandlers: Record<string, Handler> = {
return { rows: {} }
},
+ // The Linedesk app on a phone (iOS: APNs, Android: FCM; native-push.ts). A token is one install of the app on one
+ // phone: a row of someone else with it means the phone changed hands without signing out, so theirs goes.
+ 'push.registerDevice': async ({ tx, actor, now }, input: { platform: 'ios' | 'android'; token: string }) => {
+ const { workspaceId, userId } = pushMember(actor)
+ const native = await nativePushConfigs(tx)
+ if (!(input.platform === 'ios' ? native.apns : native.fcm))
+ throw Reject.t('server.api.push.appNotSetUp')
+ if (!allowSubscribe(userId)) throw new Reject('too many push subscriptions in the last hour; try again later')
+ const endpoint = nativePushEndpoint(input.platform, input.token)
+ await tx
+ .delete(push_subscriptions)
+ .where(and(eq(push_subscriptions.endpoint, endpoint), ne(push_subscriptions.user_id, userId)))
+ const values = { endpoint, p256dh: '', auth: '' }
+ await tx
+ .insert(push_subscriptions)
+ .values({ workspace_id: workspaceId, user_id: userId, ...values, created_at: now })
+ .onConflictDoUpdate({
+ target: [push_subscriptions.workspace_id, push_subscriptions.endpoint],
+ set: { created_at: now },
+ setWhere: eq(push_subscriptions.user_id, userId),
+ })
+ await keepNewestDevices(tx, workspaceId, userId)
+ return { rows: {} }
+ },
+
'push.unsubscribe': async ({ tx, actor }, input: { endpoint: string; everywhere?: boolean }) => {
const { workspaceId, userId } = pushPerson(actor)
const mine = and(eq(push_subscriptions.endpoint, input.endpoint), eq(push_subscriptions.user_id, userId))
diff --git a/apps/mobile/ios/App/App/AppDelegate.swift b/apps/mobile/ios/App/App/AppDelegate.swift
index fec95aca..b2c45939 100644
--- a/apps/mobile/ios/App/App/AppDelegate.swift
+++ b/apps/mobile/ios/App/App/AppDelegate.swift
@@ -11,6 +11,15 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
return true
}
+ // Push notifications (@capacitor/push-notifications; the web app registers the token, apps/web/src/native/push.ts).
+ func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
+ NotificationCenter.default.post(name: .capacitorDidRegisterForRemoteNotifications, object: deviceToken)
+ }
+
+ func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
+ NotificationCenter.default.post(name: .capacitorDidFailToRegisterForRemoteNotifications, object: error)
+ }
+
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
diff --git a/apps/web/src/admin/ProviderLogo.tsx b/apps/web/src/admin/ProviderLogo.tsx
index e8d5dc17..90d5ce74 100644
--- a/apps/web/src/admin/ProviderLogo.tsx
+++ b/apps/web/src/admin/ProviderLogo.tsx
@@ -195,6 +195,16 @@ export const providerMeta: Record<ProviderName, Meta> = {
keysUrl: 'https://github.com/settings/developers',
},
oidc: { mark: { icon: 'shield' }, blurb: msg('admin.provider.blurb.oidc') },
+ apns: {
+ mark: { icon: 'bell' },
+ blurb: msg('admin.provider.blurb.apns'),
+ keysUrl: 'https://developer.apple.com/account/resources/authkeys/list',
+ },
+ fcm: {
+ mark: { icon: 'bell' },
+ blurb: msg('admin.provider.blurb.fcm'),
+ keysUrl: 'https://console.firebase.google.com/',
+ },
}
/**
diff --git a/apps/web/src/native/plugins.ts b/apps/web/src/native/plugins.ts
index f66aa1bb..d73d626b 100644
--- a/apps/web/src/native/plugins.ts
+++ b/apps/web/src/native/plugins.ts
@@ -63,3 +63,20 @@ export interface KeyboardPlugin {
): Promise<Listener>
}
export const Keyboard = registerPlugin<KeyboardPlugin>('Keyboard')
+
+/** @capacitor/push-notifications */
+export interface PushNotificationsPlugin {
+ checkPermissions(): Promise<{ receive: string }>
+ requestPermissions(): Promise<{ receive: string }>
+ register(): Promise<void>
+ unregister(): Promise<void>
+ createChannel(channel: { id: string; name: string; importance?: number; visibility?: number }): Promise<void>
+ addListener(event: 'registration', fn: (token: { value: string }) => void): Promise<Listener>
+ addListener(event: 'registrationError', fn: (e: { error: string }) => void): Promise<Listener>
+ addListener(
+ event: 'pushNotificationActionPerformed',
+ fn: (action: { notification: { data?: unknown } }) => void,
+ ): Promise<Listener>
+ removeAllListeners(): Promise<void>
+}
+export const PushNotifications = registerPlugin<PushNotificationsPlugin>('PushNotifications')
diff --git a/apps/web/src/native/push.ts b/apps/web/src/native/push.ts
new file mode 100644
index 00000000..630defc3
--- /dev/null
+++ b/apps/web/src/native/push.ts
@@ -0,0 +1,96 @@
+// Push notifications in the Linedesk app (iOS: APNs, Android: FCM; apps/api/src/native-push.ts sends them). The phone's
+// permission, its device token (registered with push.registerDevice, endpoint `apns:<token>` / `fcm:<token>`), and a
+// tap on a notification opening its call. The web push of browsers (../push.ts) does the same with a service worker.
+import { nativePushEndpoint } from '@linedesk/actions'
+import { readStored, writeStored } from '../safeStorage.ts'
+import { nativePlatform, type NativePlatform } from './platform.ts'
+import { PushNotifications } from './plugins.ts'
+
+export type NativePermission = 'granted' | 'denied' | 'default'
+
+/** The token this phone registered last (it changes only with a new install or a reset): its endpoint on the server. */
+const TOKEN_KEY = 'linedesk.nativePushToken'
+
+/** The permission as last read from the phone (read() in settings/notificationPermission.ts is synchronous). */
+let permission: NativePermission = 'default'
+export const nativePermission = () => permission
+
+const fromPlugin = (state: string): NativePermission =>
+ state === 'granted' ? 'granted' : state === 'denied' ? 'denied' : 'default'
+
+/** Reads the phone's notification permission again. */
+export async function readNativePermission(): Promise<NativePermission> {
+ permission = fromPlugin((await PushNotifications.checkPermissions().catch(() => ({ receive: 'prompt' }))).receive)
+ return permission
+}
+
+/** Asks the phone once (later calls only read what the person chose; they change it in the phone's settings). */
+export async function askNativePermission(): Promise<NativePermission> {
+ permission = fromPlugin((await PushNotifications.requestPermissions().catch(() => ({ receive: 'denied' }))).receive)
+ return permission
+}
+
+/** This phone's endpoint on the server, or null before it registered. */
+export function nativeEndpointHere(): string | null {
+ const platform = nativePlatform()
+ const token = readStored('local', TOKEN_KEY)
+ return platform && token ? nativePushEndpoint(platform, token) : null
+}
+
+const REGISTER_WAIT_MS = 20_000
+
+/**
+ * Registers the phone with Apple or Google and resolves with its token for push.registerDevice. Android gets its
+ * "Calls" channel first (urgent calls make a sound and show on top).
+ */
+export async function registerNativePush(
+ callsChannelName: string,
+): Promise<{ platform: NativePlatform; token: string } | 'denied'> {
+ const platform = nativePlatform()
+ // i18n-ignore: never reached in a browser (the switch offers this only in the app)
+ if (!platform) throw new Error('not in the app')
+ if ((await askNativePermission()) !== 'granted') return 'denied'
+ if (platform === 'android')
+ await PushNotifications.createChannel({ id: 'calls', name: callsChannelName, importance: 5, visibility: 1 }).catch(
+ () => {},
+ )
+ const token = await new Promise<string>((resolve, reject) => {
+ // i18n-ignore: shown inside account.notify.pushFailed's {reason}, like the browser's own push errors
+ const timer = setTimeout(() => reject(new Error('no answer from the push service')), REGISTER_WAIT_MS)
+ void PushNotifications.addListener('registration', ({ value }) => {
+ clearTimeout(timer)
+ resolve(value)
+ })
+ void PushNotifications.addListener('registrationError', ({ error }) => {
+ clearTimeout(timer)
+ reject(new Error(error))
+ })
+ void PushNotifications.register().catch(reject)
+ }).finally(() => void PushNotifications.removeAllListeners().then(listenForTaps))
+ writeStored('local', TOKEN_KEY, token)
+ return { platform, token }
+}
+
+/** On sign-out: the phone gets no more pushes (the server forgets it first, ../push.ts stopPushOnSignOut). */
+export async function unregisterNativePush() {
+ writeStored('local', TOKEN_KEY, null)
+ await PushNotifications.unregister().catch(() => {})
+}
+
+let openCall: ((callId: string) => void) | null = null
+function listenForTaps() {
+ void PushNotifications.addListener('pushNotificationActionPerformed', ({ notification }) => {
+ const callId = (notification.data as { callId?: unknown } | undefined)?.callId
+ if (typeof callId === 'string') openCall?.(callId)
+ })
+}
+
+/** A tap on a notification opens its call (also when the tap started the app). */
+export function onNativePushOpensCall(open: (callId: string) => void): () => void {
+ if (!nativePlatform()) return () => {}
+ if (!openCall) listenForTaps()
+ openCall = open
+ return () => {
+ if (openCall === open) openCall = null
+ }
+}
diff --git a/apps/web/src/push.ts b/apps/web/src/push.ts
index ae5b0841..a5640848 100644
--- a/apps/web/src/push.ts
+++ b/apps/web/src/push.ts
@@ -2,6 +2,8 @@
// whether it gets pushes in the open workspace, and ending its subscription on sign-out. The
// subscription (endpoint and keys) only goes to the API (push.subscribe); it is never stored here.
import { pushDeviceId } from '@linedesk/actions'
+import { isNativeApp } from './native/platform.ts'
+import { nativeEndpointHere, onNativePushOpensCall, unregisterNativePush } from './native/push.ts'
import { serviceWorkerSupported } from './serviceWorker.ts'
import { workspaceHeaders } from './tabWorkspace.ts'
@@ -13,9 +15,10 @@ const isInstalled = () =>
window.matchMedia?.('(display-mode: standalone)').matches ||
(navigator as { standalone?: boolean }).standalone === true
-/** iOS and iPadOS only offer push to an app added to the Home Screen. */
+/** iOS and iPadOS only offer push to an app added to the Home Screen. The Linedesk app has its own (native/push.ts). */
export function pushSupport(): PushSupport {
if (typeof window === 'undefined') return 'unsupported'
+ if (isNativeApp()) return 'supported'
if (isIos() && !isInstalled()) return 'ios-needs-install'
if (!serviceWorkerSupported() || !('PushManager' in window) || !('Notification' in window)) return 'unsupported'
return 'supported'
@@ -28,10 +31,16 @@ export async function currentSubscription(): Promise<PushSubscription | null> {
return (await registration?.pushManager.getSubscription()) ?? null
}
-/** This browser's device id (see pushDeviceId), or null without a subscription. */
+/** Where this device gets pushes: the app's registered phone (`apns:…`, `fcm:…`), else the browser's subscription. */
+export async function currentEndpoint(): Promise<string | null> {
+ if (isNativeApp()) return nativeEndpointHere()
+ return (await currentSubscription())?.endpoint ?? null
+}
+
+/** This device's id (see pushDeviceId), or null without a subscription. */
export async function thisDeviceId(): Promise<string | null> {
- const subscription = await currentSubscription()
- return subscription ? pushDeviceId(subscription.endpoint) : null
+ const endpoint = await currentEndpoint()
+ return endpoint ? pushDeviceId(endpoint) : null
}
/** The VAPID key as the bytes pushManager.subscribe wants. */
@@ -74,20 +83,21 @@ const SIGN_OUT_WAIT_MS = 3000
* first step failed (offline): the push service then reports it gone and the server deletes it.
*/
export async function stopPushOnSignOut() {
- const subscription = await currentSubscription().catch(() => null)
- if (!subscription) return
+ const endpoint = await currentEndpoint().catch(() => null)
+ if (!endpoint) return
await fetch('/v1/actions/push.unsubscribe', {
method: 'POST',
credentials: 'include',
headers: { ...workspaceHeaders(), 'content-type': 'application/json', 'idempotency-key': crypto.randomUUID() },
- body: JSON.stringify({ endpoint: subscription.endpoint, everywhere: true }),
+ body: JSON.stringify({ endpoint, everywhere: true }),
signal: AbortSignal.timeout(SIGN_OUT_WAIT_MS),
}).catch(() => null)
- await subscription.unsubscribe().catch(() => false)
+ await endBrowserPush()
}
/** When the session is already gone (removed, another account): only the browser side is left to end. */
export async function endBrowserPush() {
+ if (isNativeApp()) return unregisterNativePush()
const subscription = await currentSubscription().catch(() => null)
await subscription?.unsubscribe().catch(() => false)
}
@@ -96,6 +106,7 @@ const OPEN_CALL = 'linedesk:open-call'
/** Clicking a push opens its call in an open Linedesk window (the service worker sends this). */
export function onPushOpensCall(open: (callId: string) => void): () => void {
+ if (isNativeApp()) return onNativePushOpensCall(open)
if (!serviceWorkerSupported()) return () => {}
const listener = (event: MessageEvent) => {
const data = event.data as { type?: string; callId?: unknown } | null
diff --git a/apps/web/src/settings/Notifications.tsx b/apps/web/src/settings/Notifications.tsx
index f276e323..3f2cf9ef 100644
--- a/apps/web/src/settings/Notifications.tsx
+++ b/apps/web/src/settings/Notifications.tsx
@@ -7,7 +7,9 @@ import { T, useT } from '@linedesk/i18n/react'
import { type ReactNode, useEffect, useState } from 'react'
import { brandName } from '../brand.ts'
import { i18n } from '../i18n/index.tsx'
-import { currentSubscription, pushSupport, subscribeThisBrowser, thisDeviceId } from '../push.ts'
+import { nativePlatform } from '../native/platform.ts'
+import { registerNativePush } from '../native/push.ts'
+import { currentEndpoint, pushSupport, subscribeThisBrowser, thisDeviceId } from '../push.ts'
import {
browserNotificationsSupported,
setNotificationSettings,
@@ -30,12 +32,18 @@ export const WhoHearsLine = () => <T k="account.notify.oneplace" values={{ link:
const blockedText = () => i18n().t('account.notify.blocked')
+/** Whether this server can push here: to this browser (Web Push key), or in the app to this kind of phone. */
+const serverPushes = (push: Pick<NotificationSettingsData['push'], 'publicKey' | 'native'>) => {
+ const platform = nativePlatform()
+ return platform ? push.native?.[platform] === true : !!push.publicKey
+}
+
/** Why push cannot be turned on here, or null when it can. */
-export function pushBlocker(publicKey: string | null): string | null {
+export function pushBlocker(push: Pick<NotificationSettingsData['push'], 'publicKey' | 'native'>): string | null {
const support = pushSupport()
if (support === 'ios-needs-install') return i18n().t('account.notify.iosInstall', { brand: brandName() })
if (support === 'unsupported') return i18n().t('account.notify.pushUnsupported')
- if (!publicKey) return i18n().t('account.notify.pushNotSetUp')
+ if (!serverPushes(push)) return i18n().t('account.notify.pushNotSetUp')
return null
}
@@ -63,9 +71,23 @@ export async function turnOnPush(
settings: NotificationSettingsData,
run: (name: string, input: object) => unknown,
): Promise<{ id: string | null; note: string | null }> {
- if (!settings.push.publicKey) return { id: null, note: pushBlocker(null) }
+ const blocked = pushBlocker(settings.push)
+ if (blocked) return { id: null, note: blocked }
try {
- const subscription = await subscribeThisBrowser(settings.push.publicKey)
+ if (nativePlatform()) {
+ // The app: Apple's or Google's device token (native/push.ts), registered like a browser's subscription.
+ const device = await registerNativePush(i18n().t('account.notify.callsChannel'))
+ if (device === 'denied') return { id: null, note: blockedText() }
+ const id = await thisDeviceId()
+ if (id)
+ setNotificationSettings({
+ ...settings,
+ push: { ...settings.push, devices: [...settings.push.devices.filter(d => d !== id), id] },
+ })
+ void run('push.registerDevice', device)
+ return { id, note: null }
+ }
+ const subscription = await subscribeThisBrowser(settings.push.publicKey!)
if (subscription === 'denied') return { id: null, note: blockedText() }
const id = await thisDeviceId()
if (id)
@@ -89,12 +111,12 @@ export async function turnOffPush(
deviceId: string | null,
run: (name: string, input: object) => unknown,
) {
- const subscription = await currentSubscription()
+ const endpoint = await currentEndpoint()
setNotificationSettings({
...settings,
push: { ...settings.push, devices: settings.push.devices.filter(d => d !== deviceId) },
})
- if (subscription) void run('push.unsubscribe', { endpoint: subscription.endpoint })
+ if (endpoint) void run('push.unsubscribe', { endpoint })
}
/** Sets the member's own in-tab setting (the fallback where push cannot work); applies at once, saved through the outbox. */
@@ -119,7 +141,7 @@ export function useDeviceNotifications(settings: NotificationSettingsData) {
const device = useThisDevice(settings.push.devices)
const [permission, askPermission] = useNotificationPermission()
const [busyNote, setBusyNote] = useState<string | null>(null)
- const viaPush = pushBlocker(settings.push.publicKey) === null
+ const viaPush = pushBlocker(settings.push) === null
const granted = permission === 'granted'
const on = granted && (viaPush ? device.on : settings.effective.browser)
const unavailable = permission === 'denied' || permission === 'unsupported' || permission === 'ios-needs-install'
@@ -132,7 +154,8 @@ export function useDeviceNotifications(settings: NotificationSettingsData) {
return
}
await askPermission()
- if (!browserNotificationsSupported() || Notification.permission !== 'granted') return
+ // The app asks the phone itself when it registers (turnOnPush); a browser has answered by now.
+ if (!nativePlatform() && (!browserNotificationsSupported() || Notification.permission !== 'granted')) return
if (!viaPush) return setOwnBrowser(settings, true, run)
// Registering with the browser's push service can take a while the first time.
setBusyNote(t('account.notify.turningOn'))
diff --git a/apps/web/src/settings/notificationPermission.ts b/apps/web/src/settings/notificationPermission.ts
index 28c2023e..6403ecee 100644
--- a/apps/web/src/settings/notificationPermission.ts
+++ b/apps/web/src/settings/notificationPermission.ts
@@ -2,6 +2,8 @@
// Notifications and the onboarding notify step, which ask for it when turned on.
import { useEffect, useState } from 'react'
import { brandName } from '../brand.ts'
+import { isNativeApp } from '../native/platform.ts'
+import { askNativePermission, nativePermission, readNativePermission } from '../native/push.ts'
import { pushSupport } from '../push.ts'
import { browserNotificationsSupported } from '../shell/useCallNotifications.ts'
import { i18n } from '../i18n/index.tsx'
@@ -9,6 +11,8 @@ import { i18n } from '../i18n/index.tsx'
export type NotificationPermissionState = 'granted' | 'default' | 'denied' | 'unsupported' | 'ios-needs-install'
const read = (): NotificationPermissionState => {
+ // The app: the phone's own permission (native/push.ts), read again on focus and after asking.
+ if (isNativeApp()) return nativePermission()
if (pushSupport() === 'ios-needs-install') return 'ios-needs-install'
return browserNotificationsSupported() ? Notification.permission : 'unsupported'
}
@@ -54,6 +58,7 @@ export function useNotificationPermission(): [NotificationPermissionState, () =>
.catch(() => {})
// Changed in the browser's site settings while the tab was in the background.
window.addEventListener('focus', update)
+ if (isNativeApp()) void readNativePermission().then(announce)
return () => {
live = false
listeners.delete(update)
@@ -62,7 +67,8 @@ export function useNotificationPermission(): [NotificationPermissionState, () =>
}
}, [])
const ask = async () => {
- if (browserNotificationsSupported()) await Notification.requestPermission().catch(() => {})
+ if (isNativeApp()) await askNativePermission()
+ else if (browserNotificationsSupported()) await Notification.requestPermission().catch(() => {})
announce()
}
return [state, ask]
diff --git a/docs/architecture.md b/docs/architecture.md
index 3fa2ab37..686d4cf3 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -535,6 +535,7 @@ Design: [white-label.md](white-label.md) (decided 2026-11-17). A partner (`partn
- **Provider sign-in.** Google refuses OAuth inside an app's web view, so in the app every provider sign-in (Google, Apple, Microsoft, GitHub, OIDC) runs in the system's sign-in browser: iOS `ASWebAuthenticationSession` (iOS 17.4, `.https` callback), Android Chrome Custom Tabs (`LinedeskAuthPlugin`, our own plugin in both projects; it opens only the app's own server). The session comes back like an OAuth code with PKCE, tied to a provider sign-in of that same flow (`apps/api/src/app-sign-in.ts`, a Better Auth plugin; security review of #1997): the app keeps a random verifier and opens `/app-sign-in?provider=…&challenge=<SHA-256 of it>`. That page posts the challenge to `POST /api/auth/app-sign-in/start` (kept with the time in a signed httpOnly cookie of that browser, 15 minutes) and signs in with the provider. Back from it, the page shows who signed in and asks for the person's OK; only then `POST /api/auth/app-sign-in/code` gives a one-use code (32 random bytes, stored hashed in `verification` with the user, the challenge and the browser's session; 2 minutes, one per start), and only for a session made after the start: a session the browser had before never counts, and an impersonation never. The code goes to the app on the server's own https address `/app-sign-in/back?code=…`, a universal link / verified app link that only the real app receives (no custom scheme another app could claim). The app's web view redeems it with the verifier (`POST /api/auth/app-sign-in/redeem`): the row is deleted in the same statement that reads it, a wrong verifier spends it, the browser's session must still exist (a password reset or "sign out everywhere" in between ends the hand-back) and is ended, the web view's own older session too, and the new session is made by Better Auth's adapter, so the session hooks run (disabled accounts, the host, the audit log with method `app`). All three endpoints check the origin like Better Auth's own sign-in endpoints (`formCsrfMiddleware`), so another site's form can neither start nor redeem. Everything the provider sign-in itself checks (address proof, sign-up gate, admin alerts) ran in the browser. Email codes, passwords and passkeys work inside the app's web view as on the web (passkeys through the app's associated domain).
- **Links.** `GET /.well-known/apple-app-site-association` and `/.well-known/assetlinks.json` (`apps/api/src/app-links.ts`, from `MOBILE_IOS_APP_IDS` and `MOBILE_ANDROID_APP`; 404 without them) let links to the start page `/` (every email link: `/#call/…`, `/?invite=…`) and the sign-in hand-back `/app-sign-in/back` open the app; the app then shows that address (`appUrlOpen`, `native/init.ts`; the hand-back belongs to the waiting sign-in). Other paths (`/app-sign-in`, the API, Stripe's return) stay in the browser.
+- **Push.** The app gets its pushes from Apple (APNs, token-based with the `.p8` key, `apps/api/src/native-push.ts`, over HTTP/2; production first, the sandbox for a build from Xcode) and Google (FCM HTTP v1, an access token from the service account), next to the browsers' Web Push and with the same payload and job (`push.ts`): who called and, for members who opted in, one line on what about; one notification per call (APNs `apns-collapse-id`, FCM `collapse_key` and tag), time-sensitive on iOS and the high-importance "Calls" channel on Android for urgent calls. Turning on notifications in the app asks the phone, registers it with Apple or Google and stores its token with `push.registerDevice` in `push_subscriptions` as the endpoint `apns:<token>` or `fcm:<token>` (no keys; the same row rules as a browser: per member and workspace, at most 10, a token of someone else's row is taken over, gone tokens are deleted when APNs or FCM say so, sign-out removes it). The keys are Server admin › Providers › Mobile app push (Apple Push Notifications: `.p8` key, key ID, team ID, bundle ID; Firebase Cloud Messaging: the service account JSON), read at each push; Test connection sends to a made-up device. Unlike Web Push (encrypted end to end, RFC 8291), Apple and Google can read the app's notifications: the caller's name or number and, for members who opted in, the summary line.
- **Phone.** Status bar, splash screen, the Android back button (closes what is open, then goes back, then puts the app in the background), the keyboard, safe areas (`viewport-fit=cover` inside the app).
- **No buying in the apps.** The store rules (App Store 3.1.1 and 3.1.3(b), Google Play payments) allow a multiplatform service whose plans are bought elsewhere, without calls to action. Inside the app every purchase step is hidden: Settings › Billing, the billing banner, the trial link, the plan step of onboarding (a neutral "Your plan is managed on the web" step that waits for the plan), extra paid phone numbers, the partner's activation and billing, prices of call quality levels, and trial wording on the sign-up and sign-in pages.
- **Account deletion** (App Store 5.1.1(v)): Account › Profile › Delete account opens Workspace settings › Danger zone, where leaving the last workspace or deleting an owned one deletes the account.
diff --git a/packages/actions/src/admin.ts b/packages/actions/src/admin.ts
index 9e9036a9..a302d77c 100644
--- a/packages/actions/src/admin.ts
+++ b/packages/actions/src/admin.ts
@@ -24,6 +24,7 @@ export type ProviderCategory =
| 'apps'
| 'bot_check'
| 'domains'
+ | 'mobile'
export const providerCategoryKeys: Record<ProviderCategory, MessageKey> = {
telephony: msg('admin.provider.category.telephony'),
stt: msg('admin.provider.category.stt'),
@@ -38,6 +39,7 @@ export const providerCategoryKeys: Record<ProviderCategory, MessageKey> = {
apps: msg('admin.provider.category.apps'),
bot_check: msg('admin.provider.category.botCheck'),
domains: msg('admin.provider.category.domains'),
+ mobile: msg('admin.provider.category.mobile'),
}
/** A category's name ("Speech to text") in the reader's words; English for the setup MCP and the CLI. */
export const providerCategoryLabel = (category: ProviderCategory, words: Words = english) =>
@@ -380,6 +382,24 @@ const guides = {
],
cost: 'Free. Cal.com cloud only (cal.com), not a self-hosted Cal.com.',
},
+ apns: {
+ url: 'https://developer.apple.com/account/resources/authkeys/list',
+ stepKeys: [
+ msg('admin.provider.guide.apns.step1'),
+ msg('admin.provider.guide.apns.step2'),
+ msg('admin.provider.guide.apns.step3'),
+ ],
+ costKey: msg('admin.provider.guide.apns.cost'),
+ },
+ fcm: {
+ url: 'https://console.firebase.google.com/',
+ stepKeys: [
+ msg('admin.provider.guide.fcm.step1'),
+ msg('admin.provider.guide.fcm.step2'),
+ msg('admin.provider.guide.fcm.step3'),
+ ],
+ costKey: msg('admin.provider.guide.fcm.cost'),
+ },
github: {
url: 'https://github.com/settings/developers',
steps: [
@@ -501,6 +521,7 @@ export const recommendedProviders: Record<ProviderCategory, ProviderName> = {
apps: 'hubspot',
bot_check: 'turnstile',
domains: 'cloudflare_saas',
+ mobile: 'apns',
}
/**
@@ -1032,6 +1053,34 @@ export const providers = {
},
help: 'Okta, Microsoft Entra, Keycloak, Authentik or any OpenID Connect provider. It must send email_verified only for verified addresses; for one that sends none, list the email domains it owns.',
},
+ // Push to the install's own iOS and Android app (apps/mobile; apps/api/src/native-push.ts). Browsers need none.
+ apns: {
+ // i18n-ignore: a product name in the English-only provider registry, like every other provider label here
+ label: 'Apple Push Notifications',
+ category: 'mobile',
+ guide: guides.apns,
+ fields: {
+ key: { labelKey: msg('admin.provider.field.apnsKey'), env: 'APNS_KEY_P8', secret: true },
+ key_id: { labelKey: msg('admin.provider.field.keyId'), env: 'APNS_KEY_ID', secret: false },
+ team_id: { labelKey: msg('admin.provider.field.teamId'), env: 'APNS_TEAM_ID', secret: false },
+ bundle_id: { labelKey: msg('admin.provider.field.iosBundleIdApp'), env: 'APNS_BUNDLE_ID', secret: false },
+ },
+ helpKey: msg('admin.provider.help.apns'),
+ },
+ fcm: {
+ // i18n-ignore: a product name in the English-only provider registry, like every other provider label here
+ label: 'Firebase Cloud Messaging',
+ category: 'mobile',
+ guide: guides.fcm,
+ fields: {
+ service_account: {
+ labelKey: msg('admin.provider.field.fcmServiceAccount'),
+ env: 'FCM_SERVICE_ACCOUNT_JSON',
+ secret: true,
+ },
+ },
+ helpKey: msg('admin.provider.help.fcm'),
+ },
// Business lookup: onboarding finds the business's listing (address, phone, hours, website, category) by name and
// city. Optional: without it the owner types the name and website. Called only from the API (business.search).
google_places: {
diff --git a/packages/actions/src/index.ts b/packages/actions/src/index.ts
index f9421cc1..bf74f60d 100644
--- a/packages/actions/src/index.ts
+++ b/packages/actions/src/index.ts
@@ -255,6 +255,7 @@ const all = [
notifications.notificationsUpdate,
notifications.notificationsSetDefaults,
notifications.pushSubscribe,
+ notifications.pushRegisterDevice,
notifications.pushUnsubscribe,
star.starPromptAnswer,
feedback.feedbackSend,
diff --git a/packages/actions/src/notifications.ts b/packages/actions/src/notifications.ts
index 7fd6c927..d2cadf63 100644
--- a/packages/actions/src/notifications.ts
+++ b/packages/actions/src/notifications.ts
@@ -14,7 +14,16 @@ export type ChangedBy = { name: string; at: string }
* install), `devices` the ids (pushDeviceId) of the browsers that get pushes in this workspace,
* `summary` whether a push says what the call was about.
*/
-export type PushSettings = { publicKey: string | null; devices: string[]; summary: boolean }
+/**
+ * `publicKey`: Web Push's key (null: no push for browsers). `native`: whether the Linedesk app can get pushes on iOS
+ * (APNs) and Android (FCM) on this server (absent from an older server).
+ */
+export type PushSettings = {
+ publicKey: string | null
+ native?: { ios: boolean; android: boolean }
+ devices: string[]
+ summary: boolean
+}
/** `data` of `notifications.get`: what applies to the caller, their own choices (null: the default), and the defaults. */
export type NotificationSettingsData = {
@@ -115,11 +124,42 @@ export const pushSubscribe = defineAction({
sensitive: ['endpoint', 'keys'],
})
+// The Linedesk app (iOS, Android: apps/mobile) gets its pushes from Apple (APNs) and Google (FCM) instead: a device
+// token per app install, stored like a browser's endpoint as `apns:<token>` or `fcm:<token>` (no keys). Whoever has a
+// token can have pushes sent to that phone, so it is just as sensitive.
+/** An APNs device token (hex), or an FCM registration token. */
+const APNS_TOKEN = /^[0-9a-f]{64,200}$/i
+const FCM_TOKEN = /^[A-Za-z0-9_:-]{20,4096}$/
+
+/** The endpoint a native device is stored under: `apns:<token>` (iOS) or `fcm:<token>` (Android). */
+export const nativePushEndpoint = (platform: 'ios' | 'android', token: string) =>
+ platform === 'ios' ? `apns:${token.toLowerCase()}` : `fcm:${token}`
+
+/** Whether an endpoint is a native app's device (not a browser's push service). */
+export const isNativePushEndpoint = (endpoint: string) =>
+ (endpoint.startsWith('apns:') && APNS_TOKEN.test(endpoint.slice(5))) ||
+ (endpoint.startsWith('fcm:') && FCM_TOKEN.test(endpoint.slice(4)))
+
+export const pushRegisterDevice = defineAction({
+ name: 'push.registerDevice',
+ // i18n-ignore: API and MCP docs for agents and developers, not shown in the app
+ description: 'Get push notifications for new calls in this workspace in the Linedesk app on this phone.',
+ input: z
+ .object({ platform: z.enum(['ios', 'android']), token: z.string().max(4096) })
+ .refine(i => (i.platform === 'ios' ? APNS_TOKEN : FCM_TOKEN).test(i.token)),
+ permission: 'call:read',
+ sensitive: ['token'],
+})
+
export const pushUnsubscribe = defineAction({
name: 'push.unsubscribe',
description:
'Stop push notifications on this browser: in this workspace, or with `everywhere` in all of yours (sign-out).',
- input: z.object({ endpoint: pushEndpoint, everywhere: z.boolean().optional() }),
+ input: z.object({
+ // i18n-ignore: an input check for the app's own request, never shown to a person
+ endpoint: z.union([pushEndpoint, z.string().max(4096).refine(isNativePushEndpoint, 'not a device')]),
+ everywhere: z.boolean().optional(),
+ }),
permission: 'call:read',
sensitive: ['endpoint'],
})
diff --git a/packages/actions/src/provider-status.ts b/packages/actions/src/provider-status.ts
index d7cc9f38..c4c7c640 100644
--- a/packages/actions/src/provider-status.ts
+++ b/packages/actions/src/provider-status.ts
@@ -26,6 +26,7 @@ export const providerGroupIds = [
'recording',
'business',
'domains',
+ 'mobile',
'billing',
] as const
export type ProviderGroupId = (typeof providerGroupIds)[number]
@@ -124,6 +125,13 @@ export const providerGroups: readonly ProviderGroupSpec[] = [
categories: ['domains'],
whyKey: msg('admin.provider.group.domains.why'),
},
+ {
+ id: 'mobile',
+ labelKey: msg('admin.provider.group.mobile.label'),
+ needed: false,
+ categories: ['mobile'],
+ whyKey: msg('admin.provider.group.mobile.why'),
+ },
{
id: 'billing',
labelKey: msg('admin.provider.group.billing.label'),
@@ -535,6 +543,8 @@ export function statusGroups(input: StatusInput, words: Words = english): Status
const used = inUse('domains')
return used ? fromLine(used) : empty('off')
}
+ case 'mobile':
+ return several(configured(providersIn('mobile')))
case 'billing': {
const used = inUse('billing')
return used ? fromLine(used) : empty('off')
diff --git a/packages/i18n/locales/en/account.json b/packages/i18n/locales/en/account.json
index 12912680..14c0c274 100644
--- a/packages/i18n/locales/en/account.json
+++ b/packages/i18n/locales/en/account.json
@@ -140,6 +140,7 @@
"nav.security.description": "Sign-in methods, passkeys, password and sessions",
"nav.security.label": "Sign-in & security",
"notify.blocked": "Blocked by the browser. Allow notifications for this site, then try again.",
+ "notify.callsChannel": "Calls",
"notify.card.assigned": "an email when a call is assigned to you",
"notify.card.deviceOpen": "notifications on this device while {brand} is open",
"notify.card.devicePush": "push notifications on this device",
diff --git a/packages/i18n/locales/en/admin.json b/packages/i18n/locales/en/admin.json
index bfe213e5..5204bc50 100644
--- a/packages/i18n/locales/en/admin.json
+++ b/packages/i18n/locales/en/admin.json
@@ -1274,6 +1274,7 @@
"provider.answeredBy": "Answered by {names}.",
"provider.answeredByEach": "Answered by {names}, as each assistant chose.",
"provider.blurb.anthropic": "Claude models.",
+ "provider.blurb.apns": "Push notifications to the iOS app.",
"provider.blurb.assemblyai_stt": "Streaming speech recognition with Universal-3.6 Pro.",
"provider.blurb.brevo": "Email with an SMTP key.",
"provider.blurb.calcom": "One-click connecting for Cal.com event types.",
@@ -1283,6 +1284,7 @@
"provider.blurb.deepgram": "Real-time speech recognition.",
"provider.blurb.elevenlabs": "Natural voices.",
"provider.blurb.elevenlabs_stt": "Streaming speech recognition with Scribe.",
+ "provider.blurb.fcm": "Push notifications to the Android app.",
"provider.blurb.file": "Recordings stay on this server.",
"provider.blurb.gemini": "Gemini models from Google.",
"provider.blurb.github": "Sign in with GitHub.",
@@ -1326,6 +1328,7 @@
"provider.category.domains": "Partner domains",
"provider.category.email": "Email",
"provider.category.llm": "Language model",
+ "provider.category.mobile": "Mobile app",
"provider.category.realtime": "Realtime model",
"provider.category.recording": "Recording storage",
"provider.category.signIn": "Sign-in and calendar",
@@ -1338,13 +1341,18 @@
"provider.devCarrierLine": "Development carrier ({setting}): numbers and calls are simulated",
"provider.emailToLog": "Sign-in codes go to the API log ({name}): for development only",
"provider.field.apiToken": "API token",
+ "provider.field.apnsKey": "Private key (.p8)",
"provider.field.appStoreUrl": "App Store listing (https://apps.shopify.com/…)",
"provider.field.clientId": "Client ID",
"provider.field.clientSecret": "Client secret",
"provider.field.cnameTarget": "CNAME target",
"provider.field.customOrigin": "Custom origin (empty: the fallback origin)",
+ "provider.field.fcmServiceAccount": "Service account (JSON)",
+ "provider.field.iosBundleIdApp": "iOS app bundle ID",
+ "provider.field.keyId": "Key ID",
"provider.field.publicAppApproved": "Public app approved in the Shopify App Store",
"provider.field.signingSecret": "Signing secret",
+ "provider.field.teamId": "Team ID",
"provider.field.waitForCaller": "Wait for callers to finish",
"provider.field.zeroDataRetention": "Zero data retention only",
"provider.field.zoneId": "Zone ID",
@@ -1364,12 +1372,18 @@
"provider.group.domains.why": "Lets white-label partners give their clients an address of their own, like app.theiragency.com.",
"provider.group.email.label": "Email",
"provider.group.email.why": "Sign-in codes, invitations and call emails.",
+ "provider.group.mobile.label": "Mobile app push",
+ "provider.group.mobile.why": "Push notifications for this server's own iOS and Android app. Browsers need nothing here.",
"provider.group.recording.label": "Recording storage",
"provider.group.recording.why": "Where call recordings are kept. Off: calls are not recorded.",
"provider.group.signIn.label": "Sign-in",
"provider.group.signIn.why": "Sign in with Google, Microsoft, GitHub or your own single sign-on.",
"provider.group.telephony.label": "Phone carrier",
"provider.group.telephony.why": "Gives the business a number and brings its calls in.",
+ "provider.guide.apns.cost": "Free with a membership in the Apple Developer Program.",
+ "provider.guide.apns.step1": "Apple Developer › Certificates, Identifiers & Profiles › Keys › New key with Apple Push Notifications service (APNs), for Sandbox & Production.",
+ "provider.guide.apns.step2": "Download the .p8 file (Apple gives it only once) and note the key ID and your team ID.",
+ "provider.guide.apns.step3": "Paste the content of the .p8 file, the key ID, the team ID and your iOS app's bundle ID here.",
"provider.guide.assemblyai_stt.cost": "About $0.0075 per call minute with Universal-3.6 Pro streaming.",
"provider.guide.assemblyai_stt.step1": "Sign up at assemblyai.com and add a payment method.",
"provider.guide.assemblyai_stt.step2": "Dashboard › API Keys: copy the key.",
@@ -1379,6 +1393,10 @@
"provider.guide.cloudflare_saas.step2": "My Profile → API Tokens → Create Token → Custom token with Zone › SSL and Certificates › Edit, for this zone only. Copy the token.",
"provider.guide.cloudflare_saas.step3": "Copy the zone ID from the zone's Overview page.",
"provider.guide.cloudflare_saas.step4": "Paste the token, the zone ID and the CNAME target here, and the custom origin if partner traffic has its own.",
+ "provider.guide.fcm.cost": "Free.",
+ "provider.guide.fcm.step1": "Firebase console: a project with your Android app (its package name).",
+ "provider.guide.fcm.step2": "Project settings › Service accounts › Generate new private key: a JSON file.",
+ "provider.guide.fcm.step3": "Paste the whole JSON file here.",
"provider.guide.google_mail.cost": "Free. A public app needs Google's verification and a yearly security assessment for gmail.readonly; in Testing, only its test users can connect.",
"provider.guide.google_mail.step1": "In Google Cloud, create a project only for mail (not the one of the Google sign-in app) and enable the Gmail API (APIs & Services › Library).",
"provider.guide.google_mail.step2": "OAuth consent screen: add the scope gmail.readonly. Keep the app in Testing and add the Google accounts that may connect as test users (100 at most), until Google has verified it.",
@@ -1406,8 +1424,10 @@
"provider.guide.zoho.step1": "At api-console.zoho.com: Add Client › Server-based Applications. Homepage URL: this server's address. Authorized Redirect URIs: the redirect URL shown below.",
"provider.guide.zoho.step2": "In the client's Settings tab, turn on every data centre (Multi-DC) and tick “Use the same OAuth credentials for all data centers”, so businesses whose Zoho account is in the EU, India, Australia or another region can connect too.",
"provider.guide.zoho.step3": "Copy the client ID and client secret from the Client Secret tab and paste them here.",
+ "provider.help.apns": "Pushes to the iOS app. One key works for the app's development and App Store builds.",
"provider.help.assemblyai_stt": "The assistant answers when AssemblyAI says the caller is done. With Wait for callers to finish on (the default), it waits as long as Deepgram Flux does. Off, it answers about a quarter of a second sooner, but it often starts while the caller only pauses (before a house number, for example). It can’t understand Polish, Ukrainian, Czech, Greek, Hungarian or Indonesian: with Deepgram set up too, calls in these languages use Deepgram (Nova-3); without it, assistants are not offered them.",
"provider.help.cloudflare_saas": "Lets white-label partners give their clients an address of their own, like app.theiragency.com. Partners point their address at the CNAME target.",
+ "provider.help.fcm": "Pushes to the Android app, through Google's Firebase Cloud Messaging.",
"provider.help.google_mail": "A Google OAuth app with the Gmail API, the gmail.readonly scope and the redirect URI below. Businesses then connect their Gmail support mailbox under Integrations, read only. Microsoft 365 mailboxes use the Microsoft sign-in app (Mail.Read).",
"provider.help.jobber": "A Jobber app with the redirect URL below and the client scopes (read and write). Businesses then connect their Jobber under Integrations, and every finished phone call is added as a note on the caller’s Jobber client.",
"provider.help.openrouter": "Calls only go to providers that don’t train on them. With Zero data retention only (on by default) they also only go to endpoints that keep nothing after answering, which leaves fewer providers for some models. You can turn it off: some providers then keep requests for a while, for example for abuse checks, and your privacy notice may need to say so.",
diff --git a/packages/i18n/locales/en/server.json b/packages/i18n/locales/en/server.json
index 65834852..1bd84818 100644
--- a/packages/i18n/locales/en/server.json
+++ b/packages/i18n/locales/en/server.json
@@ -248,6 +248,10 @@
"api.partner.noAdminFromPartner": "A partner's team adds the client's staff as members only, for now. Admins come with the client's owner.",
"api.phoneNumberNotFound": "phone number not found",
"api.providerTest.answered": "{provider} answered HTTP {status}",
+ "api.providerTest.apns.answered": "Apple answered {reason}.",
+ "api.providerTest.apns.bundle": "Apple refused the bundle ID: it must be an app of this team with Push Notifications on.",
+ "api.providerTest.apns.key": "Apple refused the key: check the .p8 key, the key ID and the team ID (the key needs Apple Push Notifications service).",
+ "api.providerTest.apns.unreachable": "Apple's push service could not be reached.",
"api.providerTest.cartesia.noVoice": "The voice {voice} is not available to this Cartesia key. Pick another or clear the field.",
"api.providerTest.cloudflareSaas.zoneId": "The zone ID is 32 hex digits. Copy it from the zone's Overview page in Cloudflare.",
"api.providerTest.connected": "Connected",
@@ -261,6 +265,10 @@
"api.providerTest.elevenlabs.noAudio": "ElevenLabs returned no audio for a test sentence.",
"api.providerTest.elevenlabs.pastDue": "The ElevenLabs payment is past due: pay it in ElevenLabs, Subscription, before the voice stops.",
"api.providerTest.elevenlabs.usedUp": "ElevenLabs quota used up ({used} of {limit} credits{resets, select, none {} other {; it resets on {resets}}}): the assistant cannot speak. Upgrade the plan or turn on usage-based billing in ElevenLabs.",
+ "api.providerTest.fcm.answered": "Firebase answered HTTP {status}.",
+ "api.providerTest.fcm.file": "Google refused the service account: paste the whole JSON file Firebase gave (Project settings › Service accounts).",
+ "api.providerTest.fcm.project": "The service account may not send with Firebase Cloud Messaging in this project: check the project and that the Cloud Messaging API is on.",
+ "api.providerTest.fcm.unreachable": "Firebase Cloud Messaging could not be reached.",
"api.providerTest.notSet": "Not set: {fields}",
"api.providerTest.notSetUp": "Not set up",
"api.providerTest.oauth.checkedAtSignIn": "Not checked: {provider} does not let the keys be tested from here. They are confirmed at the first sign-in or calendar connection.",
@@ -312,6 +320,7 @@
"api.providerTest.twilio.trial": "Twilio trial account: calls play a trial message and reach only verified numbers. Upgrade it in the Twilio Console.",
"api.providerTest.twilio.unknownSid": "Twilio does not know this account SID (HTTP 404). Copy it from the Twilio Console.",
"api.providerTest.twilio.usedUp": "Twilio balance is used up ({amount}). Add funds in the Twilio Console.",
+ "api.push.appNotSetUp": "Push notifications for the app are not set up on this server.",
"api.setup.lookupsUsed": "You used the business lookups for setting up. Fill in the rest by hand, or start your free trial for more.",
"api.setup.testMinutesUsed": "You used the test-call minutes for setting up. Start your free trial to keep testing and to get your number.",
"api.shopifyApp.linkExpired": "This link has expired. Open the app in your Shopify admin again for a new one.",