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.

Make Tucano as a server ready for other people to use (#163)

Eduardo Machado66d102fa0c52
diff --git a/docs/server.md b/docs/server.md
index dde0c92..9bee9bf 100644
--- a/docs/server.md
+++ b/docs/server.md
@@ -26,13 +26,13 @@ npm run build
npm run server
```
-It prints the address to open:
+Then, in another terminal, get the link that signs a browser in:
-```
-Tucano server: http://127.0.0.1:7337/?token=…
+```bash
+npm run server -- link # http://127.0.0.1:7337/?token=…
```
-Open that link once. The token signs the browser in, and a cookie keeps it signed in. The token lives in `~/.tucano-server/server-token`. To sign every browser out, delete that file and restart Tucano.
+Open that link once. The token signs the browser in, and a cookie keeps it signed in. The token lives in `~/.tucano-server/server-token`, and `link` is the only thing that prints it: the log never does. To sign every browser out, delete that file and restart Tucano.
### Signing the harnesses in
@@ -51,7 +51,7 @@ By default the server only listens on the server itself (`127.0.0.1`), because a
- **SSH tunnel**, the simplest: run `ssh -L 7337:127.0.0.1:7337 you@your-server`, then open the printed link on your computer.
- **Tailscale** (or another private network): set `TUCANO_HOST` to the server's Tailscale address, then open `http://<that address>:7337/?token=…` from any of your devices, including your phone.
-- **A reverse proxy with HTTPS** (Caddy, nginx) on a domain of yours: keep Tucano on `127.0.0.1` and point the proxy at it. Turn off response buffering for `/events`, which is a live event stream. For example, with Caddy:
+- **A reverse proxy with HTTPS** (Caddy, nginx) on a domain of yours: keep Tucano on `127.0.0.1` and point the proxy at it. Set `TUCANO_URL` to the address people open, so `link` prints it, and `TUCANO_TRUST_PROXY=1`, so wrong tokens are counted per visitor rather than all as the proxy. Turn off response buffering for `/events`, which is a live event stream, and keep the proxy's access log off or without query strings, since the first link carries the token. For example, with Caddy:
```
tucano.example.com {
@@ -83,7 +83,7 @@ Environment=TUCANO_PORT=7337
WantedBy=multi-user.target
```
-Then run `sudo systemctl enable --now tucano`. The logs, including the address with the token, are in `journalctl -u tucano`.
+Then run `sudo systemctl enable --now tucano`. The logs are in `journalctl -u tucano`; the link to sign in comes from `npm run server -- link`, run as the same user in the same folder.
To update Tucano, run `git pull && npm ci && npm run build && sudo systemctl restart tucano`.
@@ -95,6 +95,10 @@ To update Tucano, run `git pull && npm ci && npm run build && sudo systemctl res
| `TUCANO_HOST` | `127.0.0.1` | The address to listen on |
| `TUCANO_PORT` | `7337` | |
| `TUCANO_TOKEN` | a random token, kept in `server-token` | Set it to use a token of your own |
+| `TUCANO_URL` | where it listens | The address people open, behind a proxy (`https://tucano.example.com`): what `link` prints |
+| `TUCANO_TRUST_PROXY` | off | `1` behind a reverse proxy: each visitor's address comes from `X-Forwarded-For` |
+
+Once a browser has the cookie, the server answers only its own page: a page of another site (a sibling subdomain included) can't call it, and no site can show it inside a frame. Twenty wrong tokens from one address in ten minutes lock that address out for ten minutes.
## How it differs from the desktop app
@@ -102,7 +106,7 @@ To update Tucano, run `git pull && npm ci && npm run build && sudo systemctl res
- **Secrets** (connector keys, Telegram, GitHub) are encrypted with AES-256-GCM. The key is in `server.key` in the data folder, and only your user can read that file. A desktop app keeps that key in the system's keychain instead. Back the key up together with the data folder: the secrets can't be read without it.
- **Notifications:** connect Telegram (**Settings › Phone and GitHub**) to get approvals, questions and results on your phone. The browser doesn't pop up notifications.
- **Agents' browsers** need Chromium or Chrome on the server, and run without a window. **Take over** doesn't open a window there: the live picture of the browser in the panel becomes the browser. Click on it, type, paste and scroll, then click **Hand back**. This is how you sign in to a site for an agent.
-- **Pages agents serve** (a dashboard, an API) listen on the server's own `127.0.0.1`. Agents take their screenshots with the server's Chrome. When Tucano listens on a private address (Tailscale or a home network), it also passes each running page through on the same port at that address, so the preview panel and **Open** work from your computer. That doesn't happen on a public address, because those pages have no token. Over an SSH tunnel, forward the page's port too (`-L 5173:127.0.0.1:5173`).
+- **Pages agents serve** (a dashboard, an API), behind a reverse proxy with HTTPS (`TUCANO_URL`): each opens at `https://<port>-<your address>`, with a sign-in of its own that Tucano hands the panel. The proxy has to send those names to Tucano too (`*.tucano.example.com`, with a certificate for each name: Caddy's on-demand TLS does it). Otherwise, they listen on the server's own `127.0.0.1`. Agents take their screenshots with the server's Chrome. When Tucano listens on a private address (Tailscale or a home network), it also passes each running page through on the same port at that address, so the preview panel and **Open** work from your computer. That doesn't happen on a public address, because those pages have no token. Over an SSH tunnel, forward the page's port too (`-L 5173:127.0.0.1:5173`).
- **Choosing a folder** asks for its path on the server, since the browser can't browse the server's disk.
- **No self-update.** Update with `git pull` (see above).
- **One Tucano per data folder.** Don't run the desktop app and the server on the same data folder at the same time.
diff --git a/src/core/chrome.ts b/src/core/chrome.ts
index 8b63ae6..c37eebb 100644
--- a/src/core/chrome.ts
+++ b/src/core/chrome.ts
@@ -216,6 +216,10 @@ export class ChromeBrowsers {
private tabs = new Map<string, Tab>()
private starting = new Map<string, Promise<Tab>>()
private handingBack = new Set<string>()
+ private used = new Map<string, number>() // when each agent last asked its Chrome for something
+ private busy = new Map<string, number>() // what it's doing right now
+ private resumeAt = new Map<string, string>() // the page a Chrome closed for idling was on
+ private closing = new Map<string, Promise<void>>() // a Chrome closed for idling, still writing its cookies
constructor(
private dir: string, // profiles live in <dir>/<agentId>
@@ -224,9 +228,35 @@ export class ChromeBrowsers {
private onFrame?: OnFrame,
// No screen to open a window on (Tucano as a server): taking over keeps it
// headless and I drive it from the panel, through 'input'.
- private windowless = false
+ private windowless = false,
+ // A Chrome nobody asked anything of for this long is closed (cookies kept) and reopens on the
+ // same page when next needed: on a server several people share, each costs hundreds of MB.
+ private idleMs?: number
) {
process.on('exit', () => this.quit())
+ if (idleMs) setInterval(() => void this.closeIdle(), Math.min(60_000, Math.max(100, idleMs / 2))).unref()
+ }
+
+ running(agentId: string): boolean {
+ return this.tabs.has(agentId)
+ }
+
+ // Not one taken over (the person is on it), nor one handing back or in the middle of something.
+ private async closeIdle(): Promise<void> {
+ const now = Date.now()
+ for (const [agentId, t] of this.tabs) {
+ if (t.headed || this.handingBack.has(agentId) || this.starting.has(agentId) || (this.busy.get(agentId) ?? 0) > 0) continue
+ if (now - (this.used.get(agentId) ?? now) < this.idleMs!) continue
+ this.tabs.delete(agentId)
+ if (/^https?:/.test(t.url)) this.resumeAt.set(agentId, t.url)
+ // Until it's gone, a new one for this agent waits: started on the same profile, it would
+ // take it over from the one still writing its cookies, and the login would be lost.
+ const done = this.shutDown(t)
+ .catch(() => {})
+ .finally(() => this.closing.get(agentId) === done && this.closing.delete(agentId))
+ this.closing.set(agentId, done)
+ await done
+ }
}
quit(): void {
@@ -294,7 +324,8 @@ export class ChromeBrowsers {
private async shutDown(t: Tab): Promise<void> {
t.closedAll = undefined // this is the app closing it, not the person handing it back
await Promise.race([t.send('Browser.close').catch(() => {}), wait(2000)])
- await exited(t.proc, 5000)
+ // Usually under a second; a loaded machine (a server, CI) can take several to write them.
+ await exited(t.proc, 15_000)
t.close()
await gone(t.proc)
}
@@ -305,7 +336,15 @@ export class ChromeBrowsers {
if (t) return t
const going = this.starting.get(agentId)
if (going) return going
- const p = this.launch(agentId, false).finally(() => this.starting.delete(agentId))
+ const back = this.resumeAt.get(agentId)
+ this.resumeAt.delete(agentId)
+ const closing = this.closing.get(agentId)
+ const p = (closing ? closing.then(() => this.launch(agentId, false, back)) : this.launch(agentId, false, back))
+ .then(async (tab) => {
+ if (back) await this.settle(tab)
+ return tab
+ })
+ .finally(() => this.starting.delete(agentId))
this.starting.set(agentId, p)
return p
}
@@ -332,7 +371,19 @@ export class ChromeBrowsers {
}
async run(agentId: string, op: BrowserOp, args: Record<string, unknown> = {}): Promise<BrowserReply> {
+ this.used.set(agentId, Date.now())
+ this.busy.set(agentId, (this.busy.get(agentId) ?? 0) + 1)
+ try {
+ return await this.runOp(agentId, op, args)
+ } finally {
+ this.busy.set(agentId, (this.busy.get(agentId) ?? 1) - 1)
+ this.used.set(agentId, Date.now())
+ }
+ }
+
+ private async runOp(agentId: string, op: BrowserOp, args: Record<string, unknown>): Promise<BrowserReply> {
if (op === 'close' || op === 'clear') {
+ this.resumeAt.delete(agentId)
const t = this.tabs.get(agentId)
this.tabs.delete(agentId)
if (t && op === 'close') await this.shutDown(t)
diff --git a/src/core/index.ts b/src/core/index.ts
index b815239..bc95531 100644
--- a/src/core/index.ts
+++ b/src/core/index.ts
@@ -5,10 +5,10 @@ import { voiceRefusal } from '../shared/voice'
import { ModelDownload, Transcriber, voiceStatus, warmUp } from './transcribe'
import { createHash } from 'node:crypto'
import { execFile, spawn } from 'node:child_process'
-import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { userInfo } from 'node:os'
import { isLimited, localUrl, resolveLocal, type LocalReach } from './local-paths'
-import { basename, join } from 'node:path'
+import { basename, join, resolve, sep } from 'node:path'
import { randomUUID } from 'node:crypto'
import type { MessagePortMain } from 'electron'
import { L, langOf, locale, setLang, type Lang } from '../shared/lang'
@@ -45,7 +45,7 @@ import { WikiReviewer } from './wiki-review'
import { extractFile, extractLink } from './wiki-extract'
import { backup, backupIfDue, exportTeam, importTeam } from './team'
import { applyForeignTeam, readForeignZip } from './agent-import'
-import { zipFromBuffer, zipFromFile } from './zip'
+import { extractZip, zipFromBuffer, zipFromFile } from './zip'
import { Telegram } from './telegram'
import { mainCipher, plainCipher, Secrets } from './secrets'
import { Browser, type BrowserHost } from './browser'
@@ -66,6 +66,7 @@ const dataDir = process.env['TUCANO_DATA'] ?? join(process.cwd(), '.tucano')
const fake = process.env['TUCANO_FAKE_ENGINES'] === '1'
// Run by the server (src/server): no window, and the screens are in a browser elsewhere.
const serverMode = process.env['TUCANO_SERVER'] === '1'
+const publicUrl = process.env['TUCANO_URL']?.replace(/\/+$/, '')
const runtimePorts = workspacePorts()
const defaultWorkspace = process.env['TUCANO_DEFAULT_WORKSPACE'] !== '0'
mkdirSync(dataDir, { recursive: true })
@@ -367,6 +368,17 @@ process.parentPort.on('message', (e) => {
return
}
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') {
+ const { state = '', code = '', error = '' } = (r.data ?? {}) as { state?: string; code?: string; error?: string }
+ const reply = (ok: boolean, why?: string): void => process.parentPort.postMessage({ type: 'oauth-result', id: r.id, data: { ok, why } })
+ if (!code) return reply(false, error === 'access_denied' ? L('Você recusou o acesso na página do serviço.', 'You declined access on the service’s page.') : L('A autorização não voltou com o código.', 'The authorization came back without a code.'))
+ void connectors.finishOAuth(state, code).then(
+ (ok) => reply(ok, ok ? undefined : L('Esse pedido de autorização venceu. Tente de novo pelo app.', 'That authorization request expired. Try again from the app.')),
+ (e: unknown) => reply(false, e instanceof Error ? e.message : String(e))
+ )
+ return
+ }
if (r?.type === 'browser-shown') return browser.setShown(r.agentId ?? '', r.shown === true)
if (r?.type === 'browser-result') {
const p = pages.get(r.id)
@@ -468,7 +480,8 @@ const chrome =
(agentId, shown) => browser.setShown(agentId, shown),
undefined,
(agentId, jpeg) => browser.frame(agentId, jpeg),
- serverMode
+ serverMode,
+ serverMode ? 10 * 60_000 : undefined // on a server, an idle agent's Chrome gives its memory back
)
: undefined
const host: BrowserHost = chrome ? (agentId, op, args) => chrome.run(agentId, op, args) : electronHost
@@ -490,7 +503,8 @@ delete process.env['TUCANO_LOCAL_KEY']
// computer, and not on Windows yet, where paths don't look like this.
function localReach(messageId: string): LocalReach | undefined {
const message = db.message(messageId)
- if (serverMode || isWin || message?.author.kind !== 'agent') return undefined
+ // On a server a cited file is saved down instead of shown in Finder (src/server's /local/), so it counts there too.
+ if (isWin || message?.author.kind !== 'agent') return undefined
const agent = db.agent(message.author.id)
if (!agent) return undefined
return { agentId: agent.id, own: computers.folder(agent.id), dataRoot: dataDir, limited: isLimited(agent) }
@@ -518,7 +532,9 @@ const connectors = new ConnectorManager({
emit,
// On a server there's nothing to open it in: authorizeConnector hands it to the page.
openUrl: (url) => serverMode || toMain({ type: 'open', url }),
- oauthCallbackUrl: () => gateway.url('/oauth/callback')
+ // On a server behind https (TUCANO_URL), the provider sends the person back to the server's own
+ // address, which src/server hands over here; on a desktop, to the gateway on this computer.
+ oauthCallbackUrl: () => (serverMode && publicUrl?.startsWith('https://') ? `${publicUrl}/oauth/callback` : gateway.url('/oauth/callback'))
})
gateway.route('/oauth/callback', async (url) => {
const code = url.searchParams.get('code')
@@ -837,6 +853,9 @@ const api: Api = {
skills: db.skills(),
platform: osOf(),
packaged: process.env['TUCANO_PACKAGED'] === '1',
+ // On a desktop it's always offered (the page says when Docker is missing); a server without Docker,
+ // inside a container, can't have one, so it isn't.
+ isolatedComputers: !serverMode || onPath('docker'),
demoServer: existsSync(demoPath) ? { command: 'node', args: [demoPath] } : undefined
}),
@@ -918,7 +937,11 @@ const api: Api = {
const reach = localReach(messageId)
const found = reach && resolveLocal(path, reach)
if (!found) return null
- return { kind: found.kind, ...((found.kind === 'image' || found.kind === 'video') && localKey ? { url: localUrl(localKey, found.path) } : {}) }
+ const base = serverMode ? '/local' : undefined
+ const seen = (found.kind === 'image' || found.kind === 'video') && localKey ? { url: localUrl(localKey, found.path, base) } : {}
+ // On a server the file isn't on the person's computer: showing it in Finder means nothing, saving it does.
+ const saved = serverMode && localKey && found.kind !== 'folder' ? { download: `${localUrl(localKey, found.path, base)}?download=1` } : {}
+ return { kind: found.kind, ...seen, ...saved }
},
openLocal: ({ messageId, path, how }) => {
const reach = localReach(messageId)
@@ -1261,6 +1284,21 @@ const api: Api = {
},
wikiDismissFinding: ({ id }) => wiki.dismissFinding(id),
wikiImport: ({ dir }) => wiki.importVault(dir, settings().workspaceName || L('Você', 'You')),
+ // On a server: a vault zipped on the person's computer and sent up. Only from the uploads folder
+ // the server writes to; unpacked apart, copied in as any vault, then both go.
+ wikiImportZip: ({ path }) => {
+ const uploads = join(dataDir, 'uploads')
+ if (!serverMode || typeof path !== 'string' || !resolve(path).startsWith(uploads + sep) || !path.toLowerCase().endsWith('.zip')) throw new Error(L('Envie o vault como um arquivo .zip.', 'Send the vault as a .zip file.'))
+ const unpacked = mkdtempSync(join(uploads, 'vault-'))
+ const zip = zipFromFile(path)
+ try {
+ return wiki.importVault(extractZip(zip, unpacked), settings().workspaceName || L('Você', 'You'))
+ } finally {
+ zip.close()
+ rmSync(unpacked, { recursive: true, force: true })
+ rmSync(path, { force: true })
+ }
+ },
setWikiCapture: ({ conversationId, on }) => {
db.setWikiCapture(conversationId, on)
const c = db.conversation(conversationId)
diff --git a/src/core/local-paths.ts b/src/core/local-paths.ts
index 55e96c0..a963ec4 100644
--- a/src/core/local-paths.ts
+++ b/src/core/local-paths.ts
@@ -65,7 +65,8 @@ export function resolveLocal(raw: string, reach: LocalReach, home = homedir()):
// has checked, and a page in the window can't ask for anything else.
const sign = (key: string, path: string): string => createHmac('sha256', key).update(path).digest('base64url')
-export const localUrl = (key: string, path: string): string => `tucano://local/${sign(key, path)}/${Buffer.from(path).toString('base64url')}`
+// On a desktop the app's tucano: protocol serves it; on a server, its own /local/ path (src/server).
+export const localUrl = (key: string, path: string, base = 'tucano://local'): string => `${base}/${sign(key, path)}/${Buffer.from(path).toString('base64url')}`
export function verifyLocalUrl(key: string, url: URL): string | null {
const [signature = '', encoded = ''] = url.pathname.slice(1).split('/')
diff --git a/src/core/zip.ts b/src/core/zip.ts
index 0fede62..8ae9ec2 100644
--- a/src/core/zip.ts
+++ b/src/core/zip.ts
@@ -1,7 +1,8 @@
// Reads a .zip without a library: the central directory for the list, then only the entries asked for,
-// stored or deflated. Nothing is written to disk. Each entry has a cap, checked before inflating, so a
+// stored or deflated. Nothing is written to disk (extractZip, below, is the one that does). Each entry has a cap, checked before inflating, so a
// small file that claims to unpack into gigabytes is refused. No ZIP64 (files over 4 GB), no encryption.
-import { closeSync, fstatSync, openSync, readSync } from 'node:fs'
+import { closeSync, fstatSync, mkdirSync, openSync, readSync, writeFileSync } from 'node:fs'
+import { dirname, isAbsolute, join } from 'node:path'
import { inflateRawSync } from 'node:zlib'
import { L } from '../shared/lang'
@@ -107,3 +108,26 @@ export function zipFromFile(path: string): Zip {
throw e
}
}
+
+// A whole .zip into a folder (a vault sent from another computer): only plain relative paths
+// (never absolute, never "..", never macOS's __MACOSX copies), each file and the total capped.
+// A single folder at the top, as zipping a folder makes, becomes the root. Returns that root.
+export function extractZip(zip: Zip, to: string, caps = { file: 50 * 1024 * 1024, total: 1024 * 1024 * 1024 }): string {
+ let total = 0
+ const tops = new Set<string>()
+ for (const e of zip.entries.values()) {
+ const name = e.name.replace(/\\/g, '/')
+ if (name.endsWith('/') || name.startsWith('__MACOSX/') || /(^|\/)\.DS_Store$/.test(name)) continue
+ const parts = name.split('/')
+ if (isAbsolute(name) || /^[A-Za-z]:/.test(name) || parts.some((p) => p === '..' || p === '')) throw new Error(L(`O .zip tem um caminho que não pode: ${name}`, `The .zip has a path it can't: ${name}`))
+ total += e.size
+ if (total > caps.total) throw new Error(L('O .zip é grande demais (mais de 1 GB descompactado).', 'The .zip is too big (over 1 GB unpacked).'))
+ const data = zip.read(e.name, caps.file)
+ if (!data) continue
+ const file = join(to, ...parts)
+ mkdirSync(dirname(file), { recursive: true })
+ writeFileSync(file, data)
+ tops.add(parts.length > 1 ? parts[0]! : '')
+ }
+ return tops.size === 1 && !tops.has('') ? join(to, [...tops][0]!) : to
+}
diff --git a/src/renderer/src/components/Conversation.tsx b/src/renderer/src/components/Conversation.tsx
index 4ad3c0b..58ee698 100644
--- a/src/renderer/src/components/Conversation.tsx
+++ b/src/renderer/src/components/Conversation.tsx
@@ -1214,6 +1214,22 @@ async function prepareImage(file: File): Promise<Attached | string> {
// One draft per conversation (and per thread), kept while the app runs: leaving a
// channel doesn't lose the message you were typing.
const drafts = new Map<string, { text: string; images: Attached[] }>()
+// On a server the page reloads to reconnect (src/server's bridge): the texts are kept in this
+// tab for that moment, and come back once. Images aren't: attach them again.
+const RELOAD_KEY = 'tucano-drafts'
+try {
+ const kept = JSON.parse(sessionStorage.getItem(RELOAD_KEY) ?? '{}') as Record<string, string>
+ for (const [k, text] of Object.entries(kept)) if (typeof text === 'string' && text.trim()) drafts.set(k, { text, images: [] })
+ sessionStorage.removeItem(RELOAD_KEY)
+} catch {}
+const keepForReload = (current?: { key: string; text: string }): void => {
+ const texts: Record<string, string> = {}
+ for (const [k, d] of drafts) if (d.text.trim()) texts[k] = d.text
+ if (current?.text.trim()) texts[current.key] = current.text
+ try {
+ sessionStorage.setItem(RELOAD_KEY, JSON.stringify(texts))
+ } catch {}
+}
type DictationState = 'idle' | 'starting' | 'recording' | 'transcribing'
type DictationControls = { press: () => void; release: () => void; stop: () => void; cancel: () => void; startedAt: () => number }
@@ -1479,6 +1495,11 @@ export function Composer({ conversationId, threadId, members, placeholder }: { c
// back keeps it (like a draft). In memory: closing the app drops the drafts.
const live = useRef({ text, images })
live.current = { text, images }
+ useEffect(() => {
+ const save = (): void => keepForReload({ key, text: live.current.text })
+ window.addEventListener('tucano:reloading', save)
+ return () => window.removeEventListener('tucano:reloading', save)
+ }, [key])
useEffect(() => {
const draft = drafts.get(key)
setText(draft?.text ?? '')
@@ -1492,7 +1513,22 @@ export function Composer({ conversationId, threadId, members, placeholder }: { c
}
}, [key])
- const addFiles = async (files: File[]): Promise<void> => {
+ const addFiles = async (all: File[]): Promise<void> => {
+ if (!all.length) return
+ // On a server, a file that isn't an image goes up to it (~/Enviados) and the message says where:
+ // an agent on that computer opens it there, and the link brings it back down.
+ const upload = window.tucano.upload
+ const files = upload ? all.filter((f) => IMAGE_MIMES.includes(f.type)) : all
+ const others = upload ? all.filter((f) => !IMAGE_MIMES.includes(f.type)) : []
+ if (others.length && upload) {
+ setNote(L(`Enviando ${others.length === 1 ? others[0]!.name : `${others.length} arquivos`}…`, `Sending ${others.length === 1 ? others[0]!.name : `${others.length} files`}…`))
+ const sent = await Promise.allSettled(others.map((f) => upload(f, 'message')))
+ const paths = sent.flatMap((r) => (r.status === 'fulfilled' ? [r.value] : []))
+ if (paths.length) setText((t) => `${t.trim() ? `${t.trimEnd()}\n` : ''}${paths.map((p) => L(`Arquivo enviado: \`${p}\``, `File sent: \`${p}\``)).join('\n')}`)
+ const failed = sent.find((r): r is PromiseRejectedResult => r.status === 'rejected')
+ setNote(failed ? String(failed.reason instanceof Error ? failed.reason.message : failed.reason) : '')
+ if (!files.length) return void ref.current?.focus()
+ }
if (!files.length) return
const done = await Promise.all(files.map(prepareImage))
const ok = done.filter((d): d is Attached => typeof d !== 'string')
@@ -1713,7 +1749,7 @@ export function Composer({ conversationId, threadId, members, placeholder }: { c
if (e.target.value.trim()) typing(conversationId, threadId)
}}
onPaste={(e) => {
- const files = [...e.clipboardData.files].filter((f) => f.type.startsWith('image/'))
+ const files = [...e.clipboardData.files].filter((f) => window.tucano.upload || f.type.startsWith('image/'))
if (!files.length) return
e.preventDefault()
void addFiles(files)
@@ -1740,13 +1776,13 @@ export function Composer({ conversationId, threadId, members, placeholder }: { c
</div>
<div className="composer__bar">
<VoiceButton controls={voiceControls} state={voice} />
- <button className="icon-btn" title={L('Anexar imagem (ou arraste e solte, ou cole)', 'Attach an image (or drag and drop, or paste)')} onClick={() => picker.current?.click()}>
+ <button className="icon-btn" title={window.tucano.upload ? L('Anexar arquivo (ou arraste e solte, ou cole)', 'Attach a file (or drag and drop, or paste)') : L('Anexar imagem (ou arraste e solte, ou cole)', 'Attach an image (or drag and drop, or paste)')} onClick={() => picker.current?.click()}>
<Icon name="image" size={15} />
</button>
<input
ref={picker}
type="file"
- accept="image/*"
+ accept={window.tucano.upload ? undefined : 'image/*'}
multiple
hidden
onChange={(e) => {
diff --git a/src/renderer/src/components/Dialogs.tsx b/src/renderer/src/components/Dialogs.tsx
index 70e55e0..32767de 100644
--- a/src/renderer/src/components/Dialogs.tsx
+++ b/src/renderer/src/components/Dialogs.tsx
@@ -224,6 +224,15 @@ function OAuthDialog({ id, url, onClose }: { id: string; url: string; onClose: (
const [pasted, setPasted] = useState('')
const [error, setError] = useState<string | null>(null)
const [busy, setBusy] = useState(false)
+ // A server on its https address gets the provider's answer itself (src/server's /oauth/callback):
+ // nothing to paste, this closes when the connector is in.
+ const automatic = (() => {
+ try {
+ return !!new URL(url).searchParams.get('redirect_uri')?.startsWith(`${location.origin}/oauth/callback`)
+ } catch {
+ return false
+ }
+ })()
const finish = (): void => {
if (!pasted.trim() || busy) return
setBusy(true)
@@ -243,27 +252,33 @@ function OAuthDialog({ id, url, onClose }: { id: string; url: string; onClose: (
{L('Abrir a página de autorização', 'Open the authorization page')}
</a>
</p>
- <label className="field">
- <span className="field__label">{L('2. Cole aqui o endereço em que ela terminou', '2. Paste the address it ended on')}</span>
- <span className="row row--center modal__input">
- <input autoFocus className="grow" placeholder="http://127.0.0.1:…/oauth/callback?code=…" value={pasted} onChange={(e) => setPasted(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && finish()} />
- </span>
- <span className="hint">
- {L(
- 'Depois de permitir, o navegador vai pra um endereço que começa com http://127.0.0.1 e mostra que a página não abre. É normal: o Tucano está no servidor. Copie o endereço inteiro da barra e cole aqui.',
- 'After you allow it, the browser goes to an address starting with http://127.0.0.1 and says the page can’t be reached. That’s expected: Tucano is on the server. Copy the whole address from the bar and paste it here.'
- )}
- </span>
- </label>
+ {automatic ? (
+ <p className="small muted">{L('2. Depois de permitir, volte pra cá: o Tucano conecta sozinho e esta janela fecha.', '2. After you allow it, come back here: Tucano connects on its own and this closes.')}</p>
+ ) : (
+ <label className="field">
+ <span className="field__label">{L('2. Cole aqui o endereço em que ela terminou', '2. Paste the address it ended on')}</span>
+ <span className="row row--center modal__input">
+ <input autoFocus className="grow" placeholder="http://127.0.0.1:…/oauth/callback?code=…" value={pasted} onChange={(e) => setPasted(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && finish()} />
+ </span>
+ <span className="hint">
+ {L(
+ 'Depois de permitir, o navegador vai pra um endereço que começa com http://127.0.0.1 e mostra que a página não abre. É normal: o Tucano está no servidor. Copie o endereço inteiro da barra e cole aqui.',
+ 'After you allow it, the browser goes to an address starting with http://127.0.0.1 and says the page can’t be reached. That’s expected: Tucano is on the server. Copy the whole address from the bar and paste it here.'
+ )}
+ </span>
+ </label>
+ )}
{error && <p className="field__error">{error}</p>}
<footer className="modal__foot">
<span className="grow" />
<button className="btn btn--ghost btn--sm" onClick={onClose}>
{L('Cancelar', 'Cancel')}
</button>
- <button className="btn btn--primary btn--sm" disabled={!pasted.trim() || busy} onClick={finish}>
- {L('Concluir', 'Finish')}
- </button>
+ {!automatic && (
+ <button className="btn btn--primary btn--sm" disabled={!pasted.trim() || busy} onClick={finish}>
+ {L('Concluir', 'Finish')}
+ </button>
+ )}
</footer>
</Modal>
)
diff --git a/src/renderer/src/components/LocalLink.tsx b/src/renderer/src/components/LocalLink.tsx
index 786984a..881edd8 100644
--- a/src/renderer/src/components/LocalLink.tsx
+++ b/src/renderer/src/components/LocalLink.tsx
@@ -29,6 +29,13 @@ function LocalLink({ messageId, path, children }: { messageId: string; path: str
}, [messageId, path])
if (!info) return <>{children}</>
const title = path.split('/').filter(Boolean).pop() ?? path
+ // On a server the file is there, not here: it comes down to this computer instead of showing in Finder.
+ const save = (): void => {
+ const a = document.createElement('a')
+ a.href = info.download!
+ a.download = title
+ a.click()
+ }
const open = (e: MouseEvent<HTMLButtonElement>): void => {
if (info.url) {
// The others cited in this message, so the arrows go through them.
@@ -36,14 +43,16 @@ function LocalLink({ messageId, path, children }: { messageId: string; path: str
const items = here.map((el) => ({ url: el.dataset['mediaUrl']!, title: el.dataset['mediaTitle']!, video: el.dataset['mediaVideo'] === '1' }))
const unique = items.filter((x, i) => items.findIndex((y) => y.url === x.url) === i)
openLightbox(unique, Math.max(0, unique.findIndex((x) => x.url === info.url)))
- } else openLocal(messageId, path, info.kind === 'folder' || info.kind === 'pdf' ? 'open' : 'reveal')
+ } else if (info.download) save()
+ else openLocal(messageId, path, info.kind === 'folder' || info.kind === 'pdf' ? 'open' : 'reveal')
}
return (
<button
type="button"
className="local-link"
title={
- info.url ? L(`Abrir aqui (botão direito: mostrar ${onMac ? 'no Finder' : 'na pasta'})`, `Open here (right click: show ${onMac ? 'in Finder' : 'in its folder'})`)
+ info.download ? (info.url ? L('Abrir aqui (botão direito: baixar)', 'Open here (right click: download)') : L('Baixar', 'Download'))
+ : info.url ? L(`Abrir aqui (botão direito: mostrar ${onMac ? 'no Finder' : 'na pasta'})`, `Open here (right click: show ${onMac ? 'in Finder' : 'in its folder'})`)
: info.kind === 'file' ? L(`Mostrar ${onMac ? 'no Finder' : 'na pasta'}`, `Show ${onMac ? 'in Finder' : 'in its folder'}`)
: L('Abrir (botão direito: mostrar onde está)', 'Open (right click: show where it is)')
}
@@ -53,7 +62,8 @@ function LocalLink({ messageId, path, children }: { messageId: string; path: str
onClick={open}
onContextMenu={(e) => {
e.preventDefault()
- openLocal(messageId, path, 'reveal')
+ if (info.download) save()
+ else openLocal(messageId, path, 'reveal')
}}
>
{children}
diff --git a/src/renderer/src/components/Onboarding.tsx b/src/renderer/src/components/Onboarding.tsx
index 6f083d5..af7ac03 100644
--- a/src/renderer/src/components/Onboarding.tsx
+++ b/src/renderer/src/components/Onboarding.tsx
@@ -935,6 +935,7 @@ function Powers(p: {
const { agent, patch, computer } = p
const name = agent.name.trim() || L('Ele', 'It')
const connectors = useStore((s) => s.connectors)
+ const isolated = useStore((s) => s.isolatedComputers)
return (
<div className="onb__split">
<section className="onb__main">
@@ -976,7 +977,9 @@ function Powers(p: {
['linux', L('Linux isolado', 'Isolated Linux')],
['mac', L('Este computador', 'This computer')]
] as const
- ).map(([k, label]) => (
+ )
+ .filter(([k]) => k !== 'linux' || isolated)
+ .map(([k, label]) => (
<button key={k} className={computer === k ? 'is-active' : ''} onClick={() => p.setComputer(k)}>
{label}
</button>
diff --git a/src/renderer/src/components/Pages.tsx b/src/renderer/src/components/Pages.tsx
index b377b7b..7fc6ba2 100644
--- a/src/renderer/src/components/Pages.tsx
+++ b/src/renderer/src/components/Pages.tsx
@@ -769,6 +769,7 @@ function ComputerCard({ agentId, kind, onChange }: { agentId: string; kind: Comp
const on = kind === 'linux'
const state = on ? (info && info.state !== 'off' ? info.state : 'stopped') : 'off'
const st = COMPUTER_STATE()[state]!
+ const isolated = useStore((s) => s.isolatedComputers)
return (
<Card
@@ -779,22 +780,24 @@ function ComputerCard({ agentId, kind, onChange }: { agentId: string; kind: Comp
)}
>
<div className="segmented segmented--wide" role="radiogroup" aria-label={L('Computador', 'Computer')}>
- {COMPUTER_CHOICES().map((c) => (
- <button
- key={c.value}
- role="radio"
- aria-checked={kind === c.value}
- className={kind === c.value ? 'is-active' : ''}
- onClick={() => {
- if (kind === c.value) return
- if (c.value === 'mac') return setConfirmMac(true)
- setConfirmMac(false)
- onChange(c.value)
- }}
- >
- {c.label}
- </button>
- ))}
+ {COMPUTER_CHOICES()
+ .filter((c) => c.value !== 'linux' || isolated || kind === 'linux') // on a server without Docker there's none to have
+ .map((c) => (
+ <button
+ key={c.value}
+ role="radio"
+ aria-checked={kind === c.value}
+ className={kind === c.value ? 'is-active' : ''}
+ onClick={() => {
+ if (kind === c.value) return
+ if (c.value === 'mac') return setConfirmMac(true)
+ setConfirmMac(false)
+ onChange(c.value)
+ }}
+ >
+ {c.label}
+ </button>
+ ))}
</div>
{confirmMac && kind !== 'mac' && (
<div className="mac-confirm">
diff --git a/src/renderer/src/components/Wiki.tsx b/src/renderer/src/components/Wiki.tsx
index 5ca9f86..2c1cb02 100644
--- a/src/renderer/src/components/Wiki.tsx
+++ b/src/renderer/src/components/Wiki.tsx
@@ -598,6 +598,23 @@ function WikiShell({ view }: { view: WikiViewState }): ReactNode {
const close = (): void => navigate({ kind: 'wiki' })
const [imported, setImported] = useState<WikiImport | { error: string } | 'busy' | null>(null)
const startImport = (): void => {
+ const failed = (e: Error): void => setImported({ error: e.message.replace(/^Error invoking remote method '[^']+': (Error: )?/, '') })
+ // On a server the vault is on the person's computer, not there: it goes up as a .zip.
+ const upload = window.tucano.upload
+ if (upload) {
+ const input = document.createElement('input')
+ input.type = 'file'
+ input.accept = '.zip,application/zip'
+ input.onchange = () => {
+ const file = input.files?.[0]
+ if (!file) return
+ setSettings(false)
+ setImported('busy')
+ void upload(file).then((path) => call('wikiImportZip', { path })).then(setImported, failed)
+ }
+ input.click()
+ return
+ }
const pick = (window.tucano as unknown as { pickFolder?: () => Promise<string | null> }).pickFolder
void pick?.().then((dir) => {
if (!dir) return
@@ -1048,7 +1065,11 @@ function WikiSettingsDialog({ data, onClose, onImport }: { data: WikiData | null
<div className="wk-setting">
<span>
<b>{L('Importar um cofre do Obsidian', 'Import an Obsidian vault')}</b>
- <small>{L('As notas entram como estão, com as pastas, os links e os anexos. O cofre original não muda.', 'The notes come in as they are, with their folders, links and attachments. The original vault stays as it was.')}</small>
+ <small>
+ {window.tucano.upload
+ ? L('Compacte a pasta do cofre num .zip e envie: as notas entram como estão, com as pastas, os links e os anexos.', 'Zip the vault’s folder and send it: the notes come in as they are, with their folders, links and attachments.')
+ : L('As notas entram como estão, com as pastas, os links e os anexos. O cofre original não muda.', 'The notes come in as they are, with their folders, links and attachments. The original vault stays as it was.')}
+ </small>
</span>
<button className="btn btn--sm" onClick={onImport}>
{L('Importar…', 'Import…')}
diff --git a/src/renderer/src/rpc.ts b/src/renderer/src/rpc.ts
index 7a37144..d6db392 100644
--- a/src/renderer/src/rpc.ts
+++ b/src/renderer/src/rpc.ts
@@ -18,6 +18,7 @@ declare global {
connect: () => void
pickFolder: () => Promise<string | null>
pathOf?: (file: File) => string // a dropped or picked file's path on this computer (desktop only)
+ upload?: (file: File, purpose?: 'message') => Promise<string> // a file sent to the server, and where it landed there (server only)
onNavigate: (cb: (conversationId: string, threadId?: string) => void) => void
onNavigatePage?: (cb: (page: 'skills') => void) => void // desktop only
onCoreDown?: (cb: () => void) => void // desktop only: a browser reloads on its own
diff --git a/src/renderer/src/store.ts b/src/renderer/src/store.ts
index 713c531..9b9b2b8 100644
--- a/src/renderer/src/store.ts
+++ b/src/renderer/src/store.ts
@@ -87,6 +87,7 @@ export interface State {
voiceRev: number // goes up when dictation's model changes (downloading, done, removed)
platform: Os
packaged: boolean
+ isolatedComputers: boolean
panel: Panel | null // the side panel next to a conversation
dialog: Dialog | null // a small window: a channel's members, name or topic; archived agents; new channel; search
tabs: Record<string, string> // the open tab of each page with tabs, kept while the app is open
@@ -161,6 +162,7 @@ let state: State = {
skills: [],
platform: 'mac',
packaged: false,
+ isolatedComputers: true,
panel: null,
dialog: null,
tabs: {},
@@ -325,6 +327,7 @@ export async function start(): Promise<void> {
skills: snap.skills,
platform: snap.platform,
packaged: snap.packaged,
+ isolatedComputers: snap.isolatedComputers,
demoServer: snap.demoServer
}
})
@@ -578,7 +581,14 @@ export const browserAction = (agentId: string, action: 'show' | 'hide' | 'clear'
export const windowless = (): boolean => !!(window as { __TUCANO_WEB__?: boolean }).__TUCANO_WEB__
// A page an agent serves, as this browser reaches it: on a server, at the server's
// address (it passes running services through on a private network).
-export const reachable = (url: string): string => (windowless() ? url.replace(/^http:\/\/127\.0\.0\.1:/, `http://${location.hostname}:`) : url)
+// A page an agent serves on the server's loopback, from here. Behind https it has an address of its
+// own, reached through this server (src/server/preview.ts); on a private address, the same port there.
+export const reachable = (url: string): string => {
+ if (!windowless()) return url
+ const m = /^http:\/\/127\.0\.0\.1:(\d+)(.*)$/.exec(url)
+ if (!m) return url
+ return location.protocol === 'https:' ? `${location.origin}/preview/${m[1]}${m[2] || '/'}` : `http://${location.hostname}:${m[1]}${m[2]}`
+}
export const browserInput = (agentId: string, input: BrowserInput): void => void call('browserInput', { agentId, input }).catch(() => {})
// In a browser (Tucano as a server) the page opens it itself: the server has no screen.
export const openExternal = (url: string): void =>
diff --git a/src/server/guard.ts b/src/server/guard.ts
new file mode 100644
index 0000000..87edf2f
--- /dev/null
+++ b/src/server/guard.ts
@@ -0,0 +1,68 @@
+// What keeps the server standing and its token to itself once it's on the internet:
+// a request it can't read gets a 400 instead of taking it down, guessing the token is
+// slowed to nothing, and the page answers only its own origin, never inside another site's frame.
+import type { IncomingMessage } from 'node:http'
+
+// Guessing: after this many wrong tokens from one address in the window, that address waits.
+export const MAX_FAILS = 20
+export const WINDOW_MS = 10 * 60_000
+
+export class Limiter {
+ private fails = new Map<string, { n: number; since: number }>()
+
+ constructor(private now: () => number = Date.now) {}
+
+ blocked(ip: string): boolean {
+ const f = this.fails.get(ip)
+ if (!f) return false
+ if (this.now() - f.since > WINDOW_MS) return void this.fails.delete(ip), false
+ return f.n >= MAX_FAILS
+ }
+
+ fail(ip: string): void {
+ const f = this.fails.get(ip)
+ if (!f || this.now() - f.since > WINDOW_MS) this.fails.set(ip, { n: 1, since: this.now() })
+ else f.n++
+ // An address that only ever fails stays bounded: the oldest go first.
+ if (this.fails.size > 10_000) this.fails.delete(this.fails.keys().next().value!)
+ }
+}
+
+// Who is asking. Behind a reverse proxy (TUCANO_TRUST_PROXY=1) every request comes from the
+// proxy, so the address it was asked from is the last one it added to X-Forwarded-For. Without
+// it, that header is the asker's own word and counts for nothing.
+export function clientIp(req: Pick<IncomingMessage, 'headers' | 'socket'>, trustProxy: boolean): string {
+ const direct = req.socket.remoteAddress ?? ''
+ if (!trustProxy) return direct
+ const fwd = req.headers['x-forwarded-for']
+ const last = (Array.isArray(fwd) ? fwd.join(',') : (fwd ?? '')).split(',').pop()?.trim()
+ return last || direct
+}
+
+// A page of another origin (another person's Tucano on a sibling subdomain, for one) may not
+// talk to this one. A browser always says where a fetch or an EventSource comes from; with no
+// Origin it's a navigation or a program, which the token alone decides.
+export function sameOrigin(req: Pick<IncomingMessage, 'headers'>): boolean {
+ const origin = req.headers.origin
+ if (!origin) return true
+ try {
+ return new URL(origin).host === req.headers.host
+ } catch {
+ return false
+ }
+}
+
+// On every answer. The app's page can't be framed by any site (an approval clicked through a
+// frame); an agent's page can only be framed by the app, which shows it in its panel.
+export const BASE_HEADERS: Record<string, string> = { 'x-content-type-options': 'nosniff', 'referrer-policy': 'no-referrer' }
+export const PAGE_HEADERS: Record<string, string> = { ...BASE_HEADERS, 'x-frame-options': 'DENY', 'content-security-policy': "frame-ancestors 'none'" }
+export const ARTIFACT_CSP = "sandbox allow-scripts allow-popups; frame-ancestors 'self'"
+
+// A path out of the address, or undefined when it can't be read (a stray % from a scanner).
+export function decodedPath(raw: string): string | undefined {
+ try {
+ return decodeURIComponent(raw)
+ } catch {
+ return undefined
+ }
+}
diff --git a/src/server/index.ts b/src/server/index.ts
index 74493b0..9c722f6 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -5,16 +5,21 @@
// core (events down an event stream, requests up by POST). Every request needs
// the server's token.
//
-// node out/main/server.js (TUCANO_DATA, TUCANO_HOST, TUCANO_PORT, TUCANO_TOKEN)
+// 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
import { randomBytes, randomUUID, timingSafeEqual } from 'node:crypto'
import { EventEmitter } from 'node:events'
-import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
+import { chmodSync, createReadStream, createWriteStream, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'
+import type { Socket } from 'node:net'
import { homedir } from 'node:os'
-import { extname, join, normalize, sep } from 'node:path'
+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, Limiter, PAGE_HEADERS, sameOrigin } from './guard'
+import { Preview } from './preview'
import { vault } from './vault'
+import { verifyLocalUrl } from '../core/local-paths'
import { INSECURE_CONTEXT_SHIM } from './web-shim'
const dataDir = process.env['TUCANO_DATA'] || join(homedir(), '.tucano-server')
@@ -31,11 +36,23 @@ function kept(name: string, make: () => string): string {
return readFileSync(file, 'utf8').trim()
}
const token = process.env['TUCANO_TOKEN'] || kept('server-token', () => randomBytes(24).toString('base64url'))
+// The address people open: TUCANO_URL behind a proxy (https://ana.example.com), else where it listens.
+const publicUrl = (process.env['TUCANO_URL'] || `http://${host === '0.0.0.0' || host === '::' ? 'localhost' : host}:${port}`).replace(/\/+$/, '')
+
+// `server.js link`: the one place the token is printed. The log never has it, since logs
+// get kept, shipped and pasted into issues.
+if (process.argv[2] === 'link') {
+ console.log(`${publicUrl}/?token=${token}`)
+ 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')
const { seal, open } = vault(key)
+// The core signs the files it has checked a message may show (local-paths.ts); /local/ serves only those.
+// A new key each start: an old address stops working with the process that made it.
+const localKey = randomBytes(32).toString('base64url')
// Electron's MessagePortMain and parentPort, as far as the core uses them.
class Port extends EventEmitter {
@@ -48,14 +65,27 @@ class Port extends EventEmitter {
}
}
-type CoreRequest = { type: string; id?: string; op?: string; data?: string }
+type CoreRequest = { type: string; id?: string; op?: string; data?: string; title?: string; body?: string; conversationId?: string; page?: string }
const parent = new Port((msg) => fromCore(msg as CoreRequest))
const toCore = (data: unknown, ports: Port[] = []): boolean => parent.emit('message', { data, ports })
-// What the main process does for the core on a desktop. A server has no screen:
-// no notifications (Telegram carries them), nothing to open, no login item.
+// What the main process does for the core on a desktop. A server has no screen: nothing to
+// open, no login item. Its notifications go to the pages open on it (a browser, the desktop app's
+// server window), which show them while the person is looking elsewhere; Telegram carries them too.
+const oauthWaits = new Map<string, (r: { ok: boolean; why?: string }) => void>()
+
function fromCore(msg: CoreRequest): void {
const id = msg.id
+ if (msg.type === 'oauth-result') {
+ oauthWaits.get(id ?? '')?.((msg as unknown as { data: { ok: boolean; why?: string } }).data)
+ oauthWaits.delete(id ?? '')
+ return
+ }
+ if (msg.type === 'notify') {
+ const note = { notify: { title: String(msg.title ?? ''), body: String(msg.body ?? ''), conversationId: msg.conversationId, page: msg.page } }
+ for (const c of clients.values()) c.postMessage(note)
+ return
+ }
if (msg.type === 'secret') {
try {
toCore({ type: 'secret-result', id, data: msg.op === 'encrypt' ? seal(msg.data ?? '') : open(msg.data ?? '') })
@@ -84,6 +114,12 @@ const TYPES: Record<string, string> = {
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.webp': 'image/webp',
+ '.avif': 'image/avif',
+ '.bmp': 'image/bmp',
+ '.mp4': 'video/mp4',
+ '.webm': 'video/webm',
+ '.mov': 'video/quicktime',
+ '.m4v': 'video/mp4',
'.woff2': 'font/woff2',
'.mp3': 'audio/mpeg',
'.wav': 'audio/wav',
@@ -94,8 +130,8 @@ const TYPES: Record<string, string> = {
}
function file(res: ServerResponse, path: string, headers: Record<string, string> = {}): void {
- if (!existsSync(path)) return void res.writeHead(404).end('not found')
- res.writeHead(200, { 'content-type': TYPES[extname(path).toLowerCase()] ?? 'application/octet-stream', ...headers }).end(readFileSync(path))
+ if (!existsSync(path)) return void res.writeHead(404, BASE_HEADERS).end('not found')
+ res.writeHead(200, { 'content-type': TYPES[extname(path).toLowerCase()] ?? 'application/octet-stream', ...BASE_HEADERS, ...headers }).end(readFileSync(path))
}
const sameToken = (t: string | undefined): boolean => !!t && t.length === token.length && timingSafeEqual(Buffer.from(t), Buffer.from(token))
@@ -117,6 +153,13 @@ function sawComputers(list: Computer[]): void {
for (const c of list) servicePorts.set(c.agentId, c.services.filter((s) => s.running).flatMap((s) => loopbackPort(s.url) ?? []))
forwardServices(new Set([...servicePorts.values()].flat()))
}
+// Behind https (TUCANO_URL), each page an agent serves gets an address of its own, <port>-<this
+// address> (preview.ts): only the ports the agents' computers say they serve, never this server's.
+const publicHost = publicUrl.startsWith('https://') ? new URL(publicUrl).host : ''
+const preview = publicHost
+ ? new Preview(Buffer.from(kept('preview.key', () => randomBytes(32).toString('base64')), 'base64'), publicHost, (p) => p !== port && [...servicePorts.values()].some((l) => l.includes(p)))
+ : undefined
+
// The server's own connection to the core, to follow the services.
const watcher = new Port((msg) => {
const m = msg as { id?: number; result?: { computers?: Computer[] }; event?: { type: string; computer?: Computer } }
@@ -128,7 +171,7 @@ const watcher = new Port((msg) => {
// policy letting it frame the agents' pages from this server.
function index(): string {
return readFileSync(join(page, 'index.html'), 'utf8')
- .replace('frame-src tucano:', `frame-src 'self' tucano:${privateHost ? ` http://${host}:*` : ''}`)
+ .replace('frame-src tucano:', `frame-src 'self' tucano:${privateHost ? ` http://${host}:*` : ''}${publicHost ? ` https://*.${publicHost.split('.').slice(1).join('.')}` : ''}`)
.replace('<title>', '<meta name="viewport" content="width=device-width, initial-scale=1" />\n <script src="./tucano-web.js"></script>\n <title>')
}
@@ -146,28 +189,102 @@ function body(req: IncomingMessage): Promise<string> {
})
}
+function oauthCallback(url: URL, res: ServerResponse): void {
+ const id = randomUUID()
+ const answer = (r: { ok: boolean; why?: string }): void => {
+ const esc = (t: string): string => t.replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]!)
+ const [title, line] = r.ok ? ['Pronto · Done', 'O conector está autorizado. Pode fechar esta aba e voltar ao Tucano. · The connector is authorized. You can close this tab and go back to Tucano.'] : ['Não deu · It didn’t work', r.why ?? '']
+ res
+ .writeHead(r.ok ? 200 : 400, { ...BASE_HEADERS, 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store', 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'" })
+ .end(`<!doctype html><meta charset="utf-8"><title>Tucano</title><style>body{font:15px system-ui;display:grid;place-items:center;height:100vh;margin:0;background:#f6f3ee;color:#1d1a16}@media(prefers-color-scheme:dark){body{background:#1a1917;color:#f1ece4}}main{max-width:460px;padding:24px}p{opacity:.8;line-height:1.5}</style><main><h2>${esc(title)}</h2><p>${esc(line)}</p></main>`)
+ }
+ const timer = setTimeout(() => oauthWaits.get(id) && (oauthWaits.delete(id), answer({ ok: false, why: 'O Tucano não respondeu. Tente de novo pelo app. · Tucano didn’t answer. Try again from the app.' })), 30_000)
+ oauthWaits.set(id, (r) => (clearTimeout(timer), answer(r)))
+ toCore({ type: 'oauth-callback', id, data: { state: url.searchParams.get('state') ?? '', code: url.searchParams.get('code') ?? '', error: url.searchParams.get('error') ?? '' } })
+}
+
+const trustProxy = process.env['TUCANO_TRUST_PROXY'] === '1'
+const MAX_UPLOAD = 1024 * 1024 * 1024 // a vault with its pictures, zipped
+const guesses = new Limiter()
+
+// 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) => {
+ try {
+ handle(req, res)
+ } catch (e) {
+ console.error('[server]', req.method, e instanceof Error ? e.message : e)
+ if (!res.headersSent) res.writeHead(400, BASE_HEADERS).end()
+ }
+})
+
+function handle(req: IncomingMessage, res: ServerResponse): void {
+ // A preview address answers only its agent's page: nothing below (the app, /rpc, files) is reachable there.
+ const previewPort = preview?.portOf(req.headers.host)
+ if (previewPort) return preview!.handle(req, res, previewPort)
const url = new URL(req.url ?? '/', 'http://x')
+ const ip = clientIp(req, trustProxy)
+ if (guesses.blocked(ip)) return void res.writeHead(429, { ...BASE_HEADERS, 'retry-after': '600' }).end()
+ // Back from a connector's authorization page. No token here: it may open in a browser that never
+ // 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)
// The link with ?token= signs this browser in, then drops it from the address bar. Lax, not
// Strict: the link is often clicked from elsewhere (a chat), and a Strict cookie wouldn't ride
// the redirect that follows. Lax still keeps it off other sites' POSTs to /rpc.
- if (sameToken(url.searchParams.get('token') ?? undefined)) {
+ const offered = url.searchParams.get('token') ?? undefined
+ if (offered !== undefined && !sameToken(offered)) guesses.fail(ip)
+ if (sameToken(offered)) {
const secure = req.headers['x-forwarded-proto'] === 'https' ? '; Secure' : ''
- return void res.writeHead(302, { 'set-cookie': `tucano=${token}; HttpOnly; SameSite=Lax; Path=/; Max-Age=31536000${secure}`, location: '/' }).end()
+ return void res.writeHead(302, { ...BASE_HEADERS, 'set-cookie': `tucano=${token}; HttpOnly; SameSite=Lax; Path=/; Max-Age=31536000${secure}`, location: '/' }).end()
}
- if (!sameToken(cookieToken(req))) {
+ const cookie = cookieToken(req)
+ if (!sameToken(cookie)) {
+ if (cookie !== undefined && offered === undefined) guesses.fail(ip)
return void res
- .writeHead(401, { 'content-type': 'text/plain; charset=utf-8' })
- .end('Tucano: open the link with the token the server printed (…/?token=…).\nTucano: abra o link com o token que o servidor mostrou (…/?token=…).')
+ .writeHead(401, { ...BASE_HEADERS, 'content-type': 'text/plain; charset=utf-8' })
+ .end('Tucano: open the link from `node out/main/server.js link`.\nTucano: abra o link que o `node out/main/server.js link` mostra.')
+ }
+ // 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') && !sameOrigin(req)) return void res.writeHead(403, BASE_HEADERS).end()
+
+ // 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.
+ if (url.pathname === '/upload' && req.method === 'POST') {
+ const name = (url.searchParams.get('name') ?? 'file').replace(/[^\p{L}\p{N}._ -]/gu, '_').replace(/^\.+/, '_').slice(0, 120) || 'file'
+ // For a message: ~/Enviados, under its own name (a number added when taken), where the agents
+ // on this computer find it. Anything else (a vault): the server's own folder, for the core.
+ const forMessage = url.searchParams.get('for') === 'message'
+ const dir = forMessage ? join(homedir(), 'Enviados') : join(dataDir, 'uploads')
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
+ let path = forMessage ? join(dir, name) : join(dir, `${randomUUID()}-${name}`)
+ for (let n = 2; forMessage && existsSync(path); n++) path = join(dir, name.replace(/(\.[^.]*)?$/, ` (${n})$1`))
+ const out = createWriteStream(path, { mode: 0o600 })
+ let size = 0
+ const fail = (code: number): void => {
+ out.destroy()
+ rmSync(path, { force: true })
+ if (!res.headersSent) res.writeHead(code, BASE_HEADERS).end()
+ }
+ req.on('data', (c: Buffer) => {
+ size += c.length
+ if (size > MAX_UPLOAD) {
+ req.destroy()
+ fail(413)
+ }
+ })
+ req.on('error', () => fail(400))
+ req.pipe(out).on('finish', () => !res.headersSent && res.writeHead(200, { ...BASE_HEADERS, 'content-type': 'application/json' }).end(JSON.stringify({ path })))
+ return
}
if (url.pathname === '/events') {
const c = new Port((msg) => res.write(`data: ${JSON.stringify(msg)}\n\n`))
const id = randomUUID()
clients.set(id, c)
- res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache', 'x-accel-buffering': 'no' })
+ res.writeHead(200, { ...BASE_HEADERS, 'content-type': 'text/event-stream', 'cache-control': 'no-cache', 'x-accel-buffering': 'no' })
res.write(`event: hello\ndata: ${id}\n\n`)
- const beat = setInterval(() => res.write(': \n\n'), 25_000)
+ // 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)
toCore(null, [c])
req.on('close', () => {
clearInterval(beat)
@@ -179,62 +296,221 @@ const server = createServer((req, res) => {
if (url.pathname === '/rpc' && req.method === 'POST') {
const c = clients.get(url.searchParams.get('c') ?? '')
- if (!c) return void res.writeHead(410).end()
+ if (!c) return void res.writeHead(410, BASE_HEADERS).end()
body(req).then(
(text) => {
- c.emit('message', { data: JSON.parse(text) })
- res.writeHead(204).end()
+ let data: unknown
+ try {
+ data = JSON.parse(text)
+ } catch {
+ return void res.writeHead(400, BASE_HEADERS).end()
+ }
+ try {
+ c.emit('message', { data })
+ } catch (e) {
+ console.error('[server] rpc', e instanceof Error ? e.message : e)
+ return void res.writeHead(400, BASE_HEADERS).end()
+ }
+ res.writeHead(204, BASE_HEADERS).end()
},
- () => res.writeHead(413).end()
+ () => res.writeHead(413, BASE_HEADERS).end()
)
return
}
+ // An agent's page, from the app's panel: signed in here, the browser goes on to its own address.
+ const pv = /^\/preview\/(\d{2,5})(\/.*)?$/.exec(url.pathname)
+ if (pv && preview) {
+ const p = Number(pv[1])
+ if (p === port || ![...servicePorts.values()].some((l) => l.includes(p))) return void res.writeHead(404, BASE_HEADERS).end()
+ return void res.writeHead(302, { ...BASE_HEADERS, location: preview.grantUrl(p, `${pv[2] ?? '/'}${url.search}`), 'cache-control': 'no-store' }).end()
+ }
+
+ // Choosing a folder on the server (the wiki's, one lent to an agent): its subfolders, for the
+ // bridge's picker. Names only; it starts at the home folder.
+ if (url.pathname === '/folders') {
+ const asked = url.searchParams.get('path') || homedir()
+ const at = isAbsolute(asked) ? resolve(asked) : resolve(homedir(), asked)
+ let folders: string[]
+ try {
+ folders = readdirSync(at, { withFileTypes: true })
+ .filter((d) => d.isDirectory() || (d.isSymbolicLink() && statSync(join(at, d.name), { throwIfNoEntry: false })?.isDirectory()))
+ .map((d) => d.name)
+ .sort((a, b) => Number(a.startsWith('.')) - Number(b.startsWith('.')) || a.localeCompare(b))
+ .slice(0, 1000)
+ } catch {
+ return void res.writeHead(404, { ...BASE_HEADERS, 'content-type': 'application/json' }).end('{}')
+ }
+ return void res.writeHead(200, { ...BASE_HEADERS, 'content-type': 'application/json', 'cache-control': 'no-store' }).end(JSON.stringify({ path: at, parent: dirname(at) === at ? null : dirname(at), home: homedir(), folders }))
+ }
+
+ // A file an agent cited, checked and signed by the core: shown (an image, a video) or saved.
+ if (url.pathname.startsWith('/local/')) {
+ const path = verifyLocalUrl(localKey, new URL(url.pathname.replace(/^\/local/, ''), 'tucano://local'))
+ let size = -1
+ try {
+ size = path && statSync(path).isFile() ? statSync(path).size : -1
+ } catch {}
+ if (!path || size < 0) return void res.writeHead(404, BASE_HEADERS).end()
+ const saving = url.searchParams.has('download')
+ res.writeHead(200, {
+ ...BASE_HEADERS,
+ 'content-type': saving ? 'application/octet-stream' : (TYPES[extname(path).toLowerCase()] ?? 'application/octet-stream'),
+ 'content-length': String(size),
+ 'content-security-policy': 'sandbox',
+ ...(saving ? { 'content-disposition': `attachment; filename*=UTF-8''${encodeURIComponent(basename(path))}` } : {})
+ })
+ return void createReadStream(path).on('error', () => res.destroy()).pipe(res)
+ }
+
// What the agents showed in the chat, sandboxed as on the desktop.
const art = /^\/artifact\/([0-9a-f-]{36})\/([^/]+)$/.exec(url.pathname)
if (art) {
const dir = join(dataDir, 'artifacts', art[1]!)
- const path = normalize(join(dir, decodeURIComponent(art[2]!)))
- if (!path.startsWith(dir + sep)) return void res.writeHead(404).end()
- return file(res, path, { 'content-security-policy': 'sandbox allow-scripts allow-popups' })
+ const name = decodedPath(art[2]!)
+ const path = name === undefined ? '' : normalize(join(dir, name))
+ if (!path.startsWith(dir + sep)) return void res.writeHead(404, BASE_HEADERS).end()
+ return file(res, path, { 'content-security-policy': ARTIFACT_CSP })
}
- if (url.pathname === '/tucano-web.js') return void res.writeHead(200, { 'content-type': TYPES['.js']! }).end(WEB)
- if (url.pathname === '/' || url.pathname === '/index.html') return void res.writeHead(200, { 'content-type': TYPES['.html']!, 'cache-control': 'no-cache' }).end(index())
- const path = normalize(join(page, decodeURIComponent(url.pathname)))
- if (!path.startsWith(page + sep)) return void res.writeHead(404).end()
+ if (url.pathname === '/tucano-web.js') return void res.writeHead(200, { ...BASE_HEADERS, 'content-type': TYPES['.js']! }).end(WEB)
+ if (url.pathname === '/' || url.pathname === '/index.html') return void res.writeHead(200, { ...PAGE_HEADERS, 'content-type': TYPES['.html']!, 'cache-control': 'no-cache' }).end(index())
+ const name = decodedPath(url.pathname)
+ const path = name === undefined ? '' : normalize(join(page, name))
+ if (!path.startsWith(page + sep)) return void res.writeHead(404, BASE_HEADERS).end()
file(res, path)
-})
+}
// window.tucano for a browser: the core's port comes from the event stream and
// the requests go up by POST; what only the desktop does is left out quietly.
const WEB = `${INSECURE_CONTEXT_SHIM}(() => {
window.__TUCANO_WEB__ = true
let client = null
+ // Starting fresh is how this page reconnects. What's typed in the message field is kept first
+ // (Conversation.tsx listens), so a reload on its own never costs a draft.
+ const restart = () => {
+ window.dispatchEvent(new Event('tucano:reloading'))
+ location.reload()
+ }
+ // A line that went quiet without closing (the computer slept, the Wi-Fi changed) never says so:
+ // the server beats every 25 s, and a minute without anything means it's gone.
+ let heard = Date.now()
+ const STALE_MS = 60_000
+ const stale = () => client && Date.now() - heard > STALE_MS
+ setInterval(() => stale() && restart(), 10_000)
+ window.addEventListener('online', () => stale() && restart())
+ document.addEventListener('visibilitychange', () => document.visibilityState === 'visible' && stale() && restart())
const connect = () => {
const ch = new MessageChannel()
const es = new EventSource('./events')
let opened = false
+ es.addEventListener('ping', () => (heard = Date.now()))
es.addEventListener('hello', (e) => {
- if (opened) return location.reload() // a new connection after a drop: start fresh
+ heard = Date.now()
+ if (opened) return restart() // a new connection after a drop: start fresh
opened = true
client = e.data
window.postMessage('core:port', '*', [ch.port1])
})
- es.onmessage = (e) => ch.port2.postMessage(JSON.parse(e.data))
+ es.onmessage = (e) => {
+ heard = Date.now()
+ const m = JSON.parse(e.data)
+ if (m && m.notify) return notify(m.notify)
+ ch.port2.postMessage(m)
+ }
ch.port2.onmessage = (m) => {
fetch('./rpc?c=' + encodeURIComponent(client), { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(m.data) }).then((r) => {
- if (r.status === 410) location.reload()
+ if (r.status === 410) restart()
})
}
}
+ // A notification of the system, as the desktop app shows, while the person isn't on this page.
+ // The browser asks for permission once, on the first click (it won't ask without one).
+ let toConversation = () => {}
+ let toPage = () => {}
+ const notify = (n) => {
+ if (!('Notification' in window) || Notification.permission !== 'granted' || document.hasFocus()) return
+ const shown = new Notification(n.title, { body: n.body, tag: n.conversationId || undefined })
+ shown.onclick = () => {
+ window.focus()
+ if (n.conversationId) toConversation(n.conversationId)
+ else if (n.page === 'skills') toPage('skills')
+ shown.close()
+ }
+ }
+ // The server's folders, in the app's own dialog look: a browser can't show the server's disk.
+ const pickFolder = () =>
+ new Promise((done) => {
+ const pt = document.documentElement.lang !== 'en'
+ const t = (a, b) => (pt ? a : b)
+ const el = (tag, cls, text) => {
+ const e = document.createElement(tag)
+ if (cls) e.className = cls
+ if (text !== undefined) e.textContent = text
+ return e
+ }
+ const shade = el('div', 'modal')
+ const card = el('div', 'modal__card')
+ card.setAttribute('role', 'dialog')
+ card.setAttribute('aria-modal', 'true')
+ const head = el('header', 'modal__head')
+ head.append(el('strong', '', t('Escolher pasta no servidor', 'Choose a folder on the server')))
+ const where = el('p', 'small muted mono modal__lead')
+ const list = el('div', 'folder-pick')
+ list.style.cssText = 'max-height:320px;overflow:auto;display:grid;gap:2px;margin:8px 0'
+ const foot = el('footer', 'modal__foot')
+ const cancel = el('button', 'btn btn--ghost btn--sm', t('Cancelar', 'Cancel'))
+ const choose = el('button', 'btn btn--primary btn--sm', t('Escolher esta pasta', 'Choose this folder'))
+ foot.append(el('span', 'grow'), cancel, choose)
+ card.append(head, where, list, foot)
+ shade.append(card)
+ document.body.append(shade)
+ let current = ''
+ const close = (v) => {
+ shade.remove()
+ document.removeEventListener('keydown', onKey, true)
+ done(v)
+ }
+ const onKey = (e) => {
+ if (e.key === 'Escape') (e.stopImmediatePropagation(), close(null))
+ }
+ document.addEventListener('keydown', onKey, true)
+ shade.addEventListener('mousedown', (e) => e.target === shade && close(null))
+ cancel.onclick = () => close(null)
+ choose.onclick = () => close(current || null)
+ const row = (label, path) => {
+ const b = el('button', 'btn btn--ghost btn--sm', label)
+ b.style.cssText = 'justify-content:flex-start;text-align:left'
+ b.onclick = () => go(path)
+ list.append(b)
+ }
+ const go = (path) =>
+ fetch('./folders' + (path ? '?path=' + encodeURIComponent(path) : ''))
+ .then((r) => (r.ok ? r.json() : Promise.reject()))
+ .then((r) => {
+ current = r.path
+ where.textContent = r.path
+ list.replaceChildren()
+ if (r.parent) row('↑ ' + t('Pasta acima', 'Up a folder'), r.parent)
+ for (const f of r.folders) row(f + '/', r.path.replace(/\\/+$/, '') + '/' + f)
+ if (!r.folders.length) list.append(el('p', 'small muted', t('Nenhuma pasta aqui dentro.', 'No folders in here.')))
+ })
+ .catch(() => (where.textContent = t('Não consegui abrir essa pasta.', "Couldn't open that folder.")))
+ go('')
+ choose.focus()
+ })
+ if ('Notification' in window && Notification.permission === 'default')
+ document.addEventListener('pointerdown', () => void Notification.requestPermission().catch(() => {}), { once: true })
window.tucano = {
connect,
- pickFolder: async () => {
- const p = prompt('Pasta no servidor (caminho completo) / Folder on the server (full path):')
- return p && p.trim() ? p.trim() : null
- },
- onNavigate: () => {},
+ pickFolder: () => pickFolder(),
+ // A file from this computer up to the server; where it landed there.
+ upload: (file, purpose) =>
+ fetch('./upload?name=' + encodeURIComponent(file.name) + (purpose === 'message' ? '&for=message' : ''), { method: 'POST', body: file }).then((r) =>
+ r.ok ? r.json().then((j) => j.path) : Promise.reject(new Error(r.status === 413 ? 'O arquivo passa de 1 GB. / The file is over 1 GB.' : 'Não consegui enviar o arquivo. / Could not send the file.'))
+ ),
+ onNavigate: (cb) => (toConversation = cb),
+ onNavigatePage: (cb) => (toPage = cb),
viewing: () => {},
updateState: async () => ({ version: '', status: 'off' }),
onUpdate: () => {},
@@ -245,6 +521,7 @@ const WEB = `${INSECURE_CONTEXT_SHIM}(() => {
`
process.env['TUCANO_DATA'] = dataDir
+process.env['TUCANO_LOCAL_KEY'] = localKey
process.env['TUCANO_PACKAGED'] = '1'
process.env['TUCANO_SERVER'] = '1'
;(process as unknown as { parentPort: Port }).parentPort = parent
@@ -252,9 +529,16 @@ await import(pathToFileURL(join(import.meta.dirname, 'core.js')).href)
toCore(null, [watcher])
watcher.emit('message', { data: { id: 1, method: 'snapshot' } })
+// WebSockets: only an agent's page at its preview address has any (a dev server reloading itself).
+server.on('upgrade', (req: IncomingMessage, socket: Socket, head: Buffer) => {
+ const p = preview?.portOf(req.headers.host)
+ if (p) preview!.upgrade(req, socket, head, p)
+ else socket.destroy()
+})
+
server.listen(port, host, () => {
- const shown = host === '0.0.0.0' || host === '::' ? 'localhost' : host
- console.log(`Tucano server: http://${shown}:${port}/?token=${token}`)
+ console.log(`Tucano server: ${publicUrl}`)
+ console.log('To sign a browser in, open the link that `node out/main/server.js link` prints.')
console.log(`Data: ${dataDir}`)
if (host === '127.0.0.1') console.log('Listening on this machine only: reach it through an SSH tunnel, Tailscale or a reverse proxy with HTTPS (docs/server.md).')
})
diff --git a/src/server/preview.ts b/src/server/preview.ts
new file mode 100644
index 0000000..a07f1bf
--- /dev/null
+++ b/src/server/preview.ts
@@ -0,0 +1,126 @@
+// The pages agents serve (a site, a dashboard, an API on 127.0.0.1:5173 inside the server), opened
+// from anywhere at an address of their own: https://5173-ana.example.com for https://ana.example.com.
+//
+// That address is another origin on purpose. The page there is code an agent wrote: it never sees
+// Tucano's cookie, and the address answers nothing of Tucano's own (no page, no /rpc). It has a
+// sign-in of its own: the app's page (signed in) sends the browser to it with a grant good for a few
+// minutes, which becomes a cookie only that address knows. Only the ports the agents' computers say
+// they serve are passed through, never Tucano's own.
+import { createHmac, timingSafeEqual } from 'node:crypto'
+import { request, type IncomingMessage, type ServerResponse } from 'node:http'
+import { connect, type Socket } from 'node:net'
+
+const GRANT_MS = 5 * 60_000
+const COOKIE = 'tucano_preview'
+const ENTER = '/__tucano/enter'
+
+const safeEqual = (a: string, b: string): boolean => a.length === b.length && timingSafeEqual(Buffer.from(a), Buffer.from(b))
+
+// The person's cookies for this server (Tucano's and the preview's) stay out of what the agent's page gets.
+export function withoutOurCookies(cookie: string | undefined): string | undefined {
+ const kept = (cookie ?? '')
+ .split(';')
+ .map((c) => c.trim())
+ .filter((c) => c && !/^(tucano|tucano_preview)=/.test(c))
+ return kept.length ? kept.join('; ') : undefined
+}
+
+// What the agent's page gets of a request: the host it expects (a dev server refuses others) and the
+// person's cookies, without ours. A request that only had ours has none left, and no header for it.
+function forwarded(req: IncomingMessage, port: number, extra: Record<string, string> = {}): Record<string, string | string[]> {
+ const out: Record<string, string | string[]> = {}
+ for (const [k, v] of Object.entries(req.headers)) if (v !== undefined && k !== 'cookie') out[k] = v
+ const cookie = withoutOurCookies(req.headers.cookie)
+ if (cookie) out['cookie'] = cookie
+ return { ...out, host: `127.0.0.1:${port}`, ...extra }
+}
+
+export class Preview {
+ constructor(
+ private key: Buffer,
+ private publicHost: string, // ana.example.com
+ private allowed: (port: number) => boolean,
+ private now: () => number = Date.now
+ ) {}
+
+ private sign(text: string): string {
+ return createHmac('sha256', this.key).update(text).digest('base64url')
+ }
+
+ // The port a preview address stands for, or undefined when the address is Tucano's own (or another's).
+ portOf(host: string | undefined): number | undefined {
+ const m = /^(\d{2,5})-(.+)$/.exec((host ?? '').toLowerCase())
+ if (!m || m[2] !== this.publicHost.toLowerCase()) return undefined
+ const port = Number(m[1])
+ return port > 0 && port < 65536 ? port : undefined
+ }
+
+ // From the app's page: where its browser goes to open a page on that port.
+ grantUrl(port: number, path: string): string {
+ const exp = this.now() + GRANT_MS
+ const to = path.startsWith('/') && !path.startsWith('//') ? path : '/'
+ return `https://${port}-${this.publicHost}${ENTER}?e=${exp}&g=${this.sign(`${port}.${exp}`)}&to=${encodeURIComponent(to)}`
+ }
+
+ private cookieValue(port: number): string {
+ return this.sign(`cookie.${port}-${this.publicHost}`)
+ }
+
+ signedIn(req: IncomingMessage, port: number): boolean {
+ const got = /(?:^|;\s*)tucano_preview=([^;]+)/.exec(req.headers.cookie ?? '')?.[1]
+ return !!got && safeEqual(got, this.cookieValue(port))
+ }
+
+ // Everything asked at a preview address comes here, and nothing else of the server answers it.
+ handle(req: IncomingMessage, res: ServerResponse, port: number): void {
+ const url = new URL(req.url ?? '/', 'http://x')
+ if (url.pathname === ENTER) {
+ const exp = Number(url.searchParams.get('e'))
+ const ok = exp > this.now() && exp - this.now() <= GRANT_MS && safeEqual(url.searchParams.get('g') ?? '', this.sign(`${port}.${exp}`))
+ if (!ok) return void page(res, 403, 'Esse link de prévia venceu. Abra a página de novo pelo Tucano. · This preview link expired. Open the page again from Tucano.')
+ const to = url.searchParams.get('to') ?? '/'
+ return void res
+ .writeHead(302, {
+ 'set-cookie': `${COOKIE}=${this.cookieValue(port)}; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=43200`,
+ location: to.startsWith('/') && !to.startsWith('//') ? to : '/',
+ 'cache-control': 'no-store',
+ 'referrer-policy': 'no-referrer'
+ })
+ .end()
+ }
+ if (!this.signedIn(req, port)) return void page(res, 401, 'Abra esta página pelo Tucano: é dele que sai o acesso. · Open this page from Tucano: that’s where access comes from.')
+ if (!this.allowed(port)) return void page(res, 404, 'Nenhum agente está servindo uma página nessa porta agora. · No agent is serving a page on that port right now.')
+ const up = request(
+ { host: '127.0.0.1', port, method: req.method, path: req.url, headers: forwarded(req, port, { 'x-forwarded-host': req.headers.host ?? '', 'x-forwarded-proto': 'https' }) },
+ (r) => {
+ res.writeHead(r.statusCode ?? 502, r.headers)
+ r.pipe(res)
+ }
+ )
+ up.on('error', () => (res.headersSent ? res.destroy() : page(res, 502, 'A página do agente não respondeu. Ela pode ter parado. · The agent’s page didn’t answer. It may have stopped.')))
+ req.pipe(up)
+ }
+
+ // A WebSocket (a dev server reloading itself as the code changes): the same checks, then the bytes both ways.
+ upgrade(req: IncomingMessage, socket: Socket, head: Buffer, port: number): void {
+ if (!this.signedIn(req, port) || !this.allowed(port)) return void socket.destroy()
+ const up = connect(port, '127.0.0.1', () => {
+ const lines = Object.entries(forwarded(req, port)).flatMap(([k, v]) => (Array.isArray(v) ? v : [v]).map((x) => `${k}: ${x}`))
+ up.write(`${req.method} ${req.url} HTTP/1.1\r\n${lines.join('\r\n')}\r\n\r\n`)
+ if (head.length) up.write(head)
+ socket.pipe(up).pipe(socket)
+ })
+ const end = (): void => {
+ up.destroy()
+ socket.destroy()
+ }
+ up.on('error', end)
+ socket.on('error', end)
+ }
+}
+
+function page(res: ServerResponse, status: number, text: string): void {
+ res
+ .writeHead(status, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store', 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'", 'x-content-type-options': 'nosniff' })
+ .end(`<!doctype html><meta charset="utf-8"><title>Tucano</title><style>body{font:15px system-ui;display:grid;place-items:center;height:100vh;margin:0;background:#f6f3ee;color:#1d1a16}@media(prefers-color-scheme:dark){body{background:#1a1917;color:#f1ece4}}p{max-width:460px;padding:24px;line-height:1.5;opacity:.85}</style><p>${text.replace(/[&<>]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' })[c]!)}</p>`)
+}
diff --git a/src/shared/rpc.ts b/src/shared/rpc.ts
index 9de4ea6..422d120 100644
--- a/src/shared/rpc.ts
+++ b/src/shared/rpc.ts
@@ -19,6 +19,7 @@ export interface Snapshot {
skills: Skill[]
platform: Os
packaged: boolean // installed app, not `npm run dev` (opening at login only works there)
+ isolatedComputers: boolean // agents can have an isolated Linux computer: Docker is there (not inside a server's container)
demoServer?: { command: string; args: string[] } // the bundled demo connector, when available
}
@@ -146,6 +147,7 @@ export interface Api {
wikiRunReview(): void // reviews now, in the background; a 'wiki' event when done
wikiDismissFinding(p: { id: string }): void // and refuses its fix
wikiImport(p: { dir: string }): WikiImport // an Obsidian vault copied in, as it is
+ wikiImportZip(p: { path: string }): WikiImport // the same, from a .zip sent to a server (src/server's /upload)
setWikiCapture(p: { conversationId: string; on: boolean }): void
setThreads(p: { conversationId: string; on: boolean }): void
setWikiDir(p: { dir: string | null }): Promise<string> // null: back to the app's own folder; returns where it is now
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 45e04ad..e1ff0c7 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -252,6 +252,7 @@ export interface VoiceStatus {
export interface LocalInfo {
kind: 'image' | 'video' | 'pdf' | 'folder' | 'file'
url?: string // to see it here: images and videos
+ download?: string // on a server, where the file isn't on this computer: to save it here
}
export interface Settings {
diff --git a/test/agent-import.test.ts b/test/agent-import.test.ts
index 2ddbd8d..a2d4414 100644
--- a/test/agent-import.test.ts
+++ b/test/agent-import.test.ts
@@ -1,11 +1,11 @@
-import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs'
+import { existsSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { deflateRawSync } from 'node:zlib'
import { describe, expect, it } from 'vitest'
import { Db } from '../src/core/db'
import { applyForeignTeam, hueColor, IMPORT_CAPS, openBotSchedule, readForeignZip, tucanoSchedule } from '../src/core/agent-import'
-import { zipFromBuffer, zipFromFile } from '../src/core/zip'
+import { extractZip, zipFromBuffer, zipFromFile } from '../src/core/zip'
const fresh = (): Db => new Db(join(mkdtempSync(join(tmpdir(), 'ad-import-')), 'test.db'))
@@ -377,3 +377,23 @@ describe('importing agents from Grok Bot, through our skill', () => {
expect(tucanoSchedule({ days: [], time: '09:00' })).toBeUndefined()
})
})
+
+describe('a vault sent to a server as a .zip', () => {
+ it('unpacks it, the zipped folder as the root, without the Mac’s extras', () => {
+ const to = mkdtempSync(join(tmpdir(), 'tucano-unzip-'))
+ const z = zipFromBuffer(zip({ 'Cofre/Pessoas/Ana.md': '# Ana', 'Cofre/img/foto.png': Buffer.from([1, 2, 3]), '__MACOSX/Cofre/._Ana.md': 'x', 'Cofre/.DS_Store': 'x' }, { deflate: true }))
+ const root = extractZip(z, to)
+ expect(root).toBe(join(to, 'Cofre'))
+ expect(readFileSync(join(root, 'Pessoas', 'Ana.md'), 'utf8')).toBe('# Ana')
+ expect(readFileSync(join(root, 'img', 'foto.png'))).toEqual(Buffer.from([1, 2, 3]))
+ expect(existsSync(join(to, '__MACOSX'))).toBe(false)
+ expect(existsSync(join(root, '.DS_Store'))).toBe(false)
+ })
+
+ it('refuses a path that would land outside, and one too big', () => {
+ for (const name of ['../fora.md', 'a/../../fora.md', '/etc/x.md', 'C:/x.md'])
+ expect(() => extractZip(zipFromBuffer(zip({ [name]: 'x' })), mkdtempSync(join(tmpdir(), 'tucano-unzip-'))), name).toThrow()
+ expect(() => extractZip(zipFromBuffer(zip({ 'a.md': 'x'.repeat(100) })), mkdtempSync(join(tmpdir(), 'tucano-unzip-')), { file: 10, total: 1000 })).toThrow()
+ expect(() => extractZip(zipFromBuffer(zip({ 'a.md': 'x'.repeat(60), 'b.md': 'x'.repeat(60) })), mkdtempSync(join(tmpdir(), 'tucano-unzip-')), { file: 100, total: 100 })).toThrow()
+ })
+})
diff --git a/test/chrome-close.test.ts b/test/chrome-close.test.ts
index c6ca914..dc22f97 100644
--- a/test/chrome-close.test.ts
+++ b/test/chrome-close.test.ts
@@ -32,4 +32,21 @@ describe.skipIf(!hasChrome())('closing an agent’s Chrome', () => {
await chrome.run('ada', 'close')
expect((await chrome.run('ada', 'open', { url })).title).toBe('signed in')
}, 60_000)
+
+ it('closes a Chrome left idle, and reopens it on the same page, still signed in', async () => {
+ const idle = new ChromeBrowsers(mkdtempSync(join(tmpdir(), 'tucano-chrome-')), () => {}, undefined, undefined, false, 600)
+ try {
+ await idle.run('bia', 'open', { url: `${url}login` })
+ await idle.run('bia', 'open', { url: `${url}page` })
+ expect(idle.running('bia')).toBe(true)
+ for (let i = 0; i < 150 && idle.running('bia'); i++) await new Promise((r) => setTimeout(r, 200))
+ expect(idle.running('bia')).toBe(false)
+ // The next ask opens it again where it was: no url given, the page it left.
+ const back = await idle.run('bia', 'snapshot')
+ expect(back.url).toBe(`${url}page`)
+ expect(back.title).toBe('signed in')
+ } finally {
+ idle.quit()
+ }
+ }, 60_000)
})
diff --git a/test/local-paths.test.ts b/test/local-paths.test.ts
index 9ceba38..baac177 100644
--- a/test/local-paths.test.ts
+++ b/test/local-paths.test.ts
@@ -142,4 +142,13 @@ describe.runIf(process.platform !== 'win32')('what a path can do', () => {
const [sig] = url.pathname.slice(1).split('/')
expect(verifyLocalUrl('chave', new URL(`tucano://local/${sig}/${Buffer.from('/etc/passwd').toString('base64url')}`))).toBeNull()
})
+
+ it("on a server, the same signature under the server's own /local/ path", () => {
+ const path = localUrl('chave', '/home/tucano/work/relatório.pdf', '/local')
+ expect(path.startsWith('/local/')).toBe(true)
+ // What src/server does with the address it's asked for.
+ const asked = (p: string): string | null => verifyLocalUrl('chave', new URL(p.replace(/^\/local/, ''), 'tucano://local'))
+ expect(asked(path)).toBe('/home/tucano/work/relatório.pdf')
+ expect(asked(path.replace(/\/[^/]+$/, `/${Buffer.from('/home/tucano/.tucano-server/server.key').toString('base64url')}`))).toBeNull()
+ })
})
diff --git a/test/preview.test.ts b/test/preview.test.ts
new file mode 100644
index 0000000..5c0f579
--- /dev/null
+++ b/test/preview.test.ts
@@ -0,0 +1,140 @@
+import { randomBytes } from 'node:crypto'
+import { createServer, request, type IncomingHttpHeaders, type Server } from 'node:http'
+import { createServer as tcpServer, connect, type AddressInfo, type Socket } from 'node:net'
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import { Preview, withoutOurCookies } from '../src/server/preview'
+
+// An agent's page on the loopback, and the server's front door in front of it (as src/server does).
+let site: Server
+let ws: ReturnType<typeof tcpServer>
+let front: Server
+let sitePort = 0
+let wsPort = 0
+let frontPort = 0
+let seen: IncomingHttpHeaders = {}
+let now = 1_000_000
+const preview = new Preview(randomBytes(32), 'ana.example.com', (p) => p === sitePort || p === wsPort, () => now)
+const listen = (s: { listen: (port: number, host: string, cb: () => void) => unknown; address: () => unknown }): Promise<number> => new Promise((r) => void s.listen(0, '127.0.0.1', () => r((s.address() as AddressInfo).port)))
+
+beforeAll(async () => {
+ site = createServer((req, res) => {
+ seen = req.headers
+ res.writeHead(200, { 'content-type': 'text/plain' }).end(`site:${req.url}`)
+ })
+ sitePort = await listen(site)
+ // A WebSocket-ish server: answers the upgrade, then echoes.
+ ws = tcpServer((sock) => {
+ sock.once('data', () => {
+ sock.write('HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n')
+ sock.on('data', (d) => sock.write(`echo:${d}`))
+ })
+ })
+ wsPort = await listen(ws)
+ front = createServer((req, res) => {
+ const p = preview.portOf(req.headers.host)
+ if (p) preview.handle(req, res, p)
+ else res.writeHead(418).end()
+ })
+ front.on('upgrade', (req, socket: Socket, head) => {
+ const p = preview.portOf(req.headers.host)
+ if (p) preview.upgrade(req, socket, head, p)
+ else socket.destroy()
+ })
+ frontPort = await listen(front)
+})
+afterAll(() => {
+ site.close()
+ ws.close()
+ front.close()
+})
+
+const ask = (host: string, path: string, cookie?: string): Promise<{ status: number; headers: IncomingHttpHeaders; body: string }> =>
+ new Promise((resolve, reject) => {
+ const r = request({ host: '127.0.0.1', port: frontPort, path, headers: { host, ...(cookie ? { cookie } : {}) } }, (res) => {
+ let body = ''
+ res.on('data', (c) => (body += c))
+ res.on('end', () => resolve({ status: res.statusCode ?? 0, headers: res.headers, body }))
+ })
+ r.on('error', reject)
+ r.end()
+ })
+const signIn = async (port: number): Promise<string> => {
+ const grant = new URL(preview.grantUrl(port, '/app?x=1'))
+ const r = await ask(grant.host, `${grant.pathname}${grant.search}`)
+ expect(r.status).toBe(302)
+ expect(r.headers.location).toBe('/app?x=1')
+ return String(r.headers['set-cookie']).split(';')[0]!
+}
+
+describe("an agent's page at an address of its own", () => {
+ it('knows its own preview addresses, and nothing else', () => {
+ expect(preview.portOf('5173-ana.example.com')).toBe(5173)
+ expect(preview.portOf('ana.example.com')).toBeUndefined() // Tucano's own address
+ expect(preview.portOf('5173-bruno.example.com')).toBeUndefined()
+ expect(preview.portOf('99999-ana.example.com')).toBeUndefined()
+ expect(preview.portOf(undefined)).toBeUndefined()
+ })
+
+ it('signs in with a grant from the app, and passes the page through without our cookies', async () => {
+ const host = `${sitePort}-ana.example.com`
+ expect((await ask(host, '/app')).status).toBe(401)
+ const cookie = await signIn(sitePort)
+ const r = await ask(host, '/app?x=1', `${cookie}; tucano=the-servers-token; theirs=1`)
+ expect(r.status).toBe(200)
+ expect(r.body).toBe('site:/app?x=1')
+ expect(seen.cookie).toBe('theirs=1') // the page never sees Tucano's cookies
+ expect(seen.host).toBe(`127.0.0.1:${sitePort}`) // as a dev server expects (Vite refuses other hosts)
+ // With only our cookies, as a browser sends them: none left, and the page still answers.
+ const only = await ask(host, '/', cookie)
+ expect(only.status).toBe(200)
+ expect(seen.cookie).toBeUndefined()
+ })
+
+ it('refuses a grant that expired, was changed, or is for another port', async () => {
+ const grant = new URL(preview.grantUrl(sitePort, '/'))
+ const tampered = grant.search.replace(/g=[^&]+/, 'g=forged')
+ expect((await ask(grant.host, `${grant.pathname}${tampered}`)).status).toBe(403)
+ expect((await ask(`${wsPort}-ana.example.com`, `${grant.pathname}${grant.search}`)).status).toBe(403)
+ now += 6 * 60_000
+ expect((await ask(grant.host, `${grant.pathname}${grant.search}`)).status).toBe(403)
+ now -= 6 * 60_000
+ // A cookie made for one port opens no other.
+ const cookie = await signIn(sitePort)
+ expect((await ask(`${wsPort}-ana.example.com`, '/', cookie)).status).toBe(401)
+ })
+
+ it('passes nothing to a port no agent serves', async () => {
+ const off = new Preview(randomBytes(32), 'ana.example.com', () => false)
+ const grant = new URL(off.grantUrl(sitePort, '/'))
+ const s = createServer((req, res) => off.handle(req, res, sitePort))
+ const p = await listen(s)
+ const get = (path: string, cookie?: string): Promise<number> =>
+ new Promise((r) => request({ host: '127.0.0.1', port: p, path, headers: { host: grant.host, ...(cookie ? { cookie } : {}) } }, (res) => (res.resume(), r(res.statusCode ?? 0))).end())
+ const entered = await new Promise<string>((r) => request({ host: '127.0.0.1', port: p, path: `${grant.pathname}${grant.search}`, headers: { host: grant.host } }, (res) => (res.resume(), r(String(res.headers['set-cookie']).split(';')[0]!))).end())
+ expect(await get('/', entered)).toBe(404)
+ s.close()
+ })
+
+ it('carries a WebSocket both ways, signed in only', async () => {
+ const cookie = await signIn(wsPort)
+ const talk = (withCookie: boolean): Promise<string> =>
+ new Promise((resolve) => {
+ const sock = connect(frontPort, '127.0.0.1', () => sock.write(`GET /hmr HTTP/1.1\r\nHost: ${wsPort}-ana.example.com\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n${withCookie ? `Cookie: ${cookie}\r\n` : ''}\r\n`))
+ let got = ''
+ sock.on('data', (d) => {
+ got += d
+ if (got.includes('101') && !got.includes('echo')) sock.write('ping')
+ if (got.includes('echo:ping')) (sock.destroy(), resolve(got))
+ })
+ sock.on('close', () => resolve(got))
+ })
+ expect(await talk(true)).toContain('echo:ping')
+ expect(await talk(false)).toBe('')
+ })
+
+ it('keeps only the page’s own cookies', () => {
+ expect(withoutOurCookies('a=1; tucano=x; tucano_preview=y; b=2')).toBe('a=1; b=2')
+ expect(withoutOurCookies('tucano=x')).toBeUndefined()
+ expect(withoutOurCookies(undefined)).toBeUndefined()
+ })
+})
diff --git a/test/server.test.ts b/test/server.test.ts
index a96712e..5b93f8a 100644
--- a/test/server.test.ts
+++ b/test/server.test.ts
@@ -4,6 +4,7 @@ import type { AddressInfo } from 'node:net'
import { networkInterfaces } from 'node:os'
import { describe, expect, it } from 'vitest'
import { Forwarder, isPrivate } from '../src/server/forward'
+import { clientIp, decodedPath, Limiter, MAX_FAILS, PAGE_HEADERS, sameOrigin, WINDOW_MS } from '../src/server/guard'
import { vault } from '../src/server/vault'
describe('the server vault', () => {
@@ -48,3 +49,41 @@ describe('passing services through on a private address', () => {
await new Promise((r) => page.close(r))
})
})
+
+describe('the server on the internet', () => {
+ const req = (headers: Record<string, string | string[]>, remoteAddress = '10.0.0.9') => ({ headers, socket: { remoteAddress } }) as never
+
+ it('slows a guesser to nothing, one address at a time, and forgets after the window', () => {
+ let now = 0
+ const l = new Limiter(() => now)
+ for (let i = 0; i < MAX_FAILS - 1; i++) l.fail('1.1.1.1')
+ expect(l.blocked('1.1.1.1')).toBe(false)
+ l.fail('1.1.1.1')
+ expect(l.blocked('1.1.1.1')).toBe(true)
+ // Someone else, from another address, still gets in.
+ expect(l.blocked('2.2.2.2')).toBe(false)
+ now += WINDOW_MS + 1
+ expect(l.blocked('1.1.1.1')).toBe(false)
+ })
+
+ it("takes the proxy's word for the address only when told to", () => {
+ const r = req({ 'x-forwarded-for': '6.6.6.6, 203.0.113.7' }, '127.0.0.1')
+ expect(clientIp(r, true)).toBe('203.0.113.7') // the one the proxy itself added
+ expect(clientIp(r, false)).toBe('127.0.0.1') // without a proxy, the header is the asker's own word
+ expect(clientIp(req({}, '127.0.0.1'), true)).toBe('127.0.0.1')
+ })
+
+ it("answers its own page, not a sibling subdomain's", () => {
+ expect(sameOrigin(req({ host: 'ana.pro.example', origin: 'https://ana.pro.example' }))).toBe(true)
+ expect(sameOrigin(req({ host: 'ana.pro.example', origin: 'https://bruno.pro.example' }))).toBe(false)
+ expect(sameOrigin(req({ host: 'ana.pro.example', origin: 'null' }))).toBe(false)
+ expect(sameOrigin(req({ host: 'ana.pro.example' }))).toBe(true) // a navigation, or a program
+ })
+
+ it("can't be framed by another site, and reads a broken path as nothing", () => {
+ expect(PAGE_HEADERS['x-frame-options']).toBe('DENY')
+ expect(PAGE_HEADERS['content-security-policy']).toContain("frame-ancestors 'none'")
+ expect(decodedPath('/a%20b.png')).toBe('/a b.png')
+ expect(decodedPath('/%E0%A4%A')).toBeUndefined()
+ })
+})