Your team of AI agents, on your Mac, Windows or Linux. Agents that talk in channels, write code, review each other and use your tools, on the Claude Code, Codex, OpenCode or Pi you already have. Anything that touches the real world waits for your yes.
TypeScript agent-teamagentic-aiai-agentsai-assistantclaude-codecodexcursorelectrongrokgrok-bot-alternativelinuxlocal-firstmacosmcpmulti-agentopenclaw-alternativeopencodewindows
Notifications on the iPhone with the app closed, through a push relay (#199)
Eduardo Machado227ec68347fe
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c0900d5..1cb7e7c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,7 @@ What changed in each version of Tucano. The format follows [Keep a Changelog](ht## [Unreleased]> **Em português:**+> - **Avisos no iPhone com o app fechado.** Aprovações, perguntas e respostas prontas chegam como notificação mesmo com o app fechado, e tocar abre a conversa.> - **Entrar na IA pelo navegador ou pelo iPhone, num Tucano em servidor.** O botão Entrar roda o login da própria IA no servidor e mostra a tela dele numa janela: a página pra abrir, o código pra digitar e um campo pra colar o código de volta. Sem SSH.>> **Correções:** um agente com o GitHub em **Ler e escrever** volta a subir a branch e abrir a PR em vez de dizer que "a sessão é só leitura" (e, se algo pede aprovação ou está desligado, diz exatamente o quê); e o cartão **Computador** mostra o que vale pra cada escolha, sem misturar a confirmação de **Este computador** com o painel do Linux; e o QR code de Configurações › Celular › Seu iPhone traz o endereço do computador na rede de casa, que o iPhone alcança (antes, o nome .local fazia a conexão falhar).@@ -12,6 +13,7 @@ What changed in each version of Tucano. The format follows [Keep a Changelog](ht### Added- **Sign a harness in on a server from the browser or the phone, with no SSH.** On Tucano as a server, **Sign in** (Settings › Models and the accounts) used to show a command to run in the server's terminal. Now the server runs the harness's own login in a terminal of its own (through `script`, on Linux) and the browser shows it in a window: the screen as text, **Open the sign-in page**, the code to type there with a copy button, a field to paste a code back, and arrows, Enter and Esc for a menu. Each harness signs in the way that works with no browser on the server: Codex and Grok with a device code, Claude Code by pasting the code its page shows, Cursor by approving its page, OpenCode and Gemini in their own menus, Pi with `/login`. The window closes the login once the harness checks as signed in, and a login left open ends after 15 minutes. Tucano passes keys and shows the screen; the harness saves the login where it always does. The iPhone app shows the same window (in its next version). On a desktop, **Sign in** opens a terminal as before.+- **Notifications on the iPhone with the app closed.** Approvals, questions and finished replies used to reach the Tucano app only while it was open. Now a phone that allows notifications gives its Tucano (a server, or the computer at home) a handle, and the Tucano asks a relay at tucano.sh to deliver through Apple. The handle is the phone's Apple token sealed by the relay, which alone holds the app's push key: a Tucano can reach only the phones that connected to it, and a disconnected device stops getting them. The relay passes on the title and the line, as the desktop's notification shows them, and stores nothing. `TUCANO_PUSH_URL` points at another relay, or `off`. Tapping a notification opens its conversation, on the right Tucano (in the next version of the app).### Fixeddiff --git a/docs/server.md b/docs/server.mdindex 085bd1b..fb6074f 100644--- a/docs/server.md+++ b/docs/server.md@@ -109,6 +109,7 @@ To update Tucano, run `git pull && npm ci && npm run build && sudo systemctl res| `TUCANO_PORT` | `7337` | || `TUCANO_TOKEN` | a random token, kept in `server-token` | Set it to use a token of your own || `TUCANO_URL` | where it listens | The address people open, behind a proxy (`https://tucano.example.com`): what `link` prints |+| `TUCANO_PUSH_URL` | `https://tucano.sh/api/push` | The relay that delivers notifications to the iPhone app while it's closed (`site/push.js`), or `off`. The relay gets each notification's title and line, and the phone's handle, and keeps nothing || `TUCANO_TRUST_PROXY` | off | `1` behind a reverse proxy: each visitor's address comes from `X-Forwarded-For` |Once a browser has the cookie, the server answers only its own page: a page of another site (a sibling subdomain included) can't call it, and no site can show it inside a frame. Twenty wrong tokens from one address in ten minutes lock that address out for ten minutes.diff --git a/site/push.js b/site/push.jsnew file mode 100644index 0000000..6d3fa1c--- /dev/null+++ b/site/push.js@@ -0,0 +1,117 @@+// The push relay: how a Tucano (on a server or on a computer) reaches the Tucano app on an iPhone that+// is closed. Apple delivers only for whoever holds the app's push key (APNs), and that key stays here:+// no Tucano gets it. So:+// 1. The app gives its device token to /api/push/register and gets back a handle: the token sealed+// with a key only this worker has (AES-GCM). It hands the handle to its Tucano.+// 2. The Tucano posts the handle and the notification to /api/push/send; this opens the handle and+// asks Apple to deliver. A Tucano can reach only the phones that gave it a handle.+// Nothing is stored here. The worker's secrets (`npx wrangler secret put <name>`):+// APNS_KEY the .p8 key from developer.apple.com (Keys › Apple Push Notifications service), whole+// APNS_KEY_ID its Key ID+// APNS_TEAM_ID the team's ID+// PUSH_SEAL 32 random bytes in base64 (`openssl rand -base64 32`): seals the handles; a new+// one invalidates every handle (each app registers again on its next start)++const TOPIC = 'sh.tucano.ios' // the app's bundle id+const HOSTS = { production: 'https://api.push.apple.com', sandbox: 'https://api.sandbox.push.apple.com' }+const MAX_TARGETS = 20++const json = (status, value) => new Response(JSON.stringify(value), { status, headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' } })+const clip = (v, max) => (typeof v === 'string' ? v.slice(0, max) : '')+const b64url = (bytes) => btoa(String.fromCharCode(...new Uint8Array(bytes))).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')+const unb64url = (s) => Uint8Array.from(atob(s.replace(/-/g, '+').replace(/_/g, '/') + '==='.slice((s.length + 3) % 4)), (c) => c.charCodeAt(0))++async function sealKey(env) {+ if (!env.PUSH_SEAL) throw new Error('no PUSH_SEAL')+ return crypto.subtle.importKey('raw', Uint8Array.from(atob(env.PUSH_SEAL), (c) => c.charCodeAt(0)), 'AES-GCM', false, ['encrypt', 'decrypt'])+}++export async function seal(target, env) {+ const iv = crypto.getRandomValues(new Uint8Array(12))+ const box = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, await sealKey(env), new TextEncoder().encode(JSON.stringify(target)))+ return b64url(new Uint8Array([...iv, ...new Uint8Array(box)]))+}++export async function open(handle, env) {+ try {+ const all = unb64url(handle)+ const plain = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: all.slice(0, 12) }, await sealKey(env), all.slice(12))+ const t = JSON.parse(new TextDecoder().decode(plain))+ return typeof t?.t === 'string' && (t.e === 'production' || t.e === 'sandbox') ? t : undefined+ } catch {+ return undefined+ }+}++// The token Apple asks for (ES256 JWT), made again every 40 minutes (Apple takes one up to an hour old).+let jwt = { value: '', at: 0 }+async function bearer(env, now = Date.now()) {+ if (jwt.value && now - jwt.at < 40 * 60_000) return jwt.value+ const pem = String(env.APNS_KEY ?? '').replace(/-----[^-]+-----/g, '').replace(/\s+/g, '')+ const key = await crypto.subtle.importKey('pkcs8', Uint8Array.from(atob(pem), (c) => c.charCodeAt(0)), { name: 'ECDSA', namedCurve: 'P-256' }, false, ['sign'])+ const part = (o) => b64url(new TextEncoder().encode(JSON.stringify(o)))+ const body = `${part({ alg: 'ES256', kid: env.APNS_KEY_ID })}.${part({ iss: env.APNS_TEAM_ID, iat: Math.floor(now / 1000) })}`+ const sig = await crypto.subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, key, new TextEncoder().encode(body))+ jwt = { value: `${body}.${b64url(sig)}`, at: now }+ return jwt.value+}++// What Apple shows: the title and the text, grouped by conversation; the rest is for the app (a tap+// opens that conversation, on that Tucano).+export function payload(n, tag) {+ return {+ aps: { alert: { title: clip(n.title, 120), body: clip(n.body, 1000) }, sound: 'default', ...(n.conversationId ? { 'thread-id': clip(n.conversationId, 100) } : {}) },+ ...(n.conversationId ? { conversationId: clip(n.conversationId, 100) } : {}),+ ...(n.threadId ? { threadId: clip(n.threadId, 100) } : {}),+ ...(n.kind ? { kind: clip(n.kind, 20) } : {}),+ ...(tag ? { tag: clip(tag, 100) } : {})+ }+}++export async function register(request, env) {+ if (request.method !== 'POST') return json(405, { error: 'POST' })+ const b = await request.json().catch(() => null)+ const token = typeof b?.token === 'string' ? b.token.toLowerCase() : ''+ const e = b?.env === 'sandbox' ? 'sandbox' : 'production'+ if (!/^[0-9a-f]{64,200}$/.test(token)) return json(400, { error: 'token' })+ return json(200, { handle: await seal({ t: token, e }, env) })+}++export async function send(request, env, fetcher = fetch) {+ if (request.method !== 'POST') return json(405, { error: 'POST' })+ const text = await request.text()+ if (text.length > 16 * 1024) return json(413, { error: 'too large' })+ let b+ try {+ b = JSON.parse(text)+ } catch {+ return json(400, { error: 'json' })+ }+ const targets = Array.isArray(b?.targets) ? b.targets.slice(0, MAX_TARGETS) : []+ if (!targets.length || typeof b?.title !== 'string') return json(400, { error: 'targets, title' })+ if (!env.APNS_KEY || !env.APNS_KEY_ID || !env.APNS_TEAM_ID) return json(503, { error: 'push is not set up' })+ const auth = await bearer(env)+ let sent = 0+ const gone = []+ await Promise.all(+ targets.map(async (x) => {+ const handle = typeof x?.handle === 'string' ? x.handle : ''+ const t = handle && (await open(handle, env))+ if (!t) return void gone.push(handle)+ // At most so many a minute per phone (a Tucano gone wrong doesn't flood it).+ if (env.PUSH_LIMIT && !(await env.PUSH_LIMIT.limit({ key: handle.slice(0, 64) })).success) return+ const r = await fetcher(`${HOSTS[t.e]}/3/device/${t.t}`, {+ method: 'POST',+ headers: { authorization: `bearer ${auth}`, 'apns-topic': TOPIC, 'apns-push-type': 'alert', 'apns-priority': '10', 'content-type': 'application/json' },+ body: JSON.stringify(payload(b, typeof x?.tag === 'string' ? x.tag : undefined))+ }).catch(() => undefined)+ if (r?.ok) sent+++ else if (r && (r.status === 410 || (r.status === 400 && /BadDeviceToken|DeviceTokenNotForTopic/.test(await r.text().catch(() => ''))))) gone.push(handle)+ else if (r) console.error('apns', r.status, (await r.text().catch(() => '')).slice(0, 200))+ })+ )+ return json(200, { sent, gone })+}++// For the tests: the cached Apple token goes.+export const forgetBearer = () => void (jwt = { value: '', at: 0 })diff --git a/site/push.test.mjs b/site/push.test.mjsnew file mode 100644index 0000000..80cf36a--- /dev/null+++ b/site/push.test.mjs@@ -0,0 +1,50 @@+// The push relay against a fake Apple: nothing leaves the machine.+// node --test site/+import assert from 'node:assert/strict'+import { generateKeyPairSync, randomBytes } from 'node:crypto'+import { test } from 'node:test'+import { forgetBearer, open, payload, register, seal, send } from './push.js'++const { privateKey } = generateKeyPairSync('ec', { namedCurve: 'prime256v1' })+const env = { PUSH_SEAL: randomBytes(32).toString('base64'), APNS_KEY: privateKey.export({ type: 'pkcs8', format: 'pem' }), APNS_KEY_ID: 'KEY123', APNS_TEAM_ID: 'TEAM123' }+const TOKEN = 'ab'.repeat(32)+const post = (path, body) => new Request(`https://tucano.sh/api/push/${path}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) })++test('a device token comes back sealed, and only this key opens it', async () => {+ const r = await register(post('register', { token: TOKEN.toUpperCase(), env: 'sandbox' }), env)+ const { handle } = await r.json()+ assert.ok(!handle.includes(TOKEN))+ assert.deepEqual(await open(handle, env), { t: TOKEN, e: 'sandbox' })+ assert.equal(await open(handle, { PUSH_SEAL: randomBytes(32).toString('base64') }), undefined)+ assert.equal((await register(post('register', { token: 'not hex' }), env)).status, 400)+})++test('a send goes to Apple with a signed token, the right host and the conversation', async () => {+ forgetBearer()+ const calls = []+ const fake = async (url, init) => (calls.push({ url, init }), new Response('', { status: 200 }))+ const handle = await seal({ t: TOKEN, e: 'production' }, env)+ const r = await send(post('send', { targets: [{ handle, tag: 'server-1' }], title: 'Ana', body: 'Posso enviar?', conversationId: 'c1', kind: 'approval' }), env, fake)+ assert.deepEqual(await r.json(), { sent: 1, gone: [] })+ assert.equal(calls[0].url, `https://api.push.apple.com/3/device/${TOKEN}`)+ assert.equal(calls[0].init.headers['apns-topic'], 'sh.tucano.ios')+ const [head, claims, sig] = calls[0].init.headers.authorization.replace('bearer ', '').split('.')+ assert.deepEqual(JSON.parse(Buffer.from(head, 'base64url')), { alg: 'ES256', kid: 'KEY123' })+ assert.equal(JSON.parse(Buffer.from(claims, 'base64url')).iss, 'TEAM123')+ assert.equal(Buffer.from(sig, 'base64url').length, 64)+ assert.deepEqual(JSON.parse(calls[0].init.body), { aps: { alert: { title: 'Ana', body: 'Posso enviar?' }, sound: 'default', 'thread-id': 'c1' }, conversationId: 'c1', kind: 'approval', tag: 'server-1' })+})++test('a phone Apple no longer knows, or a handle that does not open, comes back as gone', async () => {+ const fake = async () => new Response(JSON.stringify({ reason: 'BadDeviceToken' }), { status: 400 })+ const handle = await seal({ t: TOKEN, e: 'sandbox' }, env)+ const r = await send(post('send', { targets: [{ handle }, { handle: 'garbage' }], title: 'x', body: 'y' }), env, fake)+ const out = await r.json()+ assert.deepEqual({ ...out, gone: out.gone.sort() }, { sent: 0, gone: [handle, 'garbage'].sort() })+})++test('without the key set, nothing is sent; texts are clipped for Apple', async () => {+ const handle = await seal({ t: TOKEN, e: 'sandbox' }, env)+ assert.equal((await send(post('send', { targets: [{ handle }], title: 'x' }), { PUSH_SEAL: env.PUSH_SEAL })).status, 503)+ assert.equal(payload({ title: 'x'.repeat(500), body: 'y'.repeat(5000) }).aps.alert.body.length, 1000)+})diff --git a/site/worker.js b/site/worker.jsindex e9a3ae3..efd6a4b 100644--- a/site/worker.js+++ b/site/worker.js@@ -1,4 +1,5 @@-// tucano.sh: the static pages (dist/, served as assets) and one route of code, /api/lista, where+// tucano.sh: the static pages (dist/, served as assets), the push relay for the iPhone app (push.js,+// /api/push/*) and /api/lista, where// the Tucano Pro beta's waitlist form (pro.html) lands. It checks the anti-robot token (Cloudflare// Turnstile), then saves the sign-up in Supabase (supabase/migrations/0001_waitlist.sql) with the// project's secret key, which only this worker holds:@@ -7,6 +8,8 @@// The same email twice is saved once, and both answers are the same "you're on the list": the// form never tells anyone whether an address was already there.+import { register as pushRegister, send as pushSend } from './push.js'+const MAX_BODY = 8 * 1024const EMAIL = /^[^@\s]+@[^@\s]+\.[^@\s]+$/@@ -89,6 +92,9 @@ export default {async fetch(request, env) {const url = new URL(request.url)if (url.pathname === '/api/lista') return lista(request, env)+ // The push relay for the iPhone app (push.js).+ if (url.pathname === '/api/push/register') return pushRegister(request, env)+ if (url.pathname === '/api/push/send') return pushSend(request, env)return env.ASSETS.fetch(request)},}diff --git a/site/wrangler.jsonc b/site/wrangler.jsoncindex a12afc6..f1fe69d 100644--- a/site/wrangler.jsonc+++ b/site/wrangler.jsonc@@ -1,7 +1,9 @@-// The site: the pages in dist/ (made by build.mjs) served as static files, plus worker.js for one-// route of code, /api/lista (the Tucano Pro waitlist). Everything else never reaches the worker.+// The site: the pages in dist/ (made by build.mjs) served as static files, plus worker.js for the+// routes of code: /api/lista (the Tucano Pro waitlist) and /api/push/* (the iPhone app's push relay,+// push.js). Everything else never reaches the worker.// cd site && npx wrangler deploy-// which first runs build.mjs. The worker's secrets: SUPABASE_SECRET_KEY and TURNSTILE_SECRET+// which first runs build.mjs. The worker's secrets: SUPABASE_SECRET_KEY, TURNSTILE_SECRET, and for the+// push relay APNS_KEY, APNS_KEY_ID, APNS_TEAM_ID, PUSH_SEAL// (`npx wrangler secret put <name>`).{"name": "tucano-site",@@ -9,6 +11,8 @@"main": "worker.js","build": { "command": "node build.mjs" },"assets": { "directory": "dist", "binding": "ASSETS", "run_worker_first": ["/api/*"] },+ // At most 60 notifications a minute per phone (push.js).+ "ratelimits": [{ "name": "PUSH_LIMIT", "namespace_id": "1001", "simple": { "limit": 60, "period": 60 } }],"vars": { "SUPABASE_URL": "https://ykfspxqsoahrwrneqovc.supabase.co" },"routes": [{ "pattern": "tucano.sh", "custom_domain": true }diff --git a/src/core/db.ts b/src/core/db.tsindex 2fa910b..d151569 100644--- a/src/core/db.ts+++ b/src/core/db.ts@@ -498,7 +498,9 @@ export const MIGRATIONS = [const COLUMNS: [string, string, string][] = [['agents', 'action_rules', "TEXT NOT NULL DEFAULT '{}'"],['agents', 'autonomy', 'TEXT'],- ['agents', 'outside_guard', 'INTEGER']+ ['agents', 'outside_guard', 'INTEGER'],+ // A phone's push handle (src/core/push.ts), on its device key: {"handle", "tag"} as JSON.+ ['person_keys', 'push', 'TEXT']]@@ -1723,6 +1725,31 @@ export class Db {}))}+ // A device's push handle (a phone's), or none. False: no such key of this person's.+ setKeyPush(personId: string, hash: string, push: { handle: string; tag?: string } | null): boolean {+ return this.db.prepare('UPDATE person_keys SET push = ? WHERE hash = ? AND person_id = ?').run(push ? JSON.stringify(push) : null, hash, personId).changes > 0+ }++ // The phones that take pushes: of these people (unset: everyone still here).+ pushTargets(people?: string[]): { hash: string; personId: string; handle: string; tag?: string }[] {+ const rows = this.db.prepare('SELECT k.hash, k.person_id, k.push FROM person_keys k JOIN people p ON p.id = k.person_id WHERE k.push IS NOT NULL AND p.removed_at IS NULL').all() as Row[]+ const out: { hash: string; personId: string; handle: string; tag?: string }[] = []+ for (const r of rows) {+ if (people && !people.includes(str(r['person_id']))) continue+ try {+ const p = JSON.parse(str(r['push'])) as { handle?: unknown; tag?: unknown }+ if (typeof p.handle === 'string') out.push({ hash: str(r['hash']), personId: str(r['person_id']), handle: p.handle, ...(typeof p.tag === 'string' ? { tag: p.tag } : {}) })+ } catch {+ // a broken one is skipped+ }+ }+ return out+ }++ dropKeyPush(hash: string): void {+ this.db.prepare('UPDATE person_keys SET push = NULL WHERE hash = ?').run(hash)+ }+// One of a person's keys goes; its browser reads "no access" (removed_keys) instead of counting a guess.removePersonKey(personId: string, hash: string): boolean {return this.tx(() => {diff --git a/src/core/index.ts b/src/core/index.tsindex 47754f1..b847cc6 100644--- a/src/core/index.ts+++ b/src/core/index.ts@@ -34,6 +34,7 @@ import { detectEngine, EngineCheck, type EngineFindings } from './engine-check'import { EngineSetup, SETUP_ENGINES, type SetupEngine, type SetupState } from './engine-setup'import { codexEnv } from './engines/codex'import { LoginTerminal, type LoginKey } from './login-terminal'+import { Push, pushUrl } from './push'import { fakeEngine } from './engines/fake'import { relocating } from './engines/relocate'import { DesktopApps, macApps, SELF } from './apps'@@ -416,12 +417,21 @@ const forOwner = (messageId: string): boolean => {return !q || (q.confirm === 'pending' ? q.requestedBy : q.askedTo) === db.ownerId()}+// The phones that gave this Tucano a push handle get the same notification while the app is closed.+// The test engines never reach the relay.+const push = new Push({+ url: fake ? undefined : pushUrl(),+ targets: (to) => db.pushTargets(to),+ gone: (hash) => db.dropKeyPush(hash)+})+// Desktop notification, and the same on the phone.// `fullText`: the whole reply, for the phone; `page`: a click opens that screen instead of a conversation.// `to`: the people it's for; unset, everyone (but a DM's news only ever reaches its person).const notifyAll = (title: string, shortText: string, conversationId?: string, fullText?: string, more: { kind?: 'approval'; page?: 'skills'; threadId?: string; to?: string[] } = {}): void => {const to = notifyTo(conversationId, more.to)toMain({ type: 'notify', title, body: shortText, conversationId, ...more, ...(to ? { to } : {}), sound: settings().sounds !== false })+ void push.send({ title, body: shortText, ...(conversationId ? { conversationId } : {}), ...(more.threadId ? { threadId: more.threadId } : {}), ...(more.kind ? { kind: more.kind } : {}) }, to)if (!to || to.includes(db.ownerId())) void telegram?.notice(title, fullText ?? shortText)}function notifyTo(conversationId: string | undefined, to: string[] | undefined): string[] | undefined {@@ -825,6 +835,7 @@ const runner = new Runner({if (!kind) return notifyAll(title, body, conversationId, undefined, { threadId, ...(to ? { to } : {}) })const who = notifyTo(conversationId, to)toMain({ type: 'notify', title, body, conversationId, threadId, kind, ...(who ? { to: who } : {}), sound: settings().sounds !== false })+ void push.send({ title, body, ...(conversationId ? { conversationId } : {}), ...(threadId ? { threadId } : {}), kind }, who)},jev: { key: () => secrets.get(JEV_SECRET) },onBusy: (busy) => toMain({ type: 'busy', busy }),@@ -1911,6 +1922,12 @@ const api: Handlers = {myDevices: (_, ctx) => db.personKeys(ctx.person.id).map((k) => ({ id: k.hash, label: k.label, createdAt: k.createdAt, ...(k.seenAt ? { seenAt: k.seenAt } : {}), ...(k.hash === ctx.device ? { current: true } : {}) })),// One of my devices signs out: its open pages lose the line (a moment after the answer, which may// be going down that very line: this page's own device), and the server asks again for my keys.+ // This phone's push handle (from the relay, src/core/push.ts), or none: kept on its device key.+ setPush: ({ handle, tag }, ctx) => {+ if (!ctx.device) throw new Error(L('Só um aparelho conectado com a própria chave recebe avisos.', 'Only a device signed in with its own key gets notifications.'))+ db.setKeyPush(ctx.person.id, ctx.device, handle ? { handle, ...(tag ? { tag } : {}) } : null)+ return { on: push.on }+ },removeDevice: ({ id }, ctx) => {if (!db.removePersonKey(ctx.person.id, id)) throw new Error(L('Esse aparelho já foi desconectado.', 'That device was already disconnected.'))toMain({ type: 'person-changed', id: ctx.person.id })diff --git a/src/core/policy-people.ts b/src/core/policy-people.tsindex 0a100e3..e6186df 100644--- a/src/core/policy-people.ts+++ b/src/core/policy-people.ts@@ -234,6 +234,7 @@ export const NEEDS: Record<Method, Need> = {listInvites: 'admin',removedPeople: 'admin',myDevices: 'anyone', // one's own+ setPush: 'anyone', // one's own device's (ctx.device)removeDevice: 'anyone', // one's own (the core looks only among theirs)removePerson: 'target',setRole: 'target',diff --git a/src/core/push.ts b/src/core/push.tsnew file mode 100644index 0000000..14943d0--- /dev/null+++ b/src/core/push.ts@@ -0,0 +1,69 @@+// Notifications to the Tucano app on a closed iPhone, through the push relay at tucano.sh+// (site/push.js): each phone gave this Tucano a handle (its Apple token, sealed by the relay), kept+// on its device key, so it goes when the device is disconnected. What a phone gets is what the+// desktop's notification says: a title and a line. TUCANO_PUSH_URL points at another relay, or+// `off` turns it off.+export interface PushTarget {+ hash: string // the device key's+ handle: string+ tag?: string // the app's name for this Tucano, so a tap opens the right one+}++export interface PushNote {+ title: string+ body: string+ conversationId?: string+ threadId?: string+ kind?: string+}++export const PUSH_URL = 'https://tucano.sh/api/push'++export class Push {+ constructor(+ private deps: {+ url: string | undefined // the relay; undefined: off+ targets: (to: string[] | undefined) => PushTarget[] // the phones of these people (unset: everyone's)+ gone: (hash: string) => void // Apple no longer knows that phone: forget its handle+ fetch?: typeof fetch+ }+ ) {}++ get on(): boolean {+ return !!this.deps.url+ }++ // Fire and forget: a relay that's down only means no push this time.+ send(note: PushNote, to: string[] | undefined): Promise<void> {+ const url = this.deps.url+ if (!url) return Promise.resolve()+ const all = this.deps.targets(to)+ if (!all.length) return Promise.resolve()+ const chunks: PushTarget[][] = []+ for (let i = 0; i < all.length; i += 20) chunks.push(all.slice(i, i + 20))+ return Promise.all(+ chunks.map(async (chunk) => {+ try {+ const r = await (this.deps.fetch ?? fetch)(`${url}/send`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ ...note, targets: chunk.map((t) => ({ handle: t.handle, ...(t.tag ? { tag: t.tag } : {}) })) }),+ signal: AbortSignal.timeout(15_000)+ })+ if (!r.ok) return console.error('[push]', r.status)+ const { gone } = (await r.json()) as { gone?: unknown }+ if (Array.isArray(gone)) for (const t of chunk) if (gone.includes(t.handle)) this.deps.gone(t.hash)+ } catch (e) {+ console.error('[push]', e instanceof Error ? e.message : e)+ }+ })+ ).then(() => undefined)+ }+}++// The relay from the environment: the default, another one, or none.+export function pushUrl(env: NodeJS.ProcessEnv = process.env): string | undefined {+ const v = env['TUCANO_PUSH_URL']?.trim()+ if (v === 'off' || v === '0') return undefined+ return (v || PUSH_URL).replace(/\/+$/, '')+}diff --git a/src/shared/rpc-shapes.ts b/src/shared/rpc-shapes.tsindex c144165..461c46b 100644--- a/src/shared/rpc-shapes.ts+++ b/src/shared/rpc-shapes.ts@@ -151,6 +151,7 @@ export const SHAPES: Record<Method, Record<string, string>> = {listInvites: {},removedPeople: {},myDevices: {},+ setPush: { handle: 's|null', tag: 's?' },removeDevice: { id: 's' },removePerson: { id: 's' },setRole: { id: 's', role: 's' },@@ -221,7 +222,8 @@ export const LIMITS: Partial<Record<Method, Record<string, number>>> = {wikiSaveSchema: { text: MB },wikiSearch: { q: 1_000 },wikiRelease: { title: 200 },- loginInput: { text: 4_000 } // a code or an API key, typed into a sign-in+ loginInput: { text: 4_000 }, // a code or an API key, typed into a sign-in+ setPush: { handle: 2_000, tag: 200 }}export function limitError(method: Method, params: unknown): string | undefined {diff --git a/src/shared/rpc.ts b/src/shared/rpc.tsindex 96c3ebf..461ed54 100644--- a/src/shared/rpc.ts+++ b/src/shared/rpc.ts@@ -181,6 +181,7 @@ export interface Api {listInvites(): Invite[]removedPeople(): (Person & { removedAt: number })[] // admins: who left in the last 30 days (still restorable)myDevices(): Device[] // my own keys: the browsers and phones signed in as me+ setPush(p: { handle: string | null; tag?: string }): { on: boolean } // this phone's push handle (the relay's), or none; on: this Tucano sends pushesremoveDevice(p: { id: string }): void // one of mine signs out now (Device.id)removePerson(p: { id: string }): void // their access ends at once: keys gone, open connections closed; what they owned goes to the ownersetRole(p: { id: string; role: Exclude<Role, 'owner'> }): voiddiff --git a/test/push.test.ts b/test/push.test.tsnew file mode 100644index 0000000..cfc5b25--- /dev/null+++ b/test/push.test.ts@@ -0,0 +1,57 @@+import { describe, expect, it } from 'vitest'+import { Db } from '../src/core/db'+import { Push, pushUrl, type PushTarget } from '../src/core/push'++describe('push targets on device keys', () => {+ it('keeps a handle per device, for the people asked, and forgets it with the device', () => {+ const db = new Db(':memory:')+ const owner = db.ownerId()+ db.addPersonKey('phone', owner, 'iPhone')+ db.addPersonKey('laptop', owner, 'Chrome')+ expect(db.setKeyPush(owner, 'phone', { handle: 'h1', tag: 'srv' })).toBe(true)+ expect(db.setKeyPush('someone-else', 'laptop', { handle: 'x' })).toBe(false)+ expect(db.pushTargets()).toEqual([{ hash: 'phone', personId: owner, handle: 'h1', tag: 'srv' }])+ expect(db.pushTargets([owner])).toHaveLength(1)+ expect(db.pushTargets(['nobody'])).toEqual([])+ db.dropKeyPush('phone')+ expect(db.pushTargets()).toEqual([])+ db.setKeyPush(owner, 'phone', { handle: 'h2' })+ db.removePersonKey(owner, 'phone')+ expect(db.pushTargets()).toEqual([])+ })+})++describe('Push', () => {+ const targets: PushTarget[] = [{ hash: 'a', handle: 'ha', tag: 't1' }, { hash: 'b', handle: 'hb' }]++ it('posts the note with each phone, and forgets the ones Apple dropped', async () => {+ const calls: { url: string; body: unknown }[] = []+ const gone: string[] = []+ const push = new Push({+ url: 'https://relay.example/api/push',+ targets: (to) => (to?.includes('ana') ? targets : []),+ gone: (h) => void gone.push(h),+ fetch: (async (url: string, init: RequestInit) => (calls.push({ url, body: JSON.parse(String(init.body)) }), Response.json({ sent: 1, gone: ['hb'] }))) as typeof fetch+ })+ await push.send({ title: 'Ana', body: 'Posso enviar?', conversationId: 'c1', kind: 'approval' }, ['ana'])+ expect(calls).toEqual([{ url: 'https://relay.example/api/push/send', body: { title: 'Ana', body: 'Posso enviar?', conversationId: 'c1', kind: 'approval', targets: [{ handle: 'ha', tag: 't1' }, { handle: 'hb' }] } }])+ expect(gone).toEqual(['b'])+ await push.send({ title: 'x', body: 'y' }, ['bob'])+ expect(calls).toHaveLength(1) // no phones: nothing sent+ })++ it('off sends nothing, and a relay that fails is only logged', async () => {+ let called = false+ const off = new Push({ url: undefined, targets: () => targets, gone: () => {}, fetch: (async () => ((called = true), new Response())) as unknown as typeof fetch })+ await off.send({ title: 'x', body: 'y' }, undefined)+ expect(called).toBe(false)+ const down = new Push({ url: 'https://r', targets: () => targets, gone: () => {}, fetch: (async () => { throw new Error('down') }) as typeof fetch })+ await expect(down.send({ title: 'x', body: 'y' }, undefined)).resolves.toBeUndefined()+ })++ it('reads the relay from the environment', () => {+ expect(pushUrl({})).toBe('https://tucano.sh/api/push')+ expect(pushUrl({ TUCANO_PUSH_URL: 'https://mine.example/push/' })).toBe('https://mine.example/push')+ expect(pushUrl({ TUCANO_PUSH_URL: 'off' })).toBeUndefined()+ })+})