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
Connect the iPhone app to the Tucano on your computer, over the home Wi-Fi (#191)
Eduardo Machado9cc9e81fa083
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a33c16c..3948a03 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,7 @@ What changed in each version of Tucano. The format follows [Keep a Changelog](ht- **An agent's decisions, answered one at a time with options to pick.** `ask_user` took a single string, so agents packed their findings, a proposal and several questions into one unformatted card. Now an agent asks for 1 to 4 decisions, each a single choice, a multiple choice or a short text, and writes its analysis in the reply, which renders as usual; a question over 200 characters goes back to the agent asking for the context in the reply. The decisions come as a card under the agent's reply, one at a time (with arrows and "1 of 2"): the agent suggests 1 to 3 options and the card always adds "Something else", which opens a field for your own answer. Pick with a click or the option's number, Enter confirms, "Skip" moves on, and with more than one decision there's a review before sending, where any answer can still change. The answer goes as your message, one line per decision. The message box below stays as it was: writing there answers too, and what you already picked on the card goes along. Once answered, the card keeps each decision with what was chosen, and the sidebar marks a channel or DM where an agent waits on you, with who in its tooltip. With a team, a question to someone carries its decisions too: the asked person (or whoever covers for them) answers them on the card, in the conversation or in **For you**; an admin can answer for them; everyone else sees what was asked and, afterwards, who answered. A question from a DM still waits for the DM's person's yes first, and the sidebar marks only what waits on you. Older pending questions still work, and Telegram gets the decisions as numbered text, answered by replying. Thanks [@cleitoncsalvagni](https://github.com/cleitoncsalvagni)! ([#145](https://github.com/eduwxyz/tucano/pull/145))- **How far each agent goes on its own.** **Settings › Agents › Autonomy** sets a level for every agent, and each agent's page (Tools) can set its own: **Careful** asks before anything that changes something (a write in a connector, a commit, a push, a risky click); **Normal** is how Tucano always worked, reading and writing on its own and asking before what's sensitive; **No guardrails** sends, deletes, publishes, pays and clicks without asking, after a confirmation. Under **Fine-tune action by action**, each kind (commit, push, pull request, merge, delete, send, publish, pay, a risky click in the agent's browser, a risky action in an app) can ask first, run alone or never happen, over the level; an agent's own rule wins over its level, which wins over Settings. A tool you marked high risk always asks, and a step that ran without asking says so ("Ran (no ask: autonomy)"). Commands on the agent's computer are read before they run, every command on the line (from #110, by @rjgdias): a commit, a push or an `rm -r` that a rule holds becomes an approval with the exact command, and approved, exactly that runs.- **A guard against text that tells the agent what to do.** An email, a page or an issue can carry instructions someone else wrote. After an agent reads something from outside in a reply (a connector's answer, a page, an app, the web, a trigger's event), sending, publishing, paying, deleting and risky clicks ask first, even where a rule or the level lets them run, and the card says why. It's on by default, in Settings and on each agent's page; an agent's next replies in the same conversation keep it, since its session still holds what it read.+- **Your iPhone, on your computer's Tucano.** **Settings › Phone › Your iPhone › Connect my iPhone** shows a QR code: the Tucano app for iPhone reads it and gets in as you, with your conversations, approvals and the agents' questions, over the home Wi-Fi while the computer is on. No team or server needed. The computer answers only devices on its own network, over HTTPS with a certificate of its own whose fingerprint rides in the QR code, so another device on the Wi-Fi can't pose as it; each phone gets a key of its own from a one-time code. It stays on across restarts until **Turn off**. On a Mac the phone finds the computer by its Bonjour name; on Windows and Linux, by its address on the home network. Away from home the phone can't reach the computer: that's what a server or Tucano Pro is for.## [0.2.17] - 2026-11-07diff --git a/src/core/guide/celular.md b/src/core/guide/celular.mdindex a10a8e6..faeef5d 100644--- a/src/core/guide/celular.md+++ b/src/core/guide/celular.md@@ -1,5 +1,15 @@-# Celular (Telegram)-> Aprovações com botões, perguntas dos agentes e o fim das rotinas no seu Telegram, com um bot seu.+# Celular (iPhone e Telegram)+> O app do Tucano no iPhone, pelo Wi-Fi de casa; ou aprovações, perguntas e o fim das rotinas no seu Telegram, com um bot seu.++## Seu iPhone+O app do Tucano pro iPhone entra como você neste computador: suas conversas, aprovações e as perguntas dos agentes. Funciona no Wi-Fi de casa, com o computador ligado.+1. Em **Configurações › Celular** (Settings › Phone), card **Seu iPhone**, clique em **Conectar meu iPhone**.+2. Deixe o iPhone no mesmo Wi-Fi. No app do Tucano, toque no ícone de QR code e aponte pro código. Ele vale uma vez, por 10 minutos.+3. Quando o iPhone pedir acesso à rede local, toque em **Permitir**. Se o computador perguntar se o Tucano pode aceitar conexões, permita (no Windows, nas redes privadas; no Linux com firewall, libere a porta que o card mostra).++Fica ligado mesmo depois de fechar e abrir o app, até **Desligar**. Só aparelhos da rede de casa recebem resposta, e o QR leva a impressão digital do certificado deste computador: outro aparelho no Wi-Fi não se passa por ele. Fora de casa o iPhone não alcança o computador; pra isso, um Tucano em servidor ou o Tucano Pro.++## TelegramCom um bot do Telegram seu, você decide aprovações, responde às perguntas dos agentes (é só responder a mensagem) e recebe o fim das rotinas de qualquer lugar. É útil pra rotina que pede aprovação de madrugada. O app busca as mensagens no Telegram, então nada precisa chegar até o seu computador.diff --git a/src/main/home-link.ts b/src/main/home-link.tsnew file mode 100644index 0000000..6391c54--- /dev/null+++ b/src/main/home-link.ts@@ -0,0 +1,282 @@+// The phone at home: the desktop app opens its Tucano to the iPhone app on the same Wi-Fi, as the+// owner. Off until the owner turns it on (Settings › Celular › Seu iPhone); then an HTTPS address on+// this computer's network, with a certificate of its own (self-signed.ts) whose fingerprint rides+// in the QR code, so the phone knows it's talking to this Mac.+//+// It speaks the part of the server's protocol the phone uses (src/server/index.ts): POST /pair+// trades a one-time code for a key of the phone's own (the core keeps it, as on a server), then the+// key opens /events (the core's port, as an event stream), /rpc (requests up), /artifact and /upload.+// Only addresses of a private network get an answer: nothing here is for the internet.+import { randomUUID } from 'node:crypto'+import { createReadStream, createWriteStream, existsSync, mkdirSync, rmSync, statSync } from 'node:fs'+import type { IncomingMessage, ServerResponse } from 'node:http'+import { createServer, type Server } from 'node:https'+import { homedir } from 'node:os'+import { extname, join, normalize, sep } from 'node:path'+import { ARTIFACT_CSP, BASE_HEADERS, decodedPath, Doors } from '../server/guard'+import { deviceLabel, PairCodes } from '../server/pair-codes'+import { pairingLink } from '../shared/servers'+import type { Person } from '../shared/types'++// What the link needs of the core (index.ts wires it to the workspace's process).+export interface HomeCore {+ // The person a key opens; removed: a key that was someone's who's gone.+ auth(key: string): Promise<Person | { removed: true } | undefined>+ // A new key for the owner, for one device.+ deviceKey(label: string): Promise<string | undefined>+ // A port to the core as this person: what the core says comes to onMessage.+ open(person: string, onMessage: (msg: unknown) => void): { post(data: unknown): void; close(): void }+ // Where the workspace keeps what agents showed (artifacts/<id>/<name>).+ dataDir(): string+}++type Stream = { person: string; res: ServerResponse; port: { post(data: unknown): void; close(): void } }++const PERSON_KEY = /^p_[\w-]{43}$/+const MAX_UPLOAD = 1024 * 1024 * 1024++// A private network's address (home Wi-Fi, Tailscale), loopback, or link-local; never the internet.+export function isLocalAddress(raw: string | undefined): boolean {+ const ip = (raw ?? '').replace(/^::ffff:/, '').toLowerCase()+ if (/^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\.|127\.|169\.254\.)/.test(ip)) return true+ return ip === '::1' || /^fe[89ab][0-9a-f]:/.test(ip) || /^f[cd][0-9a-f]{2}:/.test(ip)+}++const TYPES: Record<string, string> = {+ '.html': 'text/html; charset=utf-8',+ '.js': 'text/javascript; charset=utf-8',+ '.css': 'text/css; charset=utf-8',+ '.json': 'application/json',+ '.svg': 'image/svg+xml',+ '.png': 'image/png',+ '.jpg': 'image/jpeg',+ '.jpeg': 'image/jpeg',+ '.gif': 'image/gif',+ '.webp': 'image/webp',+ '.mp4': 'video/mp4',+ '.pdf': 'application/pdf',+ '.txt': 'text/plain; charset=utf-8',+ '.md': 'text/plain; charset=utf-8',+ '.csv': 'text/csv; charset=utf-8'+}++export class HomeLink {+ private server?: Server+ private streams = new Map<string, Stream>()+ private doors = new Doors()+ private codes: PairCodes+ private origin = ''+ port = 0++ constructor(+ private o: {+ tls: { key: string; cert: string; fingerprint: string }+ codesFile: string+ core: () => HomeCore | undefined+ sentDir?: string // where a phone's file for a message lands: ~/Enviados, as on a server+ onChange?: () => void // a phone connected, left, or paired+ }+ ) {+ this.codes = new PairCodes(o.codesFile)+ }++ get running(): boolean {+ return !!this.server?.listening+ }++ // Phones on the line now.+ get connected(): number {+ return this.streams.size+ }++ // Listens on every interface, at `port` or the next free one of a few: IPv6 and IPv4 together+ // (macOS, Windows, most Linux), or IPv4 alone where the system has no IPv6 (some Linux).+ async start(port: number, host: string): Promise<number> {+ if (this.server) return this.port+ let any = '::'+ for (let p = port; p < port + 10; p++) {+ const server = createServer({ key: this.o.tls.key, cert: this.o.tls.cert }, (req, res) => this.handle(req, res))+ const listen = (on: string): Promise<string | undefined> =>+ new Promise((done) => {+ server.once('error', (e: NodeJS.ErrnoException) => done(e.code ?? 'error'))+ server.listen(p, on, () => done(undefined))+ })+ let failed = await listen(any)+ if (failed === 'EAFNOSUPPORT' || failed === 'EADDRNOTAVAIL') failed = await listen((any = '0.0.0.0'))+ if (failed) continue+ server.on('error', (e) => console.error('[home-link]', e.message))+ this.server = server+ this.port = p+ this.origin = `https://${host.includes(':') ? `[${host}]` : host}:${p}`+ return p+ }+ throw new Error('no free port')+ }++ async stop(): Promise<void> {+ for (const s of this.streams.values()) s.res.end()+ this.streams.clear()+ const server = this.server+ this.server = undefined+ if (server) await new Promise<void>((done) => server.close(() => done()).closeAllConnections())+ }++ // A one-time code for the owner's phone, as the link the QR code holds.+ makeCode(): { link: string; expiresAt: number } {+ const { code, expiresAt } = this.codes.make(null)+ return { link: pairingLink({ origin: this.origin, code, fp: this.o.tls.fingerprint }), expiresAt }+ }++ // Something the core tells the phones (a notification): to each one on the line.+ deliver(msg: unknown): void {+ for (const s of this.streams.values()) s.res.write(`data: ${JSON.stringify(msg)}\n\n`)+ }++ private handle(req: IncomingMessage, res: ServerResponse): void {+ try {+ if (!isLocalAddress(req.socket.remoteAddress)) return void res.writeHead(403, BASE_HEADERS).end()+ const url = new URL(req.url ?? '/', 'https://x')+ const ip = req.socket.remoteAddress ?? ''+ if (url.pathname === '/pair' && req.method === 'POST') return void this.pair(req, res, ip)+ const key = /(?:^|;\s*)tucano=([^;]+)/.exec(req.headers.cookie ?? '')?.[1]+ if (this.doors.blocked('signin', ip)) return void res.writeHead(429, { ...BASE_HEADERS, 'retry-after': '600' }).end()+ const core = this.o.core()+ if (!core) return void res.writeHead(503, BASE_HEADERS).end()+ if (!key || !PERSON_KEY.test(key)) return this.unauthorized(res, ip)+ void core.auth(key).then(+ (who) => {+ if (!who) return this.unauthorized(res, ip)+ if ('removed' in who) return void res.writeHead(401, BASE_HEADERS).end()+ this.signedIn(req, res, url, who, core)+ },+ () => !res.headersSent && res.writeHead(503, BASE_HEADERS).end()+ )+ } catch (e) {+ console.error('[home-link]', req.method, e instanceof Error ? e.message : e)+ if (!res.headersSent) res.writeHead(400, BASE_HEADERS).end()+ }+ }++ private unauthorized(res: ServerResponse, ip: string): void {+ this.doors.fail('signin', ip)+ res.writeHead(401, { ...BASE_HEADERS, 'content-type': 'text/plain; charset=utf-8' }).end('unauthorized')+ }++ // POST /pair {code, name, platform}: the phone's key, as {key}. A wrong, used or late code: 410.+ private async pair(req: IncomingMessage, res: ServerResponse, ip: string): Promise<void> {+ if (this.doors.blocked('join', ip)) return void res.writeHead(429, { ...BASE_HEADERS, 'retry-after': '600' }).end()+ let asked: { code?: unknown; name?: unknown; platform?: unknown } = {}+ try {+ asked = JSON.parse(await body(req, 4 * 1024)) as typeof asked+ } catch {+ return void res.writeHead(400, BASE_HEADERS).end()+ }+ const spent = this.codes.spend(asked?.code)+ const key = spent ? await this.o.core()?.deviceKey(deviceLabel(asked?.name, asked?.platform)) : undefined+ if (!key) {+ this.doors.fail('join', ip)+ return json(res, 410, { error: 'Esse código já foi usado ou passou do prazo. Gere outro no Tucano do computador. · That code was already used or has expired. Make a new one in Tucano on your computer.' })+ }+ json(res, 200, { key })+ this.o.onChange?.()+ }++ private signedIn(req: IncomingMessage, res: ServerResponse, url: URL, who: Person, core: HomeCore): void {+ if (url.pathname === '/events') {+ const id = randomUUID()+ res.writeHead(200, { ...BASE_HEADERS, 'content-type': 'text/event-stream', 'cache-control': 'no-cache' })+ res.write(`event: hello\ndata: ${id}\n\n`)+ const port = core.open(who.id, (msg) => res.write(`data: ${JSON.stringify(msg)}\n\n`))+ this.streams.set(id, { person: who.id, res, port })+ // A beat the phone hears: it tells a dead line from a quiet one.+ const beat = setInterval(() => res.write('event: ping\ndata: \n\n'), 25_000)+ req.on('close', () => {+ clearInterval(beat)+ this.streams.delete(id)+ port.close()+ this.o.onChange?.()+ })+ this.o.onChange?.()+ return+ }++ if (url.pathname === '/rpc' && req.method === 'POST') {+ const s = this.streams.get(url.searchParams.get('c') ?? '')+ if (!s || s.person !== who.id) return void res.writeHead(410, BASE_HEADERS).end()+ body(req).then(+ (text) => {+ let data: unknown+ try {+ data = JSON.parse(text)+ } catch {+ return void res.writeHead(400, BASE_HEADERS).end()+ }+ s.port.post(data)+ res.writeHead(204, BASE_HEADERS).end()+ },+ () => res.writeHead(413, BASE_HEADERS).end()+ )+ return+ }++ // The conversation open on the phone: the desktop's window keeps telling its own, so the phone's isn't passed on.+ if (url.pathname === '/viewing' && req.method === 'POST') return void req.resume().on('end', () => res.writeHead(204, BASE_HEADERS).end())++ // What the agents showed in the chat, sandboxed as on the desktop.+ const art = /^\/artifact\/([0-9a-f-]{36})\/([^/]+)$/.exec(url.pathname)+ if (art && req.method === 'GET') {+ const dir = join(core.dataDir(), 'artifacts', art[1]!)+ const name = decodedPath(art[2]!)+ const path = name === undefined ? '' : normalize(join(dir, name))+ if (!path.startsWith(dir + sep) || !existsSync(path) || !statSync(path).isFile()) return void res.writeHead(404, BASE_HEADERS).end()+ res.writeHead(200, { ...BASE_HEADERS, 'content-type': TYPES[extname(path).toLowerCase()] ?? 'application/octet-stream', 'content-security-policy': ARTIFACT_CSP })+ return void createReadStream(path).on('error', () => res.destroy()).pipe(res)+ }++ // A file from the phone for a message: ~/Enviados, under its own name (a number added when taken).+ if (url.pathname === '/upload' && req.method === 'POST') {+ if (url.searchParams.get('for') !== 'message') return void res.writeHead(403, BASE_HEADERS).end()+ const name = (url.searchParams.get('name') ?? 'file').replace(/[^\p{L}\p{N}._ -]/gu, '_').replace(/^\.+/, '_').slice(0, 120) || 'file'+ const dir = this.o.sentDir ?? join(homedir(), 'Enviados')+ mkdirSync(dir, { recursive: true, mode: 0o700 })+ let path = join(dir, name)+ for (let n = 2; existsSync(path); n++) path = join(dir, name.replace(/(\.[^.]*)?$/, ` (${n})$1`))+ const out = createWriteStream(path, { mode: 0o600 })+ let size = 0+ const fail = (code: number): void => {+ out.destroy()+ rmSync(path, { force: true })+ if (!res.headersSent) res.writeHead(code, BASE_HEADERS).end()+ }+ req.on('data', (c: Buffer) => {+ size += c.length+ if (size > MAX_UPLOAD) {+ req.destroy()+ fail(413)+ }+ })+ req.on('error', () => fail(400))+ req.pipe(out).on('finish', () => !res.headersSent && json(res, 200, { path }))+ return+ }++ res.writeHead(404, BASE_HEADERS).end()+ }+}++function body(req: IncomingMessage, max = 64 * 1024 * 1024): Promise<string> {+ return new Promise((resolve, reject) => {+ const chunks: Buffer[] = []+ let size = 0+ req.on('data', (c: Buffer) => {+ size += c.length+ if (size > max) return reject(new Error('too large'))+ chunks.push(c)+ })+ req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')))+ req.on('error', reject)+ })+}++const json = (res: ServerResponse, status: number, value: unknown): void =>+ void res.writeHead(status, { ...BASE_HEADERS, 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }).end(JSON.stringify(value))diff --git a/src/main/home-phone-net.ts b/src/main/home-phone-net.tsnew file mode 100644index 0000000..acd48cc--- /dev/null+++ b/src/main/home-phone-net.ts@@ -0,0 +1,31 @@+// Where the phone finds this computer on the home network (home-phone.ts). No Electron here, so+// it can be tested on its own.+import { execFileSync } from 'node:child_process'+import { hostname, networkInterfaces } from 'node:os'++// How the phone finds this computer on the Wi-Fi: its Bonjour name (eduardos-macbook.local), which+// stays when the router hands out another address; elsewhere, its address on the home network.+export function homeHost(): string {+ if (process.platform === 'darwin') {+ try {+ const name = execFileSync('/usr/sbin/scutil', ['--get', 'LocalHostName'], { encoding: 'utf8', timeout: 2000 }).trim()+ if (/^[A-Za-z0-9-]{1,63}$/.test(name)) return `${name}.local`.toLowerCase()+ } catch {}+ }+ return lanAddress(networkInterfaces()) ?? hostname()+}++// The address of the Wi-Fi or the cable, not of a virtual network the computer also has (Docker,+// WSL and Hyper-V on Windows, VirtualBox, VMware, a VPN): those come first in some lists, and a+// phone can't reach them. A home router's 192.168.x first, then 10.x, then 172.16–31.x.+export function lanAddress(nets: Record<string, { family: string | number; address: string; internal: boolean }[] | undefined>): string | undefined {+ const virtual = /docker|veth|br-|virbr|vbox|virtualbox|vmware|vmnet|vethernet|hyper-v|wsl|utun|tun|tap|tailscale|zerotier|zt|wg|ppp|llw|awdl|bridge/i+ const rank = (ip: string): number => (ip.startsWith('192.168.') ? 0 : ip.startsWith('10.') ? 1 : /^172\.(1[6-9]|2\d|3[01])\./.test(ip) ? 2 : 9)+ const found = Object.entries(nets)+ .filter(([name]) => !virtual.test(name))+ .flatMap(([, list]) => (list ?? []).filter((a) => (a.family === 'IPv4' || a.family === 4) && !a.internal).map((a) => a.address))+ .filter((ip) => rank(ip) < 9)+ .sort((a, b) => rank(a) - rank(b))+ return found[0]+}+diff --git a/src/main/home-phone.ts b/src/main/home-phone.tsnew file mode 100644index 0000000..95c1aeb--- /dev/null+++ b/src/main/home-phone.ts@@ -0,0 +1,158 @@+// "Seu iPhone" in Settings › Celular: the home link (home-link.ts) wired to the desktop app. It+// serves one workspace, the one on screen when it was turned on, as its owner; stays on across+// restarts until turned off; and keeps its certificate (so a phone paired once stays paired) and+// its port in the app's data folder.+import { randomUUID } from 'node:crypto'+import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'+import { join } from 'node:path'+import { MessageChannelMain, type UtilityProcess } from 'electron'+import type { Person } from '../shared/types'+import { HomeLink, type HomeCore } from './home-link'+import { homeHost } from './home-phone-net'+import { fingerprintOf, makeCertificate, matches } from './self-signed'++export type HomePhoneState = { on: boolean; address: string; connected: number; workspace: string; error?: string }++type Saved = { on: boolean; port: number; workspace?: string }+const FIRST_PORT = 7350++export function homePhone(deps: {+ dir: string // the app's data folder+ selected: () => { id: string; name: string; dataDir: string }+ workspace: (id: string) => { id: string; name: string; dataDir: string } | undefined+ child: (id: string) => Promise<UtilityProcess | undefined> // the workspace's core, started if needed+ publish: (state: HomePhoneState) => void+}) {+ const configFile = join(deps.dir, 'home-link.json')+ const tlsDir = join(deps.dir, 'home-link')+ let saved: Saved = { on: false, port: FIRST_PORT }+ try {+ saved = { ...saved, ...(JSON.parse(readFileSync(configFile, 'utf8')) as Partial<Saved>) }+ } catch {}+ const save = (): void => writeFileSync(configFile, JSON.stringify(saved), { mode: 0o600 })++ // The certificate, made once: a new one would leave every paired phone talking to a stranger.+ function tls(): { key: string; cert: string; fingerprint: string } {+ mkdirSync(tlsDir, { recursive: true, mode: 0o700 })+ const keyFile = join(tlsDir, 'key.pem')+ const certFile = join(tlsDir, 'cert.pem')+ if (existsSync(keyFile) && existsSync(certFile)) {+ const pair = { key: readFileSync(keyFile, 'utf8'), cert: readFileSync(certFile, 'utf8') }+ if (matches(pair)) return { ...pair, fingerprint: fingerprintOf(pair.cert) }+ }+ const made = makeCertificate('Tucano', [homeHost()])+ writeFileSync(keyFile, made.key, { mode: 0o600 })+ writeFileSync(certFile, made.cert, { mode: 0o600 })+ chmodSync(keyFile, 0o600)+ return made+ }++ // Questions to the core that wait for its answer (a key's person, a phone's key): by id.+ const waits = new Map<string, (msg: Record<string, unknown>) => void>()+ async function ask(msg: Record<string, unknown>, timeoutMs = 10_000): Promise<Record<string, unknown> | undefined> {+ const child = await deps.child(current())+ if (!child) return undefined+ const id = randomUUID()+ return new Promise((resolve) => {+ const timer = setTimeout(() => waits.delete(id) && resolve(undefined), timeoutMs)+ waits.set(id, (m) => (clearTimeout(timer), waits.delete(id), resolve(m)))+ child.postMessage({ ...msg, id })+ })+ }++ const current = (): string => saved.workspace ?? deps.selected().id+ let child: UtilityProcess | undefined // the served workspace's core, once known+ const core: HomeCore = {+ auth: async (key) => {+ const r = await ask({ type: 'auth', key })+ return r?.['person'] ? (r['person'] as Person) : r?.['removed'] ? { removed: true } : undefined+ },+ deviceKey: async (label) => {+ const r = await ask({ type: 'device-key', person: null, label })+ return (r?.['data'] as { key?: string } | undefined)?.key+ },+ open: (person, onMessage) => {+ const { port1, port2 } = new MessageChannelMain()+ port2.on('message', (e) => onMessage(e.data))+ port2.start()+ child?.postMessage({ person }, [port1])+ return { post: (data) => port2.postMessage(data), close: () => port2.close() }+ },+ dataDir: () => deps.workspace(current())?.dataDir ?? deps.selected().dataDir+ }++ let link: HomeLink | undefined+ let error: string | undefined+ const state = (): HomePhoneState => ({+ on: saved.on && !!link?.running,+ address: link?.running ? `${homeHost()}:${link.port}` : '',+ connected: link?.connected ?? 0,+ workspace: deps.workspace(current())?.name ?? '',+ ...(error ? { error } : {})+ })+ const changed = (): void => deps.publish(state())++ async function start(): Promise<void> {+ child = await deps.child(current())+ if (!child) throw new Error('workspace not running')+ link ??= new HomeLink({ tls: tls(), codesFile: join(deps.dir, 'home-link-codes.json'), core: () => core, onChange: changed })+ saved.port = await link.start(saved.port, homeHost())+ }++ return {+ state,+ async set(on: boolean): Promise<HomePhoneState> {+ error = undefined+ if (on) {+ saved = { ...saved, on: true, workspace: saved.on ? current() : deps.selected().id }+ try {+ await start()+ } catch (e) {+ error = e instanceof Error ? e.message : String(e)+ saved.on = false+ }+ } else {+ saved = { ...saved, on: false, workspace: undefined }+ await link?.stop()+ }+ save()+ changed()+ return state()+ },+ // A one-time code for the owner's phone: the QR code's link.+ async code(): Promise<{ link: string; expiresAt: number }> {+ if (!link?.running) await this.set(true)+ if (!link?.running) throw new Error(error ?? 'not running')+ return link.makeCode()+ },+ // The core's answers to the questions above; true when the message was one.+ fromCore(msg: { type?: string; id?: string }): boolean {+ if ((msg.type === 'auth-result' || msg.type === 'device-key-result') && msg.id && waits.has(msg.id)) {+ waits.get(msg.id)!(msg as Record<string, unknown>)+ return true+ }+ return false+ },+ // A notification of the served workspace: to the phones on the line.+ notify(workspaceId: string, msg: { title?: string; body?: string; conversationId?: string }): void {+ if (link?.running && workspaceId === current()) link.deliver({ notify: { title: String(msg.title ?? ''), body: String(msg.body ?? ''), conversationId: msg.conversationId } })+ },+ // The served workspace's core started again (it crashed, or the app restarted it): the link follows.+ coreStarted(workspaceId: string, c: UtilityProcess): void {+ if (workspaceId === current()) child = c+ },+ // At launch: back on if it was.+ async restore(): Promise<void> {+ if (!saved.on) return+ try {+ await start()+ } catch (e) {+ error = e instanceof Error ? e.message : String(e)+ }+ changed()+ },+ async quit(): Promise<void> {+ await link?.stop()+ }+ }+}diff --git a/src/main/index.ts b/src/main/index.tsindex e08ef29..f3f3c04 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -13,6 +13,7 @@ import { Servers } from './servers'import { bundleOf, moveFromAgentDesk, type Moved } from './migrate'import { Updates } from './updates'import { Workspaces } from './workspaces'+import { homePhone } from './home-phone'import { suggestWorkspaceCopyName, workspaceParts, type Workspace, type WorkspaceList, type WorkspaceSummary } from '../shared/workspaces'import { autostartEntry, autostartFile, onPath } from '../core/platform'@@ -56,6 +57,8 @@ const publishWorkspaces = (): void => { mainWindow?.webContents.send('workspaces// The core (database, engines, runs) lives in its own process so agent work// never blocks the window or the main process.const localKey = randomBytes(32).toString('hex')+// The iPhone on the home Wi-Fi (Settings › Celular › Seu iPhone), once the app is ready.+let phone: ReturnType<typeof homePhone> | undefinedfunction startCore(workspace: Workspace): Runtime {const existing = cores.get(workspace.id)@@ -82,7 +85,9 @@ function startCore(workspace: Workspace): Runtime {publishWorkspaces()child.kill()}, 90_000)+ phone?.coreStarted(workspace.id, child)child.on('message', (msg: CoreRequest) => {+ if (phone?.fromCore(msg as { type?: string; id?: string })) returnif (msg.type === 'ready') {clearTimeout(timer)const theme = registry.theme()@@ -312,6 +317,7 @@ function handleCore(child: UtilityProcess, msg: CoreRequest, workspace: Workspacconst wikiFolder = runtime.wikiFolderif (path.startsWith(join(workspace.dataDir, 'computers') + sep) || path === join(workspace.dataDir, 'backups') || (!!wikiFolder && (path === wikiFolder || path.startsWith(join(wikiFolder, 'fontes', 'arquivos') + sep)))) void shell.openPath(path)} else if (msg.type === 'notify') {+ phone?.notify(workspace.id, msg)// Already looking at that conversation: nothing to tell.if (registry.selected().id === workspace.id && msg.conversationId && msg.conversationId === viewing && mainWindow?.isFocused()) returnconst sound = chirpOf(msg.kind, msg.sound)@@ -450,6 +456,10 @@ function requestWorkspace(runtime: Runtime, request: object, response: 'workspacruntime.child.postMessage(request)})}+// Seu iPhone (home-phone.ts): on or off, and a one-time code for the QR.+ipcMain.handle('home-phone:state', (event) => (fromApp(event) ? phone?.state() : undefined))+ipcMain.handle('home-phone:set', (event, on: unknown) => (fromApp(event) && typeof on === 'boolean' ? phone?.set(on) : undefined))+ipcMain.handle('home-phone:code', (event) => (fromApp(event) ? phone?.code() : undefined))ipcMain.handle('workspaces:list', (event) => { trustedWorkspaceRequest(event); return workspaceList() })ipcMain.handle('workspaces:pause', async (event, paused: unknown, id?: unknown) => {trustedWorkspaceRequest(event)@@ -791,6 +801,20 @@ if (moved === 'old-app-open' || moved === 'keychain-denied') {registry = new Workspaces(dataDir())nativeTheme.themeSource = registry.theme() ?? 'system'startWorkspaces()+ phone = homePhone({+ dir: dataDir(),+ selected: () => registry.selected(),+ workspace: (id) => registry.list().find((w) => w.id === id),+ child: async (id) => {+ const w = registry.list().find((x) => x.id === id)+ if (!w) return undefined+ const r = startCore(w)+ await r.ready+ return r.child+ },+ publish: (state) => mainWindow?.webContents.send('home-phone', state)+ })+ void phone.restore()// The Mac wakes for a few seconds at a time while asleep (maintenance, "DarkWake"):// routines wait for a real wake, so a run doesn't start and freeze mid-way.powerMonitor.on('suspend', () => { for (const r of cores.values()) r.child.postMessage({ type: 'power', awake: false }) })@@ -815,6 +839,7 @@ app.on('window-all-closed', () => {app.on('before-quit', () => {quitting = true+ void phone?.quit()servers.quit()for (const r of cores.values()) r.browsers.quit()})diff --git a/src/main/self-signed.ts b/src/main/self-signed.tsnew file mode 100644index 0000000..3fc5d93--- /dev/null+++ b/src/main/self-signed.ts@@ -0,0 +1,93 @@+// A certificate of this computer's own, for the phone link at home (home-link.ts). No authority+// vouches for it: the QR code carries its fingerprint, and the phone talks to this certificate and+// no other (the iPhone app's Pin), so someone else on the same Wi-Fi can't stand in for the Mac.+//+// Node can make the key but not the certificate, so this writes the little X.509 it needs by hand:+// ECDSA P-256 with SHA-256, the computer's names in subjectAltName, ten years.+import { createHash, createPrivateKey, createPublicKey, generateKeyPairSync, randomBytes, sign, X509Certificate } from 'node:crypto'++// DER: a tag, its length, its content.+function tlv(tag: number, content: Buffer): Buffer {+ const n = content.length+ const len = n < 0x80 ? Buffer.from([n]) : n < 0x100 ? Buffer.from([0x81, n]) : Buffer.from([0x82, n >> 8, n & 0xff])+ return Buffer.concat([Buffer.from([tag]), len, content])+}+const seq = (...parts: Buffer[]): Buffer => tlv(0x30, Buffer.concat(parts))+const set = (...parts: Buffer[]): Buffer => tlv(0x31, Buffer.concat(parts))+const explicit = (n: number, inner: Buffer): Buffer => tlv(0xa0 + n, inner)++function oid(dotted: string): Buffer {+ const [a, b, ...rest] = dotted.split('.').map(Number)+ const bytes = [a! * 40 + b!]+ for (const v of rest) {+ const chunk = [v & 0x7f]+ for (let x = v >> 7; x > 0; x >>= 7) chunk.unshift((x & 0x7f) | 0x80)+ bytes.push(...chunk)+ }+ return tlv(0x06, Buffer.from(bytes))+}++// A positive INTEGER from random bytes (a leading 0 when the top bit is set).+function serial(): Buffer {+ const b = randomBytes(16)+ b[0] = b[0]! & 0x7f || 0x01+ return tlv(0x02, b)+}++// UTCTime (YYMMDDHHMMSSZ) up to 2049, as X.509 asks; GeneralizedTime after.+function time(d: Date): Buffer {+ const p = (n: number): string => String(n).padStart(2, '0')+ const rest = `${p(d.getUTCMonth() + 1)}${p(d.getUTCDate())}${p(d.getUTCHours())}${p(d.getUTCMinutes())}${p(d.getUTCSeconds())}Z`+ const y = d.getUTCFullYear()+ return y < 2050 ? tlv(0x17, Buffer.from(`${String(y % 100).padStart(2, '0')}${rest}`, 'ascii')) : tlv(0x18, Buffer.from(`${y}${rest}`, 'ascii'))+}++const name = (cn: string): Buffer => seq(set(seq(oid('2.5.4.3'), tlv(0x0c, Buffer.from(cn, 'utf8')))))+const ECDSA_SHA256 = seq(oid('1.2.840.10045.4.3.2'))++// subjectAltName: DNS names, and IP addresses (v4) as their four bytes.+function altNames(names: string[]): Buffer {+ const entries = names.map((n) => (/^\d{1,3}(\.\d{1,3}){3}$/.test(n) ? tlv(0x87, Buffer.from(n.split('.').map(Number))) : tlv(0x82, Buffer.from(n, 'ascii'))))+ return seq(oid('2.5.29.17'), tlv(0x04, seq(...entries)))+}++export interface SelfSigned {+ key: string // PEM, PKCS#8+ cert: string // PEM+ fingerprint: string // sha256 of the certificate's DER, base64url: what the QR code's `fp` holds+}++// The fingerprint the phone checks: sha256 of the certificate (DER), base64url, no padding.+export const fingerprintOf = (certPem: string): string => createHash('sha256').update(new X509Certificate(certPem).raw).digest('base64url')++export function makeCertificate(commonName: string, names: string[], now = new Date(), years = 10): SelfSigned {+ const { privateKey, publicKey } = generateKeyPairSync('ec', { namedCurve: 'prime256v1' })+ const spki = publicKey.export({ type: 'spki', format: 'der' })+ const until = new Date(now)+ until.setUTCFullYear(until.getUTCFullYear() + years)+ const from = new Date(now.getTime() - 24 * 3600_000) // a day back: a phone whose clock runs late still takes it+ const tbs = seq(+ explicit(0, tlv(0x02, Buffer.from([2]))), // v3+ serial(),+ ECDSA_SHA256,+ name(commonName),+ seq(time(from), time(until)),+ name(commonName),+ spki,+ explicit(3, seq(altNames(names.length ? names : [commonName])))+ )+ const signature = sign('sha256', tbs, { key: privateKey, dsaEncoding: 'der' })+ const der = seq(tbs, ECDSA_SHA256, tlv(0x03, Buffer.concat([Buffer.from([0]), signature])))+ const cert = `-----BEGIN CERTIFICATE-----\n${der.toString('base64').replace(/(.{64})/g, '$1\n').replace(/\n$/, '')}\n-----END CERTIFICATE-----\n`+ return { key: privateKey.export({ type: 'pkcs8', format: 'pem' }) as string, cert, fingerprint: createHash('sha256').update(der).digest('base64url') }+}++// A saved pair still goes together (the key signs for the certificate's public key).+export function matches(pair: { key: string; cert: string }): boolean {+ try {+ const pub = new X509Certificate(pair.cert).publicKey.export({ type: 'spki', format: 'der' })+ return createPublicKey(createPrivateKey(pair.key)).export({ type: 'spki', format: 'der' }).equals(pub)+ } catch {+ return false+ }+}diff --git a/src/preload/index.ts b/src/preload/index.tsindex 0ae6f97..f9d422b 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -46,6 +46,17 @@ contextBridge.exposeInMainWorld('tucano', {},checkUpdates: (): void => ipcRenderer.send('update:check'),installUpdate: (): void => ipcRenderer.send('update:install'),+ // Seu iPhone: the app on the phone, over the home Wi-Fi (src/main/home-phone.ts).+ phone: {+ state: (): Promise<unknown> => ipcRenderer.invoke('home-phone:state'),+ set: (on: boolean): Promise<unknown> => ipcRenderer.invoke('home-phone:set', on),+ code: (): Promise<unknown> => ipcRenderer.invoke('home-phone:code'),+ onChanged: (cb: (state: unknown) => void): (() => void) => {+ const listener = (_e: unknown, state: unknown): void => cb(state)+ ipcRenderer.on('home-phone', listener)+ return () => ipcRenderer.removeListener('home-phone', listener)+ }+ },// Tucanos on servers, shown in this window over the app (Settings › Servers, the workspace list).servers: {list: (): Promise<unknown> => ipcRenderer.invoke('servers:list'),diff --git a/src/renderer/src/components/HomePhone.tsx b/src/renderer/src/components/HomePhone.tsxnew file mode 100644index 0000000..cb6c82b--- /dev/null+++ b/src/renderer/src/components/HomePhone.tsx@@ -0,0 +1,153 @@+import { useEffect, useState, type ReactNode } from 'react'+import { L } from '../../../shared/lang'+import type { PhoneState } from '../rpc'+import { toast } from '../store'+import { Card } from './Pages'+import { Qr } from './People'+import { Icon } from './ui'++// Seu iPhone (desktop only): the Tucano app on the phone, over the home Wi-Fi, as you+// (src/main/home-phone.ts). Off until turned on; a QR code with a one-time code pairs a phone.+export function HomePhoneCard(): ReactNode {+ const api = window.tucano.phone+ const [state, setState] = useState<PhoneState>()+ const [code, setCode] = useState<{ link: string; expiresAt: number } | null>(null)+ const [now, setNow] = useState(Date.now())+ const [busy, setBusy] = useState(false)+ const [error, setError] = useState('')+ const [paired, setPaired] = useState(false)++ useEffect(() => {+ if (!api) return+ void api.state().then(setState)+ return api.onChanged(setState)+ }, [])+ // A phone came on the line while the code was up: it was used.+ useEffect(() => {+ if (code && (state?.connected ?? 0) > 0) {+ setCode(null)+ setPaired(true)+ }+ }, [state?.connected])+ useEffect(() => {+ if (!code) return+ const tick = setInterval(() => setNow(Date.now()), 1000)+ return () => clearInterval(tick)+ }, [code])++ if (!api) return null+ const fail = (e: unknown): void => setError(e instanceof Error ? e.message.replace(/^Error invoking remote method '[^']+': (Error: )?/, '') : String(e))+ const connect = (): void => {+ setBusy(true)+ setError('')+ setPaired(false)+ api+ .code()+ .then((c) => {+ if (!c) throw new Error(L('Não consegui abrir a conexão.', "I couldn't open the connection."))+ setCode(c)+ setNow(Date.now())+ })+ .catch(fail)+ .finally(() => setBusy(false))+ }+ const turnOff = (): void => {+ setBusy(true)+ setCode(null)+ setPaired(false)+ api+ .set(false)+ .then((s) => s && setState(s))+ .catch(fail)+ .finally(() => setBusy(false))+ }+ const copy = (text: string): void =>+ void navigator.clipboard.writeText(text).then(+ () => toast(L('Copiado', 'Copied')),+ () => toast(L('Não consegui copiar.', "I couldn't copy."))+ )+ const left = code ? Math.max(0, Math.ceil((code.expiresAt - now) / 1000)) : 0+ const on = !!state?.on+ const firewall =+ navigator.platform.startsWith('Win')+ ? L('Se o Windows perguntar se o Tucano pode usar a rede, permita nas redes privadas.', 'If Windows asks whether Tucano may use the network, allow it on private networks.')+ : navigator.platform.startsWith('Linux') || navigator.userAgent.includes('Linux')+ ? L('Se o computador tiver firewall (ufw, firewalld), libere a porta mostrada abaixo na rede de casa.', 'If this computer has a firewall (ufw, firewalld), open the port shown below on the home network.')+ : L('Se o Mac perguntar se o Tucano pode aceitar conexões, clique em Permitir.', 'If the Mac asks whether Tucano may accept connections, click Allow.')++ return (+ <Card+ title={L('Seu iPhone', 'Your iPhone')}+ lead={L(+ 'Use o Tucano no iPhone com tudo daqui: suas conversas, aprovações e as perguntas dos agentes. Funciona no Wi-Fi de casa, com o computador ligado.',+ 'Use Tucano on your iPhone with everything here: your conversations, approvals and the questions agents ask you. It works on your home Wi-Fi, with this computer on.'+ )}+ action={+ !code ? (+ <button className="btn btn--primary btn--sm" disabled={busy} onClick={connect}>+ <Icon name="plus" size={14} /> {on ? L('Conectar outro iPhone', 'Connect another iPhone') : L('Conectar meu iPhone', 'Connect my iPhone')}+ </button>+ ) : undefined+ }+ >+ {code &&+ (left === 0 ? (+ <div className="row">+ <span className="small grow">{L('Esse código passou do prazo.', 'This code has expired.')}</span>+ <button className="btn btn--sm btn--primary" onClick={connect}>+ {L('Gerar outro', 'Make another')}+ </button>+ </div>+ ) : (+ <div className="device-pair">+ <Qr text={code.link} />+ <div className="device-pair__text">+ <ol className="small steps-list">+ <li>{L('Deixe o iPhone no mesmo Wi-Fi que este computador.', 'Put the iPhone on the same Wi-Fi as this computer.')}</li>+ <li>{L('Abra o app do Tucano, toque no ícone de QR code e aponte pra cá.', 'Open the Tucano app, tap the QR code icon and point it here.')}</li>+ <li>{L('Quando o iPhone pedir acesso à rede local, toque em Permitir.', 'When the iPhone asks for local network access, tap Allow.')}</li>+ </ol>+ <p className="muted small">+ {L('Vale uma vez, por mais', 'Good once, for')} {Math.floor(left / 60)}:{String(left % 60).padStart(2, '0')}. {firewall}+ </p>+ <div className="device-pair__actions">+ <button className="btn btn--sm btn--ghost" onClick={() => copy(code.link)}>+ <Icon name="copy" size={13} /> {L('Copiar link', 'Copy link')}+ </button>+ <button className="btn btn--sm btn--ghost" onClick={() => setCode(null)}>+ {L('Cancelar', 'Cancel')}+ </button>+ </div>+ </div>+ </div>+ ))}+ {paired && <p className="small">{L('Pronto: o iPhone está conectado.', 'Done: the iPhone is connected.')}</p>}+ {on && !code && (+ <div className="row">+ <span className="small grow muted">+ {state!.connected > 0+ ? state!.connected === 1+ ? L('1 iPhone conectado agora', '1 iPhone connected now')+ : L(`${state!.connected} iPhones conectados agora`, `${state!.connected} iPhones connected now`)+ : L('Ligado. Nenhum iPhone conectado agora.', 'On. No iPhone connected right now.')}{' '}+ · <span className="mono">{state!.address}</span>+ {state!.workspace ? ` · ${state!.workspace}` : ''}+ </span>+ <button className="btn btn--sm btn--ghost" disabled={busy} onClick={turnOff}>+ {L('Desligar', 'Turn off')}+ </button>+ </div>+ )}+ {on && (+ <p className="muted small">+ {L('Fora de casa, o iPhone não alcança este computador. Pra levar o time junto, use o Tucano Pro.', "Away from home, the iPhone can't reach this computer. To take your team along, use Tucano Pro.")}+ </p>+ )}+ {(error || state?.error) && (+ <p className="field__error" role="alert">+ {error || state?.error}+ </p>+ )}+ </Card>+ )+}diff --git a/src/renderer/src/components/Pages.tsx b/src/renderer/src/components/Pages.tsxindex 39def34..28c076c 100644--- a/src/renderer/src/components/Pages.tsx+++ b/src/renderer/src/components/Pages.tsx@@ -86,6 +86,7 @@ import { AgentAvatar, AVATARS, Icon, NumberInput, SleepingToucan, time, tokens,import { Select } from './Select'import { UpdateSettings } from './Update'import { hasServers, ServersCard } from './Servers'+import { HomePhoneCard } from './HomePhone'import { useWorkspaceList } from './Workspaces'import { workspaceLabel } from '../../../shared/workspaces'import exportSkill from '../assets/tucano-export-skill.md?raw'@@ -2379,6 +2380,7 @@ export function SettingsPage(): ReactNode {)}{pane('integracoes') && work && <OutsideGateway what={L('as aprovações, as perguntas dos agentes e o fim das rotinas vão pro seu Telegram, com o texto de cada uma.', 'approvals, the agents’ questions and routine results go to your Telegram, with the text of each.')} />}+ {pane('integracoes') && window.tucano.phone && <HomePhoneCard />}{pane('integracoes') && (defaultWorkspace ? <PhoneCard info={settings.telegram} /> : <WorkspaceTelegramNotice />)}{pane('modelos') && (diff --git a/src/renderer/src/components/People.tsx b/src/renderer/src/components/People.tsxindex 0160086..6fa0d84 100644--- a/src/renderer/src/components/People.tsx+++ b/src/renderer/src/components/People.tsx@@ -336,7 +336,7 @@ function InviteCard({ onClose, owner }: { onClose: () => void; owner: boolean })type PairCode = { code: string; link: string; browser: string; expiresAt: number }// The link as a QR code, drawn here: nothing about it leaves the page.-function Qr({ text }: { text: string }): ReactNode {+export function Qr({ text }: { text: string }): ReactNode {const q = qrcode(0, 'M')q.addData(text)q.make()diff --git a/src/renderer/src/rpc.ts b/src/renderer/src/rpc.tsindex 1b1c81f..d3e9385 100644--- a/src/renderer/src/rpc.ts+++ b/src/renderer/src/rpc.ts@@ -3,6 +3,9 @@ import type { CoreEvent, Method, Params, Request, Result, Wire } from '../../shaimport type { UpdateState } from '../../shared/types'import type { WorkspaceList, WorkspaceParts } from '../../shared/workspaces'+// Seu iPhone: on, where the phone finds this computer, and how many are on the line now.+export type PhoneState = { on: boolean; address: string; connected: number; workspace: string; error?: string }+declare global {interface Window {tucano: {@@ -27,6 +30,13 @@ declare global {onUpdate: (cb: (state: UpdateState) => void) => voidcheckUpdates: () => voidinstallUpdate: () => void+ phone?: {+ // desktop only: the iPhone app over the home Wi-Fi (src/main/home-phone.ts)+ state: () => Promise<PhoneState | undefined>+ set: (on: boolean) => Promise<PhoneState | undefined>+ code: () => Promise<{ link: string; expiresAt: number } | undefined>+ onChanged: (cb: (state: PhoneState) => void) => () => void+ }servers?: {// desktop only: Tucanos on servers, shown in this window over the app; open: the one on screenlist: () => Promise<{ id: string; name: string; origin: string; open: boolean }[]>diff --git a/src/shared/servers.ts b/src/shared/servers.tsindex 1c316dd..0bd3db1 100644--- a/src/shared/servers.ts+++ b/src/shared/servers.ts@@ -35,8 +35,10 @@ export function parsePairing(link: string): Pairing | null {// The link that pairs it: with the server's token (`server.js link`), or with a one-time code// (`server.js pair`, Settings › Pessoas › Conectar um celular) that the phone trades for a key of its own.-export const pairingLink = (p: { origin: string } & ({ token: string } | { code: string })): string =>- `tucano://connect?url=${encodeURIComponent(p.origin)}&${'code' in p ? `code=${encodeURIComponent(p.code)}` : `token=${encodeURIComponent(p.token)}`}`+// A computer at home (src/main/home-link.ts) adds its certificate's fingerprint (`fp`): the phone+// talks to that certificate and no other.+export const pairingLink = (p: { origin: string; fp?: string } & ({ token: string } | { code: string })): string =>+ `tucano://connect?url=${encodeURIComponent(p.origin)}&${'code' in p ? `code=${encodeURIComponent(p.code)}` : `token=${encodeURIComponent(p.token)}`}${p.fp ? `&fp=${encodeURIComponent(p.fp)}` : ''}`// Where a server's window may go: its own pages, and nothing else.export function onServer(url: string, origin: string): boolean {diff --git a/test/home-link.test.ts b/test/home-link.test.tsnew file mode 100644index 0000000..f722db7--- /dev/null+++ b/test/home-link.test.ts@@ -0,0 +1,171 @@+import { createHash, X509Certificate } from 'node:crypto'+import { mkdtempSync, readFileSync, rmSync } from 'node:fs'+import { request } from 'node:https'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import type { TLSSocket } from 'node:tls'+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { HomeLink, isLocalAddress, type HomeCore } from '../src/main/home-link'+import { fingerprintOf, makeCertificate, matches } from '../src/main/self-signed'+import type { Person } from '../src/shared/types'++describe('self-signed certificate', () => {+ it('is a valid X.509 signed by its own key, with the fingerprint the QR carries', () => {+ const c = makeCertificate('Tucano', ['eduardos-mac.local', '192.168.1.20'], new Date('2026-11-07T12:00:00Z'))+ const x = new X509Certificate(c.cert)+ expect(x.verify(x.publicKey)).toBe(true)+ expect(x.subject).toContain('CN=Tucano')+ expect(x.subjectAltName).toContain('DNS:eduardos-mac.local')+ expect(x.subjectAltName).toContain('IP Address:192.168.1.20')+ expect(new Date(x.validTo).getUTCFullYear()).toBe(2036)+ expect(c.fingerprint).toMatch(/^[A-Za-z0-9_-]{43}$/) // what the iPhone app's Pairing.parse takes+ expect(fingerprintOf(c.cert)).toBe(c.fingerprint)+ expect(matches(c)).toBe(true)+ expect(matches({ key: makeCertificate('x', []).key, cert: c.cert })).toBe(false)+ })+})++describe('isLocalAddress', () => {+ it('answers a home network, loopback and link-local, never the internet', () => {+ for (const ip of ['192.168.0.12', '::ffff:10.0.0.4', '172.20.1.1', '100.101.102.103', '127.0.0.1', '::1', 'fe80::1c2:3', 'fd7a:115c::1', '169.254.3.4']) expect(isLocalAddress(ip)).toBe(true)+ for (const ip of ['8.8.8.8', '::ffff:1.1.1.1', '2001:db8::1', '172.32.0.1', undefined]) expect(isLocalAddress(ip)).toBe(false)+ })+})++const OWNER: Person = { id: 'owner-1', name: 'Eduardo', role: 'owner' } as Person++function fakeCore(dir: string): HomeCore & { keys: string[]; posted: unknown[]; say: (m: unknown) => void } {+ const keys: string[] = []+ const posted: unknown[] = []+ let listener: ((m: unknown) => void) | undefined+ return {+ keys,+ posted,+ say: (m) => listener?.(m),+ auth: async (key) => (keys.includes(key) ? OWNER : undefined),+ deviceKey: async () => {+ const k = `p_${'k'.repeat(42)}${keys.length}`+ keys.push(k)+ return k+ },+ open: (_person, onMessage) => {+ listener = onMessage+ return { post: (d) => posted.push(d), close: () => (listener = undefined) }+ },+ dataDir: () => dir+ }+}++type Reply = { status: number; body: string; fp: string }+function call(port: number, path: string, o: { method?: string; body?: string; cookie?: string } = {}): Promise<Reply> {+ return new Promise((resolve, reject) => {+ const req = request({ host: '127.0.0.1', port, path, method: o.method ?? 'GET', rejectUnauthorized: false, agent: false, headers: { ...(o.cookie ? { cookie: `tucano=${o.cookie}` } : {}), 'content-type': 'application/json' } }, (res) => {+ const fp = createHash('sha256').update((res.socket as TLSSocket).getPeerCertificate().raw).digest('base64url')+ let text = ''+ res.on('data', (c) => (text += c))+ res.on('end', () => resolve({ status: res.statusCode ?? 0, body: text, fp }))+ })+ req.on('error', reject)+ req.end(o.body)+ })+}++// The first lines of an event stream, then it hangs up.+function listen(port: number, key: string, until: (text: string) => boolean): Promise<string> {+ return new Promise((resolve, reject) => {+ const req = request({ host: '127.0.0.1', port, path: '/events', rejectUnauthorized: false, headers: { cookie: `tucano=${key}` } }, (res) => {+ let text = ''+ res.on('data', (c) => {+ text += c+ if (until(text)) (req.destroy(), resolve(text))+ })+ })+ req.on('error', (e) => (e.message.includes('socket hang up') ? undefined : reject(e)))+ req.end()+ })+}++describe('HomeLink', () => {+ let dir: string+ let link: HomeLink+ let core: ReturnType<typeof fakeCore>+ const tls = makeCertificate('Tucano', ['localhost'])++ beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), 'home-link-'))+ core = fakeCore(dir)+ link = new HomeLink({ tls, codesFile: join(dir, 'codes.json'), core: () => core, sentDir: join(dir, 'Enviados') })+ })+ afterEach(async () => {+ await link.stop()+ rmSync(dir, { recursive: true, force: true })+ })++ it('pairs the phone once with a code, over the pinned certificate', async () => {+ const port = await link.start(47350, '127.0.0.1')+ const { link: qr } = link.makeCode()+ const u = new URL(qr)+ expect(u.protocol).toBe('tucano:')+ expect(u.searchParams.get('url')).toBe(`https://127.0.0.1:${port}`)+ expect(u.searchParams.get('fp')).toBe(tls.fingerprint)+ const code = u.searchParams.get('code')!+ const first = await call(port, '/pair', { method: 'POST', body: JSON.stringify({ code, name: 'iPhone', platform: 'ios' }) })+ expect(first.status).toBe(200)+ expect(first.fp).toBe(tls.fingerprint)+ expect(JSON.parse(first.body).key).toBe(core.keys[0])+ const again = await call(port, '/pair', { method: 'POST', body: JSON.stringify({ code, name: 'iPhone', platform: 'ios' }) })+ expect(again.status).toBe(410)+ })++ it('opens the core to a paired phone only: events down, requests up', async () => {+ const port = await link.start(47360, '127.0.0.1')+ expect((await call(port, '/events')).status).toBe(401)+ expect((await call(port, '/events', { cookie: `p_${'x'.repeat(43)}` })).status).toBe(401)+ const key = await core.deviceKey('iPhone')+ const stream = listen(port, key!, (t) => t.includes('"hi"'))+ await new Promise((r) => setTimeout(r, 100))+ expect(link.connected).toBe(1)+ core.say({ hi: true })+ const text = await stream+ const client = /event: hello\ndata: (\S+)/.exec(text)?.[1]+ expect(client).toBeTruthy()+ expect(text).toContain('data: {"hi":true}')+ })++ it('takes requests on the stream it opened, and nobody else’s', async () => {+ const port = await link.start(47370, '127.0.0.1')+ const key = (await core.deviceKey('iPhone'))!+ let client = ''+ const stream = listen(port, key, (t) => !!(client = /event: hello\ndata: (\S+)/.exec(t)?.[1] ?? ''))+ await stream+ // The stream it named is gone once it hung up: a request on it is refused.+ await new Promise((r) => setTimeout(r, 50))+ expect((await call(port, `/rpc?c=${client}`, { method: 'POST', body: '{"id":1}', cookie: key })).status).toBe(410)+ })++ it('saves a file sent for a message in Enviados, under a name of its own', async () => {+ const port = await link.start(47380, '127.0.0.1')+ const key = (await core.deviceKey('iPhone'))!+ const one = await call(port, '/upload?name=nota.txt&for=message', { method: 'POST', body: 'oi', cookie: key })+ const two = await call(port, '/upload?name=nota.txt&for=message', { method: 'POST', body: 'de novo', cookie: key })+ expect(readFileSync(JSON.parse(one.body).path, 'utf8')).toBe('oi')+ expect(JSON.parse(two.body).path).toMatch(/nota \(2\)\.txt$/)+ expect((await call(port, '/upload?name=x.zip', { method: 'POST', body: 'x', cookie: key })).status).toBe(403)+ })+})++describe('lanAddress', () => {+ it('picks the Wi-Fi or the cable over the virtual networks Windows and Linux add', async () => {+ const { lanAddress } = await import('../src/main/home-phone-net')+ const nets = {+ 'vEthernet (WSL)': [{ family: 'IPv4', address: '172.28.48.1', internal: false }],+ 'VirtualBox Host-Only Network': [{ family: 'IPv4', address: '192.168.56.1', internal: false }],+ docker0: [{ family: 'IPv4', address: '172.17.0.1', internal: false }],+ 'Wi-Fi': [{ family: 'IPv6', address: 'fe80::1', internal: false }, { family: 'IPv4', address: '192.168.0.12', internal: false }],+ lo: [{ family: 'IPv4', address: '127.0.0.1', internal: true }]+ }+ expect(lanAddress(nets)).toBe('192.168.0.12')+ expect(lanAddress({ eth0: [{ family: 4, address: '10.0.0.7', internal: false }], wlan0: [{ family: 'IPv4', address: '172.20.10.2', internal: false }] })).toBe('10.0.0.7')+ expect(lanAddress({ eth0: [{ family: 'IPv4', address: '8.8.8.8', internal: false }] })).toBeUndefined()+ })+})