Skip to content

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.

Let phones sign in to a Tucano on a server as their person, and let people leave (#185)

Eduardo Machado870ef2e003a1
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2e69c88..7a15e37 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,11 @@ What changed in each version of Tucano. The format follows [Keep a Changelog](ht
## [Unreleased]
+### Added
+
+- **Phones sign in to a Tucano on a server, as their person.** **Settings › People › Connect a phone** shows a QR code that's good once, for 10 minutes: the Tucano app on the iPhone reads it and gets a key of its own, signed in as whoever made the code, with their DMs, approvals and questions. On the server, `npm run server -- pair [minutes]` makes one for the owner (the same link opens a browser too, with `/?code=`). An invite link also works in the app: it asks the name and the person is in.
+- **Leaving a Tucano on your own.** Someone invited (not the owner) can leave from the iPhone app: their access ends at once on every device, and their direct messages, memories and own routines are deleted right away instead of after 30 days. What they said in channels stays the channel's, and the agents they made go to the owner.
+
## [0.2.15] - 2026-11-07
> **Em português:**
diff --git a/docs/server.md b/docs/server.md
index 3876ebe..3705321 100644
--- a/docs/server.md
+++ b/docs/server.md
@@ -45,6 +45,19 @@ npm install -g @openai/codex
Codex is signed in from Tucano's **Settings › Models**, like on a desktop. On a server, the **Sign in** button can't open a terminal, so it shows the command to run in your SSH session.
+### On a phone
+
+The Tucano app for iPhone signs in with a one-time code, not the token. On the server, run:
+
+```bash
+npm run server -- pair # tucano://connect?url=…&code=… and https://…/?code=…
+npm run server -- pair 1440 # good for a day instead of 10 minutes (up to a week: 10080)
+```
+
+Open the first line on the phone (or show it as a QR code and point the Camera at it). The app trades the code for a key of its own, and the code stops working. The second line does the same for a browser. Once you're signed in, **Settings › People › Connect a phone** makes a code too, as a QR code, for whoever is signed in: each person connects their own phone, as themselves. Each phone has its own key; removing someone ends all of theirs. The app needs the server on HTTPS (a reverse proxy, below), or on `127.0.0.1` while testing.
+
+Someone you invite can also open the invite link in the app: it asks their name, and they're in.
+
## Reaching it
By default the server only listens on the server itself (`127.0.0.1`), because anyone who has the token controls your agents. Pick one of these ways to reach it:
diff --git a/package-lock.json b/package-lock.json
index a6ffeb4..2d7a1c1 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -13,6 +13,7 @@
"@modelcontextprotocol/sdk": "^1.32.1",
"electron-updater": "^6.8.11",
"gsap": "^3.14.2",
+ "qrcode-generator": "^2.0.4",
"smol-toml": "^1.9.1"
},
"devDependencies": {
@@ -8405,6 +8406,12 @@
"node": ">=16.0.0"
}
},
+ "node_modules/qrcode-generator": {
+ "version": "2.0.4",
+ "resolved": "https://registry.npmjs.org/qrcode-generator/-/qrcode-generator-2.0.4.tgz",
+ "integrity": "sha512-mZSiP6RnbHl4xL2Ap5HfkjLnmxfKcPWpWe/c+5XxCuetEenqmNFf1FH/ftXPCtFG5/TDobjsjz6sSNL0Sr8Z9g==",
+ "license": "MIT"
+ },
"node_modules/qs": {
"version": "6.16.1",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.16.1.tgz",
diff --git a/package.json b/package.json
index e619a1e..0d67c8f 100644
--- a/package.json
+++ b/package.json
@@ -48,6 +48,7 @@
"@modelcontextprotocol/sdk": "^1.32.1",
"electron-updater": "^6.8.11",
"gsap": "^3.14.2",
+ "qrcode-generator": "^2.0.4",
"smol-toml": "^1.9.1"
},
"build": {
diff --git a/src/core/index.ts b/src/core/index.ts
index ab39f57..9aff340 100644
--- a/src/core/index.ts
+++ b/src/core/index.ts
@@ -348,6 +348,7 @@ type ToMain =
| { type: 'notify'; title: string; body: string; conversationId?: string; threadId?: string; kind?: 'approval' | 'question' | 'done'; page?: 'skills'; sound?: boolean; to?: string[] } // to: the people it's for (a server delivers it only to them); unset: everyone
| { type: 'auth-result'; id: string; person?: Person; removed?: true } // removed: a key of someone removed since
| { type: 'join-result'; id: string; data: { key?: string; person?: Person; error?: string } }
+ | { type: 'device-key-result'; id: string; data: { key?: string; person?: Person } }
| { type: 'person-removed'; id: string }
| { type: 'person-changed'; id: string } // a role changed: the server forgets what it remembered of them
| { type: 'login_item'; open: boolean }
@@ -364,7 +365,7 @@ const shots = new Map<string, { resolve: (b: Buffer) => void; reject: (e: Error)
// Agents' browsers too (spec §24).
const pages = new Map<string, { resolve: (r: BrowserReply) => void; reject: (e: Error) => void }>()
process.parentPort.on('message', (e) => {
- const r = e.data as { type?: string; id: string; data?: unknown; error?: string; awake?: boolean; agentId?: string; shown?: boolean; conversationId?: string | null; targetDir?: string; name?: string; theme?: unknown; paused?: unknown; parts?: unknown; path?: unknown; person?: unknown; key?: unknown; code?: unknown; artifact?: unknown; port?: unknown } | undefined
+ const r = e.data as { type?: string; id: string; data?: unknown; error?: string; awake?: boolean; agentId?: string; shown?: boolean; conversationId?: string | null; targetDir?: string; name?: string; theme?: unknown; paused?: unknown; parts?: unknown; path?: unknown; person?: unknown; key?: unknown; code?: unknown; label?: unknown; artifact?: unknown; port?: unknown } | undefined
if (r?.type === 'workspace-pause') {
try {
if (closing || typeof r.paused !== 'boolean') throw new Error('Workspace cannot change pause state right now')
@@ -459,6 +460,12 @@ process.parentPort.on('message', (e) => {
}
return toMain({ type: 'join-result', id: r.id, data: 'person' in out ? { person: out.person, key: out.key } : out })
}
+ // A server's POST /pair: a one-time code it checked, spent for this person (none: the owner), becomes a key of a device's own.
+ if (r?.type === 'device-key') {
+ const out = people.deviceKey(r.person, r.label)
+ if (out) emitPeople()
+ return toMain({ type: 'device-key-result', id: r.id, data: out ?? {} })
+ }
if (r?.type === 'power') return routines.setAwake(r.awake === true)
// A server's /oauth/callback: the code the provider sent back, checked against the state only this core made.
if (r?.type === 'oauth-callback') {
@@ -1823,6 +1830,22 @@ const api: Handlers = {
emit({ type: 'inbox' })
},
purgePerson: ({ id }, ctx) => purged([people.purge(ctx.person, id)]),
+ // Leaving on one's own: gone now, with what was theirs alone. Their own line closes a moment after
+ // the answer, so the app hears that it worked.
+ leave: (_, ctx) => {
+ const id = ctx.person.id
+ const { agents, routines: given, purged: gone } = people.leave(ctx.person)
+ purged([gone])
+ for (const a of agents) emit({ type: 'agent', agent: db.agent(a)! })
+ for (const r of given) emit({ type: 'routine', routine: db.routine(r)! })
+ setTimeout(() => {
+ hub.closeFor(id)
+ viewing.delete(id)
+ toMain({ type: 'person-removed', id })
+ emitPeople()
+ emit({ type: 'inbox' })
+ }, 200)
+ },
activity: ({ personId, kind, before }) => db.activity({ personId, kind, before }),
inbox: (_, ctx) => people.inbox(ctx.person),
answerQuestion: ({ id, text }, ctx) => runner.answer(id, text, ctx.person),
diff --git a/src/core/people.ts b/src/core/people.ts
index 591f17e..5f13064 100644
--- a/src/core/people.ts
+++ b/src/core/people.ts
@@ -571,6 +571,16 @@ export class People {
})
}
+ // A one-time pairing code spent on a server (src/server/pair-codes.ts): a new key for that person
+ // (unset: the owner), for one device. Someone removed, or no one, gets none.
+ deviceKey(personId: unknown, label: unknown): { person: Person; key: string } | undefined {
+ const person = personId === undefined || personId === null ? this.db.owner() : typeof personId === 'string' ? this.db.person(personId) : undefined
+ if (!person) return undefined
+ const key = newKey()
+ this.db.addPersonKey(hashSecret(key), person.id, typeof label === 'string' && label ? label.slice(0, 120) : 'aparelho')
+ return { person: this.db.person(person.id) ?? person, key }
+ }
+
// Whether this name would read as someone else's: a person here, one removed who may still come
// back (until purged), or, once there are people to call, an agent (by its name or its handle: @lia
// would call both). A Tucano of one calls no person: its owner may be a Nina next to the agent Nina.
@@ -616,6 +626,24 @@ export class People {
})
}
+ // Someone leaves on their own (the phone app's "Sair deste Tucano", the account deletion app
+ // stores ask for): access ends now, and what was theirs alone goes now too, not in 30 days (their
+ // DMs, memories, own routines). What they made for the team (agents, a channel's routines) goes
+ // to the owner, as when someone is removed; what they said in channels stays the channel's. The
+ // owner can't leave their own Tucano.
+ leave(by: Person, now = Date.now()): { agents: string[]; routines: string[]; purged: Purged } {
+ if (by.role === 'owner') throw new Error(L('O dono não sai do próprio Tucano. Pra apagar tudo, desligue o servidor e apague a pasta de dados dele.', "The owner can't leave their own Tucano. To delete everything, stop the server and delete its data folder."))
+ const out = this.db.tx(() => {
+ this.db.removePerson(by.id)
+ const given = this.db.handOver(by.id)
+ const purged = { person: by.id, ...this.db.purgePerson(by.id, now) }
+ this.db.addActivity({ personId: by.id, kind: 'person.left', target: by.id, detail: { name: by.name, agents: given.agents.length, routines: given.routines.length }, at: now })
+ return { ...given, purged }
+ })
+ this.db.scrub()
+ return out
+ }
+
// Member ⇄ admin. Only the owner touches admins (or makes one); no one, the owner.
setRole(by: Person, id: string, role: Exclude<Role, 'owner'>): Person {
const p = this.db.person(id)
diff --git a/src/core/policy-people.ts b/src/core/policy-people.ts
index 418e25d..c225b2d 100644
--- a/src/core/policy-people.ts
+++ b/src/core/policy-people.ts
@@ -229,6 +229,7 @@ export const NEEDS: Record<Method, Need> = {
setRole: 'target',
activity: 'admin',
purgePerson: 'owner',
+ leave: 'anyone', // one's own access (the owner is refused in the core)
setTelegramToken: 'owner', // the phone is the owner's
unpairTelegram: 'owner'
}
diff --git a/src/renderer/src/components/People.tsx b/src/renderer/src/components/People.tsx
index 642fd72..0160086 100644
--- a/src/renderer/src/components/People.tsx
+++ b/src/renderer/src/components/People.tsx
@@ -1,5 +1,6 @@
// The people of a Tucano with a team: the first access's name, Settings › Pessoas and
// Settings › Atividade, and the "Só um admin…" note where an action is the admins'.
+import qrcode from 'qrcode-generator'
import { useEffect, useState, type ReactNode } from 'react'
import { L } from '../../../shared/lang'
import {
@@ -23,6 +24,7 @@ import {
setRole,
toast,
useStore,
+ windowless,
youPerson,
type ActivityEntry,
type Invite,
@@ -128,6 +130,7 @@ export function PeoplePane(): ReactNode {
return (
<>
<MeCard />
+ {windowless() && <PhoneCard />}
<Card
title={L(`Pessoas ${team ? `de ${team}` : 'do Tucano'}`, `People ${team ? `of ${team}` : 'in this Tucano'}`)}
@@ -328,6 +331,101 @@ function InviteCard({ onClose, owner }: { onClose: () => void; owner: boolean })
)
}
+// ---------- Conectar um celular ----------
+
+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 {
+ const q = qrcode(0, 'M')
+ q.addData(text)
+ q.make()
+ return <div className="device-qr" role="img" aria-label={L('QR code de conexão', 'Connection QR code')} dangerouslySetInnerHTML={{ __html: q.createSvgTag({ cellSize: 4, margin: 2, scalable: true }) }} />
+}
+
+// On a server: the Tucano app on a phone signs in as me with a one-time code (src/server/pair-codes.ts).
+// Each phone gets a key of its own; removing someone ends all of theirs.
+function PhoneCard(): ReactNode {
+ const me = useStore(youPerson)
+ const [code, setCode] = useState<PairCode | null>(null)
+ const [now, setNow] = useState(Date.now())
+ const [error, setError] = useState('')
+ const devices = me?.devices ?? 0
+ const [before, setBefore] = useState(devices)
+ useEffect(() => {
+ if (!code) return
+ const tick = setInterval(() => setNow(Date.now()), 1000)
+ return () => clearInterval(tick)
+ }, [code])
+ // A new device of mine arrived (the people event counts keys): the code was used.
+ useEffect(() => {
+ if (code && devices > before) setCode(null)
+ }, [devices])
+ const make = (): void => {
+ setError('')
+ setBefore(devices)
+ void fetch('./pair/new', { method: 'POST' })
+ .then((r) => (r.ok ? (r.json() as Promise<PairCode>) : Promise.reject(new Error(String(r.status)))))
+ .then((c) => (setCode(c), setNow(Date.now())))
+ .catch(() => setError(L('Não consegui gerar o código. Tente de novo.', "I couldn't make the code. Try again.")))
+ }
+ const left = code ? Math.max(0, Math.ceil((code.expiresAt - now) / 1000)) : 0
+ 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."))
+ )
+ return (
+ <Card
+ title={L('Conectar um celular', 'Connect a phone')}
+ lead={L('Use o Tucano no iPhone com a sua conta daqui: suas DMs, suas aprovações e as perguntas que os agentes fazem pra você.', 'Use Tucano on an iPhone with your account here: your DMs, your approvals and the questions agents ask you.')}
+ action={
+ !code ? (
+ <button className="btn btn--primary btn--sm" onClick={make}>
+ <Icon name="plus" size={14} /> {L('Gerar código', 'Make a code')}
+ </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={make}>
+ {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('No iPhone, abra a Câmera ou o app do Tucano e aponte pro código.', 'On the iPhone, open the Camera or the Tucano app and point it at the code.')}</li>
+ <li>{L('Toque em Abrir no Tucano e confirme.', 'Tap Open in Tucano and confirm.')}</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')}.
+ </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 do app', 'Copy the app link')}
+ </button>
+ <button className="btn btn--sm btn--ghost" onClick={() => copy(code.browser)}>
+ <Icon name="globe" size={13} /> {L('Copiar link do navegador', 'Copy the browser link')}
+ </button>
+ <button className="btn btn--sm btn--ghost" onClick={() => setCode(null)}>
+ {L('Cancelar', 'Cancel')}
+ </button>
+ </div>
+ </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>}
+ {error && <p className="note note--error">{error}</p>}
+ </Card>
+ )
+}
+
// 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/styles.css b/src/renderer/src/styles.css
index 07b8de8..9c8a10f 100644
--- a/src/renderer/src/styles.css
+++ b/src/renderer/src/styles.css
@@ -8454,3 +8454,12 @@ button.wk-pill.is-on { box-shadow: 0 0 0 1.5px var(--k); background: color-mix(i
.wk-heritage h5 { margin: 8px 0 4px; font-size: 12px; opacity: .8; }
.wk-heritage ul { list-style: none; margin: 0; padding: 0; display: grid; gap: 4px; }
.wk-heritage li { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
+
+/* Conectar um celular (People.tsx PhoneCard) */
+.device-pair { display: flex; gap: 18px; align-items: flex-start; padding: 14px; border: 1px solid var(--border); border-radius: 12px; margin-bottom: 10px; }
+.device-pair__text { flex: 1; min-width: 0; display: grid; gap: 10px; align-content: start; }
+.device-pair__text .steps-list { margin: 0; }
+.device-pair__actions { display: flex; flex-wrap: wrap; gap: 6px; }
+.device-qr { flex: none; width: 168px; height: 168px; padding: 6px; border-radius: 10px; background: #fff; }
+.device-qr svg { display: block; width: 100%; height: 100%; }
+@media (max-width: 560px) { .device-pair { flex-direction: column; align-items: center; } }
diff --git a/src/server/index.ts b/src/server/index.ts
index b059627..513e90b 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -7,6 +7,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 { EventEmitter } from 'node:events'
import { chmodSync, createReadStream, createWriteStream, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
@@ -17,6 +18,7 @@ import { basename, dirname, extname, isAbsolute, join, normalize, resolve, sep }
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 { Preview } from './preview'
import { vault } from './vault'
import { verifyLocal } from '../core/local-paths'
@@ -50,6 +52,18 @@ if (process.argv[2] === 'link') {
console.log(pairingLink({ origin: publicUrl, token }))
process.exit(0)
}
+
+// One-time codes that sign a device in as a person (pair-codes.ts).
+const pairCodes = new PairCodes(join(dataDir, 'pair-codes.json'))
+
+// `server.js pair [minutes]`: a one-time code for the owner, as the link the phone opens (or a QR
+// code of it) and as the browser's. Good once, for 10 minutes unless asked otherwise (up to a week).
+if (process.argv[2] === 'pair') {
+ const { code } = pairCodes.make(null, codeMinutes(process.argv[3]))
+ console.log(pairingLink({ origin: publicUrl, code }))
+ console.log(`${publicUrl}/?code=${code}`)
+ process.exit(0)
+}
// The secrets (Telegram, GitHub, connector keys) are sealed with this key; on a
// desktop it's the system's keychain, which a server doesn't have.
const key = Buffer.from(kept('server.key', () => randomBytes(32).toString('base64')), 'base64')
@@ -99,7 +113,7 @@ function fromCore(msg: CoreRequest): void {
return
}
if (msg.type === 'auth-result') return waits.get(id ?? '')?.(msg.person ?? (msg.removed ? { removed: true } : undefined))
- if (msg.type === 'join-result' || msg.type === 'invite-info-result') return waits.get(id ?? '')?.((msg as unknown as { data: unknown }).data)
+ if (msg.type === 'join-result' || msg.type === 'invite-info-result' || msg.type === 'device-key-result') return waits.get(id ?? '')?.((msg as unknown as { data: unknown }).data)
if (msg.type === 'access-result') return waits.get(id ?? '')?.((msg as unknown as { ok: boolean }).ok)
// Removed, or their role changed: what the server remembered of them goes (see personNotice).
if (personNotice(msg, { signins, grants, viewers, streams })) return
@@ -266,12 +280,17 @@ 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)
+ 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)
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).
if (doorOf(url.pathname, req.method, url.searchParams.has('invite')) === 'join' && !sameToken(offered)) {
if (doors.blocked('join', ip)) return void res.writeHead(429, { ...BASE_HEADERS, 'retry-after': '600' }).end()
- if (req.method === 'GET') return void invitePageFor(res, url.searchParams.get('invite') ?? '')
+ if (req.method === 'GET') return void invitePageFor(req, res, url.searchParams.get('invite') ?? '')
return void joinPage(req, res, ip)
}
// The link with ?token= signs this browser in, then drops it from the address bar. Lax, not
@@ -298,11 +317,55 @@ function handle(req: IncomingMessage, res: ServerResponse): void {
}
// An invite that brings someone back comes with their name filled in (they can still change it).
-async function invitePageFor(res: ServerResponse, code: string): Promise<void> {
+// An app asks for JSON (accept: application/json): whose Tucano it is, and that name.
+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) : undefined
+ if (wantsJson(req)) return json(res, 200, { owner: ownerName, ...(info?.name ? { name: info.name } : {}) })
page200(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 {
@@ -313,18 +376,26 @@ function page200(res: ServerResponse, html: string, status = 200): void {
// A code that's wrong, used or expired counts as a guess.
async function joinPage(req: IncomingMessage, res: ServerResponse, ip: string): Promise<void> {
if (!sameOrigin(req)) return void res.writeHead(403, BASE_HEADERS).end()
+ // An app (the phone) sends JSON and reads JSON: the key itself, never a cookie.
+ const app = /application\/json/.test(String(req.headers['content-type'] ?? ''))
let fields: { code: string; name: string }
try {
fields = joinFields(await body(req, 16 * 1024), req.headers['content-type'])
} catch {
return void res.writeHead(413, BASE_HEADERS).end()
}
- if (!fields.name.trim()) return page200(res, invitePage({ owner: ownerName, code: fields.code, error: 'Diga seu nome. · Tell us your name.' }), 400)
+ 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)
+ }
const out = await ask<{ key?: string; error?: string }>({ type: 'join', code: fields.code, name: fields.name })
if (!out?.key) {
doors.fail('join', ip)
- return page200(res, invitePage({ owner: ownerName, code: fields.code, name: fields.name, error: out?.error ?? 'O Tucano não respondeu. Tente de novo. · Tucano didn’t answer. Try again.' }), 400)
+ 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)
}
+ if (app) return json(res, 200, { key: out.key })
const secure = req.headers['x-forwarded-proto'] === 'https' ? '; Secure' : ''
res.writeHead(302, { ...BASE_HEADERS, 'set-cookie': `tucano=${out.key}; HttpOnly; SameSite=Lax; Path=/; Max-Age=31536000${secure}`, location: './', 'cache-control': 'no-store' }).end()
}
@@ -341,7 +412,14 @@ function authed(req: IncomingMessage, res: ServerResponse, url: URL, who: Who):
function signedIn(req: IncomingMessage, res: ServerResponse, url: URL, who: Who): void {
// Signed in, but asked from another site's page: a sibling subdomain shares the cookie's site.
- if ((url.pathname === '/events' || url.pathname === '/rpc' || url.pathname === '/upload' || url.pathname === '/viewing') && !sameOrigin(req)) return void res.writeHead(403, BASE_HEADERS).end()
+ if ((url.pathname === '/events' || url.pathname === '/rpc' || url.pathname === '/upload' || url.pathname === '/viewing' || url.pathname === '/pair/new') && !sameOrigin(req)) return void res.writeHead(403, BASE_HEADERS).end()
+
+ // Conectar um celular: a one-time code for whoever asks (their own person), as the link the phone
+ // opens and as the browser's.
+ if (url.pathname === '/pair/new' && req.method === 'POST') {
+ const { code, expiresAt } = pairCodes.make(who.owner ? null : who.person)
+ return json(res, 200, { code, link: pairingLink({ origin: publicUrl, code }), browser: `${publicUrl}/?code=${code}`, expiresAt })
+ }
// A file sent from the person's computer (a vault's .zip): straight to disk, in parts, into a
// folder of the server's own; the core takes it from there and deletes it when done.
diff --git a/src/server/pair-codes.ts b/src/server/pair-codes.ts
new file mode 100644
index 0000000..44f991a
--- /dev/null
+++ b/src/server/pair-codes.ts
@@ -0,0 +1,97 @@
+// 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.
+//
+// `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.
+import { createHash, randomBytes } from 'node:crypto'
+import { chmodSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs'
+
+export const CODE_MINUTES = 10
+export const MAX_CODE_MINUTES = 7 * 24 * 60
+export const CODE_SHAPE = /^[A-Za-z0-9_-]{16,64}$/
+
+interface Saved {
+ hash: string
+ expires: number
+ person: string | null // null: the owner (the server's own `pair`, or the owner's token)
+}
+
+const hashOf = (code: string): string => createHash('sha256').update(code).digest('base64url')
+
+// How long a code asked for lives: whole minutes, 1 to a week.
+export const codeMinutes = (asked: unknown): number => Math.min(MAX_CODE_MINUTES, Math.max(1, Math.floor(Number(asked)) || CODE_MINUTES))
+
+export class PairCodes {
+ private codes: Saved[] = []
+ private mtime = -2
+
+ constructor(
+ private file: string,
+ private now: () => number = Date.now
+ ) {}
+
+ // Read again when another process (`server.js pair`) wrote it.
+ private load(): void {
+ let m = -1
+ try {
+ m = statSync(this.file).mtimeMs
+ } catch {}
+ if (m === this.mtime) return
+ this.mtime = m
+ try {
+ const s = JSON.parse(readFileSync(this.file, 'utf8')) as { codes?: unknown }
+ this.codes = Array.isArray(s.codes) ? (s.codes as Saved[]).filter((c) => typeof c?.hash === 'string' && typeof c.expires === 'number') : []
+ } catch {
+ this.codes = []
+ }
+ }
+
+ private save(): void {
+ this.codes = this.codes.filter((c) => c.expires > this.now())
+ const tmp = `${this.file}.${process.pid}.tmp`
+ writeFileSync(tmp, JSON.stringify({ codes: this.codes }), { mode: 0o600 })
+ renameSync(tmp, this.file)
+ chmodSync(this.file, 0o600)
+ this.mtime = statSync(this.file).mtimeMs
+ }
+
+ // A new code for a person (null: the owner), good for `minutes`.
+ make(person: string | null, minutes = CODE_MINUTES): { code: string; expiresAt: number } {
+ this.load()
+ const code = randomBytes(18).toString('base64url')
+ const expiresAt = this.now() + codeMinutes(minutes) * 60_000
+ this.codes.push({ hash: hashOf(code), expires: expiresAt, person })
+ this.save()
+ return { code, expiresAt }
+ }
+
+ // 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 undefined
+ this.load()
+ const h = hashOf(code)
+ const found = this.codes.find((c) => c.hash === h)
+ if (!found) return undefined
+ this.codes = this.codes.filter((c) => c !== found)
+ this.save()
+ return found.expires > this.now() ? { person: found.person ?? null } : undefined
+ }
+}
+
+// What a device says it is, as the label its key keeps: never trusted, only shown.
+export function deviceLabel(name: unknown, platform: unknown): string {
+ const clean = (s: unknown, max: number): string => (typeof s === 'string' ? s.replace(/[\p{Cc}\p{Cf}]/gu, ' ').replace(/\s+/g, ' ').trim().slice(0, max) : '')
+ const n = clean(name, 80)
+ const p = clean(platform, 20).toLowerCase()
+ return [n || 'Aparelho', p].filter(Boolean).join(' · ')
+}
+
+// A browser's User-Agent, as a short name for the device it signs in.
+export function browserName(ua: string): string {
+ const b = /Edg\//.test(ua) ? 'Edge' : /Firefox\//.test(ua) ? 'Firefox' : /Chrome\//.test(ua) ? 'Chrome' : /Safari\//.test(ua) ? 'Safari' : 'Navegador'
+ const os = /iPhone/.test(ua) ? 'iPhone' : /iPad/.test(ua) ? 'iPad' : /Android/.test(ua) ? 'Android' : /Mac OS X/.test(ua) ? 'macOS' : /Windows/.test(ua) ? 'Windows' : /Linux/.test(ua) ? 'Linux' : ''
+ return os ? `${b} · ${os}` : b
+}
diff --git a/src/shared/rpc-shapes.ts b/src/shared/rpc-shapes.ts
index 57c8ea4..efa12be 100644
--- a/src/shared/rpc-shapes.ts
+++ b/src/shared/rpc-shapes.ts
@@ -147,6 +147,7 @@ export const SHAPES: Record<Method, Record<string, string>> = {
removePerson: { id: 's' },
setRole: { id: 's', role: 's' },
purgePerson: { id: 's' },
+ leave: {},
activity: { personId: 's?', kind: 's?', before: 'n?' },
inbox: {},
answerQuestion: { id: 's', text: 's' },
diff --git a/src/shared/rpc.ts b/src/shared/rpc.ts
index 6d99f70..5f69a3c 100644
--- a/src/shared/rpc.ts
+++ b/src/shared/rpc.ts
@@ -174,6 +174,7 @@ export interface Api {
removePerson(p: { id: string }): void // their access ends at once: keys gone, open connections closed; what they owned goes to the owner
setRole(p: { id: string; role: Exclude<Role, 'owner'> }): void
purgePerson(p: { id: string }): void // the owner, before the 30 days: a removed person's DMs and memories go now
+ leave(): void // someone (not the owner) leaves on their own: access ends, and their DMs, memories and own routines go now
activity(p: { personId?: string; kind?: string; before?: number }): ActivityEntry[] // admins: newest first, a page at a time (before: the last page's oldest `at`)
inbox(): Inbox
answerQuestion(p: { id: string; text: string }): void // a question an agent asked me (or someone I cover for)
diff --git a/src/shared/servers.ts b/src/shared/servers.ts
index 59ea470..1c316dd 100644
--- a/src/shared/servers.ts
+++ b/src/shared/servers.ts
@@ -1,6 +1,7 @@
// A Tucano on a server, opened from this app: the link that pairs it, and what belongs to it.
//
// tucano://connect?url=https://ana.example.com&token=… (`server.js link` prints it)
+// tucano://connect?url=https://ana.example.com&code=… (a one-time code: `server.js pair`, for the phone)
export interface Pairing {
origin: string // https://ana.example.com, nothing after it
@@ -32,8 +33,10 @@ export function parsePairing(link: string): Pairing | null {
return { origin: server.origin, token }
}
-// The link that pairs it again (`server.js link` prints the first one).
-export const pairingLink = (p: Pairing): string => `tucano://connect?url=${encodeURIComponent(p.origin)}&token=${encodeURIComponent(p.token)}`
+// 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)}`}`
// 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/pair.test.ts b/test/pair.test.ts
new file mode 100644
index 0000000..ffdd71d
--- /dev/null
+++ b/test/pair.test.ts
@@ -0,0 +1,124 @@
+// Signing a phone in: one-time codes (src/server/pair-codes.ts) that become a key of a person's own
+// (People.deviceKey), for the owner as for anyone invited.
+import { mkdtempSync, readFileSync, statSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { describe, expect, it } from 'vitest'
+import { Db } from '../src/core/db'
+import { People } from '../src/core/people'
+import { browserName, CODE_MINUTES, codeMinutes, deviceLabel, MAX_CODE_MINUTES, PairCodes } from '../src/server/pair-codes'
+import { Doors, signIn } from '../src/server/guard'
+import { pairingLink, parsePairing } from '../src/shared/servers'
+
+const file = (): string => join(mkdtempSync(join(tmpdir(), 'tucano-pair-')), 'pair-codes.json')
+
+describe('one-time pairing codes', () => {
+ it('are good once, for whom they were made, and the file keeps only their hash', () => {
+ const f = file()
+ const codes = new PairCodes(f)
+ const { code, expiresAt } = codes.make('bia')
+ expect(code).toMatch(/^[A-Za-z0-9_-]{24}$/)
+ expect(expiresAt - Date.now()).toBeGreaterThan((CODE_MINUTES - 1) * 60_000)
+ if (process.platform !== 'win32') expect(statSync(f).mode & 0o777).toBe(0o600) // Windows has no Unix modes
+ expect(readFileSync(f, 'utf8')).not.toContain(code)
+ expect(codes.spend(code)).toEqual({ person: 'bia' })
+ expect(codes.spend(code)).toBeUndefined()
+ })
+
+ it("are the owner's when made with no one (the server's `pair`)", () => {
+ const codes = new PairCodes(file())
+ expect(codes.spend(codes.make(null).code)).toEqual({ person: null })
+ })
+
+ it('are spent even when late, and a wrong or odd one opens nothing', () => {
+ let now = 1_000_000
+ const codes = new PairCodes(file(), () => now)
+ const { code } = codes.make(null, 1)
+ now += 61_000
+ expect(codes.spend(code)).toBeUndefined()
+ now -= 61_000
+ expect(codes.spend(code)).toBeUndefined() // gone, not just late
+ for (const x of ['', 'short', 'x'.repeat(65), 'a b c d e f g h i j k', 42, null]) expect(codes.spend(x)).toBeUndefined()
+ })
+
+ it('made by another process (`server.js pair`) are seen by the running server', () => {
+ const f = file()
+ const server = new PairCodes(f)
+ expect(server.spend('A'.repeat(24))).toBeUndefined() // read once, empty
+ const { code } = new PairCodes(f).make(null)
+ expect(server.spend(code)).toEqual({ person: null })
+ })
+
+ it('last whole minutes, one to a week', () => {
+ expect(codeMinutes(undefined)).toBe(CODE_MINUTES)
+ expect(codeMinutes('abc')).toBe(CODE_MINUTES)
+ expect(codeMinutes('0')).toBe(CODE_MINUTES)
+ expect(codeMinutes('-5')).toBe(1)
+ expect(codeMinutes('30')).toBe(30)
+ expect(codeMinutes(String(10 * MAX_CODE_MINUTES))).toBe(MAX_CODE_MINUTES)
+ })
+
+ it('name the device from what it says, never trusting it', () => {
+ expect(deviceLabel('iPhone de Ana', 'iOS')).toBe('iPhone de Ana · ios')
+ expect(deviceLabel('a\u0000b‮c', undefined)).toBe('a b c')
+ expect(deviceLabel(undefined, undefined)).toBe('Aparelho')
+ expect(deviceLabel('x'.repeat(500), 'p'.repeat(50)).length).toBeLessThanOrEqual(80 + 3 + 20)
+ expect(browserName('Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 Version/18.0 Mobile/15E148 Safari/604.1')).toBe('Safari · iPhone')
+ })
+})
+
+describe('the link a code makes', () => {
+ it('carries the code, not a token, and the token link still reads', () => {
+ expect(pairingLink({ origin: 'https://ana.example.com', code: 'abcDEF123_-abcDEF123_-ab' })).toBe('tucano://connect?url=https%3A%2F%2Fana.example.com&code=abcDEF123_-abcDEF123_-ab')
+ const p = { origin: 'https://ana.example.com', token: 'abcdefghijklmnopqrstuvwxyz' }
+ expect(parsePairing(pairingLink(p))).toEqual(p)
+ })
+})
+
+describe('a key of a device of its own', () => {
+ const team = (): { db: Db; people: People } => {
+ const db = new Db(':memory:')
+ db.renamePerson(db.ownerId(), 'Ana')
+ return { db, people: new People(db) }
+ }
+
+ it("signs the owner in as themselves, counted as one more device", () => {
+ const { db, people } = team()
+ const out = people.deviceKey(null, 'iPhone de Ana · ios')!
+ expect(out.key).toMatch(/^p_[\w-]{43}$/)
+ const who = people.authenticate(out.key)!
+ expect(who.id).toBe(db.ownerId())
+ expect(who.role).toBe('owner')
+ expect(db.people().find((p) => p.id === db.ownerId())!.devices).toBe(1)
+ })
+
+ it('signs someone invited in as them, and stops when they are removed', () => {
+ const { db, people } = team()
+ const { code } = people.createInvite(db.owner(), { role: 'member' })
+ const joined = people.join(code, 'Bia')
+ if (!('person' in joined)) throw new Error(joined.error)
+ const phone = people.deviceKey(joined.person.id, 'iPhone · ios')!
+ expect(people.authenticate(phone.key)!.id).toBe(joined.person.id)
+ expect(db.people().find((p) => p.id === joined.person.id)!.devices).toBe(2) // the invite's browser and the phone
+ people.remove(db.owner(), joined.person.id)
+ expect(people.authenticate(phone.key)).toBeUndefined()
+ expect(people.removedKey(phone.key)).toBe(true)
+ expect(people.deviceKey(joined.person.id, 'x')).toBeUndefined()
+ })
+
+ it('is no one for an unknown person', () => {
+ expect(team().people.deviceKey('nobody', 'x')).toBeUndefined()
+ expect(team().people.deviceKey(42, 'x')).toBeUndefined()
+ })
+
+ it("opens the server for the owner by a person's key, never by guessing", async () => {
+ const { people } = team()
+ const { key } = people.deviceKey(null, 'phone')!
+ const lookup = async (k: string) => ({ person: people.authenticate(k) })
+ const base = { ip: '1.2.3.4', doors: new Doors(), isOwnerToken: () => false, strongOwnerToken: true, lookup }
+ const r = await signIn({ ...base, cookie: key })
+ expect(r.status).toBe('person')
+ expect(r.status === 'person' && r.person.role).toBe('owner')
+ expect((await signIn({ ...base, cookie: `p_${'x'.repeat(43)}` })).status).toBe('unauthorized')
+ })
+})
diff --git a/test/people.test.ts b/test/people.test.ts
index 1b531e0..8a9f4a9 100644
--- a/test/people.test.ts
+++ b/test/people.test.ts
@@ -270,6 +270,33 @@ describe('invites, keys and removal', () => {
})
})
+describe('leaving on one\'s own', () => {
+ it('ends access now and takes what was theirs alone with it; the owner cannot leave', () => {
+ const db = new Db(':memory:')
+ const people = new People(db)
+ const owner = db.owner()
+ const joined = people.join(people.createInvite(owner, { role: 'member' }).code, 'Bia')
+ if (!('person' in joined)) throw new Error(joined.error)
+ const bia = joined.person
+ db.saveAgent(agent('a1', 'lia'))
+ db.createConversation({ id: 'bia-dm', kind: 'dm', name: 'a1', members: ['a1'], owner: bia.id })
+ db.createConversation({ id: 'ch', kind: 'channel', name: 'geral', members: ['a1'] })
+ db.saveMessage({ id: 'm1', conversationId: 'bia-dm', author: { kind: 'person', id: bia.id }, text: 'só meu', at: 1 })
+ db.saveMessage({ id: 'm2', conversationId: 'ch', author: { kind: 'person', id: bia.id }, text: 'pro time', at: 2 })
+ db.saveMemory({ id: 'k', scope: personScope(bia.id), text: 'da Bia', state: 'active', origin: 'me', messageIds: [], createdAt: 1, confirmedAt: 1 })
+
+ expect(() => people.leave(owner)).toThrow()
+ const out = people.leave(bia)
+ expect(out.purged.dms).toEqual(['bia-dm'])
+ expect(people.authenticate(joined.key)).toBeUndefined()
+ expect(db.people().map((p) => p.id)).toEqual([owner.id])
+ expect(db.conversation('bia-dm')).toBeUndefined()
+ expect(db.memories().some((m) => m.id === 'k')).toBe(false)
+ expect(db.messages().map((m) => m.id)).toEqual(['m2']) // what was said in a channel stays the channel's
+ expect(db.removedPeople().some((p) => p.id === bia.id)).toBe(false) // nothing kept for a re-invite
+ })
+})
+
describe('a reply, with people', () => {
let db: Db
let turns: Turn[]