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
Spend a pairing link only on a click, and let people disconnect their devices (#192)
Eduardo Machadoeb19590098b7
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3948a03..d6ef3fb 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,6 +12,11 @@ What changed in each version of Tucano. The format follows [Keep a Changelog](ht- **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.+### Fixed++- **A server's one-time link signs in the browser that opens it, not whatever opened it first.** Opening the link from **Settings › People › Connect a phone** (or `server.js pair`) spent the code at once. A chat's link preview (Discord, WhatsApp, iMessage, Slack), a browser's prefetch or prerender of a pasted address, or a mail scanner got there first: each became a device no one holds, the person's own visit read "this link was already used or has expired", and "You're signed in on N devices" went up by one every time. Now the link opens a page that says whose Tucano it is and as whom, with a **Sign in on this browser** button; only that button (a POST from the same page) spends the code, once. A prefetch gets nothing, and a wrong or used code still counts as a guess, as before. The phone's QR code and link, the desktop app's pairing and invites (`/?invite=`, which never spent anything on opening) work as they did.+- **Your devices can be seen and disconnected.** Under "You're signed in on N devices", **Settings › People** lists each browser and phone signed in as you, when it was added, when it was last seen (or "never used", like the ones a link preview made), and a **Disconnect** button. Disconnecting signs that device out at once and closes its open pages; the others stay. The one you're using is marked, and asks before going. On the desktop app, **Settings › Phone › Your iPhone** lists the iPhones paired over the home Wi-Fi the same way, and **Disconnect** cuts that phone off right away, open connection included.+## [0.2.17] - 2026-11-07> **Em português:**diff --git a/src/core/db.ts b/src/core/db.tsindex e920206..2fa910b 100644--- a/src/core/db.ts+++ b/src/core/db.ts@@ -1713,6 +1713,26 @@ export class Db {this.db.prepare('INSERT INTO person_keys (hash, person_id, label, created_at) VALUES (?, ?, ?, ?)').run(hash, personId, label ?? null, Date.now())}+ // A person's own keys, newest first: what each device said it is, and when it was last seen.+ personKeys(personId: string): { hash: string; label: string; createdAt: number; seenAt?: number }[] {+ return (this.db.prepare('SELECT hash, label, created_at, last_seen FROM person_keys WHERE person_id = ? ORDER BY created_at DESC').all(personId) as Row[]).map((r) => ({+ hash: str(r['hash']),+ label: str(r['label']),+ createdAt: Number(r['created_at']),+ ...(r['last_seen'] ? { seenAt: Number(r['last_seen']) } : {})+ }))+ }++ // 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(() => {+ if (!this.db.prepare('SELECT 1 FROM person_keys WHERE hash = ? AND person_id = ?').get(hash, personId)) return false+ this.db.prepare('INSERT OR IGNORE INTO removed_keys (hash, person_id, removed_at) SELECT hash, person_id, ? FROM person_keys WHERE hash = ?').run(Date.now(), hash)+ this.db.prepare('DELETE FROM person_keys WHERE hash = ?').run(hash)+ return true+ })+ }+// The person a key opens, if they still have access; seen now.removedKey(hash: string): boolean {return !!this.db.prepare('SELECT 1 FROM removed_keys WHERE hash = ?').get(hash)diff --git a/src/core/index.ts b/src/core/index.tsindex 5e0351b..2b1ca94 100644--- a/src/core/index.ts+++ b/src/core/index.ts@@ -271,7 +271,7 @@ const hub = new Hub<MessagePortMain>(people, db)// The conversation each person has open: what arrives there is read already.const viewing = new Map<string, string | null>()let closing = false-type Ctx = { person: Person }+type Ctx = { person: Person; device?: string } // device: the hash of the key a server's page signed in withconst ownerCtx = (): Ctx => ({ person: db.owner() })// What the workspace switcher shows of this workspace: its name, whether it's paused, and two// counts. Coalesced: a reply streaming updates its message many times a second.@@ -1817,6 +1817,15 @@ const api: Handlers = {revokeInvite: ({ id }, ctx) => people.revokeInvite(ctx.person, id),listInvites: () => db.invites(),removedPeople: () => db.removedPeople(),+ 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.+ 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 })+ emitPeople()+ setTimeout(() => hub.closeDevice(id), 200)+ },// Access ends now: keys, open connections, the server's remembered sign-ins. Their agents and// routines go to the owner; their DMs and memories wait 30 days for a re-invite (the daily sweep).removePerson: ({ id }, ctx) => {@@ -1978,7 +1987,7 @@ function handle(port: MessagePortMain, req: Request): void {const wrong = paramsError(req.method as Method, req.params) ?? limitError(req.method as Method, req.params)if (wrong) return reply({ error: wrong })Promise.resolve()- .then(() => (admit(person, req.method as Method), fn(req.params ?? {}, { person })))+ .then(() => (admit(person, req.method as Method), fn(req.params ?? {}, { person, device: hub.deviceOf(port) }))).then((result) => reply({ result }),(e: unknown) => {diff --git a/src/core/people.ts b/src/core/people.tsindex bc62c6a..6ea0fa2 100644--- a/src/core/people.ts+++ b/src/core/people.ts@@ -735,6 +735,7 @@ export interface PortLike {export class Hub<P extends PortLike> {private ports = new Map<P, string>() // port → person id+ private devices = new Map<P, string>() // port → the hash of the key it signed in with (a server's browser)constructor(private people: People, private db: Db) {}@@ -746,11 +747,27 @@ export class Hub<P extends PortLike> {return undefined}this.ports.set(port, person.id)+ const device = (data as { device?: unknown } | null | undefined)?.device+ if (typeof device === 'string') this.devices.set(port, device)return person}delete(port: P): void {this.ports.delete(port)+ this.devices.delete(port)+ }++ deviceOf(port: P): string | undefined {+ return this.devices.get(port)+ }++ // A device disconnected: the connections it opened end at once.+ closeDevice(hash: string): void {+ for (const [port, h] of [...this.devices]) {+ if (h !== hash) continue+ this.delete(port)+ port.close()+ }}personOf(port: P): Person | undefined {@@ -772,7 +789,7 @@ export class Hub<P extends PortLike> {closeFor(personId: string): void {for (const [port, id] of [...this.ports]) {if (id !== personId) continue- this.ports.delete(port)+ this.delete(port)port.close()}}diff --git a/src/core/policy-people.ts b/src/core/policy-people.tsindex 636ee10..b425dbe 100644--- a/src/core/policy-people.ts+++ b/src/core/policy-people.ts@@ -227,6 +227,8 @@ export const NEEDS: Record<Method, Need> = {revokeInvite: 'admin',listInvites: 'admin',removedPeople: 'admin',+ myDevices: 'anyone', // one's own+ removeDevice: 'anyone', // one's own (the core looks only among theirs)removePerson: 'target',setRole: 'target',activity: 'admin',diff --git a/src/main/home-link.ts b/src/main/home-link.tsindex 6391c54..a132fd0 100644--- a/src/main/home-link.ts+++ b/src/main/home-link.ts@@ -7,7 +7,7 @@// 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 { createHash, 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'@@ -24,8 +24,10 @@ export interface HomeCore {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 }+ // A port to the core as this person: what the core says comes to onMessage. `device`: the hash of+ // the key the phone signed in with, so the core can end this line when that device is disconnected+ // (Settings › Celular › Seu iPhone); then onClose.+ open(person: string, onMessage: (msg: unknown) => void, o?: { device?: string; onClose?: () => void }): { post(data: unknown): void; close(): void }// Where the workspace keeps what agents showed (artifacts/<id>/<name>).dataDir(): string}@@ -129,7 +131,7 @@ export class HomeLink {// 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`)+ for (const s of this.streams.values()) if (!s.res.writableEnded) s.res.write(`data: ${JSON.stringify(msg)}\n\n`)}private handle(req: IncomingMessage, res: ServerResponse): void {@@ -147,7 +149,7 @@ export class HomeLink {(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)+ this.signedIn(req, res, url, who, core, key)},() => !res.headersSent && res.writeHead(503, BASE_HEADERS).end())@@ -181,15 +183,24 @@ export class HomeLink {this.o.onChange?.()}- private signedIn(req: IncomingMessage, res: ServerResponse, url: URL, who: Person, core: HomeCore): void {+ private signedIn(req: IncomingMessage, res: ServerResponse, url: URL, who: Person, core: HomeCore, key: string): 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`))+ // Disconnected from the computer (the core closed the port): the phone loses the line now,+ // and its next request finds its key gone.+ const device = createHash('sha256').update(key).digest('base64url')+ const port = core.open(who.id, (msg) => void (!res.writableEnded && res.write(`data: ${JSON.stringify(msg)}\n\n`)), {+ device,+ onClose: () => {+ if (this.streams.delete(id)) this.o.onChange?.()+ if (!res.writableEnded) res.end()+ }+ })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)+ const beat = setInterval(() => !res.writableEnded && res.write('event: ping\ndata: \n\n'), 25_000)req.on('close', () => {clearInterval(beat)this.streams.delete(id)diff --git a/src/main/home-phone.ts b/src/main/home-phone.tsindex 95c1aeb..69a2686 100644--- a/src/main/home-phone.ts+++ b/src/main/home-phone.ts@@ -71,11 +71,13 @@ export function homePhone(deps: {const r = await ask({ type: 'device-key', person: null, label })return (r?.['data'] as { key?: string } | undefined)?.key},- open: (person, onMessage) => {+ open: (person, onMessage, o) => {const { port1, port2 } = new MessageChannelMain()port2.on('message', (e) => onMessage(e.data))+ // The core closed it: the device was disconnected (hub.closeDevice).+ port2.on('close', () => o?.onClose?.())port2.start()- child?.postMessage({ person }, [port1])+ child?.postMessage({ person, ...(o?.device ? { device: o.device } : {}) }, [port1])return { post: (data) => port2.postMessage(data), close: () => port2.close() }},dataDir: () => deps.workspace(current())?.dataDir ?? deps.selected().dataDirdiff --git a/src/renderer/src/components/HomePhone.tsx b/src/renderer/src/components/HomePhone.tsxindex cb6c82b..82dca88 100644--- a/src/renderer/src/components/HomePhone.tsx+++ b/src/renderer/src/components/HomePhone.tsx@@ -1,9 +1,9 @@import { useEffect, useState, type ReactNode } from 'react'import { L } from '../../../shared/lang'import type { PhoneState } from '../rpc'-import { toast } from '../store'+import { toast, useStore, youPerson } from '../store'import { Card } from './Pages'-import { Qr } from './People'+import { MyDevices, Qr } from './People'import { Icon } from './ui'// Seu iPhone (desktop only): the Tucano app on the phone, over the home Wi-Fi, as you@@ -16,6 +16,8 @@ export function HomePhoneCard(): ReactNode {const [busy, setBusy] = useState(false)const [error, setError] = useState('')const [paired, setPaired] = useState(false)+ // The phones paired with this computer: each one a key of the owner's (people.deviceKey).+ const devices = useStore(youPerson)?.devices ?? 0useEffect(() => {if (!api) return@@ -138,6 +140,13 @@ export function HomePhoneCard(): ReactNode {</button></div>)}+ {!code && devices > 0 && (+ <MyDevices+ count={devices}+ refresh={state?.connected}+ lead={L(`Pareados com este computador: ${devices} aparelho${devices > 1 ? 's' : ''}. Desconectar tira o acesso na hora.`, `Paired with this computer: ${devices} device${devices > 1 ? 's' : ''}. Disconnecting takes the access away at once.`)}+ />+ )}{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.")}diff --git a/src/renderer/src/components/People.tsx b/src/renderer/src/components/People.tsxindex 6fa0d84..48c61ab 100644--- a/src/renderer/src/components/People.tsx+++ b/src/renderer/src/components/People.tsx@@ -12,10 +12,12 @@ import {initials,inviteLink,listInvites,+ myDevices,loadActivity,personById,purgePerson,removedPeople,+ removeDevice,removePerson,revokeInvite,roleLabel,@@ -27,6 +29,7 @@ import {windowless,youPerson,type ActivityEntry,+ type Device,type Invite,type Person,type State@@ -420,12 +423,57 @@ function PhoneCard(): ReactNode {</div></div>))}- {!code && devices > 0 && <p className="muted small">{L(`Você está conectado em ${devices} aparelho${devices > 1 ? 's' : ''}.`, `You're signed in on ${devices} device${devices > 1 ? 's' : ''}.`)}</p>}+ {!code && devices > 0 && <MyDevices count={devices} />}{error && <p className="note note--error">{error}</p>}</Card>)}+// The browsers and phones signed in as me, each one disconnectable: on a server, under Conectar um+// celular; on a desktop, the iPhones paired over the home Wi-Fi, under Seu iPhone (HomePhone.tsx).+// One that never signed in was made by something that opened a pairing link before its person did+// (a chat's preview, say). `lead`: the line above the list; `refresh`: fetch again when it changes.+export function MyDevices({ count, lead, refresh }: { count: number; lead?: string; refresh?: unknown }): ReactNode {+ const [list, setList] = useState<Device[]>([])+ const reload = (): void => void myDevices().then(setList, () => {})+ useEffect(reload, [count, refresh])+ const disconnect = (d: Device): void => {+ const go = (): void => void removeDevice(d.id).then(reload, (e: unknown) => toast(message(e)))+ if (!d.current) return go()+ void confirmDialog({+ title: L('Desconectar este navegador?', 'Disconnect this browser?'),+ body: L('Ele sai da sua conta agora. Pra voltar, gere um código em outro aparelho conectado ou peça um novo convite.', "It signs out of your account now. To come back, make a code on another connected device or ask for a new invite."),+ confirm: L('Desconectar', 'Disconnect'),+ danger: true+ }).then((ok) => ok && go())+ }+ return (+ <>+ <p className="muted small">{lead ?? L(`Você está conectado em ${count} aparelho${count > 1 ? 's' : ''}.`, `You're signed in on ${count} device${count > 1 ? 's' : ''}.`)}</p>+ {list.length > 0 && (+ <div className="table">+ {list.map((d) => (+ <div key={d.id} className="table__row">+ <div className="grow person-row__who">+ <span>+ <strong>{d.label === 'convite' ? L('Navegador do convite', 'Browser from the invite') : d.label}</strong>+ {d.current && <span className="muted"> {L('(este)', '(this one)')}</span>}+ </span>+ <span className="muted small">+ {[L(`adicionado ${ago(d.createdAt)}`, `added ${ago(d.createdAt)}`), d.seenAt ? L(`visto ${ago(d.seenAt)}`, `seen ${ago(d.seenAt)}`) : L('nunca usado', 'never used')].join(' · ')}+ </span>+ </div>+ <button className="btn btn--ghost btn--sm" onClick={() => disconnect(d)}>+ {L('Desconectar', 'Disconnect')}+ </button>+ </div>+ ))}+ </div>+ )}+ </>+ )+}+// My own: the name the agents call me, what I do, and who covers for me while I'm away.function MeCard(): ReactNode {const me = useStore(youPerson)diff --git a/src/renderer/src/store.ts b/src/renderer/src/store.tsindex 02bc1c7..4b4063b 100644--- a/src/renderer/src/store.ts+++ b/src/renderer/src/store.ts@@ -32,6 +32,7 @@ import {type Model,type Person,type Inbox,+ type Device,type Invite,type ActivityEntry,delegating,@@ -971,6 +972,8 @@ export const revokeInvite = (id: string): Promise<void> => call('revokeInvite',export const listInvites = (): Promise<Invite[]> => call('listInvites')export const removedPeople = (): Promise<(Person & { removedAt: number })[]> => call('removedPeople')export const removePerson = (id: string): Promise<void> => call('removePerson', { id })+export const myDevices = (): Promise<Device[]> => call('myDevices')+export const removeDevice = (id: string): Promise<void> => call('removeDevice', { id })export const setRole = (id: string, role: 'admin' | 'member'): Promise<void> => call('setRole', { id, role })export const purgePerson = (id: string): Promise<void> => call('purgePerson', { id })export const loadActivity = (f: { personId?: string; kind?: string; before?: number }): Promise<ActivityEntry[]> => call('activity', f)diff --git a/src/server/guard.ts b/src/server/guard.tsindex 069706d..27428e1 100644--- a/src/server/guard.ts+++ b/src/server/guard.ts@@ -134,3 +134,18 @@ export function decodedPath(raw: string): string | undefined {return undefined}}++// A request's body, up to `max` bytes (past it: an error).+export 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)+ })+}diff --git a/src/server/index.ts b/src/server/index.tsindex 513e90b..145a1dc 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -8,7 +8,7 @@// node out/main/server.js (TUCANO_DATA, TUCANO_HOST, TUCANO_PORT, TUCANO_TOKEN, TUCANO_URL, TUCANO_TRUST_PROXY)// node out/main/server.js link prints the link that signs a browser in// node out/main/server.js pair [minutes] a one-time link for the owner's phone (or a browser)-import { randomBytes, randomUUID, timingSafeEqual } from 'node:crypto'+import { createHash, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto'import { EventEmitter } from 'node:events'import { chmodSync, createReadStream, createWriteStream, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'@@ -17,14 +17,15 @@ import { homedir } from 'node:os'import { basename, dirname, extname, isAbsolute, join, normalize, resolve, sep } from 'node:path'import { pathToFileURL } from 'node:url'import { Forwarder, isPrivate } from './forward'-import { ARTIFACT_CSP, BASE_HEADERS, clientIp, decodedPath, Doors, doorOf, PAGE_HEADERS, sameOrigin, signIn } from './guard'-import { browserName, CODE_SHAPE, codeMinutes, deviceLabel, PairCodes } from './pair-codes'+import { ARTIFACT_CSP, BASE_HEADERS, body, clientIp, decodedPath, Doors, doorOf, PAGE_HEADERS, PERSON_KEY, sameOrigin, signIn } from './guard'+import { codeMinutes, PairCodes } from './pair-codes'+import { htmlPage, pairLinkPage, pairPost, type PairDoor } from './pair-http'import { Preview } from './preview'import { vault } from './vault'import { verifyLocal } from '../core/local-paths'import { pairingLink } from '../shared/servers'import { ACCESS_SHIM, INSECURE_CONTEXT_SHIM } from './web-shim'-import { Grants, invitePage, joinFields, NO_ACCESS_PAGE, PAGE_CSP, personNotice, Signins, Streams, UNAUTHORIZED_TEXT, Viewers, type Stream, type Who } from './people'+import { Grants, invitePage, joinFields, NO_ACCESS_PAGE, personNotice, Signins, Streams, UNAUTHORIZED_TEXT, Viewers, type Stream, type Who } from './people'import type { Person } from '../shared/types'const dataDir = process.env['TUCANO_DATA'] || join(homedir(), '.tucano-server')@@ -215,7 +216,11 @@ const watcher = new Port((msg) => {} else if (m.event?.type === 'computer' && m.event.computer) sawComputers([m.event.computer])else if (m.event?.type === 'people') sawPeople(m.event.people ?? [])})+// Everyone's name by id: whom a pairing link's page says the browser signs in as.+const names = new Map<string, string>()function sawPeople(list: Person[]): void {+ names.clear()+ for (const p of list) names.set(p.id, p.name)const owner = list.find((p) => p.role === 'owner')if (owner) [ownerId, ownerName] = [owner.id, owner.name]}@@ -228,19 +233,6 @@ function index(): string {.replace('<title>', '<meta name="viewport" content="width=device-width, initial-scale=1" />\n <script src="./tucano-web.js"></script>\n <title>')}-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)- })-}function oauthCallback(url: URL, res: ServerResponse): void {const id = randomUUID()@@ -259,6 +251,14 @@ function oauthCallback(url: URL, res: ServerResponse): void {const trustProxy = process.env['TUCANO_TRUST_PROXY'] === '1'const MAX_UPLOAD = 1024 * 1024 * 1024 // a vault with its pictures, zippedconst doors = new Doors()+// A one-time code's door (pair-http.ts): a spent code's person gets a key of this device's own, from the core.+const pairDoor: PairDoor = {+ codes: pairCodes,+ doors,+ mint: async (person, label) => (await ask<{ key?: string }>({ type: 'device-key', person, label }))?.key,+ owner: () => ownerName,+ nameOf: (person) => names.get(person ?? ownerId ?? '')+}// A request it can't read (a scanner's, a broken client's) gets an answer, never the whole server.const server = createServer((req, res) => {@@ -280,11 +280,12 @@ function handle(req: IncomingMessage, res: ServerResponse): void {// signed in (the desktop app sends it to the system's). What makes it count is the state, made// by the core for that one request and good once.if (url.pathname === '/oauth/callback') return oauthCallback(url, res)- // A one-time code (pair-codes.ts), traded for a key of the device's own: the phone posts it here;- // a browser opens /?code=. No sign-in: the code is what counts, and a wrong one counts as a guess.- if (url.pathname === '/pair' && req.method === 'POST') return void pairDevice(req, res, ip)+ // A one-time code (pair-codes.ts), traded for a key of the device's own: the phone posts it here,+ // and so does the page a browser's /?code= opens (opening it spends nothing: see pair-http.ts).+ // No sign-in: the code is what counts, and a wrong one counts as a guess.+ if (url.pathname === '/pair' && req.method === 'POST') return void pairPost(pairDoor, req, res, ip)const offeredCode = url.searchParams.get('code')- if (offeredCode !== null && req.method === 'GET' && (url.pathname === '/' || url.pathname === '/index.html')) return void pairBrowser(req, res, ip, offeredCode)+ if (offeredCode !== null && req.method === 'GET' && (url.pathname === '/' || url.pathname === '/index.html')) return pairLinkPage(pairDoor, req, res, ip, offeredCode)const offered = url.searchParams.get('token') ?? undefined// An invite's page and its form come before signing in: they're how someone new gets a key. A// guesser of codes waits at that door; the other door stays open (see Doors).@@ -307,7 +308,7 @@ function handle(req: IncomingMessage, res: ServerResponse): void {if (r.status === 'person') return authed(req, res, url, { person: r.person.id, role: r.person.role })if (r.status === 'blocked') return void res.writeHead(429, { ...BASE_HEADERS, 'retry-after': '600' }).end()// Someone removed: their page says so (the bridge reads the 401), and nothing more.- if (r.status === 'removed') return page200(res, NO_ACCESS_PAGE, 401)+ if (r.status === 'removed') return htmlPage(res, NO_ACCESS_PAGE, 401)res.writeHead(401, { ...BASE_HEADERS, 'content-type': 'text/plain; charset=utf-8' }).end(UNAUTHORIZED_TEXT)}).catch((e: unknown) => {@@ -321,56 +322,12 @@ function handle(req: IncomingMessage, res: ServerResponse): void {async function invitePageFor(req: IncomingMessage, res: ServerResponse, code: string): Promise<void> {const info = code ? await ask<{ name?: string }>({ type: 'invite-info', code: code.slice(0, 200) }, 5_000) : undefinedif (wantsJson(req)) return json(res, 200, { owner: ownerName, ...(info?.name ? { name: info.name } : {}) })- page200(res, invitePage({ owner: ownerName, code, ...(info?.name ? { name: info.name } : {}) }))+ htmlPage(res, invitePage({ owner: ownerName, code, ...(info?.name ? { name: info.name } : {}) }))}const wantsJson = (req: IncomingMessage): boolean => /application\/json/.test(String(req.headers['accept'] ?? ''))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))-const cookieFor = (req: IncomingMessage, key: string): string => `tucano=${key}; HttpOnly; SameSite=Lax; Path=/; Max-Age=31536000${req.headers['x-forwarded-proto'] === 'https' ? '; Secure' : ''}`--// A spent code's person gets a key of this device's own, from the core (people.deviceKey).-async function keyFor(code: unknown, label: string): Promise<string | undefined> {- const spent = pairCodes.spend(code)- if (!spent) return undefined- const out = await ask<{ key?: string }>({ type: 'device-key', person: spent.person, label })- return out?.key-}--// POST /pair {code, name, platform}: the phone's (or the desktop app's) key, as {key}. A code that's-// wrong, used or late answers 410 and counts as a guess at the invite's door.-async function pairDevice(req: IncomingMessage, res: ServerResponse, ip: string): Promise<void> {- if (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 key = await keyFor(asked?.code, deviceLabel(asked?.name, asked?.platform))- if (!key) {- doors.fail('join', ip)- return json(res, 410, { error: 'Esse código já foi usado ou passou do prazo. Gere outro. · That code was already used or has expired. Make a new one.' })- }- json(res, 200, { key })-}--// /?code=: this browser becomes a device of the code's person, signed in with its key.-async function pairBrowser(req: IncomingMessage, res: ServerResponse, ip: string, code: string): Promise<void> {- if (doors.blocked('join', ip)) return void res.writeHead(429, { ...BASE_HEADERS, 'retry-after': '600' }).end()- const key = CODE_SHAPE.test(code) ? await keyFor(code, deviceLabel(browserName(String(req.headers['user-agent'] ?? '')), 'browser')) : undefined- if (key) return void res.writeHead(302, { ...BASE_HEADERS, 'set-cookie': cookieFor(req, key), location: '/', 'cache-control': 'no-store' }).end()- doors.fail('join', ip)- res- .writeHead(410, { ...BASE_HEADERS, 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' })- .end('Tucano: este link já foi usado ou passou do prazo. Gere outro em Configurações › Pessoas, ou com `node out/main/server.js pair`.\nTucano: this link was already used or has expired. Make a new one in Settings › People, or with `node out/main/server.js pair`.')-}--// Same-origin, not no-referrer: with no-referrer the browser sends the invite form's POST with-// `Origin: null`, which /join (rightly) refuses as another site's.-function page200(res: ServerResponse, html: string, status = 200): void {- res.writeHead(status, { ...BASE_HEADERS, 'referrer-policy': 'same-origin', 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store', 'content-security-policy': PAGE_CSP, 'x-frame-options': 'DENY' }).end(html)-}// The invite's form: a code and a name become a person with a key, kept in this browser's cookie.// A code that's wrong, used or expired counts as a guess.@@ -386,14 +343,14 @@ async function joinPage(req: IncomingMessage, res: ServerResponse, ip: string):}if (!fields.name.trim()) {if (app) return json(res, 400, { error: 'Diga seu nome. · Tell us your name.' })- return page200(res, invitePage({ owner: ownerName, code: fields.code, error: 'Diga seu nome. · Tell us your name.' }), 400)+ return htmlPage(res, invitePage({ owner: ownerName, code: fields.code, error: 'Diga seu nome. · Tell us your name.' }), 400)}const out = await ask<{ key?: string; error?: string }>({ type: 'join', code: fields.code, name: fields.name })if (!out?.key) {doors.fail('join', ip)const error = out?.error ?? 'O Tucano não respondeu. Tente de novo. · Tucano didn’t answer. Try again.'if (app) return json(res, 400, { error })- return page200(res, invitePage({ owner: ownerName, code: fields.code, name: fields.name, error }), 400)+ return htmlPage(res, invitePage({ owner: ownerName, code: fields.code, name: fields.name, error }), 400)}if (app) return json(res, 200, { key: out.key })const secure = req.headers['x-forwarded-proto'] === 'https' ? '; Secure' : ''@@ -455,7 +412,8 @@ function signedIn(req: IncomingMessage, res: ServerResponse, url: URL, who: Who)}if (url.pathname === '/events') {- const port = new Port((msg) => res.write(`data: ${JSON.stringify(msg)}\n\n`))+ // Once the line is closed (the person removed, a device disconnected), a late answer goes nowhere.+ const port = new Port((msg) => void (!res.writableEnded && res.write(`data: ${JSON.stringify(msg)}\n\n`)))const id = randomUUID()// Ended by the server (the person was removed) or by the core (it closed the port): the page loses the line.const end = (): void => {@@ -468,8 +426,10 @@ function signedIn(req: IncomingMessage, res: ServerResponse, url: URL, who: Who)res.write(`event: hello\ndata: ${id}\n\n`)// A beat the page can hear (a comment line it couldn't): it tells a dead line from a quiet one.const beat = setInterval(() => res.write('event: ping\ndata: \n\n'), 25_000)- // The core learns whose port this is: nothing named is the owner, as on a desktop.- toCore(who.owner ? null : { person: who.person }, [port])+ // The core learns whose port this is: nothing named is the owner, as on a desktop. A person's+ // page also says which of their keys (by its hash): the one Settings › Pessoas marks as this device.+ const cookie = cookieToken(req)+ toCore(who.owner ? null : { person: who.person, ...(cookie && PERSON_KEY.test(cookie) ? { device: createHash('sha256').update(cookie).digest('base64url') } : {}) }, [port])req.on('close', () => {clearInterval(beat)streams.delete(id)diff --git a/src/server/pair-codes.ts b/src/server/pair-codes.tsindex 44f991a..c5d0627 100644--- a/src/server/pair-codes.ts+++ b/src/server/pair-codes.ts@@ -1,8 +1,10 @@// One-time codes that sign a device in (a phone, a browser, the desktop app) as a person of this// Tucano. A code is made on a page already signed in (Settings › Pessoas › Conectar um celular) for// whoever is asking, or by `server.js pair` on the server for the owner, and is good once, for a few-// minutes. Spent at POST /pair (or the browser's /?code=), it becomes a key of that person's own-// (the core makes it, like an invite's): one per device, so one can go without the others.+// minutes. Spent at POST /pair (the phone's JSON, or the form the browser's /?code= page posts), it+// becomes a key of that person's own (the core makes it, like an invite's): one per device, so one+// can go without the others. Opening /?code= only looks at it (peek): link previews, prefetches and+// scanners open links too, and must not spend one.//// `server.js pair` runs as another process than the server, so the codes live in a file of the data// folder (only this user reads it), read again whenever it changed. Only each code's hash is kept.@@ -68,6 +70,15 @@ export class PairCodes {return { code, expiresAt }}+ // Whose the code is, without spending it: undefined when it's wrong, used or late.+ peek(code: unknown): { person: string | null } | undefined {+ if (typeof code !== 'string' || !CODE_SHAPE.test(code)) return undefined+ this.load()+ const h = hashOf(code)+ const found = this.codes.find((c) => c.hash === h && c.expires > this.now())+ return found ? { person: found.person ?? null } : undefined+ }+// The code, spent (once, even when it's late): whose it was, or undefined when it's wrong, used or late.spend(code: unknown): { person: string | null } | undefined {if (typeof code !== 'string' || !CODE_SHAPE.test(code)) return undefineddiff --git a/src/server/pair-http.ts b/src/server/pair-http.tsnew file mode 100644index 0000000..37a6f3f--- /dev/null+++ b/src/server/pair-http.ts@@ -0,0 +1,100 @@+// A one-time code (pair-codes.ts) at the door: the browser's link (/?code=) and POST /pair.+//+// Opening the link never spends the code. Link previews (Discord, WhatsApp, iMessage, Slack), a+// browser's prefetch or prerender of a pasted address, and mail scanners all open links before the+// person does: each would spend the code on a device no one holds, and the person's own visit would+// find it used. So the link answers a page that only looks at the code and asks; its button posts+// the code back (same origin only), and that spends it, once.+//+// POST /pair also takes the phone's (or a program's) JSON, as before: {code, name, platform} → {key}.+import type { IncomingMessage, ServerResponse } from 'node:http'+import { BASE_HEADERS, body, type Doors, sameOrigin } from './guard'+import { browserName, CODE_SHAPE, deviceLabel } from './pair-codes'+import { esc, PAGE_CSP, PAGE_STYLE } from './people'++export interface PairDoor {+ codes: { peek(code: unknown): { person: string | null } | undefined; spend(code: unknown): { person: string | null } | undefined }+ doors: Doors+ // The core's key for a new device of this person (null: the owner), or undefined.+ mint(person: string | null, label: string): Promise<string | undefined>+ owner(): string // whose Tucano it is, by name ('' before they said it)+ nameOf(person: string | null): string | undefined+}++const USED =+ 'Esse código já foi usado ou passou do prazo. Gere outro. · That code was already used or has expired. Make a new one.'++// A browser that only asks ahead (Chrome's prefetch and prerender, Firefox's link prefetch, Safari's+// preload): Sec-Purpose, or the older Purpose, X-Purpose and X-Moz.+export function prefetching(req: Pick<IncomingMessage, 'headers'>): boolean {+ const h = req.headers+ return /prefetch|prerender|preview/i.test([h['sec-purpose'], h['purpose'], h['x-purpose'], h['x-moz']].flat().filter(Boolean).join(' '))+}++export const cookieFor = (req: Pick<IncomingMessage, 'headers'>, key: string): string =>+ `tucano=${key}; HttpOnly; SameSite=Lax; Path=/; Max-Age=31536000${req.headers['x-forwarded-proto'] === 'https' ? '; Secure' : ''}`++// Same-origin, not no-referrer: with no-referrer the browser sends a form's POST with `Origin: null`,+// which /join and /pair (rightly) refuse as another site's.+export function htmlPage(res: ServerResponse, html: string, status = 200): void {+ res.writeHead(status, { ...BASE_HEADERS, 'referrer-policy': 'same-origin', 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store', 'content-security-policy': PAGE_CSP, 'x-frame-options': 'DENY' }).end(html)+}++const shell = (inner: string): string =>+ `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="robots" content="noindex"><title>Tucano</title><style>${PAGE_STYLE}</style><main>${inner}</main>`++// "Entrar no Tucano de <owner>": whose it is, as whom, and one button that spends the code.+export function pairPage(o: { owner: string; code: string; as?: string }): string {+ const whose = o.owner.trim()+ const title = whose ? `Entrar no Tucano de ${whose} · Sign in to ${whose}'s Tucano` : 'Entrar no Tucano · Sign in to Tucano'+ const as = o.as?.trim()+ return shell(+ `<h2>${esc(title)}</h2>${as ? `<p>Este navegador vai entrar como <b>${esc(as)}</b>. · This browser will sign in as <b>${esc(as)}</b>.</p>` : ''}<p>O link vale uma vez. Se não foi você quem pediu, feche esta página. · The link works once. If you didn't ask for it, close this page.</p><form method="post" action="./pair"><input type="hidden" name="code" value="${esc(o.code)}"><button type="submit">Entrar neste navegador · Sign in on this browser</button></form>`+ )+}++export const USED_PAGE = shell(+ '<h2>Este link já foi usado ou passou do prazo. · This link was already used or has expired.</h2><p>Gere outro em Configurações › Pessoas › Conectar um celular, ou com <code>node out/main/server.js pair</code>. · Make a new one in Settings › People › Connect a phone, or with <code>node out/main/server.js pair</code>.</p>'+)++const blocked = (res: ServerResponse): void => void res.writeHead(429, { ...BASE_HEADERS, 'retry-after': '600' }).end()++// GET /?code=: the page that asks. Only looks at the code: a wrong, used or late one counts as a+// guess at the invite's door, as spending it did. A prefetch gets nothing (and costs no guess): the+// person's own visit asks again.+export function pairLinkPage(door: PairDoor, req: IncomingMessage, res: ServerResponse, ip: string, code: string): void {+ if (door.doors.blocked('join', ip)) return blocked(res)+ if (prefetching(req)) return void res.writeHead(503, { ...BASE_HEADERS, 'cache-control': 'no-store', 'retry-after': '1' }).end()+ const found = CODE_SHAPE.test(code) ? door.codes.peek(code) : undefined+ if (!found) {+ door.doors.fail('join', ip)+ return htmlPage(res, USED_PAGE, 410)+ }+ htmlPage(res, pairPage({ owner: door.owner(), code, as: door.nameOf(found.person) }))+}++// POST /pair: the page's form (this browser, signed in by a cookie) or the phone's JSON (the key+// itself). A code that's wrong, used or late answers 410 and counts as a guess at the invite's door.+export async function pairPost(door: PairDoor, req: IncomingMessage, res: ServerResponse, ip: string): Promise<void> {+ if (door.doors.blocked('join', ip)) return blocked(res)+ const form = /application\/x-www-form-urlencoded/.test(String(req.headers['content-type'] ?? ''))+ // A form from another site would sign this browser in as someone else's device.+ if (form && !sameOrigin(req)) return void res.writeHead(403, BASE_HEADERS).end()+ let asked: { code?: unknown; name?: unknown; platform?: unknown } = {}+ try {+ const text = await body(req, 4 * 1024)+ asked = form ? { code: new URLSearchParams(text).get('code') ?? '' } : (JSON.parse(text) as typeof asked)+ } catch {+ return void res.writeHead(400, BASE_HEADERS).end()+ }+ const label = form ? deviceLabel(browserName(String(req.headers['user-agent'] ?? '')), 'browser') : deviceLabel(asked?.name, asked?.platform)+ const spent = door.codes.spend(asked?.code)+ const key = spent ? await door.mint(spent.person, label) : undefined+ if (!key) {+ door.doors.fail('join', ip)+ if (form) return htmlPage(res, USED_PAGE, 410)+ return void res.writeHead(410, { ...BASE_HEADERS, 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }).end(JSON.stringify({ error: USED }))+ }+ if (form) return void res.writeHead(302, { ...BASE_HEADERS, 'set-cookie': cookieFor(req, key), location: '/', 'cache-control': 'no-store' }).end()+ res.writeHead(200, { ...BASE_HEADERS, 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }).end(JSON.stringify({ key }))+}diff --git a/src/server/people.ts b/src/server/people.tsindex 9dced68..9259861 100644--- a/src/server/people.ts+++ b/src/server/people.ts@@ -151,11 +151,11 @@ export function personNotice(return true}-const esc = (t: string): string => t.replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]!)+export const esc = (t: string): string => t.replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]!)// The plain page every server-made page shares (the OAuth callback's look).export const PAGE_STYLE =- 'body{font:15px system-ui;display:grid;place-items:center;min-height:100vh;margin:0;background:#f6f3ee;color:#1d1a16}@media(prefers-color-scheme:dark){body{background:#1a1917;color:#f1ece4}input{background:#262421;color:inherit}}main{max-width:460px;padding:24px}p{opacity:.8;line-height:1.5}form{display:grid;gap:10px;margin-top:16px}input{font:inherit;padding:10px 12px;border:1px solid #8884;border-radius:8px}button{font:inherit;padding:10px 12px;border:0;border-radius:8px;background:#1d1a16;color:#f6f3ee;cursor:pointer}.err{color:#b3261e;opacity:1}'+ 'body{font:15px system-ui;display:grid;place-items:center;min-height:100vh;margin:0;background:#f6f3ee;color:#1d1a16}@media(prefers-color-scheme:dark){body{background:#1a1917;color:#f1ece4}input{background:#262421;color:inherit}}main{max-width:460px;padding:24px}p{opacity:.8;line-height:1.5}form{display:grid;gap:10px;margin-top:16px}input{font:inherit;padding:10px 12px;border:1px solid #8884;border-radius:8px}button{font:inherit;padding:10px 12px;border:0;border-radius:8px;background:#1d1a16;color:#f6f3ee;cursor:pointer}.err{color:#b3261e;opacity:1}@media(prefers-color-scheme:dark){button{background:#f1ece4;color:#1a1917}}'export const PAGE_CSP = "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'"// "Você foi convidado pro Tucano de <name>": a name, and in. The code goes back in a hidden field;diff --git a/src/shared/rpc-shapes.ts b/src/shared/rpc-shapes.tsindex be994fb..53d0b6c 100644--- a/src/shared/rpc-shapes.ts+++ b/src/shared/rpc-shapes.ts@@ -144,6 +144,8 @@ export const SHAPES: Record<Method, Record<string, string>> = {revokeInvite: { id: 's' },listInvites: {},removedPeople: {},+ myDevices: {},+ removeDevice: { id: 's' },removePerson: { id: 's' },setRole: { id: 's', role: 's' },purgePerson: { id: 's' },diff --git a/src/shared/rpc.ts b/src/shared/rpc.tsindex 4b92929..b4fd500 100644--- a/src/shared/rpc.ts+++ b/src/shared/rpc.ts@@ -2,7 +2,7 @@import type { Answer } from './questions'import type { WikiChange, WikiHit, WikiPage, WikiImport, WikiPageInfo, WikiReview, WikiSource, WikiVersion } from './types'import type { AppProvider } from './connector-catalog'-import type { Os, Account, AccountEngine, ActivityEntry, Inbox, Agent, BrowserInput, Approval, Artifact, ImageUpload, BrowserView, ComputerInfo, Connector, ConnectorInput, ConnectorTool, HarnessMcp, Conversation, EngineId, Invite, Memory, Person, Role, MemoryScope, Message, Routine, RoutineInput, Report, Settings, LocalSkill, Skill, SkillInput, SkillVersion, Trigger, UsageReport, LocalInfo, VoiceModelId, VoiceStatus } from './types'+import type { Os, Account, AccountEngine, ActivityEntry, Device, Inbox, Agent, BrowserInput, Approval, Artifact, ImageUpload, BrowserView, ComputerInfo, Connector, ConnectorInput, ConnectorTool, HarnessMcp, Conversation, EngineId, Invite, Memory, Person, Role, MemoryScope, Message, Routine, RoutineInput, Report, Settings, LocalSkill, Skill, SkillInput, SkillVersion, Trigger, UsageReport, LocalInfo, VoiceModelId, VoiceStatus } from './types'export interface Snapshot {webhookPort?: number@@ -172,6 +172,8 @@ export interface Api {revokeInvite(p: { id: string }): voidlistInvites(): 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+ removeDevice(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'> }): voidpurgePerson(p: { id: string }): void // the owner, before the 30 days: a removed person's DMs and memories go nowdiff --git a/src/shared/types.ts b/src/shared/types.tsindex 94525fa..27e0c02 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -246,6 +246,16 @@ export interface Person {devices?: number // how many keys (browsers, apps) they have}+// One of my own keys (a browser, the phone, the desktop app), as Settings › Pessoas lists them.+// `id` is the key's hash, never the key. No `seenAt`: it never signed in (a link preview's, say).+export interface Device {+ id: string+ label: string+ createdAt: number+ seenAt?: number+ current?: boolean // the one this page is signed in with+}+// Whether `of` has `who` covering for them right now.export const delegating = (of: Pick<Person, 'delegateTo' | 'delegateUntil'> | undefined, who: string, now = Date.now()): boolean =>!!of && of.delegateTo === who && (of.delegateUntil ?? 0) > nowdiff --git a/test/home-link.test.ts b/test/home-link.test.tsindex f722db7..b2d56c5 100644--- a/test/home-link.test.ts+++ b/test/home-link.test.ts@@ -154,6 +154,79 @@ describe('HomeLink', () => {})})+// A phone paired over the home Wi-Fi is one of the owner's devices (people.deviceKey): Settings ›+// Celular › Seu iPhone lists it and disconnects it (removeDevice), which ends its open line at once.+describe('HomeLink, a phone disconnected from the computer', () => {+ let dir: string+ let link: HomeLink+ afterEach(async () => {+ await link.stop()+ rmSync(dir, { recursive: true, force: true })+ })++ it('shows as a device of the owner, and losing it closes its stream and its key', async () => {+ const { Db } = await import('../src/core/db')+ const { Hub, People } = await import('../src/core/people')+ dir = mkdtempSync(join(tmpdir(), 'home-link-dev-'))+ const db = new Db(':memory:')+ const people = new People(db)+ type P = { postMessage(m: unknown): void; close(): void }+ const hub = new Hub<P>(people, db)+ // The core as home-phone.ts wires it, minus Electron: a port the hub knows by person and device.+ const core: HomeCore = {+ auth: async (key) => people.authenticate(key) ?? (db.removedKey(createHash('sha256').update(key).digest('base64url')) ? { removed: true } : undefined),+ deviceKey: async (label) => people.deviceKey(null, label)?.key,+ open: (person, onMessage, o) => {+ let open = true+ const port: P = { postMessage: (m) => open && onMessage(m), close: () => void (open && ((open = false), o?.onClose?.())) }+ hub.add(port, { person, device: o?.device })+ return { post: () => {}, close: () => port.close() }+ },+ dataDir: () => dir+ }+ link = new HomeLink({ tls: makeCertificate('Tucano', ['localhost']), codesFile: join(dir, 'codes.json'), core: () => core })+ const port = await link.start(47390, '127.0.0.1')+ const code = new URL(link.makeCode().link).searchParams.get('code')!+ const { key } = JSON.parse((await call(port, '/pair', { method: 'POST', body: JSON.stringify({ code, name: 'iPhone de Eduardo', platform: 'ios' }) })).body) as { key: string }+ const mine = db.personKeys(db.ownerId())+ expect(mine.map((k) => k.label)).toEqual(['iPhone de Eduardo · ios'])++ // On the line; then disconnected from the computer, as the core's removeDevice does.+ let ended = false+ const stream = new Promise<string>((resolve) => {+ 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))+ res.on('end', () => ((ended = true), resolve(text)))+ })+ req.end()+ })+ await new Promise((r) => setTimeout(r, 150))+ expect(link.connected).toBe(1)+ expect(db.removePersonKey(db.ownerId(), mine[0]!.hash)).toBe(true)+ hub.closeDevice(mine[0]!.hash)+ expect(await stream).toContain('event: hello')+ expect(ended).toBe(true)+ expect(link.connected).toBe(0)+ // Its key opens nothing now (and reads as signed out, not as a guess).+ expect((await call(port, '/events', { cookie: key })).status).toBe(401)+ expect(people.authenticate(key)).toBeUndefined()+ // Deliveries to a closed line go nowhere.+ expect(() => link.deliver({ notify: {} })).not.toThrow()+ })++ it('never spends a code on a GET', async () => {+ dir = mkdtempSync(join(tmpdir(), 'home-link-get-'))+ const core = fakeCore(dir)+ link = new HomeLink({ tls: makeCertificate('Tucano', ['localhost']), codesFile: join(dir, 'codes.json'), core: () => core })+ const port = await link.start(47395, '127.0.0.1')+ const code = new URL(link.makeCode().link).searchParams.get('code')!+ for (const path of [`/?code=${code}`, `/pair?code=${code}`]) expect((await call(port, path)).status).toBe(401)+ expect(core.keys).toHaveLength(0)+ expect((await call(port, '/pair', { method: 'POST', body: JSON.stringify({ code, name: 'iPhone', platform: 'ios' }) })).status).toBe(200)+ })+})+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')diff --git a/test/pair-link.test.ts b/test/pair-link.test.tsnew file mode 100644index 0000000..c2e4cae--- /dev/null+++ b/test/pair-link.test.ts@@ -0,0 +1,216 @@+// A pairing link opened by something other than its person (a chat's link preview, a browser's+// prefetch or prerender, a scanner) spends nothing: only the page's button, a same-origin POST, does+// (src/server/pair-http.ts). And the devices a code made can be seen and disconnected.+import { createHash } from 'node:crypto'+import { mkdtempSync } from 'node:fs'+import { createServer, type Server } from 'node:http'+import type { AddressInfo } from 'node:net'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, describe, expect, it } from 'vitest'+import { Db } from '../src/core/db'+import { Hub, People } from '../src/core/people'+import { Doors, MAX_FAILS } from '../src/server/guard'+import { PairCodes } from '../src/server/pair-codes'+import { pairLinkPage, pairPost, prefetching, type PairDoor } from '../src/server/pair-http'+import { parsePairing } from '../src/shared/servers'++const hashOf = (key: string): string => createHash('sha256').update(key).digest('base64url')++let server: Server | undefined+afterEach(() => new Promise<void>((r) => (server ? server.close(() => r()) : r())))++// The two routes as the server has them, with a real code file and a real core's People behind.+async function start(): Promise<{ base: string; host: string; codes: PairCodes; db: Db; people: People; doors: Doors }> {+ const db = new Db(':memory:')+ db.renamePerson(db.ownerId(), 'Ana')+ const people = new People(db)+ const codes = new PairCodes(join(mkdtempSync(join(tmpdir(), 'tucano-pairlink-')), 'pair-codes.json'))+ const doors = new Doors()+ const door: PairDoor = {+ codes,+ doors,+ mint: async (person, label) => people.deviceKey(person, label)?.key,+ owner: () => 'Ana',+ nameOf: (person) => (person ? db.person(person)?.name : db.owner().name)+ }+ server = createServer((req, res) => {+ const url = new URL(req.url ?? '/', 'http://x')+ if (url.pathname === '/pair' && req.method === 'POST') return void pairPost(door, req, res, '10.0.0.1')+ const code = url.searchParams.get('code')+ if (code !== null && req.method === 'GET') return pairLinkPage(door, req, res, '10.0.0.1', code)+ res.writeHead(404).end()+ })+ await new Promise<void>((r) => server!.listen(0, '127.0.0.1', r))+ const host = `127.0.0.1:${(server.address() as AddressInfo).port}`+ return { base: `http://${host}`, host, codes, db, people, doors }+}++const devices = (db: Db): number => db.people().find((p) => p.id === db.ownerId())?.devices ?? 0+const form = (host: string, code: string, origin = `http://${host}`): RequestInit => ({+ method: 'POST',+ redirect: 'manual',+ headers: { 'content-type': 'application/x-www-form-urlencoded', origin },+ body: new URLSearchParams({ code }).toString()+})++describe('a pairing link opened before its person opens it', () => {+ it('knows a prefetch or prerender from a visit', () => {+ const r = (headers: Record<string, string>) => ({ headers })+ expect(prefetching(r({ 'sec-purpose': 'prefetch' }))).toBe(true)+ expect(prefetching(r({ 'sec-purpose': 'prefetch;prerender' }))).toBe(true)+ expect(prefetching(r({ purpose: 'prefetch' }))).toBe(true)+ expect(prefetching(r({ 'x-purpose': 'preview' }))).toBe(true)+ expect(prefetching(r({ 'x-moz': 'prefetch' }))).toBe(true)+ expect(prefetching(r({}))).toBe(false)+ })++ it('a plain GET, a prefetch and a link preview spend nothing and make no device', async () => {+ const { base, codes, db } = await start()+ const { code } = codes.make(null)+ const plain = await fetch(`${base}/?code=${code}`, { redirect: 'manual' })+ expect(plain.status).toBe(200)+ expect(plain.headers.get('set-cookie')).toBeNull()+ expect(plain.headers.get('cache-control')).toBe('no-store')+ const html = await plain.text()+ expect(html).toContain('Entrar no Tucano de Ana')+ expect(html).toContain('Entrar neste navegador · Sign in on this browser')+ expect(html).toContain('method="post" action="./pair"')+ for (const headers of <Record<string, string>[]>[{ 'sec-purpose': 'prefetch;prerender' }, { purpose: 'prefetch' }, { 'user-agent': 'Mozilla/5.0 (compatible; Discordbot/2.0; +https://discordapp.com)' }, { 'user-agent': 'WhatsApp/2.23.20.0' }, { 'user-agent': 'facebookexternalhit/1.1' }]) {+ const r = await fetch(`${base}/?code=${code}`, { headers, redirect: 'manual' })+ expect(r.headers.get('set-cookie')).toBeNull()+ expect([200, 503]).toContain(r.status)+ }+ expect(devices(db)).toBe(0)+ expect(codes.peek(code)).toEqual({ person: null }) // still good+ })++ it("says whom the browser signs in as, someone invited's code included", async () => {+ const { base, codes, db } = await start()+ const { code: invite } = new People(db).createInvite(db.owner(), { role: 'member' })+ const bia = new People(db).join(invite, 'Bia')+ if ('error' in bia) throw new Error(bia.error)+ const { code } = codes.make(bia.person.id)+ const html = await (await fetch(`${base}/?code=${code}`)).text()+ expect(html).toContain('<b>Bia</b>')+ })++ it('the POST spends it once: a cookie and a device; a second POST gets 410', async () => {+ const { base, host, codes, db, people } = await start()+ const { code } = codes.make(null)+ await fetch(`${base}/?code=${code}`) // a preview got there first+ const r = await fetch(`${base}/pair`, form(host, code))+ expect(r.status).toBe(302)+ expect(r.headers.get('location')).toBe('/')+ const key = /tucano=(p_[\w-]{43})/.exec(r.headers.get('set-cookie') ?? '')?.[1]+ expect(key).toBeDefined()+ expect(people.authenticate(key!)?.id).toBe(db.ownerId())+ expect(devices(db)).toBe(1)+ const again = await fetch(`${base}/pair`, form(host, code))+ expect(again.status).toBe(410)+ expect(again.headers.get('set-cookie')).toBeNull()+ expect(devices(db)).toBe(1)+ // And now the link itself says so.+ const used = await fetch(`${base}/?code=${code}`)+ expect(used.status).toBe(410)+ expect(await used.text()).toContain('já foi usado ou passou do prazo')+ })++ it("refuses another site's form, and spends nothing", async () => {+ const { host, base, codes, db } = await start()+ const { code } = codes.make(null)+ expect((await fetch(`${base}/pair`, form(host, code, 'https://evil.example'))).status).toBe(403)+ expect((await fetch(`${base}/pair`, form(host, code, 'null'))).status).toBe(403)+ expect(devices(db)).toBe(0)+ expect(codes.peek(code)).toBeDefined()+ })++ it('counts a wrong or late code as a guess, the same at the link and at the form; a good one costs none', async () => {+ const { base, host, codes, doors } = await start()+ const { code } = codes.make(null)+ for (let i = 0; i < MAX_FAILS + 3; i++) expect((await fetch(`${base}/?code=${code}`)).status).toBe(200)+ expect(doors.blocked('join', '10.0.0.1')).toBe(false)+ for (let i = 0; i < MAX_FAILS / 2; i++) expect((await fetch(`${base}/?code=${'x'.repeat(24)}`)).status).toBe(410)+ for (let i = 0; i < MAX_FAILS / 2 - 1; i++) expect((await fetch(`${base}/pair`, form(host, 'y'.repeat(24)))).status).toBe(410)+ expect((await fetch(`${base}/?code=short`)).status).toBe(410)+ expect(doors.blocked('join', '10.0.0.1')).toBe(true)+ expect((await fetch(`${base}/?code=${code}`)).status).toBe(429) // a waiting address reads nothing, not even a good code+ expect((await fetch(`${base}/pair`, form(host, code))).status).toBe(429)+ // And the good code is still unspent.+ expect(codes.peek(code)).toBeDefined()+ })++ it('a prefetch costs no guess, even with a wrong code', async () => {+ const { base, doors } = await start()+ for (let i = 0; i < MAX_FAILS + 1; i++) expect((await fetch(`${base}/?code=${'z'.repeat(24)}`, { headers: { 'sec-purpose': 'prefetch' } })).status).toBe(503)+ expect(doors.blocked('join', '10.0.0.1')).toBe(false)+ })+})++describe('the other ways a code is spent', () => {+ it("the phone's JSON POST still trades it for a key, once", async () => {+ const { base, codes, db, people } = await start()+ const { code } = codes.make(null)+ const post = () => fetch(`${base}/pair`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ code, name: 'iPhone de Ana', platform: 'ios' }) })+ const r = await post()+ expect(r.status).toBe(200)+ const { key } = (await r.json()) as { key: string }+ expect(people.authenticate(key)?.id).toBe(db.ownerId())+ expect(db.personKeys(db.ownerId())[0]!.label).toBe('iPhone de Ana · ios')+ const again = await post()+ expect(again.status).toBe(410)+ expect(((await again.json()) as { error: string }).error).toContain('já foi usado')+ expect((await fetch(`${base}/pair`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{' })).status).toBe(400)+ })++ it('the desktop app pairs by the server token, never a code (nothing it opens spends one)', () => {+ expect(parsePairing(`tucano://connect?url=https%3A%2F%2Fana.example.com&token=${'t'.repeat(32)}`)).toEqual({ origin: 'https://ana.example.com', token: 't'.repeat(32) })+ expect(parsePairing(`tucano://connect?url=https%3A%2F%2Fana.example.com&code=${'c'.repeat(24)}`)).toBeNull()+ })+})++describe('my devices', () => {+ it('are listed, a never-used one says so, and one can go without the others', async () => {+ const { db, people } = await start()+ const used = people.deviceKey(null, 'Chrome · macOS · browser')!.key+ const orphan = people.deviceKey(null, 'Discordbot · browser')!.key+ people.authenticate(used)+ const list = db.personKeys(db.ownerId())+ expect(list.map((k) => k.label).sort()).toEqual(['Chrome · macOS · browser', 'Discordbot · browser'])+ expect(list.find((k) => k.hash === hashOf(used))!.seenAt).toBeGreaterThan(0)+ expect(list.find((k) => k.hash === hashOf(orphan))!.seenAt).toBeUndefined()+ expect(list.some((k) => JSON.stringify(k).includes(orphan))).toBe(false) // only hashes+ expect(db.removePersonKey(db.ownerId(), hashOf(orphan))).toBe(true)+ expect(db.removePersonKey(db.ownerId(), hashOf(orphan))).toBe(false)+ expect(people.authenticate(orphan)).toBeUndefined()+ expect(db.removedKey(hashOf(orphan))).toBe(true) // its browser reads "no access", not a guess+ expect(people.authenticate(used)?.id).toBe(db.ownerId())+ expect(devices(db)).toBe(1)+ })++ it("no one disconnects someone else's device by its id", async () => {+ const { db, people } = await start()+ const { code } = people.createInvite(db.owner(), { role: 'member' })+ const bia = people.join(code, 'Bia')+ if ('error' in bia) throw new Error(bia.error)+ const ana = people.deviceKey(null, 'phone')!.key+ expect(db.removePersonKey(bia.person.id, hashOf(ana))).toBe(false)+ expect(people.authenticate(ana)?.id).toBe(db.ownerId())+ })++ it("the hub knows each page's device, and closes only that device's pages", async () => {+ const { db, people } = await start()+ const hub = new Hub<{ postMessage(m: unknown): void; close(): void; closed?: boolean }>(people, db)+ const port = () => ({ postMessage() {}, close() { this.closed = true }, closed: false })+ const a = port()+ const b = port()+ hub.add(a, { person: db.ownerId(), device: 'h1' })+ hub.add(b, { person: db.ownerId(), device: 'h2' })+ expect(hub.deviceOf(a)).toBe('h1')+ hub.closeDevice('h1')+ expect(a.closed).toBe(true)+ expect(b.closed).toBe(false)+ expect(hub.personOf(a)).toBeUndefined()+ expect(hub.personOf(b)?.id).toBe(db.ownerId())+ })+})