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.

17.6 KB
Raw Blame
// 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 { ANDROID_CALLS_CHANNEL } from '@linedesk/actions'
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 app's calls channel, newer news replacing older; private on
 * the lock screen (only that a notification came, not who called or why), whatever the channel says.
 */
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: ANDROID_CALLS_CHANNEL, visibility: 'PRIVATE' },
      },
    },
  }
}

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: FCM says UNREGISTERED (with a 404). Only that says the
  // phone is gone; a 404 without it (a wrong project id, a proxy), INVALID_ARGUMENT or SENDER_ID_MISMATCH can be our
  // message or the project, which must not delete devices (review of #1999; LIN-874).
  if (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)
}