Cotton code
208 lines · 10.6 KB · TypeScriptRaw
/** * A Cotton message's alert push (Cotton chat, 12 Nov 2026): the phone that * has no socket open is told "New message". The Worker holds only ciphertext, * so the title is all it could say. On iOS the push also carries the message's * sealed box when it fits (13 Nov 2026): the notification service extension * opens it with the phone's key and says who and what, and reaches no server * (a Swift request to the object would carry no device signature). A * stranger's request carries no box, so it stays "New message"; nor does it * name the sender, whose number is inside the box. The FCM handler (Android) * takes the held envelopes from its own object and decrypts them on the phone. * * The senders are Calling's (src/calling/apns.ts, src/calling/fcm.ts): the * same provider token, the same access token, the same fakes in the tests. * Only the push differs: an APNs `alert` push to the app's own topic (never * `.voip`, which iOS keeps for calls), an FCM high-priority data message * `{ kind: "chat" }`. */import type { Env } from "../env.ts";import { apnsHost, canPush, forgetProviderToken, providerToken } from "../calling/apns.ts";import { accessToken, account, canPushAndroid, fcmHosts, forgetAccessToken, project } from "../calling/fcm.ts";import type { Platform, PushOutcome } from "../calling/push.ts";/** The words of every chat push: the Worker cannot read more. */export const ALERT_TITLE = "New message";/** The apps a chat push token may be for: Cotton Messages and Cotton, each with its development build. */export const CHAT_TOPICS = ["com.cottondb.messages", "com.cottondb.messages.dev", "com.cottondb.cotton", "com.cottondb.cotton.dev"];/** The most of a box an APNs push carries: the payload's limit is 4 KB, and the rest of the body is under 200 bytes. */export const PUSHED_BOX_MAX = 3500;/** The envelope an alert is for: a message, its box, and whether it is a stranger's request. */export interface Alerted {  kind: string;  request: boolean;  box: string;  id?: string;  peer?: string;  out?: boolean;  at?: number;  group?: string | null;}export interface AlertDevice {  platform: Platform;  token: string;  topic: string;  sandbox: boolean;}/** The APNs body: a title, mutable so the extension may replace it with the decrypted line, and the sealed box when it fits and is not a request. */export function apnsBody(item?: Alerted): Record<string, unknown> {  const body: Record<string, unknown> = { aps: { alert: { title: ALERT_TITLE }, sound: "default", "mutable-content": 1 }, chat: 1 };  if (item && item.kind === "message" && !item.request && item.box.length <= PUSHED_BOX_MAX) {    body.box = item.box;    // A c2 box is opened by the core's read-only `chat.peek` (SEALING.md), which checks the box's inside against the    // envelope's outside, so the outside goes beside it. Only an iPhone that advertises c2 is ever sealed one.    if (item.box.startsWith("c2:")) body.item = { id: item.id, kind: item.kind, peer: item.peer, out: item.out ?? false, at: item.at, group: item.group ?? null };  }  return body;}/** The FCM message: data only, so the app's own handler draws the notification after it decrypts. */export function fcmMessage(token: string): Record<string, unknown> {  return { message: { token, data: { kind: "chat", title: ALERT_TITLE }, android: { priority: "HIGH", ttl: "86400s" } } };}export function canAlert(env: Env, platform: Platform): boolean {  return platform === "ios" ? canPush(env) : canPushAndroid(env);}/** The APNs body of a read nudge: a background push the app wakes for, says nothing, and shows nothing. */export function apnsNudgeBody(): Record<string, unknown> {  return { aps: { "content-available": 1 }, chat: 1, read: 1 };}/** The FCM message of a read nudge: data only, the app lands what is held and takes away what was read. */export function fcmNudge(token: string): Record<string, unknown> {  return { message: { token, data: { kind: "chat", read: "1" }, android: { priority: "HIGH", ttl: "3600s" } } };}/** * A read nudge to one phone (20 Nov 2026): another of the * person's phones read a chat, and its sealed read receipt waits here for * this one. The phone wakes, takes it (chat.incoming) and takes away that * chat's notification. The push says nothing of which chat or whose. */export async function nudge(env: Env, device: AlertDevice): Promise<PushOutcome> {  if (!canAlert(env, device.platform)) return "failed";  return device.platform === "ios" ? sendApns(env, device, "background", "5", apnsNudgeBody()) : sendFcm(env, fcmNudge(device.token));}/** One alert to one phone. Nothing of the token is logged. */export async function alert(env: Env, device: AlertDevice, item?: Alerted): Promise<PushOutcome> {  if (!canAlert(env, device.platform)) return "failed";  return device.platform === "ios" ? alertApns(env, device, item) : alertFcm(env, device);}async function alertApns(env: Env, device: AlertDevice, item?: Alerted): Promise<PushOutcome> {  return sendApns(env, device, "alert", "10", apnsBody(item));}async function sendApns(env: Env, device: AlertDevice, type: "alert" | "background", priority: "5" | "10", body: Record<string, unknown>): Promise<PushOutcome> {  let res: Response;  try {    const jwt = await providerToken(env);    res = await fetch(`${apnsHost(env, device.sandbox)}/3/device/${encodeURIComponent(device.token)}`, {      method: "POST",      headers: { authorization: `bearer ${jwt}`, "apns-topic": device.topic, "apns-push-type": type, "apns-priority": priority, "content-type": "application/json" },      body: JSON.stringify(body),    });  } catch {    return "failed";  }  if (res.ok) return "sent";  if (res.status === 410) return "gone";  const reason = await res.json().then((b) => (b as { reason?: string }).reason, () => undefined);  if (reason === "ExpiredProviderToken") forgetProviderToken();  return reason === "BadDeviceToken" || reason === "Unregistered" ? "gone" : "failed";}async function alertFcm(env: Env, device: AlertDevice): Promise<PushOutcome> {  return sendFcm(env, fcmMessage(device.token));}async function sendFcm(env: Env, message: Record<string, unknown>): Promise<PushOutcome> {  const sa = account(env);  const id = sa ? project(env, sa) : null;  if (!sa || !id) return "failed";  let res: Response;  try {    const bearer = await accessToken(env);    if (!bearer) return "failed";    res = await fetch(`${fcmHosts(env).send}/v1/projects/${encodeURIComponent(id)}/messages:send`, {      method: "POST",      headers: { authorization: `Bearer ${bearer}`, "content-type": "application/json" },      body: JSON.stringify(message),    });  } catch {    return "failed";  }  if (res.ok) return "sent";  if (res.status === 401) forgetAccessToken();  const error = await res.json().then(    (b) => (b as { error?: { status?: string; details?: { errorCode?: string }[] } }).error,    () => undefined,  );  const code = error?.details?.find((d) => d.errorCode)?.errorCode;  if (res.status === 404 || code === "UNREGISTERED" || (res.status === 400 && (error?.status === "INVALID_ARGUMENT" || code === "INVALID_ARGUMENT"))) return "gone";  return "failed";}/** The words of a mail push (OWN-MAIL.md): the object sealed the mail as it came, so it says no more. */export const MAIL_TITLE = "New mail";/** Mail came on the person's own domain: an alert saying only "New mail" (APNs), a data message `{ kind: "mail" }` (FCM). */export async function mailAlert(env: Env, device: AlertDevice): Promise<PushOutcome> {  if (!canAlert(env, device.platform)) return "failed";  if (device.platform === "ios") return sendApns(env, device, "alert", "10", { aps: { alert: { title: MAIL_TITLE }, sound: "default" }, mail: 1 });  return sendFcm(env, { message: { token: device.token, data: { kind: "mail", title: MAIL_TITLE }, android: { priority: "HIGH", ttl: "86400s" } } });}/** * A new device asks to sign in (GETTING-IN.md): an alert to each of the person's devices that takes pushes. APNs: the * words, which the server knows (the device's kind and name are the ask's, never the person's things). FCM: a data * message `{ kind: "approval" }`, and the app draws the core's words from `signin.asks`. Never sent to the asking * device itself. */export function approvalTitle(kind: string | null): string {  const word = kind ? ({ mac: "Mac", iphone: "iPhone", ipad: "iPad", android: "Android phone", computer: "computer" } as Record<string, string>)[kind] : undefined;  return word ? `Your ${word} wants to sign in to your Cotton` : "A new device wants to sign in to your Cotton";}export async function approvalAlert(env: Env, device: AlertDevice, kind: string | null, name: string | null): Promise<PushOutcome> {  if (!canAlert(env, device.platform)) return "failed";  const title = approvalTitle(kind);  if (device.platform === "ios") {    const body = `${name ?? "It"} asked just now. If you're holding it yourself, open this to approve.`;    return sendApns(env, device, "alert", "10", { aps: { alert: { title, body }, sound: "default" }, approval: 1 });  }  return sendFcm(env, { message: { token: device.token, data: { kind: "approval", title }, android: { priority: "HIGH", ttl: "180s" } } });}/** * Getting back in with help (TRUSTED RECOVERY BUILD 1): every device of the person is told a new device started it, * and that it was stopped. The words are the server's own (it knows only that this happened); the phone opens the * core's page, where Stop is. Drafts for the owner's sheet. */export function recoveryTitle(what: "started" | "stopped" | "help" | "weak"): string {  if (what === "help") return "Someone you help is getting back in to their Cotton";  if (what === "weak") return "Fewer people can help you get back in";  return what === "started" ? "Someone is getting into your Cotton on a new phone" : "Getting back in on a new phone was stopped";}export async function recoveryAlert(env: Env, device: AlertDevice, what: "started" | "stopped" | "help" | "weak"): Promise<PushOutcome> {  if (!canAlert(env, device.platform)) return "failed";  const title = recoveryTitle(what);  if (device.platform === "ios") {    const body =      what === "started" ? "If this isn't you, open Cotton to stop it."      : what === "help" ? "Talk to them in person, or on a call where you know their voice, before you help."      : what === "weak" ? "Open Cotton to choose who helps you again."      : "Nothing was opened.";    return sendApns(env, device, "alert", "10", { aps: { alert: { title, body }, sound: "default" }, recovery: what });  }  return sendFcm(env, { message: { token: device.token, data: { kind: "recovery", what, title }, android: { priority: "HIGH", ttl: "3600s" } } });}