SPB Git

Repository Public

core.ts 14.3 KB 316 lines typescript

1/**2 * Engine host for the native Apple apps. The same client engine as the web application (identity,3 * MLS, sync, attachments) runs here, inside the app bundle, with no page loaded from the network:4 * HTTP, WebSocket and storage are provided by Swift through a message bridge, the interface is SwiftUI.5 */6import { b64, unb64 } from "../web/src/core/bytes"7import { Engine, type Conv } from "../web/src/core/engine"8import { prepare } from "../web/src/core/media"9import * as mls from "../web/src/core/mls"10import { fingerprint, safetyNumber } from "../web/src/core/crypto"11import type { Store } from "../web/src/core/store"12import { ApiError, type FileRef, type Me, type Msg, type Transport } from "../web/src/core/types"1314declare const webkit: { messageHandlers: { spm: { postMessage(m: unknown): void } } }15const post = (m: unknown) => void (webkit.messageHandlers.spm.postMessage(m) as unknown as Promise<unknown>)?.catch?.(() => {})16/** Every bridge call is answered by Swift through a reply handler (a rejected promise carries the error text). */17function native<T = any>(op: string, args: Record<string, unknown> = {}): Promise<T> {18  return (webkit.messageHandlers.spm.postMessage({ op, ...args }) as unknown as Promise<T>)19}2021// ---- transport over URLSession22let sockHandlers: { onMessage: (m: any) => void; onState: (open: boolean) => void } | null = null23;(globalThis as any).__spmSocket = (kind: string, data?: string) => {24  if (!sockHandlers) return25  if (kind === "open") sockHandlers.onState(true)26  else if (kind === "close") sockHandlers.onState(false)27  else if (kind === "message" && data) {28    try {29      sockHandlers.onMessage(JSON.parse(data))30    } catch {}31  }32}33const transport: Transport = {34  async request<T>(method: string, path: string, body?: unknown): Promise<T> {35    const r = await native<{ status: number; body: string }>("http", { method, path, json: body === undefined ? null : JSON.stringify(body) })36    let j: any = {}37    try {38      j = r.body ? JSON.parse(r.body) : {}39    } catch {}40    if (r.status === 0) throw new ApiError(0, "network", "Network unavailable")41    if (r.status < 200 || r.status >= 300) throw new ApiError(r.status, j.error ?? "error", j.message)42    return j as T43  },44  async getBytes(path: string) {45    const r = await native<{ status: number; body: string }>("http", { method: "GET", path, binary: true })46    if (r.status === 0) throw new ApiError(0, "network", "Network unavailable")47    if (r.status !== 200) throw new ApiError(r.status, "error")48    return unb64(r.body)49  },50  async putBytes(path: string, data: Uint8Array) {51    const r = await native<{ status: number; body: string }>("http", { method: "PUT", path, bytes: b64(data) })52    if (r.status === 0) throw new ApiError(0, "network", "Network unavailable")53    if (r.status < 200 || r.status >= 300) throw new ApiError(r.status, "error")54  },55  socket(onMessage, onState) {56    sockHandlers = { onMessage, onState }57    post({ op: "ws-open" })58    return { send: (m: unknown) => post({ op: "ws-send", text: JSON.stringify(m) }), close: () => post({ op: "ws-close" }) }59  },60}6162// ---- storage in the app's own encrypted database63const enc = (v: unknown) => JSON.stringify(v, (_k, x) => (x instanceof Uint8Array ? { $b: b64(x) } : x))64const dec = (s: string) => JSON.parse(s, (_k, x) => (x && typeof x === "object" && typeof x.$b === "string" ? unb64(x.$b) : x))65class BridgeStore implements Store {66  constructor(private ns: string) {}67  async get<T>(key: string) {68    const v = await native<string | null>("kv-get", { key: this.ns + key })69    return v == null ? undefined : (dec(v) as T)70  }71  async set(key: string, value: unknown) {72    await native("kv-set", { key: this.ns + key, value: enc(value) })73  }74  async del(key: string) {75    await native("kv-del", { key: this.ns + key })76  }77  async list<T>(prefix: string) {78    const rows = await native<[string, string][]>("kv-list", { prefix: this.ns + prefix })79    return rows.map(([k, v]) => [k.slice(this.ns.length), dec(v) as T] as [string, T])80  }81  async clear() {82    await native("kv-clear", { prefix: this.ns })83  }84}8586// ---- state87let me: Me | null = null88let sessionId = ""89let store: BridgeStore | null = null90let engine: Engine | null = null91let changeTimer: ReturnType<typeof setTimeout> | null = null92const changed = () => {93  if (changeTimer) return94  changeTimer = setTimeout(() => {95    changeTimer = null96    post({ op: "changed" })97  }, 40)98}99100function previewOf(e: Engine, c: Conv): string {101  const last = [...c.messages].reverse().find((m) => m.kind === "text" || m.kind === "call")102  if (!last) return ""103  if (last.kind === "call") return last.sys?.video ? "📹" : "📞"104  if (last.deleted) return "—"105  const f = last.files?.[0]106  const who = last.from === e.me.id ? "↗ " : c.kind === "group" ? `${e.userName(last.from).split(" ")[0]}: ` : ""107  return who + (last.body || (f ? (f.voice ? "🎙" : f.mime.startsWith("image/") ? "📷" : `📎 ${f.name}`) : ""))108}109function msgOut(e: Engine, c: Conv, m: Msg, readUpTo: number, deliveredUpTo: number) {110  return {111    id: m.id, seq: m.seq ?? 0, from: m.from, fromName: e.userName(m.from), mine: m.from === e.me.id, ts: m.ts, kind: m.kind, body: m.body,112    deleted: !!m.deleted, edited: !!m.edited, pinned: !!m.pinned, status: m.status ?? "sent", untrusted: !!m.untrusted,113    receipt: m.from !== e.me.id || !m.seq ? 0 : m.seq <= readUpTo ? 2 : m.seq <= deliveredUpTo ? 1 : 0,114    reply: m.reply ? { id: m.reply.id, name: e.userName(m.reply.from), excerpt: m.reply.excerpt } : null,115    fwd: m.fwd?.from ?? null,116    reactions: Object.entries(m.reactions ?? {}).map(([emoji, users]) => ({ emoji, count: users.length, mine: users.includes(e.me.id) })),117    files: (m.files ?? []).map((f) => ({ id: f.id, name: f.name, mime: f.mime, size: f.size, w: f.w ?? 0, h: f.h ?? 0, dur: f.dur ?? 0, voice: !!f.voice, thumb: f.thumb ?? "", ref: JSON.stringify(f) })),118    sys: m.sys ? { type: m.sys.type, users: (m.sys.users ?? []).map((u) => e.userName(u)), text: m.sys.text ?? "", video: !!m.sys.video } : null,119  }120}121122const api = {123  /** Determines where the person is in the sign-in and enrolment flow. */124  async boot(): Promise<{ phase: string; name?: string; handle?: string }> {125    engine?.stop()126    engine = null127    let r: any128    try {129      r = await transport.request<any>("GET", "/api/me")130    } catch (e) {131      if (e instanceof ApiError && e.status === 401) return { phase: "anon" }132      throw e133    }134    me = r.user as Me135    sessionId = r.session.id136    store = new BridgeStore(`u/${me.id}/`)137    let dev = await Engine.loadDevice(store, me)138    if (dev && r.session.device_id !== dev.deviceId) {139      try {140        await Engine.bindSession(transport, dev, sessionId)141      } catch (e) {142        if (e instanceof ApiError && (e.code === "unknown_device" || e.code === "invalid_signature")) {143          await store.clear()144          dev = null145        } else throw e146      }147    }148    if (dev && me.identity_key && b64(dev.identityKey) !== me.identity_key) {149      await store.clear()150      dev = null151    }152    const who = { name: me.display_name, handle: me.handle }153    if (!dev) return { phase: me.identity_key ? "link" : "first", ...who }154    if (me.status !== "active") return { phase: "pending", ...who }155    engine = new Engine(transport, store, me, dev)156    engine.subscribe(changed)157    engine.onNotify = (c, m) => post({ op: "notify", conv: c.id, title: engine!.convTitle(c), from: engine!.userName(m.from) })158    await engine.start()159    return { phase: "ready", ...who }160  },161  async createIdentity(label: string) {162    return (await Engine.createIdentity(transport, store!, me!, label)).recoveryKey163  },164  async requestLink(label: string) {165    return (await Engine.requestLink(transport, store!, me!, label)).code166  },167  async pollLink() {168    const fresh = await transport.request<any>("GET", "/api/me")169    me = fresh.user170    return !!(await Engine.completeLink(transport, store!, me!))171  },172  async cancelLink() {173    await Engine.cancelLink(transport, store!)174  },175  async recover(key: string, label: string) {176    await Engine.recover(transport, store!, me!, key, label)177  },178179  snapshot(open: string | null) {180    const e = engine181    if (!e) return JSON.stringify({ ready: false })182    const convs = [...e.convs.values()].filter((c) => !c.left || c.messages.length).sort((a, b) => b.lastTs - a.lastTs).map((c) => {183      const peer = e.peerOf(c)184      return {185        id: c.id, kind: c.kind, title: e.convTitle(c), peer: peer ?? "", unread: c.unread, lastTs: c.lastTs, preview: previewOf(e, c), muted: !!c.muted,186        left: !!c.left, waiting: !c.state && !c.left, online: peer ? e.users.get(peer)?.online === true : false,187        typing: Object.keys(c.typing).filter((u) => u !== e.me.id).map((u) => e.userName(u)),188        warnings: c.warnings.map((u) => ({ id: u, name: e.userName(u), canAccept: !!e.pins.get(u)?.changed })),189        missing: c.missing.map((u) => ({ id: u, name: e.userName(u) })), ttl: c.ttl ?? 0,190        members: c.serverMembers.map((m) => ({ id: m.user_id, name: e.userName(m.user_id), role: m.role, verified: !!e.pins.get(m.user_id)?.verified, me: m.user_id === e.me.id })),191        epoch: c.state ? mls.epochOf(c.state) : 0, devices: c.state ? mls.members(c.state).length : 0,192      }193    })194    let messages: unknown[] = []195    const c = open ? e.convs.get(open) : undefined196    if (c) {197      const others = (rec: Record<string, number>) => Object.entries(rec).reduce((n, [u, s]) => (u === e.me.id ? n : Math.max(n, s)), 0)198      const r = others(c.read), d = others(c.delivered)199      messages = c.messages.slice(-400).map((m) => msgOut(e, c, m, r, d))200    }201    return JSON.stringify({202      ready: true, online: e.online, fatal: e.fatal, me: { id: e.me.id, name: e.me.display_name, handle: e.me.handle, role: e.me.role },203      convs, messages, pending: e.pendingDevices, notices: e.notices.map((n) => n.text), unread: convs.reduce((n, c) => n + (c.muted ? 0 : c.unread), 0),204      prefs: e.prefs,205    })206  },207  setActive(conv: string | null, focused: boolean) {208    if (!engine) return209    engine.activeConv = conv210    engine.focused = focused211    if (conv && focused) void engine.markRead(conv)212  },213  async send(conv: string, body: string, replyId: string | null) {214    const e = engine!215    const r = replyId ? e.convs.get(conv)?.messages.find((m) => m.id === replyId) : undefined216    await e.send(conv, { t: "text", body, reply: r ? { id: r.id, from: r.from, excerpt: (r.body || r.files?.[0]?.name || "").slice(0, 120) } : undefined })217  },218  async edit(conv: string, target: string, body: string) {219    await engine!.send(conv, { t: "edit", target, body })220  },221  async remove(conv: string, target: string) {222    await engine!.send(conv, { t: "del", target })223  },224  async react(conv: string, target: string, emoji: string) {225    const m = engine!.convs.get(conv)?.messages.find((x) => x.id === target)226    await engine!.send(conv, { t: "react", target, emoji, on: !m?.reactions?.[emoji]?.includes(engine!.me.id) })227  },228  async pin(conv: string, target: string, on: boolean) {229    await engine!.send(conv, { t: "pin", target, on })230  },231  typing(conv: string) {232    engine?.typing(conv, true)233  },234  /** Encrypts and sends a file handed over by the app (photo picker, file importer, drag and drop, paste). */235  async sendFile(conv: string, name: string, mime: string, data: string, caption: string) {236    const e = engine!237    const file = new File([unb64(data) as unknown as BlobPart], name, { type: mime })238    const { blob, ...info } = await prepare(file, e.prefs.compress)239    const ref = await e.upload(conv, blob, info)240    await e.send(conv, { t: "text", body: caption, files: [ref] })241  },242  /** Downloads and decrypts an attachment; the plaintext only ever exists inside the app. */243  async fetchFile(ref: string) {244    const blob = await engine!.download(JSON.parse(ref) as FileRef)245    return b64(new Uint8Array(await blob.arrayBuffer()))246  },247  async directory() {248    const d = await transport.request<{ id: string; handle: string; display_name: string }[]>("GET", "/api/directory")249    return JSON.stringify(d.filter((u) => u.id !== engine!.me.id).map((u) => ({ id: u.id, handle: u.handle, name: u.display_name, verified: !!engine!.pins.get(u.id)?.verified })))250  },251  async create(userIds: string[], name: string | null) {252    return engine!.createConversation(userIds.length > 1 ? "group" : "dm", userIds, name ?? undefined)253  },254  async approve(deviceId: string) {255    await engine!.approveDevice(deviceId)256  },257  async reject(deviceId: string) {258    await engine!.rejectDevice(deviceId)259  },260  async acceptKey(userId: string) {261    await engine!.acceptIdentityChange(userId)262  },263  async reAdd(conv: string, userId: string) {264    await engine!.reAdd(conv, userId)265  },266  async setTtl(conv: string, ttl: number) {267    await engine!.send(conv, { t: "meta", ttl })268  },269  async setMuted(conv: string, muted: boolean) {270    await engine!.setMuted(conv, muted)271  },272  async leave(conv: string) {273    await engine!.leave(conv)274  },275  async safety(userId: string) {276    const e = engine!277    const pin = e.pins.get(userId)278    if (!pin) return ""279    return safetyNumber({ id: e.me.id, key: e.dev.identityKey }, { id: userId, key: unb64(pin.ik) })280  },281  async setVerified(userId: string, v: boolean) {282    await engine!.setVerified(userId, v)283  },284  async myFingerprint() {285    return fingerprint(engine!.dev.identityKey, engine!.me.id)286  },287  async devices() {288    return JSON.stringify(await transport.request("GET", "/api/devices"))289  },290  async removeDevice(id: string) {291    await transport.request("DELETE", `/api/devices/${id}`)292    void engine?.sync()293  },294  async newRecoveryKey() {295    return engine!.rotateRecoveryKey()296  },297  async setPref(key: string, value: boolean) {298    await engine!.setPrefs({ [key]: value } as never)299  },300  search(q: string) {301    const e = engine!302    return JSON.stringify(e.search(q).slice(0, 60).map((m) => ({ id: m.id, conv: m.conv, title: e.convTitle(e.convs.get(m.conv)!), from: e.userName(m.from), body: m.body || m.files?.[0]?.name || "", ts: m.ts })))303  },304  /** wipe = true also removes this device from the account and erases its local data. */305  async signOut(wipe: boolean) {306    if (engine && wipe) {307      await transport.request("DELETE", `/api/devices/${engine.deviceId}`).catch(() => {})308      await engine.wipe()309    } else engine?.stop()310    engine = null311    await transport.request("POST", "/api/logout").catch(() => {})312  },313}314;(globalThis as any).spm = api315post({ op: "loaded", subtle: !!globalThis.crypto?.subtle })316
Files main
Menu

Theme