Public: anyone can read this; the crew can change it.
Talk reads a link you paste: fetch_url, a page as short Markdown #16365
Check · Review · Land · Live done — Landed and live in production.
talk/fetch → main 0 commits 1 thread · 1 unresolved
19 files
changed +2345
−10
AGENTS.md +2
| @@ -73,6 +73,8 @@ The check queue hands work to a runner through `src/checks/runner.ts` (#13652, R | ||
| 73 | 73 | |
| 74 | 74 | `src/actions/jobs.ts`: `jobReach.override`, a test seam only (a test hands in its own way to reach an app); the real one is `runtimeReach`. A durable job's runs are the app's own rows (`src/jobs.ts`, carried in the app template bundle `templates/app-template.json`; the template repository `trevato/app-template` must take the same files before a forge that reads that repository hands them out); the template's `Jobs` keeps in process memory only the ids of runs being advanced now (`active`), so a restart forgets nothing it needs. |
| 75 | 75 | |
| 76 | `src/core/web_page.ts`: `webPageReach.override`, a test seam only (a test hands the outbound guard its own resolver and allow list); `limiters`, per forge (a WeakMap on its database), each person's fetches of the last hour (`FETCHES_PER_HOUR`, 10,000 people at most), gone on restart, which only forgives an hour; the pages and the links a conversation was shown are rows (`web_page`, `web_page_reach`). | |
| 77 | ||
| 76 | 78 | `src/spawn/child_reach.ts`: `said`, when each hosted forge's refusal of each name was last written to the log (one `[egress] <child> was refused <host>:<port>` line an hour; pruned past 2,000 keys), and `calls`, each child's signed calls in the last minute; both gone on restart, and neither is state (asks and grants are rows: `child_reach_ask`, `child_reach_grant`). `src/actions/ask_host.ts` on a hosted forge: `looking` (the one refresh in flight), `lookedAt` (when the host was last asked, so a page is heard at most every 3 s) and `watching` (the one timer that looks every 10 s while an ask is under an hour old); a restart loses nothing, since every ask is a row (`reach_ask`) and the heartbeat looks again. The terminal door is `src/tui/screens/hostreach.ts` (palette entry for admins; `a` allows for that forge, `e` for every hosted forge, `n` not now, `x` takes a grant back; `allowReach`, `putAsideReach` and `revokeReach` in `actions/child_reach.ts` give the pages and the terminal the same gate and the `forge.reach_*` events). |
| 77 | 79 | |
| 78 | 80 | ## Awake ceiling and the boot |
docs/features/talk.md +23
| @@ -280,3 +280,26 @@ Talk's agent opens the pane on the screen to try: `pane { repo, path?, version?, | ||
| 280 | 280 | - **The terminal**: the conversation's pane (`p`) prints the same address as `Preview: <url>` and the line as `Try: <try>`. |
| 281 | 281 | |
| 282 | 282 | Proof: `test/talk-pane-steer.test.ts`. |
| 283 | ||
| 284 | ## Talk reads a link you paste | |
| 285 | ||
| 286 | Paste a link in Talk and the forge's agent can read the page. The tool is `fetch_url` (`src/core/web_page.ts`, `src/http/mcp/tools/fetch_url.ts`). The page comes back as short Markdown: only its main content, with headings, lists, code (with its language when the page names it), tables and quotes. Images are dropped and their alt text is kept. Links are numbered, and each slice lists the ones it names below it. A long page comes in slices of about 8,000 tokens, and `cursor` reads the next one. The forge keeps a page for 15 minutes, so a second slice costs no second fetch. `fresh: true` fetches again. | |
| 287 | ||
| 288 | In the terminal, open the palette and choose **Read a web page** (`src/tui/forge.ts`). Paste the link and you read the same Markdown the agent reads (`src/tui/screens/docs.ts`, `markdownScreen`). | |
| 289 | ||
| 290 | ### What it will not fetch | |
| 291 | ||
| 292 | - **Private addresses.** Everything goes through the forge's one outbound guard (`src/kernel/outbound.ts`). It reads only https on the standard port. It resolves the name and refuses private, loopback, link-local, CGNAT, benchmarking, protocol-assignment, metadata, NAT64-, 6to4- or IPv4-mapped-wrapped (judged by the address inside), SIIT and Teredo addresses. It connects to the address it checked, and never to the forge's own host. Each redirect is checked again, and after five redirects it stops. | |
| 293 | - **A link the conversation was never shown.** The agent may read a link you wrote in this conversation, or a link on a page it already read here. It may not read a URL that appears only in its own words, so a page cannot talk it into reading somewhere else. | |
| 294 | - **A URL that looks like it carries a credential.** That is a name or password in the URL, or a query value named like one (`token`, `api-key`, `x-api-key`, `access-token`, `auth_token`, `bearer`, `private_key`, `sig`, `sas`, `code`, `X-Amz-Signature`, `X-Amz-Security-Token` and more). It is also a key or token shape anywhere in the URL: a JWT, `sk-ant-…`, `sk-…`, `AKIA…`, `ghp_…`, `github_pat_…`, `xoxb-…` and the shapes the forge redacts from logs. Ask for the link without it. | |
| 295 | - **Other kinds of content.** It reads HTML, plain text, Markdown and JSON (shown pretty-printed). Anything else is refused in one sentence. | |
| 296 | - **More than 60 pages an hour for one person.** This counts both doors together; a page still kept from the last 15 minutes is free. A refusal says when to try again. | |
| 297 | - **More than the caps.** It reads at most 2 MB off the wire and 5 MB once decoded, so a gzip bomb stops at the cap. It waits at most 10 seconds across every redirect. A cut page says `truncated`. | |
| 298 | ||
| 299 | ### Privacy | |
| 300 | ||
| 301 | The request is built fresh each time. It sends `User-Agent: forge-fetch/1` and no cookie, authorization, referer or forwarded-for header. The site still sees the forge's IP address, or, on a hosted forge, the address of the host's egress gate. The forge never sends the URL to a reading service. | |
| 302 | ||
| 303 | Text a reader cannot see is left out: an element that is hidden, invisible, of no size, fully transparent, moved off the page, clipped to nothing, or the colour of its own background. Brackets the page writes are escaped, so a link reads only as its number and the address listed below. The forge's own host is matched by name whatever its case, trailing dot or escaped dot. `/a` and `/a/` are two pages. | |
| 304 | ||
| 305 | What the page says is someone else's text. It reaches the agent fenced, like an issue body, and once the agent has read it, a write you did not ask for waits for your confirm. |
src/apps/egress.ts +2
| @@ -490,6 +490,8 @@ const V6_PRIVATE = [ | ||
| 490 | 490 | "fe80::/10", // link-local |
| 491 | 491 | "fec0::/10", // site-local, deprecated but still routed by some |
| 492 | 492 | "ff00::/8", // multicast |
| 493 | "::ffff:0:0:0/96", // SIIT's IPv4-translated form, as the outbound guard refuses it (#16365) | |
| 494 | "2001::/32", // Teredo, which tunnels to an address it carries | |
| 493 | 495 | ].map((c) => parseCidr(c)!) satisfies Cidr[]; |
| 494 | 496 | const NAT64 = parseCidr("64:ff9b::/96")!; |
| 495 | 497 | const SIX_TO_FOUR = parseCidr("2002::/16")!; |
src/core/migration-pins/20261125001539-web-page.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | 03d48af39013f7129c16cde945588d7a28f0c4aeb75948f79e00d64b79e644e5 |
src/core/migrations/20261125001539-web-page.ts added +26
| @@ -0,0 +1,26 @@ | ||
| 1 | // What `fetch_url` keeps (`core/web_page.ts`): a page's extracted Markdown for 15 minutes, by the | |
| 2 | // URL asked, at most 100 rows; and the links a Talk conversation was shown by a page it fetched, | |
| 3 | // for a day, so its agent may follow them and nothing else it did not hear from the person. | |
| 4 | // Additive. | |
| 5 | export default ` | |
| 6 | CREATE TABLE web_page ( | |
| 7 | url TEXT PRIMARY KEY, | |
| 8 | final_url TEXT NOT NULL, | |
| 9 | status INTEGER NOT NULL, | |
| 10 | title TEXT NOT NULL, | |
| 11 | markdown TEXT NOT NULL, | |
| 12 | links TEXT NOT NULL, | |
| 13 | bytes INTEGER NOT NULL, | |
| 14 | truncated INTEGER NOT NULL, | |
| 15 | at INTEGER NOT NULL | |
| 16 | ); | |
| 17 | CREATE INDEX web_page_at ON web_page (at); | |
| 18 | CREATE TABLE web_page_reach ( | |
| 19 | via TEXT NOT NULL, | |
| 20 | url TEXT NOT NULL, | |
| 21 | at INTEGER NOT NULL, | |
| 22 | PRIMARY KEY (via, url) | |
| 23 | ); | |
| 24 | CREATE INDEX web_page_reach_at ON web_page_reach (at); | |
| 25 | CREATE INDEX web_page_reach_via_at ON web_page_reach (via, at); | |
| 26 | `; |
src/core/web_page.ts added +1447
| @@ -0,0 +1,1447 @@ | ||
| 1 | /** | |
| 2 | * A web page read for Talk's agent and the terminal (`fetch_url`): fetched through the one | |
| 3 | * outbound guard (`kernel/outbound.ts`: https, public addresses only, the judged address pinned, | |
| 4 | * never the forge's own host), each redirect hop judged again, and the page handed back as short | |
| 5 | * Markdown: its main content only, links numbered below the text, in slices of about 8,000 | |
| 6 | * tokens. The request is built fresh and says nothing of who asks: no cookie, no authorization, | |
| 7 | * no referer. The destination still sees the forge's address, or the gate's in a cell. | |
| 8 | * | |
| 9 | * The forge's own agent may fetch only a URL the person wrote in this conversation, or one a page | |
| 10 | * it fetched here links to (Anthropic's rule for its own fetch tool): never one that appears only | |
| 11 | * in what the model wrote. A URL that looks like it carries a credential is refused to everyone. | |
| 12 | * | |
| 13 | * The HTML is someone else's and may be hostile, so the converter is linear by construction: one | |
| 14 | * pass of `indexOf` and character scans (no regular expression runs over markup), an unclosed | |
| 15 | * comment, quote or raw element ends the page there, nesting past `DEPTH_MAX` is flattened and | |
| 16 | * past `ELEMENTS_MAX` elements the rest is left out. Script, style, template, iframe, object, svg | |
| 17 | * and noscript content is never kept. | |
| 18 | * | |
| 19 | * Extracted Markdown is kept in `web_page` for 15 minutes (`fresh` skips it), at most | |
| 20 | * `CACHE_ROWS` rows; the links a conversation was shown are kept in `web_page_reach` for a day. | |
| 21 | */ | |
| 22 | ||
| 23 | import type { Database } from "bun:sqlite"; | |
| 24 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 25 | import { | |
| 26 | GateRefusedError, | |
| 27 | outboundFetch, | |
| 28 | RefusedError, | |
| 29 | type OutboundOptions, | |
| 30 | } from "../kernel/outbound.ts"; | |
| 31 | import { hostKey, isOwnHost } from "../kernel/own_host.ts"; | |
| 32 | import { redactSecrets } from "../kernel/log.ts"; | |
| 33 | import { RateLimiter } from "./ratelimit.ts"; | |
| 34 | ||
| 35 | /** About 8,000 tokens a slice, at about 4 characters a token. */ | |
| 36 | export const SLICE_CHARS = 32_000; | |
| 37 | /** Most bytes read off the wire, and most once decoded (a small gzip can decode to gigabytes). */ | |
| 38 | export const WIRE_MAX = 2 * 1024 * 1024; | |
| 39 | export const DECODED_MAX = 5 * 1024 * 1024; | |
| 40 | export const REDIRECTS_MAX = 5; | |
| 41 | /** One deadline across every hop. */ | |
| 42 | export const DEADLINE_MS = 10_000; | |
| 43 | export const CACHE_MS = 15 * 60_000; | |
| 44 | export const CACHE_ROWS = 100; | |
| 45 | /** Most Markdown kept of one page (about 12 slices); past it the page reads truncated. */ | |
| 46 | export const KEPT_CHARS = 400_000; | |
| 47 | const REACH_MS = 24 * 3600_000; | |
| 48 | const REACH_PER_CONVERSATION = 2000; | |
| 49 | const LINKS_MAX = 500; | |
| 50 | ||
| 51 | /** Pages one person may fetch from the web an hour, through either door; a cached read is free. */ | |
| 52 | export const FETCHES_PER_HOUR = 60; | |
| 53 | const limiters = new WeakMap<Database, RateLimiter>(); | |
| 54 | /** The person's hourly window, counted per forge (`core/ratelimit.ts`, the one limiter). */ | |
| 55 | const limiterOf = (db: Database): RateLimiter => { | |
| 56 | let limiter = limiters.get(db); | |
| 57 | if (limiter === undefined) { | |
| 58 | limiter = new RateLimiter({ perMinute: FETCHES_PER_HOUR, adminPerMinute: FETCHES_PER_HOUR, enabled: true, windowMs: 3600_000, maxKeys: 10_000 }); | |
| 59 | limiters.set(db, limiter); | |
| 60 | } | |
| 61 | return limiter; | |
| 62 | }; | |
| 63 | ||
| 64 | /** A test seam only: how the guard resolves and what it allows. The real one is the default. */ | |
| 65 | export const webPageReach: { override: OutboundOptions | undefined } = { | |
| 66 | override: undefined, | |
| 67 | }; | |
| 68 | ||
| 69 | const TYPES = new Set([ | |
| 70 | "text/html", | |
| 71 | "text/plain", | |
| 72 | "text/markdown", | |
| 73 | "application/json", | |
| 74 | ]); | |
| 75 | ||
| 76 | const HEADERS = { | |
| 77 | "user-agent": "forge-fetch/1", | |
| 78 | accept: "text/html, text/markdown, text/plain, application/json;q=0.9", | |
| 79 | "accept-encoding": "gzip, deflate", | |
| 80 | }; | |
| 81 | ||
| 82 | export interface PageSlice { | |
| 83 | readonly url: string; | |
| 84 | readonly finalUrl: string; | |
| 85 | readonly status: number; | |
| 86 | readonly title: string; | |
| 87 | /** This slice, with the links it names listed below it as `[n]: url`. */ | |
| 88 | readonly markdown: string; | |
| 89 | /** How many links the whole page has. */ | |
| 90 | readonly links: number; | |
| 91 | readonly nextCursor?: string; | |
| 92 | /** The page was cut: past a byte cap, or past what is kept. */ | |
| 93 | readonly truncated: boolean; | |
| 94 | /** The page's size once decoded. */ | |
| 95 | readonly bytes: number; | |
| 96 | } | |
| 97 | ||
| 98 | export interface PageRefusal { | |
| 99 | readonly code: string; | |
| 100 | readonly message: string; | |
| 101 | } | |
| 102 | ||
| 103 | export interface PageAsk { | |
| 104 | readonly url: string; | |
| 105 | readonly cursor?: string | undefined; | |
| 106 | readonly fresh?: boolean | undefined; | |
| 107 | /** The forge's own agent's conversation (`conversation:<id>`); absent for a person's own door. */ | |
| 108 | readonly via?: string | undefined; | |
| 109 | /** The account asking, counted against `FETCHES_PER_HOUR`. */ | |
| 110 | readonly who: string; | |
| 111 | /** The host this request reached the forge on: never fetched. */ | |
| 112 | readonly ownHost?: string | undefined; | |
| 113 | } | |
| 114 | ||
| 115 | const no = (code: string, message: string): Result<never, PageRefusal> => | |
| 116 | err({ code, message }); | |
| 117 | ||
| 118 | /** Query names that carry a credential. */ | |
| 119 | const SECRET_NAMES = | |
| 120 | /^(token|(access|refresh|id|auth|session|security)[-_]?token|(x-)?api[-_]?key|apikey|key|secret|client[-_]?secret|private[-_]?key|password|passwd|pwd|auth|authorization|bearer|sig|sas|signature|x-amz-signature|x-amz-credential|x-amz-security-token|x-goog-signature|x-goog-credential|session|sessionid|sid|jwt|code)$/i; | |
| 121 | /** Credential shapes wherever they sit in a URL: provider keys and tokens by their prefixes. */ | |
| 122 | const SECRET_SHAPES = | |
| 123 | /(sk-ant-[\w-]{8,}|\bsk-[A-Za-z0-9_-]{20,}|\bAKIA[0-9A-Z]{16}|\bASIA[0-9A-Z]{16}|gh[pousr]_[A-Za-z0-9]{16,}|github_pat_[A-Za-z0-9_]{20,}|xox[abprs]-[A-Za-z0-9-]{10,}|glpat-[\w-]{16,}|\beyJ[\w-]{8,}\.[\w-]{8,})/; | |
| 124 | ||
| 125 | const decodeOr = (s: string): string => { | |
| 126 | try { | |
| 127 | return decodeURIComponent(s); | |
| 128 | } catch { | |
| 129 | return s; | |
| 130 | } | |
| 131 | }; | |
| 132 | ||
| 133 | /** Why this URL is not fetched before anything is dialled, or undefined. */ | |
| 134 | export function urlRefusal( | |
| 135 | url: URL, | |
| 136 | ownHost?: string, | |
| 137 | plain = false, | |
| 138 | ): PageRefusal | undefined { | |
| 139 | if (url.protocol !== "https:" && !(plain && url.protocol === "http:")) | |
| 140 | return { code: "not_https", message: "only https pages are read" }; | |
| 141 | if (url.username !== "" || url.password !== "") | |
| 142 | return { | |
| 143 | code: "credential", | |
| 144 | message: | |
| 145 | "a URL with a name or password in it is not fetched: ask for the link without it", | |
| 146 | }; | |
| 147 | if (url.port !== "" && !plain) | |
| 148 | return { code: "port", message: "only the standard https port is fetched" }; | |
| 149 | for (const [name, value] of url.searchParams) | |
| 150 | if ( | |
| 151 | (SECRET_NAMES.test(name) && value.length >= 6) || | |
| 152 | /^eyJ[\w-]{8,}\.[\w-]{8,}/.test(value) | |
| 153 | ) | |
| 154 | return { | |
| 155 | code: "credential", | |
| 156 | message: `this URL looks like it carries a credential (\`${name.slice(0, 40)}\`), so it is not fetched: ask for the link without it`, | |
| 157 | }; | |
| 158 | if (redactSecrets(url.href) !== url.href || SECRET_SHAPES.test(decodeOr(url.href))) | |
| 159 | return { | |
| 160 | code: "credential", | |
| 161 | message: | |
| 162 | "this URL looks like it carries a credential, so it is not fetched: ask for the link without it", | |
| 163 | }; | |
| 164 | if ( | |
| 165 | (ownHost !== undefined && hostKey(url.host) === hostKey(ownHost)) || | |
| 166 | isOwnHost(url) | |
| 167 | ) | |
| 168 | return { | |
| 169 | code: "own_host", | |
| 170 | message: | |
| 171 | "that is this forge's own address: read it with the forge's own tools", | |
| 172 | }; | |
| 173 | return undefined; | |
| 174 | } | |
| 175 | ||
| 176 | /** | |
| 177 | * The form two URLs compare in, and the cache's key: the parsed URL without its fragment. `/a` and | |
| 178 | * `/a/` stay two pages: a server may answer them differently, so one never stands for the other. | |
| 179 | */ | |
| 180 | const sameForm = (url: URL): string => { | |
| 181 | const u = new URL(url.href); | |
| 182 | u.hash = ""; | |
| 183 | return u.href; | |
| 184 | }; | |
| 185 | ||
| 186 | /** The URLs a person's words hold, with or without `https://`. */ | |
| 187 | export function urlsIn(words: string): string[] { | |
| 188 | const found: string[] = []; | |
| 189 | for (const raw of words.split(/[\s<>"'`]+/)) { | |
| 190 | const word = raw.replace(/^[([{]+/, "").replace(/[.,;:!?)\]}*_]+$/, ""); | |
| 191 | if (word.length < 4 || word.length > 2000) continue; | |
| 192 | const scheme = /^https?:\/\//i.test(word); | |
| 193 | if (!scheme && !/^[a-z0-9-]+(\.[a-z0-9-]+)+(\/|$)/i.test(word)) continue; | |
| 194 | const url = URL.parse(scheme ? word : `https://${word}`); | |
| 195 | if (url !== null) found.push(sameForm(url)); | |
| 196 | } | |
| 197 | return found; | |
| 198 | } | |
| 199 | ||
| 200 | /** | |
| 201 | * Whether the conversation was shown this URL: by the person, or as a link of a page fetched in it. | |
| 202 | */ | |
| 203 | function shown(db: Database, via: string, url: URL): boolean { | |
| 204 | const want = sameForm(url); | |
| 205 | const turns = db | |
| 206 | .query< | |
| 207 | { text: string }, | |
| 208 | [string] | |
| 209 | >("SELECT text FROM conversation_turn WHERE conversation_id = ?1 AND role = 'person' AND replaced_at IS NULL") | |
| 210 | .all(via.slice("conversation:".length)); | |
| 211 | if (turns.some((t) => urlsIn(t.text).includes(want))) return true; | |
| 212 | return ( | |
| 213 | db | |
| 214 | .query("SELECT 1 FROM web_page_reach WHERE via = ?1 AND url = ?2") | |
| 215 | .get(via, want) !== null | |
| 216 | ); | |
| 217 | } | |
| 218 | ||
| 219 | /** The links of a page the conversation read, so it may follow them. */ | |
| 220 | function keepReach(db: Database, via: string, links: readonly string[]): void { | |
| 221 | const now = Date.now(); | |
| 222 | db.transaction(() => { | |
| 223 | db.query("DELETE FROM web_page_reach WHERE at < ?1").run(now - REACH_MS); | |
| 224 | const put = db.query( | |
| 225 | "INSERT INTO web_page_reach (via, url, at) VALUES (?1, ?2, ?3) ON CONFLICT(via, url) DO UPDATE SET at = excluded.at", | |
| 226 | ); | |
| 227 | for (const link of links) { | |
| 228 | const url = URL.parse(link); | |
| 229 | if (url !== null) put.run(via, sameForm(url), now); | |
| 230 | } | |
| 231 | db.query( | |
| 232 | "DELETE FROM web_page_reach WHERE via = ?1 AND url NOT IN (SELECT url FROM web_page_reach WHERE via = ?1 ORDER BY at DESC LIMIT ?2)", | |
| 233 | ).run(via, REACH_PER_CONVERSATION); | |
| 234 | })(); | |
| 235 | } | |
| 236 | ||
| 237 | interface Kept { | |
| 238 | final_url: string; | |
| 239 | status: number; | |
| 240 | title: string; | |
| 241 | markdown: string; | |
| 242 | links: string; | |
| 243 | bytes: number; | |
| 244 | truncated: number; | |
| 245 | at: number; | |
| 246 | } | |
| 247 | ||
| 248 | interface Page { | |
| 249 | readonly finalUrl: string; | |
| 250 | readonly status: number; | |
| 251 | readonly title: string; | |
| 252 | readonly markdown: string; | |
| 253 | readonly links: readonly string[]; | |
| 254 | readonly bytes: number; | |
| 255 | readonly truncated: boolean; | |
| 256 | } | |
| 257 | ||
| 258 | /** A page fetched and made Markdown, or why not. */ | |
| 259 | async function fetchFresh( | |
| 260 | start: URL, | |
| 261 | ownHost: string | undefined, | |
| 262 | options: OutboundOptions, | |
| 263 | ): Promise<Result<Page, PageRefusal>> { | |
| 264 | const signal = AbortSignal.timeout(DEADLINE_MS); | |
| 265 | let at = start; | |
| 266 | let res: Response; | |
| 267 | try { | |
| 268 | for (let hop = 0; ; hop++) { | |
| 269 | // Bun decodes gzip itself unless told not to; decoded here, the bytes are counted both ways. | |
| 270 | const init: BunFetchRequestInit = { headers: HEADERS, signal, decompress: false }; | |
| 271 | res = await outboundFetch(at.href, init, options); | |
| 272 | const location = res.headers.get("location"); | |
| 273 | if (res.status < 300 || res.status > 399 || location === null) break; | |
| 274 | await res.body?.cancel().catch(() => undefined); | |
| 275 | if (hop >= REDIRECTS_MAX) | |
| 276 | return no( | |
| 277 | "redirects", | |
| 278 | `the page redirects more than ${REDIRECTS_MAX} times`, | |
| 279 | ); | |
| 280 | const next = URL.parse(location, at.href); | |
| 281 | if (next === null) | |
| 282 | return no( | |
| 283 | "redirect", | |
| 284 | "the page redirects to an address that does not read", | |
| 285 | ); | |
| 286 | const refused = urlRefusal(next, ownHost, options.plain === true); | |
| 287 | if (refused !== undefined) | |
| 288 | return err({ | |
| 289 | code: refused.code, | |
| 290 | message: `the page redirects to an address that is not fetched: ${refused.message}`, | |
| 291 | }); | |
| 292 | at = next; | |
| 293 | } | |
| 294 | } catch (e) { | |
| 295 | if (e instanceof RefusedError) | |
| 296 | return no("refused", `${e.message} (${at.host})`); | |
| 297 | if (e instanceof GateRefusedError) return no("refused", e.message); | |
| 298 | if (signal.aborted) | |
| 299 | return no( | |
| 300 | "timeout", | |
| 301 | `the page did not answer within ${DEADLINE_MS / 1000} seconds`, | |
| 302 | ); | |
| 303 | return no( | |
| 304 | "unreachable", | |
| 305 | `could not read the page: ${e instanceof Error ? e.message.slice(0, 200) : "no answer"}`, | |
| 306 | ); | |
| 307 | } | |
| 308 | const type = (res.headers.get("content-type") ?? "") | |
| 309 | .split(";")[0]! | |
| 310 | .trim() | |
| 311 | .toLowerCase(); | |
| 312 | if (!TYPES.has(type)) { | |
| 313 | await res.body?.cancel().catch(() => undefined); | |
| 314 | return no( | |
| 315 | "content_type", | |
| 316 | `the page is ${type === "" ? "of no stated type" : type.slice(0, 80)}; only HTML, text, Markdown and JSON are read`, | |
| 317 | ); | |
| 318 | } | |
| 319 | const body = await readCapped(res, signal); | |
| 320 | const charset = | |
| 321 | /charset=["']?([\w-]{1,40})/i.exec( | |
| 322 | res.headers.get("content-type") ?? "", | |
| 323 | )?.[1] ?? "utf-8"; | |
| 324 | let text: string; | |
| 325 | try { | |
| 326 | text = new TextDecoder(charset as ConstructorParameters<typeof TextDecoder>[0]).decode(body.bytes); | |
| 327 | } catch { | |
| 328 | text = new TextDecoder().decode(body.bytes); | |
| 329 | } | |
| 330 | const made = asMarkdown(type, text, at.href); | |
| 331 | const cut = made.markdown.length > KEPT_CHARS; | |
| 332 | return ok({ | |
| 333 | finalUrl: at.href, | |
| 334 | status: res.status, | |
| 335 | title: made.title, | |
| 336 | markdown: cut ? made.markdown.slice(0, KEPT_CHARS) : made.markdown, | |
| 337 | links: made.links.slice(0, LINKS_MAX), | |
| 338 | bytes: body.bytes.byteLength, | |
| 339 | truncated: body.cut || cut, | |
| 340 | }); | |
| 341 | } | |
| 342 | ||
| 343 | /** | |
| 344 | * The body, decoded, stopped at `WIRE_MAX` bytes off the wire or `DECODED_MAX` decoded, whichever | |
| 345 | * comes first; what was read by then is kept. | |
| 346 | */ | |
| 347 | async function readCapped( | |
| 348 | res: Response, | |
| 349 | signal: AbortSignal, | |
| 350 | ): Promise<{ bytes: Uint8Array; cut: boolean }> { | |
| 351 | if (res.body === null) return { bytes: new Uint8Array(), cut: false }; | |
| 352 | let wire = 0; | |
| 353 | let cut = false; | |
| 354 | const counted = res.body.pipeThrough( | |
| 355 | new TransformStream<Uint8Array, Uint8Array>({ | |
| 356 | transform(chunk, c) { | |
| 357 | if (cut) return; | |
| 358 | wire += chunk.byteLength; | |
| 359 | if (wire > WIRE_MAX) { | |
| 360 | cut = true; | |
| 361 | c.enqueue(chunk.subarray(0, chunk.byteLength - (wire - WIRE_MAX))); | |
| 362 | c.terminate(); | |
| 363 | return; | |
| 364 | } | |
| 365 | c.enqueue(chunk); | |
| 366 | }, | |
| 367 | }), | |
| 368 | { signal }, | |
| 369 | ); | |
| 370 | const encoding = (res.headers.get("content-encoding") ?? "") | |
| 371 | .trim() | |
| 372 | .toLowerCase(); | |
| 373 | const format = | |
| 374 | encoding === "gzip" || encoding === "x-gzip" | |
| 375 | ? "gzip" | |
| 376 | : encoding === "deflate" | |
| 377 | ? "deflate" | |
| 378 | : undefined; | |
| 379 | const decoded = | |
| 380 | format === undefined | |
| 381 | ? counted | |
| 382 | : counted.pipeThrough(new DecompressionStream(format) as unknown as ReadableWritablePair<Uint8Array, Uint8Array>); | |
| 383 | const reader = decoded.getReader(); | |
| 384 | const parts: Uint8Array[] = []; | |
| 385 | let size = 0; | |
| 386 | try { | |
| 387 | for (;;) { | |
| 388 | const { done, value } = await reader.read(); | |
| 389 | if (done) break; | |
| 390 | const room = DECODED_MAX - size; | |
| 391 | if (value.byteLength > room) { | |
| 392 | parts.push(value.subarray(0, room)); | |
| 393 | size += room; | |
| 394 | cut = true; | |
| 395 | await reader.cancel().catch(() => undefined); | |
| 396 | break; | |
| 397 | } | |
| 398 | parts.push(value); | |
| 399 | size += value.byteLength; | |
| 400 | } | |
| 401 | } catch { | |
| 402 | // A body cut at the wire cap ends mid-stream for the decoder, and a timeout ends it too: what | |
| 403 | // was decoded by then is the page. | |
| 404 | cut = true; | |
| 405 | } | |
| 406 | return { bytes: Buffer.concat(parts, size), cut }; | |
| 407 | } | |
| 408 | ||
| 409 | function asMarkdown(type: string, text: string, base: string): PageMarkdown { | |
| 410 | if (type === "text/html") return pageMarkdown(text, base); | |
| 411 | if (type === "application/json") { | |
| 412 | try { | |
| 413 | return { | |
| 414 | title: "", | |
| 415 | markdown: `\`\`\`json\n${JSON.stringify(JSON.parse(text), null, 1)}\n\`\`\``, | |
| 416 | links: [], | |
| 417 | }; | |
| 418 | } catch { | |
| 419 | // Not JSON after all: read as text. | |
| 420 | } | |
| 421 | } | |
| 422 | return { title: "", markdown: text, links: [] }; | |
| 423 | } | |
| 424 | ||
| 425 | /** The slice from `from`, ended at a paragraph where one is near, and the cursor after it. */ | |
| 426 | function sliceAt( | |
| 427 | markdown: string, | |
| 428 | from: number, | |
| 429 | room: number, | |
| 430 | ): { text: string; next?: number } { | |
| 431 | if (markdown.length - from <= room) return { text: markdown.slice(from) }; | |
| 432 | const hard = from + room; | |
| 433 | const para = markdown.lastIndexOf("\n\n", hard); | |
| 434 | const line = markdown.lastIndexOf("\n", hard); | |
| 435 | const end = | |
| 436 | para > from + room / 2 ? para : line > from + room / 2 ? line : hard; | |
| 437 | return { text: markdown.slice(from, end), next: end }; | |
| 438 | } | |
| 439 | ||
| 440 | /** | |
| 441 | * The slice from `from` with its links listed below it, the two within `SLICE_CHARS`: cut once, | |
| 442 | * then cut again shorter by what its link list took (a shorter slice names no more links). | |
| 443 | */ | |
| 444 | function sliceWithLinks( | |
| 445 | page: Page, | |
| 446 | from: number, | |
| 447 | ): { text: string; next?: number } { | |
| 448 | const first = sliceAt(page.markdown, from, SLICE_CHARS); | |
| 449 | const listed = withLinks(first.text, page.links); | |
| 450 | if (listed.length <= SLICE_CHARS) return { ...first, text: listed }; | |
| 451 | const cut = sliceAt( | |
| 452 | page.markdown, | |
| 453 | from, | |
| 454 | Math.max(SLICE_CHARS / 4, SLICE_CHARS - (listed.length - first.text.length)), | |
| 455 | ); | |
| 456 | return { ...cut, text: withLinks(cut.text, page.links) }; | |
| 457 | } | |
| 458 | ||
| 459 | /** A slice with the links it names listed below it. */ | |
| 460 | function withLinks(text: string, links: readonly string[]): string { | |
| 461 | const named = new Set<number>(); | |
| 462 | for (let at = text.indexOf("]["); at >= 0; at = text.indexOf("][", at + 2)) { | |
| 463 | const close = text.indexOf("]", at + 2); | |
| 464 | const n = | |
| 465 | close > at + 2 && close - at < 8 | |
| 466 | ? Number(text.slice(at + 2, close)) | |
| 467 | : NaN; | |
| 468 | if (Number.isInteger(n) && n >= 1 && n <= links.length) named.add(n); | |
| 469 | } | |
| 470 | if (named.size === 0) return text; | |
| 471 | return `${text}\n\n${[...named] | |
| 472 | .sort((a, b) => a - b) | |
| 473 | .map((n) => `[${n}]: ${links[n - 1]!}`) | |
| 474 | .join("\n")}`; | |
| 475 | } | |
| 476 | ||
| 477 | /** Read a page as Markdown, one slice at a time. */ | |
| 478 | export async function fetchPage( | |
| 479 | db: Database, | |
| 480 | ask: PageAsk, | |
| 481 | ): Promise<Result<PageSlice, PageRefusal>> { | |
| 482 | const options = webPageReach.override ?? {}; | |
| 483 | const url = URL.parse(ask.url.trim()); | |
| 484 | if (url === null) | |
| 485 | return no( | |
| 486 | "bad_url", | |
| 487 | "that is not a URL: give the whole link, starting https://", | |
| 488 | ); | |
| 489 | const refused = urlRefusal(url, ask.ownHost, options.plain === true); | |
| 490 | if (refused !== undefined) return err(refused); | |
| 491 | if (ask.via !== undefined && !shown(db, ask.via, url)) | |
| 492 | return no( | |
| 493 | "not_shown", | |
| 494 | "only a page the person linked in this conversation, or one a fetched page links to, is read: ask them to paste the link", | |
| 495 | ); | |
| 496 | if (ask.cursor !== undefined && !/^\d{1,7}$/.test(ask.cursor)) | |
| 497 | return no("bad_cursor", "cursor is the nextCursor a slice gave"); | |
| 498 | const from = ask.cursor === undefined ? 0 : Number(ask.cursor); | |
| 499 | const key = sameForm(url); | |
| 500 | const now = Date.now(); | |
| 501 | const kept = | |
| 502 | ask.fresh === true | |
| 503 | ? null | |
| 504 | : db | |
| 505 | .query< | |
| 506 | Kept, | |
| 507 | [string, number] | |
| 508 | >("SELECT * FROM web_page WHERE url = ?1 AND at >= ?2") | |
| 509 | .get(key, now - CACHE_MS); | |
| 510 | let page: Page; | |
| 511 | if (kept !== null) { | |
| 512 | page = { | |
| 513 | finalUrl: kept.final_url, | |
| 514 | status: kept.status, | |
| 515 | title: kept.title, | |
| 516 | markdown: kept.markdown, | |
| 517 | links: JSON.parse(kept.links) as string[], | |
| 518 | bytes: kept.bytes, | |
| 519 | truncated: kept.truncated === 1, | |
| 520 | }; | |
| 521 | } else { | |
| 522 | const turn = limiterOf(db).take(`fetch:${ask.who}`, "rw"); | |
| 523 | if (!turn.allowed) { | |
| 524 | const at = new Date(turn.reset * 1000).toISOString().slice(11, 16); | |
| 525 | return no("rate_limited", `at most ${FETCHES_PER_HOUR} pages an hour are fetched for one person; try again in ${Math.ceil(turn.retryAfter / 60)} minutes (${at} UTC)`); | |
| 526 | } | |
| 527 | const got = await fetchFresh(url, ask.ownHost, options); | |
| 528 | if (!got.ok) return got; | |
| 529 | page = got.value; | |
| 530 | db.transaction(() => { | |
| 531 | db.query("DELETE FROM web_page WHERE at < ?1").run(now - CACHE_MS); | |
| 532 | db.query( | |
| 533 | `INSERT INTO web_page (url, final_url, status, title, markdown, links, bytes, truncated, at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9) | |
| 534 | ON CONFLICT(url) DO UPDATE SET final_url = excluded.final_url, status = excluded.status, title = excluded.title, markdown = excluded.markdown, | |
| 535 | links = excluded.links, bytes = excluded.bytes, truncated = excluded.truncated, at = excluded.at`, | |
| 536 | ).run( | |
| 537 | key, | |
| 538 | page.finalUrl, | |
| 539 | page.status, | |
| 540 | page.title, | |
| 541 | page.markdown, | |
| 542 | JSON.stringify(page.links), | |
| 543 | page.bytes, | |
| 544 | page.truncated ? 1 : 0, | |
| 545 | now, | |
| 546 | ); | |
| 547 | db.query( | |
| 548 | "DELETE FROM web_page WHERE url NOT IN (SELECT url FROM web_page ORDER BY at DESC LIMIT ?1)", | |
| 549 | ).run(CACHE_ROWS); | |
| 550 | })(); | |
| 551 | } | |
| 552 | if (from > 0 && from >= page.markdown.length) | |
| 553 | return no("bad_cursor", "cursor is past the end of the page"); | |
| 554 | if (ask.via !== undefined && page.links.length > 0) | |
| 555 | keepReach(db, ask.via, page.links); | |
| 556 | const slice = sliceWithLinks(page, from); | |
| 557 | return ok({ | |
| 558 | url: url.href, | |
| 559 | finalUrl: page.finalUrl, | |
| 560 | status: page.status, | |
| 561 | title: page.title, | |
| 562 | markdown: slice.text, | |
| 563 | links: page.links.length, | |
| 564 | ...(slice.next === undefined ? {} : { nextCursor: String(slice.next) }), | |
| 565 | truncated: page.truncated, | |
| 566 | bytes: page.bytes, | |
| 567 | }); | |
| 568 | } | |
| 569 | ||
| 570 | /** A slice as a person reads it in the terminal: where it came from, then the Markdown. */ | |
| 571 | export function pageText(slice: PageSlice): string { | |
| 572 | const more = slice.nextCursor === undefined ? "" : `\n\n_The page goes on past this slice (cursor ${slice.nextCursor})._`; | |
| 573 | const cut = slice.truncated ? " It was cut at the size cap." : ""; | |
| 574 | return `${slice.finalUrl} · ${slice.status} · ${slice.bytes} bytes.${cut}\n\n${slice.markdown}${more}`; | |
| 575 | } | |
| 576 | ||
| 577 | // --------------------------------------------------------------------------------------------- | |
| 578 | // HTML to Markdown. | |
| 579 | ||
| 580 | interface Node { | |
| 581 | readonly tag: string; | |
| 582 | readonly attrs: Readonly<Record<string, string>>; | |
| 583 | readonly kids: (Node | string)[]; | |
| 584 | readonly parent: Node | undefined; | |
| 585 | } | |
| 586 | ||
| 587 | /** Deepest nesting kept; deeper elements are read as siblings at this depth. */ | |
| 588 | export const DEPTH_MAX = 256; | |
| 589 | /** Most elements read of one page; past it the rest is left out. */ | |
| 590 | export const ELEMENTS_MAX = 100_000; | |
| 591 | /** The attributes the converter reads; every other is skipped, and a value is cut at 2,048. */ | |
| 592 | const ATTRS = new Set([ | |
| 593 | "href", | |
| 594 | "alt", | |
| 595 | "class", | |
| 596 | "id", | |
| 597 | "role", | |
| 598 | "hidden", | |
| 599 | "aria-hidden", | |
| 600 | "style", | |
| 601 | "data-language", | |
| 602 | ]); | |
| 603 | const ATTR_MAX = 2048; | |
| 604 | ||
| 605 | const VOID = new Set([ | |
| 606 | "area", | |
| 607 | "base", | |
| 608 | "br", | |
| 609 | "col", | |
| 610 | "embed", | |
| 611 | "hr", | |
| 612 | "img", | |
| 613 | "input", | |
| 614 | "link", | |
| 615 | "meta", | |
| 616 | "source", | |
| 617 | "track", | |
| 618 | "wbr", | |
| 619 | "param", | |
| 620 | ]); | |
| 621 | /** Elements whose content is not markup, read to their end tag; only a title's is kept. */ | |
| 622 | const RAW = new Set([ | |
| 623 | "script", | |
| 624 | "style", | |
| 625 | "textarea", | |
| 626 | "title", | |
| 627 | "noscript", | |
| 628 | "template", | |
| 629 | "svg", | |
| 630 | "math", | |
| 631 | "iframe", | |
| 632 | "object", | |
| 633 | "xmp", | |
| 634 | "plaintext", | |
| 635 | ]); | |
| 636 | /** A start tag of the key closes an open element of these: `<p>a<p>b`, `<li>a<li>b`. */ | |
| 637 | const CLOSES: Readonly<Record<string, readonly string[]>> = { | |
| 638 | p: ["p"], | |
| 639 | li: ["li"], | |
| 640 | dt: ["dt", "dd"], | |
| 641 | dd: ["dt", "dd"], | |
| 642 | tr: ["tr", "td", "th"], | |
| 643 | td: ["td", "th"], | |
| 644 | th: ["td", "th"], | |
| 645 | option: ["option"], | |
| 646 | }; | |
| 647 | const BLOCK_CLOSES_P = new Set([ | |
| 648 | "h1", | |
| 649 | "h2", | |
| 650 | "h3", | |
| 651 | "h4", | |
| 652 | "h5", | |
| 653 | "h6", | |
| 654 | "ul", | |
| 655 | "ol", | |
| 656 | "pre", | |
| 657 | "table", | |
| 658 | "div", | |
| 659 | "blockquote", | |
| 660 | "section", | |
| 661 | "article", | |
| 662 | "hr", | |
| 663 | ]); | |
| 664 | ||
| 665 | const ENTITIES: Readonly<Record<string, string>> = { | |
| 666 | amp: "&", | |
| 667 | lt: "<", | |
| 668 | gt: ">", | |
| 669 | quot: '"', | |
| 670 | apos: "'", | |
| 671 | nbsp: " ", | |
| 672 | mdash: "—", | |
| 673 | ndash: "–", | |
| 674 | hellip: "…", | |
| 675 | rsquo: "’", | |
| 676 | lsquo: "‘", | |
| 677 | ldquo: "“", | |
| 678 | rdquo: "”", | |
| 679 | copy: "©", | |
| 680 | reg: "®", | |
| 681 | trade: "™", | |
| 682 | middot: "·", | |
| 683 | bull: "•", | |
| 684 | laquo: "«", | |
| 685 | raquo: "»", | |
| 686 | times: "×", | |
| 687 | rarr: "→", | |
| 688 | larr: "←", | |
| 689 | deg: "°", | |
| 690 | euro: "€", | |
| 691 | pound: "£", | |
| 692 | shy: "", | |
| 693 | zwj: "", | |
| 694 | zwnj: "", | |
| 695 | thinsp: " ", | |
| 696 | ensp: " ", | |
| 697 | emsp: " ", | |
| 698 | }; | |
| 699 | ||
| 700 | /** Character references as characters; bounded, so linear. */ | |
| 701 | const decode = (s: string): string => | |
| 702 | s.indexOf("&") < 0 | |
| 703 | ? s | |
| 704 | : s.replace( | |
| 705 | /&(#[xX][0-9a-fA-F]{1,6}|#[0-9]{1,7}|[a-zA-Z]{2,8});?/g, | |
| 706 | (m, e: string) => { | |
| 707 | if (e[0] === "#") { | |
| 708 | const n = | |
| 709 | e[1] === "x" || e[1] === "X" | |
| 710 | ? parseInt(e.slice(2), 16) | |
| 711 | : parseInt(e.slice(1), 10); | |
| 712 | return n > 0 && n <= 0x10ffff && !(n >= 0xd800 && n <= 0xdfff) | |
| 713 | ? String.fromCodePoint(n) | |
| 714 | : ""; | |
| 715 | } | |
| 716 | return ENTITIES[e.toLowerCase()] ?? m; | |
| 717 | }, | |
| 718 | ); | |
| 719 | ||
| 720 | const isNameChar = (c: number): boolean => | |
| 721 | (c >= 97 && c <= 122) || | |
| 722 | (c >= 65 && c <= 90) || | |
| 723 | (c >= 48 && c <= 57) || | |
| 724 | c === 45 || | |
| 725 | c === 58 || | |
| 726 | c === 95; | |
| 727 | const isSpace = (c: number): boolean => | |
| 728 | c === 32 || c === 9 || c === 10 || c === 13 || c === 12; | |
| 729 | ||
| 730 | /** | |
| 731 | * The page as a tree; never throws, linear in the input: each character is looked at a bounded | |
| 732 | * number of times, and anything left open at the end (a comment, a quote, a script) ends the page. | |
| 733 | */ | |
| 734 | export function parseHtml(html: string): Node { | |
| 735 | const root: Node = { tag: "#root", attrs: {}, kids: [], parent: undefined }; | |
| 736 | const lower = html.toLowerCase(); | |
| 737 | const openCount = new Map<string, number>(); | |
| 738 | let at = root; | |
| 739 | let depth = 0; | |
| 740 | let elements = 0; | |
| 741 | let i = 0; | |
| 742 | const enter = (n: Node) => { | |
| 743 | at = n; | |
| 744 | depth++; | |
| 745 | openCount.set(n.tag, (openCount.get(n.tag) ?? 0) + 1); | |
| 746 | }; | |
| 747 | const leave = () => { | |
| 748 | openCount.set(at.tag, (openCount.get(at.tag) ?? 1) - 1); | |
| 749 | at = at.parent ?? root; | |
| 750 | depth--; | |
| 751 | }; | |
| 752 | const close = (tag: string) => { | |
| 753 | if ((openCount.get(tag) ?? 0) <= 0) return; | |
| 754 | while (at !== root) { | |
| 755 | const was = at.tag; | |
| 756 | leave(); | |
| 757 | if (was === tag) return; | |
| 758 | } | |
| 759 | }; | |
| 760 | const n = html.length; | |
| 761 | while (i < n) { | |
| 762 | const lt = html.indexOf("<", i); | |
| 763 | if (lt < 0) { | |
| 764 | at.kids.push(html.slice(i)); | |
| 765 | break; | |
| 766 | } | |
| 767 | if (lt > i) at.kids.push(html.slice(i, lt)); | |
| 768 | const c1 = html.charCodeAt(lt + 1); | |
| 769 | if (html.startsWith("<!--", lt)) { | |
| 770 | const end = html.indexOf("-->", lt + 4); | |
| 771 | if (end < 0) break; | |
| 772 | i = end + 3; | |
| 773 | continue; | |
| 774 | } | |
| 775 | if (c1 === 33 || c1 === 63) { | |
| 776 | // `<!doctype …>`, `<![CDATA[`, `<?xml …?>`. | |
| 777 | const end = html.indexOf(">", lt); | |
| 778 | if (end < 0) break; | |
| 779 | i = end + 1; | |
| 780 | continue; | |
| 781 | } | |
| 782 | if (c1 === 47) { | |
| 783 | let j = lt + 2; | |
| 784 | while (j < n && isNameChar(html.charCodeAt(j))) j++; | |
| 785 | if (j === lt + 2) { | |
| 786 | at.kids.push("</"); | |
| 787 | i = lt + 2; | |
| 788 | continue; | |
| 789 | } | |
| 790 | const tag = lower.slice(lt + 2, j); | |
| 791 | const end = html.indexOf(">", j); | |
| 792 | if (end < 0) break; | |
| 793 | i = end + 1; | |
| 794 | close(tag); | |
| 795 | continue; | |
| 796 | } | |
| 797 | if (!((c1 >= 97 && c1 <= 122) || (c1 >= 65 && c1 <= 90))) { | |
| 798 | at.kids.push("<"); | |
| 799 | i = lt + 1; | |
| 800 | continue; | |
| 801 | } | |
| 802 | let j = lt + 1; | |
| 803 | while (j < n && isNameChar(html.charCodeAt(j))) j++; | |
| 804 | const tag = lower.slice(lt + 1, j); | |
| 805 | const attrs: Record<string, string> = {}; | |
| 806 | let selfClosing = false; | |
| 807 | let ended = false; | |
| 808 | while (j < n) { | |
| 809 | const c = html.charCodeAt(j); | |
| 810 | if (c === 62) { | |
| 811 | ended = true; | |
| 812 | j++; | |
| 813 | break; | |
| 814 | } | |
| 815 | if (isSpace(c) || c === 47) { | |
| 816 | selfClosing = c === 47; | |
| 817 | j++; | |
| 818 | continue; | |
| 819 | } | |
| 820 | selfClosing = false; | |
| 821 | const nameAt = j; | |
| 822 | while (j < n) { | |
| 823 | const d = html.charCodeAt(j); | |
| 824 | if (isSpace(d) || d === 61 || d === 62 || d === 47) break; | |
| 825 | j++; | |
| 826 | } | |
| 827 | if (j === nameAt) j++; | |
| 828 | const name = lower.slice(nameAt, j); | |
| 829 | while (j < n && isSpace(html.charCodeAt(j))) j++; | |
| 830 | let value = ""; | |
| 831 | if (html.charCodeAt(j) === 61) { | |
| 832 | j++; | |
| 833 | while (j < n && isSpace(html.charCodeAt(j))) j++; | |
| 834 | const q = html.charCodeAt(j); | |
| 835 | if (q === 34 || q === 39) { | |
| 836 | const end = html.indexOf(q === 34 ? '"' : "'", j + 1); | |
| 837 | if (end < 0) { | |
| 838 | j = n; | |
| 839 | break; | |
| 840 | } | |
| 841 | value = html.slice(j + 1, Math.min(end, j + 1 + ATTR_MAX)); | |
| 842 | j = end + 1; | |
| 843 | } else { | |
| 844 | const from = j; | |
| 845 | while ( | |
| 846 | j < n && | |
| 847 | !isSpace(html.charCodeAt(j)) && | |
| 848 | html.charCodeAt(j) !== 62 | |
| 849 | ) | |
| 850 | j++; | |
| 851 | value = html.slice(from, Math.min(j, from + ATTR_MAX)); | |
| 852 | } | |
| 853 | } | |
| 854 | if (ATTRS.has(name) && !(name in attrs)) attrs[name] = decode(value); | |
| 855 | } | |
| 856 | if (!ended) break; | |
| 857 | i = j; | |
| 858 | if (++elements > ELEMENTS_MAX) break; | |
| 859 | const closes = CLOSES[tag] ?? (BLOCK_CLOSES_P.has(tag) ? ["p"] : []); | |
| 860 | if (closes.includes(at.tag)) leave(); | |
| 861 | else if ( | |
| 862 | tag !== "p" && | |
| 863 | at.parent !== undefined && | |
| 864 | closes.includes(at.parent.tag) && | |
| 865 | closes.includes(tag) && | |
| 866 | !["ul", "ol", "table", "tbody", "thead", "dl"].includes(at.tag) | |
| 867 | ) { | |
| 868 | // `<li><b>a<li>`: the open item closes too, but a nested list's item never closes its | |
| 869 | // parent's. | |
| 870 | leave(); | |
| 871 | leave(); | |
| 872 | } | |
| 873 | const node: Node = { tag, attrs, kids: [], parent: at }; | |
| 874 | at.kids.push(node); | |
| 875 | if (RAW.has(tag)) { | |
| 876 | const end = lower.indexOf(`</${tag}`, i); | |
| 877 | if (end < 0) break; | |
| 878 | if (tag === "title") node.kids.push(html.slice(i, end)); | |
| 879 | const gt = html.indexOf(">", end); | |
| 880 | if (gt < 0) break; | |
| 881 | i = gt + 1; | |
| 882 | continue; | |
| 883 | } | |
| 884 | if (VOID.has(tag) || selfClosing) continue; | |
| 885 | if (depth < DEPTH_MAX) enter(node); | |
| 886 | } | |
| 887 | return root; | |
| 888 | } | |
| 889 | ||
| 890 | /** Never content: chrome, controls and what a reader cannot see. */ | |
| 891 | const DROP = new Set([ | |
| 892 | "script", | |
| 893 | "style", | |
| 894 | "noscript", | |
| 895 | "template", | |
| 896 | "svg", | |
| 897 | "math", | |
| 898 | "iframe", | |
| 899 | "object", | |
| 900 | "embed", | |
| 901 | "nav", | |
| 902 | "footer", | |
| 903 | "aside", | |
| 904 | "form", | |
| 905 | "button", | |
| 906 | "input", | |
| 907 | "select", | |
| 908 | "textarea", | |
| 909 | "dialog", | |
| 910 | "label", | |
| 911 | "menu", | |
| 912 | "canvas", | |
| 913 | "video", | |
| 914 | "audio", | |
| 915 | "picture", | |
| 916 | "source", | |
| 917 | "head", | |
| 918 | "link", | |
| 919 | "meta", | |
| 920 | "xmp", | |
| 921 | "plaintext", | |
| 922 | ]); | |
| 923 | const CHROME_ROLES = new Set([ | |
| 924 | "navigation", | |
| 925 | "banner", | |
| 926 | "contentinfo", | |
| 927 | "complementary", | |
| 928 | "search", | |
| 929 | "menu", | |
| 930 | "menubar", | |
| 931 | "toolbar", | |
| 932 | "dialog", | |
| 933 | "alert", | |
| 934 | "tablist", | |
| 935 | ]); | |
| 936 | const CHROME_WORDS = new Set([ | |
| 937 | "nav", | |
| 938 | "navbar", | |
| 939 | "navigation", | |
| 940 | "menu", | |
| 941 | "footer", | |
| 942 | "sidebar", | |
| 943 | "cookie", | |
| 944 | "cookies", | |
| 945 | "consent", | |
| 946 | "banner", | |
| 947 | "share", | |
| 948 | "sharing", | |
| 949 | "social", | |
| 950 | "breadcrumb", | |
| 951 | "breadcrumbs", | |
| 952 | "related", | |
| 953 | "advert", | |
| 954 | "ads", | |
| 955 | "promo", | |
| 956 | "subscribe", | |
| 957 | "newsletter", | |
| 958 | "skip", | |
| 959 | "masthead", | |
| 960 | "header", | |
| 961 | "toolbar", | |
| 962 | "pagination", | |
| 963 | "popup", | |
| 964 | "modal", | |
| 965 | ]); | |
| 966 | const KEPT = new Set(["html", "body", "main", "article", "#root"]); | |
| 967 | ||
| 968 | /** A class or id that names chrome: the word alone, or first or last in a dashed name. */ | |
| 969 | const chromeNamed = (n: Node): boolean => { | |
| 970 | for (const token of `${n.attrs["class"] ?? ""} ${n.attrs["id"] ?? ""}` | |
| 971 | .toLowerCase() | |
| 972 | .split(/\s+/)) { | |
| 973 | if (token === "") continue; | |
| 974 | const parts = token.split(/[-_]/); | |
| 975 | if ( | |
| 976 | CHROME_WORDS.has(token) || | |
| 977 | CHROME_WORDS.has(parts[0]!) || | |
| 978 | CHROME_WORDS.has(parts[parts.length - 1]!) | |
| 979 | ) | |
| 980 | return true; | |
| 981 | } | |
| 982 | return false; | |
| 983 | }; | |
| 984 | ||
| 985 | const within = (n: Node, tags: ReadonlySet<string>): boolean => { | |
| 986 | for (let p = n.parent; p !== undefined; p = p.parent) | |
| 987 | if (tags.has(p.tag)) return true; | |
| 988 | return false; | |
| 989 | }; | |
| 990 | const HEADER_SET = new Set(["header"]); | |
| 991 | const CONTENT_SET = new Set(["main", "article"]); | |
| 992 | ||
| 993 | /** An inline style's declarations, by property, lower case; a later one wins. */ | |
| 994 | const declarations = (style: string): Map<string, string> => { | |
| 995 | const out = new Map<string, string>(); | |
| 996 | for (const part of style.toLowerCase().split(";")) { | |
| 997 | const colon = part.indexOf(":"); | |
| 998 | if (colon > 0) out.set(part.slice(0, colon).trim(), part.slice(colon + 1).replace(/!important/g, "").replace(/\s+/g, "").trim()); | |
| 999 | } | |
| 1000 | return out; | |
| 1001 | }; | |
| 1002 | /** A length or number that is zero: `0`, `0px`, `.0em`, `0%`. */ | |
| 1003 | const ZERO = /^[+-]?0*\.?0*(px|em|rem|pt|%|vw|vh|ch|ex)?$/; | |
| 1004 | /** A length far off the page: `-9999px`, `-100em`. */ | |
| 1005 | const FAR_OFF = /^-\d{3,}(\.\d+)?(px|em|rem|pt|vw|vh|%)?$/; | |
| 1006 | ||
| 1007 | /** | |
| 1008 | * Whether an inline style hides what it holds from a reader: not displayed, invisible, of no size, | |
| 1009 | * fully transparent, moved off the page, clipped to nothing, or written in the colour of its own | |
| 1010 | * background. Text a person cannot see is how a page speaks to a model behind their back. | |
| 1011 | */ | |
| 1012 | function hiddenByStyle(style: string | undefined): boolean { | |
| 1013 | if (style === undefined || style === "") return false; | |
| 1014 | const d = declarations(style); | |
| 1015 | const is = (k: string, test: (v: string) => boolean) => { | |
| 1016 | const v = d.get(k); | |
| 1017 | return v !== undefined && test(v); | |
| 1018 | }; | |
| 1019 | if (is("display", (v) => v === "none") || is("visibility", (v) => v === "hidden" || v === "collapse")) return true; | |
| 1020 | if (is("font-size", (v) => ZERO.test(v)) || is("opacity", (v) => ZERO.test(v))) return true; | |
| 1021 | if (["left", "top", "right", "bottom", "text-indent", "margin-left", "margin-top"].some((k) => is(k, (v) => FAR_OFF.test(v)))) return true; | |
| 1022 | if (is("clip", (v) => v.startsWith("rect(0") || v.startsWith("rect(1px,1px,1px,1px") || v.startsWith("rect(1px1px1px1px"))) return true; | |
| 1023 | if (is("clip-path", (v) => /^(inset\((50|100)%|circle\(0)/.test(v))) return true; | |
| 1024 | if ((is("width", (v) => ZERO.test(v)) || is("height", (v) => ZERO.test(v))) && is("overflow", (v) => v === "hidden")) return true; | |
| 1025 | const color = d.get("color"); | |
| 1026 | const background = d.get("background-color") ?? d.get("background"); | |
| 1027 | return color !== undefined && background !== undefined && color === background; | |
| 1028 | } | |
| 1029 | ||
| 1030 | export interface PageMarkdown { | |
| 1031 | readonly title: string; | |
| 1032 | readonly markdown: string; | |
| 1033 | readonly links: readonly string[]; | |
| 1034 | } | |
| 1035 | ||
| 1036 | const HEADING = /^h[1-6]$/; | |
| 1037 | const BLOCKS = new Set([ | |
| 1038 | "p", | |
| 1039 | "div", | |
| 1040 | "section", | |
| 1041 | "article", | |
| 1042 | "main", | |
| 1043 | "header", | |
| 1044 | "figure", | |
| 1045 | "figcaption", | |
| 1046 | "address", | |
| 1047 | "details", | |
| 1048 | "summary", | |
| 1049 | "center", | |
| 1050 | "body", | |
| 1051 | "dl", | |
| 1052 | "hgroup", | |
| 1053 | "ul", | |
| 1054 | "ol", | |
| 1055 | "pre", | |
| 1056 | "table", | |
| 1057 | "blockquote", | |
| 1058 | "hr", | |
| 1059 | "dt", | |
| 1060 | "dd", | |
| 1061 | "li", | |
| 1062 | "h1", | |
| 1063 | "h2", | |
| 1064 | "h3", | |
| 1065 | "h4", | |
| 1066 | "h5", | |
| 1067 | "h6", | |
| 1068 | ]); | |
| 1069 | const LIST_PARENTS = new Set(["ul", "ol", "table", "tbody", "thead", "dl"]); | |
| 1070 | ||
| 1071 | /** A page's HTML as Markdown, with its links numbered; `base` resolves relative links. */ | |
| 1072 | export function pageMarkdown(html: string, base: string): PageMarkdown { | |
| 1073 | const root = parseHtml(html); | |
| 1074 | const drops = new Map<Node, boolean>(); | |
| 1075 | const texts = new Map<Node, string>(); | |
| 1076 | const linkTexts = new Map<Node, number>(); | |
| 1077 | ||
| 1078 | const dropped = (n: Node): boolean => { | |
| 1079 | let d = drops.get(n); | |
| 1080 | if (d === undefined) { | |
| 1081 | d = | |
| 1082 | DROP.has(n.tag) || | |
| 1083 | n.attrs["hidden"] !== undefined || | |
| 1084 | n.attrs["aria-hidden"] === "true" || | |
| 1085 | hiddenByStyle(n.attrs["style"]) || | |
| 1086 | CHROME_ROLES.has(n.attrs["role"] ?? "") || | |
| 1087 | (!KEPT.has(n.tag) && chromeNamed(n) && !holdsProse(n)) || | |
| 1088 | (n.tag === "header" && !within(n, CONTENT_SET)) || | |
| 1089 | // A header's lists are its menus. | |
| 1090 | ((n.tag === "ul" || n.tag === "ol") && within(n, HEADER_SET)); | |
| 1091 | drops.set(n, d); | |
| 1092 | } | |
| 1093 | return d; | |
| 1094 | }; | |
| 1095 | /** | |
| 1096 | * A block named like chrome that still holds prose (a page's "layout__header" around its title | |
| 1097 | * and first paragraphs): at least 500 characters, under a third of them links. Read from its | |
| 1098 | * children, so the block's own drop is not asked while it is decided. | |
| 1099 | */ | |
| 1100 | const holdsProse = (n: Node): boolean => { | |
| 1101 | let text = 0; | |
| 1102 | let linked = 0; | |
| 1103 | for (const k of n.kids) { | |
| 1104 | text += typeof k === "string" ? k.length : textOf(k).length; | |
| 1105 | linked += linkText(k); | |
| 1106 | } | |
| 1107 | return text >= 500 && linked < text / 3; | |
| 1108 | }; | |
| 1109 | const textOf = (n: Node | string): string => { | |
| 1110 | if (typeof n === "string") return decode(n); | |
| 1111 | let t = texts.get(n); | |
| 1112 | if (t === undefined) | |
| 1113 | texts.set(n, (t = dropped(n) ? "" : n.kids.map(textOf).join(""))); | |
| 1114 | return t; | |
| 1115 | }; | |
| 1116 | const linkText = (n: Node | string): number => { | |
| 1117 | if (typeof n === "string") return 0; | |
| 1118 | let t = linkTexts.get(n); | |
| 1119 | if (t === undefined) { | |
| 1120 | t = dropped(n) | |
| 1121 | ? 0 | |
| 1122 | : n.tag === "a" | |
| 1123 | ? textOf(n).length | |
| 1124 | : n.kids.reduce((s: number, k) => s + linkText(k), 0); | |
| 1125 | linkTexts.set(n, t); | |
| 1126 | } | |
| 1127 | return t; | |
| 1128 | }; | |
| 1129 | const all = (n: Node, test: (n: Node) => boolean): Node[] => { | |
| 1130 | const out: Node[] = []; | |
| 1131 | const go = (m: Node) => { | |
| 1132 | if (dropped(m)) return; | |
| 1133 | if (test(m)) out.push(m); | |
| 1134 | for (const k of m.kids) if (typeof k !== "string") go(k); | |
| 1135 | }; | |
| 1136 | go(n); | |
| 1137 | return out; | |
| 1138 | }; | |
| 1139 | const size = (n: Node) => textOf(n).replace(/\s+/g, " ").length; | |
| 1140 | const largest = (ns: readonly Node[]): Node | undefined => | |
| 1141 | ns.reduce<Node | undefined>( | |
| 1142 | (a, b) => (a === undefined || size(b) > size(a) ? b : a), | |
| 1143 | undefined, | |
| 1144 | ); | |
| 1145 | ||
| 1146 | /** | |
| 1147 | * Where the content is: the largest `<main>` (or `role=main`), narrowed to its one article when | |
| 1148 | * that holds most of it (a repository page's README); else the largest article; else the element | |
| 1149 | * the paragraphs score highest for, each paragraph's text counting fully to its parent and half | |
| 1150 | * to its grandparent, less its links (Readability's rule, in miniature). | |
| 1151 | */ | |
| 1152 | const mainOf = (): Node => { | |
| 1153 | const body = all(root, (n) => n.tag === "body")[0] ?? root; | |
| 1154 | const main = largest( | |
| 1155 | all(body, (n) => n.tag === "main" || n.attrs["role"] === "main"), | |
| 1156 | ); | |
| 1157 | if (main !== undefined) { | |
| 1158 | const inner = all(main, (n) => n.tag === "article"); | |
| 1159 | const big = largest(inner); | |
| 1160 | return big !== undefined && | |
| 1161 | size(big) > 0.3 * size(main) && | |
| 1162 | inner.filter((a) => size(a) > 200).length === 1 | |
| 1163 | ? big | |
| 1164 | : main; | |
| 1165 | } | |
| 1166 | const article = largest(all(body, (n) => n.tag === "article")); | |
| 1167 | if (article !== undefined && size(article) > 500) return article; | |
| 1168 | const score = new Map<Node, number>(); | |
| 1169 | for (const p of all( | |
| 1170 | body, | |
| 1171 | (n) => | |
| 1172 | n.tag === "p" || n.tag === "pre" || n.tag === "td" || n.tag === "li", | |
| 1173 | )) { | |
| 1174 | const length = size(p); | |
| 1175 | if (length < 25 || p.parent === undefined) continue; | |
| 1176 | let commas = 0; | |
| 1177 | for ( | |
| 1178 | let at = textOf(p).indexOf(","); | |
| 1179 | at >= 0 && commas < 20; | |
| 1180 | at = textOf(p).indexOf(",", at + 1) | |
| 1181 | ) | |
| 1182 | commas++; | |
| 1183 | const points = | |
| 1184 | 1 + | |
| 1185 | Math.min(3, length / 100) + | |
| 1186 | commas * 0.3 - | |
| 1187 | (linkText(p) / Math.max(1, length)) * 3; | |
| 1188 | score.set(p.parent, (score.get(p.parent) ?? 0) + points); | |
| 1189 | if (p.parent.parent !== undefined) | |
| 1190 | score.set( | |
| 1191 | p.parent.parent, | |
| 1192 | (score.get(p.parent.parent) ?? 0) + points / 2, | |
| 1193 | ); | |
| 1194 | } | |
| 1195 | let best: Node = body; | |
| 1196 | let top = 0; | |
| 1197 | for (const [n, s] of score) if (s > top) [best, top] = [n, s]; | |
| 1198 | // An article split across sibling blocks is kept whole by climbing while the parent scores | |
| 1199 | // nearly as well. | |
| 1200 | while ( | |
| 1201 | best.parent !== undefined && | |
| 1202 | best !== body && | |
| 1203 | (score.get(best.parent) ?? 0) > top * 0.75 | |
| 1204 | ) | |
| 1205 | best = best.parent; | |
| 1206 | return best; | |
| 1207 | }; | |
| 1208 | ||
| 1209 | // The title sits in the head, which is never content: looked for without the drop rule. | |
| 1210 | const titleNode = ((): Node | undefined => { | |
| 1211 | const stack: Node[] = [root]; | |
| 1212 | for (let n = stack.pop(); n !== undefined; n = stack.pop()) { | |
| 1213 | if (n.tag === "title") return n; | |
| 1214 | if (n.tag === "body") continue; | |
| 1215 | for (const k of n.kids) if (typeof k !== "string") stack.push(k); | |
| 1216 | } | |
| 1217 | return undefined; | |
| 1218 | })(); | |
| 1219 | const h1 = all(root, (n) => n.tag === "h1")[0]; | |
| 1220 | const title = ( | |
| 1221 | titleNode !== undefined | |
| 1222 | ? decode(titleNode.kids.join("")) | |
| 1223 | : h1 !== undefined | |
| 1224 | ? textOf(h1) | |
| 1225 | : "" | |
| 1226 | ) | |
| 1227 | .replace(/\s+/g, " ") | |
| 1228 | .trim() | |
| 1229 | .slice(0, 300); | |
| 1230 | const baseUrl = URL.parse(base); | |
| 1231 | const links: string[] = []; | |
| 1232 | const numbers = new Map<string, number>(); | |
| 1233 | const linkNo = (href: string): number | undefined => { | |
| 1234 | const url = URL.parse(href.trim(), base); | |
| 1235 | if (url === null || (url.protocol !== "https:" && url.protocol !== "http:")) | |
| 1236 | return undefined; | |
| 1237 | if ( | |
| 1238 | baseUrl !== null && | |
| 1239 | url.hash !== "" && | |
| 1240 | url.origin + url.pathname + url.search === | |
| 1241 | baseUrl.origin + baseUrl.pathname + baseUrl.search | |
| 1242 | ) | |
| 1243 | return undefined; | |
| 1244 | const had = numbers.get(url.href); | |
| 1245 | if (had !== undefined) return had; | |
| 1246 | links.push(url.href); | |
| 1247 | numbers.set(url.href, links.length); | |
| 1248 | return links.length; | |
| 1249 | }; | |
| 1250 | ||
| 1251 | const squeeze = (s: string) => s.replace(/\s+/g, " ").trim(); | |
| 1252 | /** Brackets in the page's text, escaped: only the converter writes a link. */ | |
| 1253 | const brackets = (s: string) => s.replace(/[[\]]/g, "\\$&"); | |
| 1254 | ||
| 1255 | const inline = (n: Node | string, pre: boolean): string => { | |
| 1256 | if (typeof n === "string") | |
| 1257 | return pre ? decode(n) : brackets(decode(n).replace(/\s+/g, " ")); | |
| 1258 | if (dropped(n)) return ""; | |
| 1259 | const kids = () => n.kids.map((k) => inline(k, pre)).join(""); | |
| 1260 | switch (n.tag) { | |
| 1261 | case "br": | |
| 1262 | return "\n"; | |
| 1263 | case "img": { | |
| 1264 | const alt = squeeze(n.attrs["alt"] ?? ""); | |
| 1265 | return alt === "" ? "" : `[image: ${brackets(alt)}]`; | |
| 1266 | } | |
| 1267 | case "code": | |
| 1268 | case "kbd": | |
| 1269 | case "samp": | |
| 1270 | case "tt": { | |
| 1271 | if (pre) return kids(); | |
| 1272 | const t = squeeze(textOf(n)); | |
| 1273 | if (t === "") return ""; | |
| 1274 | const ticks = t.includes("`") ? "``" : "`"; | |
| 1275 | return `${ticks}${t}${ticks}`; | |
| 1276 | } | |
| 1277 | case "strong": | |
| 1278 | case "b": { | |
| 1279 | const t = kids(); | |
| 1280 | return t.trim() === "" ? t : `**${t.trim()}**`; | |
| 1281 | } | |
| 1282 | case "em": | |
| 1283 | case "i": { | |
| 1284 | const t = kids(); | |
| 1285 | return t.trim() === "" ? t : `_${t.trim()}_`; | |
| 1286 | } | |
| 1287 | case "a": { | |
| 1288 | const t = squeeze(kids()); | |
| 1289 | if (t === "" || t === "#" || t === "¶" || t === "§") return ""; | |
| 1290 | const no = | |
| 1291 | n.attrs["href"] === undefined ? undefined : linkNo(n.attrs["href"]); | |
| 1292 | // The page's own words never make Markdown link syntax: the link is its number only. | |
| 1293 | return no === undefined ? t : `[${t.replace(/[()]/g, "\\$&")}][${no}]`; | |
| 1294 | } | |
| 1295 | default: | |
| 1296 | return BLOCKS.has(n.tag) || | |
| 1297 | n.tag === "tr" || | |
| 1298 | n.tag === "td" || | |
| 1299 | n.tag === "th" | |
| 1300 | ? ` ${kids()} ` | |
| 1301 | : kids(); | |
| 1302 | } | |
| 1303 | }; | |
| 1304 | ||
| 1305 | const tableOf = (n: Node): Node | undefined => { | |
| 1306 | for (let p = n.parent; p !== undefined; p = p.parent) | |
| 1307 | if (p.tag === "table") return p; | |
| 1308 | return undefined; | |
| 1309 | }; | |
| 1310 | const table = (t: Node): string => { | |
| 1311 | const grid = all(t, (n) => n.tag === "tr" && tableOf(n) === t).map((r) => | |
| 1312 | r.kids | |
| 1313 | .filter( | |
| 1314 | (k): k is Node => | |
| 1315 | typeof k !== "string" && (k.tag === "td" || k.tag === "th"), | |
| 1316 | ) | |
| 1317 | .map((c) => squeeze(inline(c, false)).replaceAll("|", "\\|")), | |
| 1318 | ); | |
| 1319 | const width = grid.reduce((w, r) => Math.max(w, r.length), 0); | |
| 1320 | if (width === 0) return ""; | |
| 1321 | if (width === 1 || grid.length === 1) | |
| 1322 | return grid.map((r) => r.join(" ")).join("\n\n"); | |
| 1323 | const pad = (r: string[]) => [ | |
| 1324 | ...r, | |
| 1325 | ...Array<string>(width - r.length).fill(""), | |
| 1326 | ]; | |
| 1327 | const [head, ...rows] = grid.map(pad); | |
| 1328 | return [ | |
| 1329 | `| ${head!.join(" | ")} |`, | |
| 1330 | `|${" --- |".repeat(width)}`, | |
| 1331 | ...rows.map((r) => `| ${r.join(" | ")} |`), | |
| 1332 | ].join("\n"); | |
| 1333 | }; | |
| 1334 | ||
| 1335 | const language = (n: Node): string => { | |
| 1336 | for (const m of [ | |
| 1337 | n, | |
| 1338 | ...all(n, (c) => c.tag === "code").slice(0, 1), | |
| 1339 | ...(n.parent === undefined ? [] : [n.parent]), | |
| 1340 | ]) { | |
| 1341 | if (m.attrs["data-language"] !== undefined) | |
| 1342 | return squeeze(m.attrs["data-language"]).slice(0, 20); | |
| 1343 | // `brush: js` (MDN) names it in the token after. | |
| 1344 | const brush = /(?:^|\s)brush:\s?([\w+#.-]{1,20})/.exec(m.attrs["class"] ?? ""); | |
| 1345 | if (brush !== null) return brush[1]!; | |
| 1346 | for (const token of (m.attrs["class"] ?? "").split(/\s+/)) { | |
| 1347 | const at = token.startsWith("language-") | |
| 1348 | ? 9 | |
| 1349 | : token.startsWith("lang-") | |
| 1350 | ? 5 | |
| 1351 | : token.startsWith("highlight-source-") | |
| 1352 | ? 17 | |
| 1353 | : -1; | |
| 1354 | if (at > 0 && /^[\w+#.-]{1,20}$/.test(token.slice(at))) | |
| 1355 | return token.slice(at); | |
| 1356 | } | |
| 1357 | } | |
| 1358 | return ""; | |
| 1359 | }; | |
| 1360 | ||
| 1361 | const blocks = (n: Node): string[] => { | |
| 1362 | const out: string[] = []; | |
| 1363 | let run = ""; | |
| 1364 | const flush = () => { | |
| 1365 | const t = run | |
| 1366 | .replace(/[ \t]+/g, " ") | |
| 1367 | .replace(/ ?\n ?/g, "\n") | |
| 1368 | .trim(); | |
| 1369 | if (t !== "") out.push(t); | |
| 1370 | run = ""; | |
| 1371 | }; | |
| 1372 | for (const k of n.kids) { | |
| 1373 | if (typeof k === "string" || !BLOCKS.has(k.tag)) { | |
| 1374 | run += inline(k, false); | |
| 1375 | continue; | |
| 1376 | } | |
| 1377 | if (dropped(k)) continue; | |
| 1378 | flush(); | |
| 1379 | out.push(...block(k)); | |
| 1380 | } | |
| 1381 | flush(); | |
| 1382 | return out; | |
| 1383 | }; | |
| 1384 | ||
| 1385 | const block = (n: Node): string[] => { | |
| 1386 | if (HEADING.test(n.tag)) { | |
| 1387 | const t = squeeze(inline(n, false)); | |
| 1388 | return t === "" ? [] : [`${"#".repeat(Number(n.tag[1]))} ${t}`]; | |
| 1389 | } | |
| 1390 | switch (n.tag) { | |
| 1391 | case "hr": | |
| 1392 | return ["---"]; | |
| 1393 | case "pre": { | |
| 1394 | const body = n.kids | |
| 1395 | .map((k) => inline(k, true)) | |
| 1396 | .join("") | |
| 1397 | .replace(/^\n+/, "") | |
| 1398 | .trimEnd(); | |
| 1399 | if (body === "") return []; | |
| 1400 | const fence = body.includes("```") ? "````" : "```"; | |
| 1401 | return [`${fence}${language(n)}\n${body}\n${fence}`]; | |
| 1402 | } | |
| 1403 | case "table": { | |
| 1404 | const t = table(n); | |
| 1405 | return t === "" ? [] : [t]; | |
| 1406 | } | |
| 1407 | case "blockquote": { | |
| 1408 | const t = blocks(n).join("\n\n"); | |
| 1409 | return t === "" ? [] : [t.replace(/^/gm, "> ")]; | |
| 1410 | } | |
| 1411 | case "ul": | |
| 1412 | case "ol": { | |
| 1413 | const items = n.kids.filter( | |
| 1414 | (k): k is Node => | |
| 1415 | typeof k !== "string" && k.tag === "li" && !dropped(k), | |
| 1416 | ); | |
| 1417 | const lines = items.flatMap((li, i) => { | |
| 1418 | const mark = n.tag === "ol" ? `${i + 1}.` : "-"; | |
| 1419 | const inner = blocks(li).join("\n"); | |
| 1420 | return inner === "" | |
| 1421 | ? [] | |
| 1422 | : [ | |
| 1423 | `${mark} ${inner.replaceAll("\n", `\n${" ".repeat(mark.length + 1)}`)}`, | |
| 1424 | ]; | |
| 1425 | }); | |
| 1426 | return lines.length === 0 ? [] : [lines.join("\n")]; | |
| 1427 | } | |
| 1428 | case "li": | |
| 1429 | // An item outside a list reads as one. | |
| 1430 | return LIST_PARENTS.has(n.parent?.tag ?? "") | |
| 1431 | ? blocks(n) | |
| 1432 | : blocks(n).map((b) => `- ${b}`); | |
| 1433 | case "dt": { | |
| 1434 | const t = squeeze(inline(n, false)); | |
| 1435 | return t === "" ? [] : [`**${t}**`]; | |
| 1436 | } | |
| 1437 | default: | |
| 1438 | return blocks(n); | |
| 1439 | } | |
| 1440 | }; | |
| 1441 | ||
| 1442 | const markdown = blocks(mainOf()) | |
| 1443 | .join("\n\n") | |
| 1444 | .replace(/\n{3,}/g, "\n\n") | |
| 1445 | .trim(); | |
| 1446 | return { title, markdown, links }; | |
| 1447 | } |
src/http/mcp/catalog.ts +4 −4
| @@ -23,9 +23,9 @@ export const DEFAULT_TOOLS: readonly string[] = [ | ||
| 23 | 23 | * `tools/list` named, so a tool left out here is one Talk cannot use at all. The rule: the reads a |
| 24 | 24 | * question about the work needs (issues, pulls and their commits, threads and checks, search, |
| 25 | 25 | * files, runs and logs, health, releases, people, the person's own GitHub and other forge accounts |
| 26 | * and what each holds (`origins`), and who the person is and what they may do, `whoami_can`, and | |
| 27 | * `show`, which draws the forge's own data in a reply as a chart), and the | |
| 28 | * everyday writes on that work (comment, close or reopen, assign, | |
| 26 | * and what each holds (`origins`), and who the person is and what they may do, `whoami_can`, | |
| 27 | * `show`, which draws the forge's own data in a reply as a chart, and `fetch_url`, which reads a | |
| 28 | * page the person linked), and the everyday writes on that work (comment, close or reopen, assign, | |
| 29 | 29 | * labels, edit, review, merge, the plan on an issue, a word to or a stop of a crew run, a |
| 30 | 30 | * branch, a file and a pull for an app built in Talk, a new app). Each write is held as any write |
| 31 | 31 | * of this token is: after the agent has read text someone else wrote, a write the person's own |
| @@ -48,7 +48,7 @@ export const TALK_TOOLS: readonly string[] = [ | ||
| 48 | 48 | "issue", "issues", "pull", "pulls", "commits", "threads", "search", "read_file", "repo", "run_log", |
| 49 | 49 | "preview", "assigned", "health", "releases", "person", "whoami_can", "show", "pane", "origins", "invite", |
| 50 | 50 | "close", "assign", "labels", "edit", "review", "merge", "keep_plan", "steer", "stop", |
| 51 | "write_file", "branches", "open_pull", "new_app", | |
| 51 | "write_file", "branches", "open_pull", "new_app", "fetch_url", | |
| 52 | 52 | ]; |
| 53 | 53 | |
| 54 | 54 | /** |
src/http/mcp/tools/fetch_url.ts added +28
| @@ -0,0 +1,28 @@ | ||
| 1 | import { fetchPage } from "../../../core/web_page.ts"; | |
| 2 | import { bad, good, str, type Tool } from "../shared.ts"; | |
| 3 | ||
| 4 | export const tool: Tool = { | |
| 5 | name: "fetch_url", | |
| 6 | description: "Read a linked page at `url` as Markdown; `cursor` pages on, `fresh` refetches.", | |
| 7 | inputSchema: { | |
| 8 | type: "object", | |
| 9 | properties: { | |
| 10 | url: { type: "string", maxLength: 2000 }, | |
| 11 | cursor: { type: "string", maxLength: 10 }, | |
| 12 | fresh: { type: "boolean" }, | |
| 13 | }, | |
| 14 | required: ["url"], | |
| 15 | }, | |
| 16 | writes: false, | |
| 17 | run: async (ctx, user, args) => { | |
| 18 | const got = await fetchPage(ctx.app.db, { | |
| 19 | url: str(args["url"]), | |
| 20 | cursor: typeof args["cursor"] === "string" ? args["cursor"] : undefined, | |
| 21 | fresh: args["fresh"] === true, | |
| 22 | via: ctx.auth.through, | |
| 23 | who: user.id, | |
| 24 | ownHost: ctx.url.host, | |
| 25 | }); | |
| 26 | return got.ok ? good(got.value) : bad(got.error.code, got.error.message); | |
| 27 | }, | |
| 28 | }; |
src/http/mcp/tools/index.ts +1
| @@ -68,6 +68,7 @@ export { tool as feed } from "./feed.ts"; | ||
| 68 | 68 | export { tool as feed_chips } from "./feed_chips.ts"; |
| 69 | 69 | export { tool as feed_dismiss } from "./feed_dismiss.ts"; |
| 70 | 70 | export { tool as feed_like } from "./feed_like.ts"; |
| 71 | export { tool as fetch_url } from "./fetch_url.ts"; | |
| 71 | 72 | export { tool as find_tool } from "./find_tool.ts"; |
| 72 | 73 | export { tool as flag_set } from "./flag_set.ts"; |
| 73 | 74 | export { tool as flag_winner } from "./flag_winner.ts"; |
src/http/mcp/tools/system.ts +1 −1
Diff not shown — a line 3,081 characters wide (limit 2,000). +1 −1
View filesrc/kernel/outbound.ts +12 −1
| @@ -27,13 +27,20 @@ const REFUSED = [ | ||
| 27 | 27 | "127.0.0.0/8", |
| 28 | 28 | "169.254.0.0/16", |
| 29 | 29 | "172.16.0.0/12", |
| 30 | "192.0.0.0/24", | |
| 30 | 31 | "192.168.0.0/16", |
| 32 | // Benchmarking (RFC 2544): never a public service. | |
| 33 | "198.18.0.0/15", | |
| 31 | 34 | "224.0.0.0/4", |
| 32 | 35 | "240.0.0.0/4", |
| 33 | 36 | // Unspecified, loopback and the old IPv4-compatible form (`::127.0.0.1`). |
| 34 | 37 | "::/96", |
| 35 | 38 | // NAT64 local-use: a site's own translator, nothing public behind it. |
| 36 | 39 | "64:ff9b:1::/48", |
| 40 | // SIIT's IPv4-translated form (`::ffff:0:a.b.c.d`), and Teredo, which tunnels to an address it | |
| 41 | // carries: neither is where a public name points. | |
| 42 | "::ffff:0:0:0/96", | |
| 43 | "2001::/32", | |
| 37 | 44 | "fc00::/7", |
| 38 | 45 | "fe80::/10", |
| 39 | 46 | "ff00::/8", |
| @@ -55,7 +62,11 @@ function wrappedIpv4(address: string): string | undefined { | ||
| 55 | 62 | return at < 0 ? undefined : [...bytes.slice(at, at + 4)].join("."); |
| 56 | 63 | } |
| 57 | 64 | |
| 58 | /** Is this address one a public service would never have? Unparseable counts. */ | |
| 65 | /** | |
| 66 | * Is this address one a public service would never have? Unparseable counts. An IPv4-mapped | |
| 67 | * literal (`::ffff:0:0/96`) is read as the IPv4 address it carries (`addressBytes`), so a private | |
| 68 | * one is refused here and the egress gate judges it the same way (`isPublicAddress`). | |
| 69 | */ | |
| 59 | 70 | export function isRefusedAddress(address: string): boolean { |
| 60 | 71 | if (addressBytes(address) === undefined || inCidrs(address, REFUSED)) return true; |
| 61 | 72 | const inner = wrappedIpv4(address); |
src/kernel/own_host.ts +18 −1
| @@ -37,11 +37,28 @@ export function ownHost(): string | undefined { | ||
| 37 | 37 | return own?.host; |
| 38 | 38 | } |
| 39 | 39 | |
| 40 | /** | |
| 41 | * A host (`name[:port]`) in the one form two hosts compare in: lower case, percent escapes read, | |
| 42 | * and the trailing dot of a fully qualified name dropped, so `Forge.example.com.:443` and | |
| 43 | * `forge.example%2ecom` are the names they resolve as. | |
| 44 | */ | |
| 45 | export function hostKey(host: string): string { | |
| 46 | let h = host.toLowerCase(); | |
| 47 | try { | |
| 48 | h = decodeURIComponent(h); | |
| 49 | } catch { | |
| 50 | // A stray `%` is left as written. | |
| 51 | } | |
| 52 | const port = /:\d{1,5}$/.exec(h); | |
| 53 | const name = port === null ? h : h.slice(0, port.index); | |
| 54 | return `${name.replace(/\.+$/, "")}${port?.[0] ?? ""}`; | |
| 55 | } | |
| 56 | ||
| 40 | 57 | /** Whether `url` names the forge's own public host. */ |
| 41 | 58 | export function isOwnHost(url: string | URL): boolean { |
| 42 | 59 | if (own === undefined) return false; |
| 43 | 60 | try { |
| 44 | return new URL(url).host.toLowerCase() === own.host; | |
| 61 | return hostKey(new URL(url).host) === hostKey(own.host); | |
| 45 | 62 | } catch { |
| 46 | 63 | return false; |
| 47 | 64 | } |
src/tui/forge.ts +19 −1
| @@ -110,7 +110,8 @@ import { queuesFor, systemFor } from "../system/telemetry.ts"; | ||
| 110 | 110 | import { flowGatesFor } from "../actions/runs.ts"; |
| 111 | 111 | import { apiScreen } from "./screens/api.ts"; |
| 112 | 112 | import { changelogScreen } from "./screens/changelog.ts"; |
| 113 | import { docScreen, docsScreen } from "./screens/docs.ts"; | |
| 113 | import { docScreen, docsScreen, markdownScreen } from "./screens/docs.ts"; | |
| 114 | import { fetchPage, pageText } from "../core/web_page.ts"; | |
| 114 | 115 | import { anyDocEntry } from "../view/docs.ts"; |
| 115 | 116 | import { keeperScreen } from "./screens/keeper.ts"; |
| 116 | 117 | import { releasesScreen } from "./screens/releases.ts"; |
| @@ -503,6 +504,23 @@ export function forgeCommands(session: Session): (ctx: Ctx) => Command[] { | ||
| 503 | 504 | hint: "say what to build; versions, diff, restore and publish. n starts one", |
| 504 | 505 | run: () => ctx.push(talkBuildScreen(session, ctx)), |
| 505 | 506 | }); |
| 507 | // A web page as the forge's agent reads it (`fetch_url`): the same Markdown, the same guard. | |
| 508 | if (session.signedIn) | |
| 509 | commands.push({ | |
| 510 | id: "fetch-page", | |
| 511 | title: "Read a web page", | |
| 512 | hint: "paste an https link; the page as Markdown, as Talk's agent reads it", | |
| 513 | run: () => | |
| 514 | ctx.push( | |
| 515 | askFor(ctx, "Read a web page", "An https link", (url) => { | |
| 516 | if (url === "") return "Paste a link."; | |
| 517 | return fetchPage(session.app.db, { url, who: session.user?.id ?? "" }).then((got) => { | |
| 518 | if (!got.ok) ctx.toast(got.error.message, "danger"); | |
| 519 | else ctx.push(markdownScreen(ctx, got.value.title || got.value.finalUrl, pageText(got.value))); | |
| 520 | }); | |
| 521 | }), | |
| 522 | ), | |
| 523 | }); | |
| 506 | 524 | // Only while the SSH switch is on (`settings/ssh.ts`); off, the keys are not a thing here. |
| 507 | 525 | if (session.signedIn && sshOn(session.app.db)) |
| 508 | 526 | commands.push({ |
src/tui/screens/docs.ts +6 −2
| @@ -17,11 +17,15 @@ export function docRows(entries: readonly DocEntry[]): ListRow[] { | ||
| 17 | 17 | } |
| 18 | 18 | |
| 19 | 19 | export function docScreen(ctx: Ctx, entry: DocEntry, ssh: boolean): Screen { |
| 20 | return markdownScreen(ctx, entry.title, docText(entry, ssh)); | |
| 21 | } | |
| 22 | ||
| 23 | /** Any Markdown to read, scrolled with j and k: a document, or a web page (`fetch_url`). */ | |
| 24 | export function markdownScreen(ctx: Ctx, title: string, text: string): Screen { | |
| 20 | 25 | const scroll = new Scroll(); |
| 21 | 26 | let cache: { w: number; lines: ReturnType<typeof renderMarkdown> } | undefined; |
| 22 | const text = docText(entry, ssh); | |
| 23 | 27 | return { |
| 24 | title: entry.title, | |
| 28 | title, | |
| 25 | 29 | keys: [binding(["j", "k"], "scroll"), binding(["esc", "q"], "back")], |
| 26 | 30 | render(area, s) { |
| 27 | 31 | const w = Math.max(20, area.w - 2); |
test/fetch-url.test.ts added +727
| @@ -0,0 +1,727 @@ | ||
| 1 | /** | |
| 2 | * `fetch_url` (`core/web_page.ts`): a page the person linked, read through the outbound guard as | |
| 3 | * short Markdown. Every address class the guard refuses is refused here before a byte is sent, a | |
| 4 | * redirect is judged again at each hop, the body is capped on the wire and once decoded, only the | |
| 5 | * listed types are read, a URL carrying a credential is refused, and the forge's own agent may read | |
| 6 | * only what its conversation was shown. A local server stands in for the web and an injected | |
| 7 | * resolver for DNS: nothing here reaches the internet. | |
| 8 | */ | |
| 9 | import { | |
| 10 | afterAll, | |
| 11 | beforeAll, | |
| 12 | beforeEach, | |
| 13 | describe, | |
| 14 | expect, | |
| 15 | test, | |
| 16 | } from "bun:test"; | |
| 17 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 18 | import { tmpdir } from "node:os"; | |
| 19 | import { join } from "node:path"; | |
| 20 | import { createApp, type App } from "../src/app.ts"; | |
| 21 | import { appendTurn, createConversation } from "../src/core/conversations.ts"; | |
| 22 | import { fenceUp } from "../src/core/fence.ts"; | |
| 23 | import { createUser, type User } from "../src/core/users.ts"; | |
| 24 | import { mintViaToken } from "../src/core/via_token.ts"; | |
| 25 | import { | |
| 26 | DECODED_MAX, | |
| 27 | fetchPage, | |
| 28 | pageMarkdown, | |
| 29 | parseHtml, | |
| 30 | SLICE_CHARS, | |
| 31 | WIRE_MAX, | |
| 32 | webPageReach, | |
| 33 | FETCHES_PER_HOUR, | |
| 34 | type PageAsk, | |
| 35 | } from "../src/core/web_page.ts"; | |
| 36 | import type { OutboundOptions } from "../src/kernel/outbound.ts"; | |
| 37 | import { forgetOwnHost, localFor, setOwnHost } from "../src/kernel/own_host.ts"; | |
| 38 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 39 | import { createForgeApp, forgeCommands } from "../src/tui/forge.ts"; | |
| 40 | import { docScreen } from "../src/tui/screens/docs.ts"; | |
| 41 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; | |
| 42 | import { docEntry } from "../src/view/docs.ts"; | |
| 43 | import { settleApp } from "./helpers/tui.ts"; | |
| 44 | ||
| 45 | interface Seen { | |
| 46 | readonly path: string; | |
| 47 | readonly headers: Record<string, string>; | |
| 48 | } | |
| 49 | const seen: Seen[] = []; | |
| 50 | const big = Array.from( | |
| 51 | { length: 400 }, | |
| 52 | (_, i) => | |
| 53 | `<p>Paragraph ${i} of a long page, with words enough to count, and a <a href="/far/${i}">link</a>.</p>`, | |
| 54 | ).join(""); | |
| 55 | const pages: Record<string, () => Response> = { | |
| 56 | "/page": () => | |
| 57 | new Response( | |
| 58 | `<html><head><title>A page</title><style>.x{color:red}</style><script>var secretScript = 1;</script></head><body> | |
| 59 | <header><ul><li><a href="/home">Home</a></li><li><a href="/about">About</a></li></ul></header> | |
| 60 | <nav><ul><li><a href="/n1">Navigation one</a></li></ul></nav> | |
| 61 | <main><h1>Hello</h1><p>The <b>first</b> paragraph, with a <a href="/next">next page</a>.</p> | |
| 62 | <pre><code class="language-ts">const x: number = 1;</code></pre> | |
| 63 | <table><tr><th>a</th><th>b</th></tr><tr><td>1</td><td>2</td></tr></table> | |
| 64 | <template>templateSecret</template><iframe>iframeSecret</iframe><object>objectSecret</object><svg><text>svgSecret</text></svg><noscript>noscriptSecret</noscript> | |
| 65 | <img src="/x.png" alt="A cat"></main> | |
| 66 | <aside><ul><li>asideSecret</li></ul></aside><footer><ul><li>footerSecret</li></ul></footer></body></html>`, | |
| 67 | { headers: { "content-type": "text/html; charset=utf-8" } }, | |
| 68 | ), | |
| 69 | "/a": () => new Response("<main><p>page a without a slash</p></main>", { headers: { "content-type": "text/html" } }), | |
| 70 | "/a/": () => new Response("<main><p>page a with a slash</p></main>", { headers: { "content-type": "text/html" } }), | |
| 71 | "/hidden": () => | |
| 72 | new Response( | |
| 73 | `<main><p>Seen text.</p> | |
| 74 | <p style="visibility:hidden">INJECT-visibility</p> | |
| 75 | <p style="font-size: 0px">INJECT-fontsize</p> | |
| 76 | <p style="opacity:0">INJECT-opacity</p> | |
| 77 | <p style="position:absolute; left:-9999px">INJECT-left</p> | |
| 78 | <p style="position:absolute;top:-10000px">INJECT-top</p> | |
| 79 | <p style="clip: rect(0 0 0 0); position:absolute">INJECT-clip</p> | |
| 80 | <p style="color:#fff;background-color:#FFF">INJECT-samecolour</p> | |
| 81 | <p style="display: none !important">INJECT-display</p> | |
| 82 | <p style="opacity:0.5;color:#000;background:#fff">Half seen.</p></main>`, | |
| 83 | { headers: { "content-type": "text/html" } }, | |
| 84 | ), | |
| 85 | "/smuggle": () => | |
| 86 | new Response( | |
| 87 | `<main><p>Read <a href="/next">[click](https://evil.test/x) here</a> and [plain](https://evil.test/y) text, <img alt="x](https://evil.test/z) [y"></p></main>`, | |
| 88 | { headers: { "content-type": "text/html" } }, | |
| 89 | ), | |
| 90 | "/next": () => | |
| 91 | new Response("<main><p>The next page.</p></main>", { | |
| 92 | headers: { "content-type": "text/html" }, | |
| 93 | }), | |
| 94 | "/big": () => | |
| 95 | new Response(`<main>${big}</main>`, { | |
| 96 | headers: { "content-type": "text/html" }, | |
| 97 | }), | |
| 98 | "/json": () => | |
| 99 | new Response('{"a":[1,2]}', { | |
| 100 | headers: { "content-type": "application/json" }, | |
| 101 | }), | |
| 102 | "/png": () => | |
| 103 | new Response(new Uint8Array([137, 80, 78, 71]), { | |
| 104 | headers: { "content-type": "image/png" }, | |
| 105 | }), | |
| 106 | "/huge": () => | |
| 107 | new Response(`<main><p>${"x".repeat(3 * 1024 * 1024)}</p></main>`, { | |
| 108 | headers: { "content-type": "text/html" }, | |
| 109 | }), | |
| 110 | "/bomb": () => | |
| 111 | new Response( | |
| 112 | Bun.gzipSync( | |
| 113 | new TextEncoder().encode( | |
| 114 | `<main><p>${"a".repeat(40 * 1024 * 1024)}</p></main>`, | |
| 115 | ), | |
| 116 | ), | |
| 117 | { | |
| 118 | headers: { "content-type": "text/html", "content-encoding": "gzip" }, | |
| 119 | }, | |
| 120 | ), | |
| 121 | "/to-private": () => | |
| 122 | new Response(null, { | |
| 123 | status: 302, | |
| 124 | headers: { location: "http://inside.test/secret" }, | |
| 125 | }), | |
| 126 | }; | |
| 127 | const server = Bun.serve({ | |
| 128 | port: 0, | |
| 129 | hostname: "127.0.0.1", | |
| 130 | fetch(req) { | |
| 131 | const url = new URL(req.url); | |
| 132 | seen.push({ path: url.pathname, headers: Object.fromEntries(req.headers) }); | |
| 133 | const five = /^\/five\/(\d+)$/.exec(url.pathname); | |
| 134 | if (five !== null) | |
| 135 | return new Response(null, { | |
| 136 | status: 302, | |
| 137 | headers: { location: Number(five[1]) === 4 ? "/next" : `/five/${Number(five[1]) + 1}` }, | |
| 138 | }); | |
| 139 | const loop = /^\/loop\/(\d+)$/.exec(url.pathname); | |
| 140 | if (loop !== null) | |
| 141 | return new Response(null, { | |
| 142 | status: 302, | |
| 143 | headers: { location: `/loop/${Number(loop[1]) + 1}` }, | |
| 144 | }); | |
| 145 | return ( | |
| 146 | pages[url.pathname]?.() ?? | |
| 147 | new Response("<p>missing</p>", { | |
| 148 | status: 404, | |
| 149 | headers: { "content-type": "text/html" }, | |
| 150 | }) | |
| 151 | ); | |
| 152 | }, | |
| 153 | }); | |
| 154 | const site = `http://pages.test:${server.port}`; | |
| 155 | ||
| 156 | /** Names → addresses: the stand-in for DNS. */ | |
| 157 | const names: Record<string, string[]> = { | |
| 158 | "pages.test": ["127.0.0.1"], | |
| 159 | "inside.test": ["10.0.0.1"], | |
| 160 | "intranet.test": ["192.168.1.5"], | |
| 161 | localhost: ["127.0.0.1", "::1"], | |
| 162 | }; | |
| 163 | const reach = (extra: Partial<OutboundOptions> = {}): OutboundOptions => ({ | |
| 164 | resolve: (host) => Promise.resolve(names[host] ?? ["93.184.216.34"]), | |
| 165 | allow: ["127.0.0.1"], | |
| 166 | plain: true, | |
| 167 | proxy: undefined, | |
| 168 | ...extra, | |
| 169 | }); | |
| 170 | ||
| 171 | let dir: string; | |
| 172 | let app: App; | |
| 173 | let servers: Servers; | |
| 174 | let alice: User; | |
| 175 | ||
| 176 | beforeAll(async () => { | |
| 177 | dir = await mkdtemp(join(tmpdir(), "forge-fetch-url-")); | |
| 178 | app = createApp({ dataDir: dir, port: 0 }); | |
| 179 | servers = await serve(app); | |
| 180 | const u = await createUser(app.db, { | |
| 181 | origin: "seed", | |
| 182 | trusted: true, | |
| 183 | username: "alice", | |
| 184 | email: "[email protected]", | |
| 185 | password: "a-good-passphrase", | |
| 186 | adminIfFirst: true, | |
| 187 | }); | |
| 188 | if (!u.ok) throw new Error(u.error); | |
| 189 | alice = u.value; | |
| 190 | }); | |
| 191 | afterAll(async () => { | |
| 192 | webPageReach.override = undefined; | |
| 193 | forgetOwnHost(); | |
| 194 | server.stop(true); | |
| 195 | servers.stop(); | |
| 196 | app.close(); | |
| 197 | await rm(dir, { recursive: true, force: true }); | |
| 198 | }); | |
| 199 | beforeEach(() => { | |
| 200 | webPageReach.override = reach(); | |
| 201 | app.db.query("DELETE FROM web_page").run(); | |
| 202 | }); | |
| 203 | ||
| 204 | /** | |
| 205 | * Each test reads as a person of its own, so the hourly limit counts only where a test means it to. | |
| 206 | */ | |
| 207 | /** | |
| 208 | * A credential-shaped string made at run time from two parts, so no tracked file holds one | |
| 209 | * (`test/no-secrets-tracked.test.ts`); every one here is made up. | |
| 210 | */ | |
| 211 | const shaped = (head: string, tail: string): string => head + tail; | |
| 212 | let people = 0; | |
| 213 | const someone = () => `reader-${++people}`; | |
| 214 | const read = (ask: Omit<PageAsk, "who"> & { who?: string }) => fetchPage(app.db, { fresh: true, who: someone(), ...ask }); | |
| 215 | /** How many requests the server took while `run` ran. */ | |
| 216 | const counted = async <T>( | |
| 217 | run: () => Promise<T>, | |
| 218 | ): Promise<{ value: T; requests: Seen[] }> => { | |
| 219 | const before = seen.length; | |
| 220 | const value = await run(); | |
| 221 | return { value, requests: seen.slice(before) }; | |
| 222 | }; | |
| 223 | ||
| 224 | describe("addresses the guard refuses, before a request is sent", () => { | |
| 225 | const cases: [string, string[] | undefined, string][] = [ | |
| 226 | ["private IPv4", undefined, "http://10.0.0.7/"], | |
| 227 | ["private IPv6", undefined, "http://[fd00::1]/"], | |
| 228 | ["IPv4-mapped IPv6", undefined, "http://[::ffff:10.0.0.1]/"], | |
| 229 | [ | |
| 230 | "NAT64 around the metadata address", | |
| 231 | undefined, | |
| 232 | "http://[64:ff9b::a9fe:a9fe]/", | |
| 233 | ], | |
| 234 | [ | |
| 235 | "the metadata address", | |
| 236 | undefined, | |
| 237 | "http://169.254.169.254/latest/meta-data/", | |
| 238 | ], | |
| 239 | ["loopback by name", undefined, "http://localhost/"], | |
| 240 | [ | |
| 241 | "a name that resolves to a private address", | |
| 242 | undefined, | |
| 243 | "http://intranet.test/", | |
| 244 | ], | |
| 245 | ]; | |
| 246 | for (const [what, , url] of cases) | |
| 247 | test(what, async () => { | |
| 248 | // No address is exempt here: the test server's own address is refused like any other. | |
| 249 | webPageReach.override = reach({ allow: [] }); | |
| 250 | const { value, requests } = await counted(() => read({ url })); | |
| 251 | expect(value.ok).toBe(false); | |
| 252 | if (!value.ok) expect(value.error.code).toBe("refused"); | |
| 253 | expect(requests).toEqual([]); | |
| 254 | }); | |
| 255 | ||
| 256 | test("the forge's own host, as the request reached it and as it was told at boot", async () => { | |
| 257 | expect( | |
| 258 | ( | |
| 259 | await read({ | |
| 260 | url: "https://forge.example.com/x", | |
| 261 | ownHost: "forge.example.com", | |
| 262 | }) | |
| 263 | ).ok, | |
| 264 | ).toBe(false); | |
| 265 | setOwnHost("https://own.example.com", servers.url); | |
| 266 | try { | |
| 267 | const r = await read({ url: "https://own.example.com/settings" }); | |
| 268 | expect(r.ok ? "" : r.error.code).toBe("own_host"); | |
| 269 | } finally { | |
| 270 | forgetOwnHost(); | |
| 271 | } | |
| 272 | }); | |
| 273 | ||
| 274 | test("plain http, another port and a name or password in the URL", async () => { | |
| 275 | webPageReach.override = { | |
| 276 | resolve: () => Promise.resolve(["93.184.216.34"]), | |
| 277 | }; | |
| 278 | for (const [url, code] of [ | |
| 279 | ["http://example.com/", "not_https"], | |
| 280 | ["https://example.com:8443/", "port"], | |
| 281 | ["https://bob:[email protected]/", "credential"], | |
| 282 | ] as const) { | |
| 283 | const r = await read({ url }); | |
| 284 | expect(r.ok ? "" : r.error.code).toBe(code); | |
| 285 | } | |
| 286 | }); | |
| 287 | ||
| 288 | test("a URL that looks like it carries a credential", async () => { | |
| 289 | const { value, requests } = await counted(async () => [ | |
| 290 | await read({ url: `${site}/page?token=abcdef123456` }), | |
| 291 | await read({ url: `${site}/page?api_key=abcdef123456` }), | |
| 292 | await read({ | |
| 293 | url: `${site}/page?x=eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTYifQ.abc`, | |
| 294 | }), | |
| 295 | await read({ url: `${site}/${shaped("ghp", "_abcdefghijklmnopqrstuvwxyz0123")}` }), | |
| 296 | ]); | |
| 297 | for (const r of value) expect(r.ok ? "" : r.error.code).toBe("credential"); | |
| 298 | expect(requests).toEqual([]); | |
| 299 | }); | |
| 300 | }); | |
| 301 | ||
| 302 | describe("redirects", () => { | |
| 303 | test("a redirect to a private address is refused at that hop", async () => { | |
| 304 | const { value, requests } = await counted(() => | |
| 305 | read({ url: `${site}/to-private` }), | |
| 306 | ); | |
| 307 | expect(value.ok ? "" : value.error.code).toBe("refused"); | |
| 308 | expect(requests.map((r) => r.path)).toEqual(["/to-private"]); | |
| 309 | }); | |
| 310 | ||
| 311 | test("more than five redirects are refused", async () => { | |
| 312 | const { value, requests } = await counted(() => | |
| 313 | read({ url: `${site}/loop/0` }), | |
| 314 | ); | |
| 315 | expect(value.ok ? "" : value.error.code).toBe("redirects"); | |
| 316 | expect(requests.length).toBe(6); | |
| 317 | }); | |
| 318 | ||
| 319 | test("five are followed, and the page at the end is read", async () => { | |
| 320 | const { value, requests } = await counted(() => read({ url: `${site}/five/0` })); | |
| 321 | expect(value.ok ? value.value.finalUrl : "").toBe(`http://pages.test:${server.port}/next`); | |
| 322 | // Five redirects, then the page. | |
| 323 | expect(requests.length).toBe(6); | |
| 324 | }); | |
| 325 | }); | |
| 326 | ||
| 327 | describe("what is read", () => { | |
| 328 | test("a body over the wire cap is cut there", async () => { | |
| 329 | const r = await read({ url: `${site}/huge` }); | |
| 330 | expect(r.ok).toBe(true); | |
| 331 | if (!r.ok) return; | |
| 332 | expect(r.value.truncated).toBe(true); | |
| 333 | expect(r.value.bytes).toBeLessThanOrEqual(WIRE_MAX); | |
| 334 | }); | |
| 335 | ||
| 336 | test("a gzip bomb is cut once decoded", async () => { | |
| 337 | const r = await read({ url: `${site}/bomb` }); | |
| 338 | expect(r.ok).toBe(true); | |
| 339 | if (!r.ok) return; | |
| 340 | expect(r.value.truncated).toBe(true); | |
| 341 | expect(r.value.bytes).toBeLessThanOrEqual(DECODED_MAX); | |
| 342 | }); | |
| 343 | ||
| 344 | test("a type outside HTML, text, Markdown and JSON is refused", async () => { | |
| 345 | const r = await read({ url: `${site}/png` }); | |
| 346 | expect(r.ok ? "" : r.error.code).toBe("content_type"); | |
| 347 | }); | |
| 348 | ||
| 349 | test("JSON reads pretty-printed in a fence", async () => { | |
| 350 | const r = await read({ url: `${site}/json` }); | |
| 351 | expect(r.ok ? r.value.markdown : "").toBe( | |
| 352 | '```json\n{\n "a": [\n 1,\n 2\n ]\n}\n```', | |
| 353 | ); | |
| 354 | }); | |
| 355 | ||
| 356 | test("the request carries no referer, cookie or authorization, and says what it is", async () => { | |
| 357 | const { requests } = await counted(() => read({ url: `${site}/page` })); | |
| 358 | const h = requests[0]!.headers; | |
| 359 | for (const name of [ | |
| 360 | "referer", | |
| 361 | "cookie", | |
| 362 | "authorization", | |
| 363 | "proxy-authorization", | |
| 364 | "x-forwarded-for", | |
| 365 | "forwarded", | |
| 366 | ]) | |
| 367 | expect(h[name]).toBeUndefined(); | |
| 368 | expect(h["user-agent"]).toBe("forge-fetch/1"); | |
| 369 | expect(h["accept-encoding"]).toBe("gzip, deflate"); | |
| 370 | expect(h["host"]).toBe(`pages.test:${server.port}`); | |
| 371 | }); | |
| 372 | ||
| 373 | test("the page as Markdown: main content, code with its language, a table, numbered links; no script, chrome or hidden content", async () => { | |
| 374 | const r = await read({ url: `${site}/page` }); | |
| 375 | expect(r.ok).toBe(true); | |
| 376 | if (!r.ok) return; | |
| 377 | const md = r.value.markdown; | |
| 378 | expect(r.value.title).toBe("A page"); | |
| 379 | expect(md).toContain("# Hello"); | |
| 380 | expect(md).toContain("The **first** paragraph, with a [next page][1]."); | |
| 381 | expect(md).toContain("```ts\nconst x: number = 1;\n```"); | |
| 382 | expect(md).toContain("| a | b |\n| --- | --- |\n| 1 | 2 |"); | |
| 383 | expect(md).toContain("[image: A cat]"); | |
| 384 | expect(md).toContain(`[1]: http://pages.test:${server.port}/next`); | |
| 385 | for (const gone of [ | |
| 386 | "secretScript", | |
| 387 | "color:red", | |
| 388 | "templateSecret", | |
| 389 | "iframeSecret", | |
| 390 | "objectSecret", | |
| 391 | "svgSecret", | |
| 392 | "noscriptSecret", | |
| 393 | "asideSecret", | |
| 394 | "footerSecret", | |
| 395 | "Navigation one", | |
| 396 | "About", | |
| 397 | ]) | |
| 398 | expect(md).not.toContain(gone); | |
| 399 | }); | |
| 400 | }); | |
| 401 | ||
| 402 | describe("slices and the cache", () => { | |
| 403 | test("a long page reads in slices with a cursor, from one fetch; fresh fetches again", async () => { | |
| 404 | const { value: first, requests } = await counted(() => | |
| 405 | fetchPage(app.db, { who: someone(), url: `${site}/big` }), | |
| 406 | ); | |
| 407 | expect(requests.length).toBe(1); | |
| 408 | expect(first.ok).toBe(true); | |
| 409 | if (!first.ok) return; | |
| 410 | expect(first.value.markdown.length).toBeLessThanOrEqual(SLICE_CHARS + 4000); | |
| 411 | expect(first.value.nextCursor).toBeDefined(); | |
| 412 | expect(first.value.markdown).toContain("Paragraph 0 "); | |
| 413 | // Only the links this slice names are listed below it. | |
| 414 | expect(first.value.markdown).not.toContain("/far/399"); | |
| 415 | const second = await counted(() => | |
| 416 | fetchPage(app.db, { who: someone(), url: `${site}/big`, cursor: first.value.nextCursor }), | |
| 417 | ); | |
| 418 | expect(second.requests).toEqual([]); | |
| 419 | expect(second.value.ok ? second.value.value.markdown : "").toContain( | |
| 420 | "Paragraph 399 ", | |
| 421 | ); | |
| 422 | expect( | |
| 423 | second.value.ok ? second.value.value.nextCursor : "x", | |
| 424 | ).toBeUndefined(); | |
| 425 | const again = await counted(() => | |
| 426 | fetchPage(app.db, { who: someone(), url: `${site}/big`, fresh: true }), | |
| 427 | ); | |
| 428 | expect(again.requests.length).toBe(1); | |
| 429 | }); | |
| 430 | ||
| 431 | test("a cursor that is not one is refused", async () => { | |
| 432 | for (const cursor of ["abc", "-1", "99999999"]) { | |
| 433 | const r = await fetchPage(app.db, { who: someone(), url: `${site}/big`, cursor }); | |
| 434 | expect(r.ok ? "" : r.error.code).toBe("bad_cursor"); | |
| 435 | } | |
| 436 | }); | |
| 437 | }); | |
| 438 | ||
| 439 | describe("the forge's own agent reads only what its conversation was shown", () => { | |
| 440 | const conversation = (words: string): string => { | |
| 441 | const c = createConversation(app.db, alice.id); | |
| 442 | if (!c.ok) throw new Error(c.error); | |
| 443 | appendTurn(app.db, alice.id, c.value.id, { role: "person", text: words }); | |
| 444 | return `conversation:${c.value.id}`; | |
| 445 | }; | |
| 446 | ||
| 447 | test("a URL only in the model's own words is refused; the person's, and a link of a page read, are not", async () => { | |
| 448 | const via = conversation("what does this page say?"); | |
| 449 | appendTurn(app.db, alice.id, via.slice("conversation:".length), { | |
| 450 | role: "agent", | |
| 451 | text: `I will read ${site}/page`, | |
| 452 | }); | |
| 453 | const own = await counted(() => read({ url: `${site}/page`, via })); | |
| 454 | expect(own.value.ok ? "" : own.value.error.code).toBe("not_shown"); | |
| 455 | expect(own.requests).toEqual([]); | |
| 456 | appendTurn(app.db, alice.id, via.slice("conversation:".length), { | |
| 457 | role: "person", | |
| 458 | text: `this one: ${site}/page.`, | |
| 459 | }); | |
| 460 | expect((await read({ url: `${site}/page`, via })).ok).toBe(true); | |
| 461 | // The page links to /next, so the conversation may follow it; not to /big. | |
| 462 | expect((await read({ url: `${site}/next`, via })).ok).toBe(true); | |
| 463 | const other = await read({ url: `${site}/big`, via }); | |
| 464 | expect(other.ok ? "" : other.error.code).toBe("not_shown"); | |
| 465 | }); | |
| 466 | ||
| 467 | test("through MCP the answer is fenced and the conversation's fence is up", async () => { | |
| 468 | const via = conversation(`read ${site}/page please`); | |
| 469 | const minted = mintViaToken( | |
| 470 | app.db, | |
| 471 | alice.id, | |
| 472 | via, | |
| 473 | "read it", | |
| 474 | new Date(Date.now() + 600_000).toISOString(), | |
| 475 | ); | |
| 476 | if (!minted.ok) throw new Error(minted.error); | |
| 477 | expect(fenceUp(app.db, via)).toBeUndefined(); | |
| 478 | const res = await fetch(`${servers.url}/mcp`, { | |
| 479 | method: "POST", | |
| 480 | headers: { | |
| 481 | "content-type": "application/json", | |
| 482 | accept: "application/json, text/event-stream", | |
| 483 | authorization: `Bearer ${minted.value.token}`, | |
| 484 | }, | |
| 485 | body: JSON.stringify({ | |
| 486 | jsonrpc: "2.0", | |
| 487 | id: 1, | |
| 488 | method: "tools/call", | |
| 489 | params: { name: "fetch_url", arguments: { url: `${site}/page` } }, | |
| 490 | }), | |
| 491 | }); | |
| 492 | const text = JSON.stringify(await res.json()); | |
| 493 | expect(text).toContain("Hello"); | |
| 494 | expect(text).toMatch(/\[\[data [0-9a-f]+\]\][^[]*# Hello/); | |
| 495 | expect(fenceUp(app.db, via)).toBeDefined(); | |
| 496 | }); | |
| 497 | }); | |
| 498 | ||
| 499 | describe("the validator's round (#16365)", () => { | |
| 500 | test("the own host with a trailing dot, an escaped dot or another case is still the own host", async () => { | |
| 501 | setOwnHost("https://own.example.com", servers.url); | |
| 502 | try { | |
| 503 | for (const url of ["https://own.example.com./x", "https://OWN.Example.COM../x", "https://own.example%2ecom/x", "https://own%2Eexample.com./x"]) { | |
| 504 | const r = await read({ url }); | |
| 505 | expect(r.ok ? "" : r.error.code).toBe("own_host"); | |
| 506 | // The guard's own door sends it to the listener, never the network. | |
| 507 | expect(localFor(url)?.origin).toBe(new URL(servers.url).origin); | |
| 508 | } | |
| 509 | } finally { | |
| 510 | forgetOwnHost(); | |
| 511 | } | |
| 512 | for (const url of ["https://forge.example.com./x", "https://FORGE.example.com/x"]) { | |
| 513 | const r = await read({ url, ownHost: "forge.example.com" }); | |
| 514 | expect(r.ok ? "" : r.error.code).toBe("own_host"); | |
| 515 | } | |
| 516 | }); | |
| 517 | ||
| 518 | test("`/a/` and `/a` are two pages: one neither authorises nor answers for the other", async () => { | |
| 519 | const c = createConversation(app.db, alice.id); | |
| 520 | if (!c.ok) throw new Error(c.error); | |
| 521 | appendTurn(app.db, alice.id, c.value.id, { role: "person", text: `read ${site}/a/` }); | |
| 522 | const via = `conversation:${c.value.id}`; | |
| 523 | const bare = await read({ url: `${site}/a`, via }); | |
| 524 | expect(bare.ok ? "" : bare.error.code).toBe("not_shown"); | |
| 525 | const who = someone(); | |
| 526 | const slash = await counted(() => fetchPage(app.db, { who, url: `${site}/a/` })); | |
| 527 | const plain = await counted(() => fetchPage(app.db, { who, url: `${site}/a` })); | |
| 528 | expect(slash.value.ok ? slash.value.value.markdown : "").toBe("page a with a slash"); | |
| 529 | expect(plain.value.ok ? plain.value.value.markdown : "").toBe("page a without a slash"); | |
| 530 | expect(plain.requests.length).toBe(1); | |
| 531 | }); | |
| 532 | ||
| 533 | test("text a reader cannot see never reaches the model", async () => { | |
| 534 | const r = await read({ url: `${site}/hidden` }); | |
| 535 | const md = r.ok ? r.value.markdown : ""; | |
| 536 | expect(md).toContain("Seen text."); | |
| 537 | expect(md).toContain("Half seen."); | |
| 538 | expect(md).not.toContain("INJECT"); | |
| 539 | }); | |
| 540 | ||
| 541 | test("more credential names and shapes are refused before a request", async () => { | |
| 542 | const { value, requests } = await counted(() => | |
| 543 | Promise.all( | |
| 544 | [ | |
| 545 | "?x-api-key=abcdef123456", | |
| 546 | "?api-key=abcdef123456", | |
| 547 | "?access-token=abcdef123456", | |
| 548 | "?auth_token=abcdef123456", | |
| 549 | "?bearer=abcdef123456", | |
| 550 | "?private_key=abcdef123456", | |
| 551 | "?X-Amz-Security-Token=abcdef123456", | |
| 552 | "?X-Amz-Signature=abcdef123456", | |
| 553 | "?sig=abcdef123456", | |
| 554 | "?sas=abcdef123456", | |
| 555 | `?q=${shaped("sk-", "ant-api03-abcdefghijklmnop")}`, | |
| 556 | `?q=${shaped("sk-", "abcdefghijklmnopqrstuvwx")}`, | |
| 557 | `/${shaped("AKIA", "IOSFODNN7EXAMPLE")}/x`, | |
| 558 | `/${shaped("ghp", "_abcdefghijklmnopqrstuvwxyz0123")}`, | |
| 559 | `?q=${shaped("github", "_pat_11ABCDEFG0123456789abcdef")}`, | |
| 560 | `?q=${shaped("xo", "xb-1234567890-abcdefghij")}`, | |
| 561 | `?q=${shaped("xo", "xp-1234567890-abcdefghij")}`, | |
| 562 | `?q=${shaped("xo", "xa-1234567890-abcdefghij")}`, | |
| 563 | ].map((tail) => read({ url: `${site}/page${tail}` })), | |
| 564 | ), | |
| 565 | ); | |
| 566 | for (const r of value) expect(r.ok ? "" : r.error.code).toBe("credential"); | |
| 567 | expect(requests).toEqual([]); | |
| 568 | }); | |
| 569 | ||
| 570 | test("a link is only its number: the page's own brackets cannot make Markdown links", async () => { | |
| 571 | const r = await read({ url: `${site}/smuggle` }); | |
| 572 | const md = r.ok ? r.value.markdown : ""; | |
| 573 | // Every bracket the page wrote is escaped, so none closes a link text before an address. | |
| 574 | expect(md).not.toMatch(/(^|[^\\])\]\(https:\/\/evil/); | |
| 575 | expect(md).not.toMatch(/(^|[^\\])\[plain\]/); | |
| 576 | expect(md).toContain("[\\[click\\]\\(https://evil.test/x\\) here][1]"); | |
| 577 | expect(md).toContain(`[1]: http://pages.test:${server.port}/next`); | |
| 578 | expect(md).not.toContain("[2]:"); | |
| 579 | }); | |
| 580 | ||
| 581 | test(`a person fetches at most ${FETCHES_PER_HOUR} pages an hour, told when to try again; a kept page is still read`, async () => { | |
| 582 | const who = someone(); | |
| 583 | const { value, requests } = await counted(async () => { | |
| 584 | const out = []; | |
| 585 | for (let i = 0; i < FETCHES_PER_HOUR + 1; i++) out.push(await fetchPage(app.db, { who, url: `${site}/next`, fresh: true })); | |
| 586 | return out; | |
| 587 | }); | |
| 588 | expect(requests.length).toBe(FETCHES_PER_HOUR); | |
| 589 | expect(value.slice(0, FETCHES_PER_HOUR).every((r) => r.ok)).toBe(true); | |
| 590 | const last = value[FETCHES_PER_HOUR]!; | |
| 591 | expect(last.ok ? "" : last.error.code).toBe("rate_limited"); | |
| 592 | expect(last.ok ? "" : last.error.message).toMatch(/try again in \d+ minutes \(\d\d:\d\d UTC\)/); | |
| 593 | expect((await fetchPage(app.db, { who, url: `${site}/next` })).ok).toBe(true); | |
| 594 | // Another person is not held by this one. | |
| 595 | expect((await fetchPage(app.db, { who: someone(), url: `${site}/next`, fresh: true })).ok).toBe(true); | |
| 596 | }); | |
| 597 | }); | |
| 598 | ||
| 599 | describe("the converter on hostile HTML", () => { | |
| 600 | const timed = (html: string): { ms: number; markdown: string } => { | |
| 601 | const t = performance.now(); | |
| 602 | const { markdown } = pageMarkdown(html, "https://example.com/"); | |
| 603 | return { ms: performance.now() - t, markdown }; | |
| 604 | }; | |
| 605 | ||
| 606 | test("100,000 nested divs, a 5 MB attribute, an unclosed comment and script end fragments finish in time", () => { | |
| 607 | const cases = [ | |
| 608 | `${"<div>".repeat(100_000)}deep text${"</div>".repeat(100_000)}`, | |
| 609 | `<p title="${"a".repeat(5 * 1024 * 1024)}">after a long attribute</p>`, | |
| 610 | `<p class="${"x".repeat(5 * 1024 * 1024)}`, | |
| 611 | `<p>before</p><!-- ${"-".repeat(1_000_000)} never closed <p>hidden</p>`, | |
| 612 | `<main><p>kept</p><script>var a = "</scr" + "ipt>"; leaked1 </scr leaked2</script><p>after</p></main>`, | |
| 613 | "<".repeat(2_000_000), | |
| 614 | `${"<a ".repeat(500_000)}`, | |
| 615 | `${"<script>".repeat(300_000)}`, | |
| 616 | `${"&".repeat(500_000)}`, | |
| 617 | `<pre>${" ".repeat(2_000_000)}x</pre>`, | |
| 618 | `${"<li>".repeat(100_000)}`, | |
| 619 | ]; | |
| 620 | for (const html of cases) expect(timed(html).ms).toBeLessThan(3000); | |
| 621 | expect(timed(cases[0]!).markdown).toContain("deep text"); | |
| 622 | expect(timed(cases[1]!).markdown).toBe("after a long attribute"); | |
| 623 | expect(timed(cases[3]!).markdown).toBe("before"); | |
| 624 | const script = timed(cases[4]!).markdown; | |
| 625 | expect(script).toContain("kept"); | |
| 626 | expect(script).not.toContain("leaked"); | |
| 627 | }); | |
| 628 | ||
| 629 | test("nesting past the cap is flattened, not followed", () => { | |
| 630 | let depth = 0; | |
| 631 | let widest = 0; | |
| 632 | for (let n = parseHtml("<div>".repeat(10_000)); ; depth++) { | |
| 633 | widest = Math.max(widest, n.kids.length); | |
| 634 | const next = n.kids[0]; | |
| 635 | if (next === undefined || typeof next === "string") break; | |
| 636 | n = next; | |
| 637 | } | |
| 638 | expect(depth).toBeLessThanOrEqual(260); | |
| 639 | // What is deeper is read as siblings at the cap, not dropped. | |
| 640 | expect(widest).toBeGreaterThan(9000); | |
| 641 | }); | |
| 642 | }); | |
| 643 | ||
| 644 | describe("the terminal door: Read a web page", () => { | |
| 645 | const identity = (user?: User) => ({ sshUsername: user?.username ?? "git", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user }); | |
| 646 | /** The palette entry, run in a live terminal, with `url` typed into its prompt. */ | |
| 647 | const open = async (url: string) => { | |
| 648 | const terminal = headlessTerminal(120, 40); | |
| 649 | const { app: tui, session } = createForgeApp(app, identity(alice), { terminal, exitHooks: false, toastMs: 10 * 60_000 }); | |
| 650 | tui.start(); | |
| 651 | await settleApp(tui); | |
| 652 | const entry = forgeCommands(session)(tui.ctx).find((c) => c.id === "fetch-page"); | |
| 653 | expect(entry).toBeDefined(); | |
| 654 | entry!.run(); | |
| 655 | await settleApp(tui); | |
| 656 | expect(tui.screen.toText()).toContain("An https link"); | |
| 657 | terminal.feed(`${url}\r`); | |
| 658 | await settleApp(tui); | |
| 659 | return { tui, text: tui.screen.toText() }; | |
| 660 | }; | |
| 661 | ||
| 662 | test("a signed-in person gets a screen with the page's Markdown", async () => { | |
| 663 | const { tui, text } = await open(`${site}/page`); | |
| 664 | try { | |
| 665 | expect(text).toContain("A page"); | |
| 666 | expect(text).toContain("Hello"); | |
| 667 | expect(text).toContain("const x: number = 1;"); | |
| 668 | expect(text).not.toContain("An https link"); | |
| 669 | } finally { | |
| 670 | tui.stop(); | |
| 671 | } | |
| 672 | }); | |
| 673 | ||
| 674 | test("a refusal is a toast and pushes no screen: a private address, a credential in the URL, the hourly limit", async () => { | |
| 675 | webPageReach.override = reach({ allow: [] }); | |
| 676 | for (const [url, says] of [ | |
| 677 | ["https://intranet.test/", "private"], | |
| 678 | [`https://user:${shaped("hunter", "22")}@pages.test/page`, "name or password"], | |
| 679 | ] as const) { | |
| 680 | const { tui, text } = await open(url); | |
| 681 | try { | |
| 682 | // The prompt closes and the toast says why; no page screen is pushed over the home screen. | |
| 683 | expect(text.toLowerCase()).toContain(says); | |
| 684 | expect(text).toContain("find a repository"); | |
| 685 | expect(text).not.toContain("Hello"); | |
| 686 | } finally { | |
| 687 | tui.stop(); | |
| 688 | } | |
| 689 | } | |
| 690 | webPageReach.override = reach(); | |
| 691 | for (let i = 0; i < FETCHES_PER_HOUR; i++) await fetchPage(app.db, { who: alice.id, url: `${site}/next`, fresh: true }); | |
| 692 | const { tui, text } = await open(`${site}/page`); | |
| 693 | try { | |
| 694 | expect(text).toMatch(/try again in \d+ minutes/); | |
| 695 | expect(text).toContain("find a repository"); | |
| 696 | expect(text).not.toContain("Hello"); | |
| 697 | } finally { | |
| 698 | tui.stop(); | |
| 699 | } | |
| 700 | }); | |
| 701 | ||
| 702 | test("a guest is not offered it", () => { | |
| 703 | const ids = (user?: User) => { | |
| 704 | const { app: tui, session } = createForgeApp(app, identity(user), { terminal: headlessTerminal(120, 40), exitHooks: false }); | |
| 705 | return forgeCommands(session)(tui.ctx).map((c) => c.id); | |
| 706 | }; | |
| 707 | expect(ids()).not.toContain("fetch-page"); | |
| 708 | expect(ids(alice)).toContain("fetch-page"); | |
| 709 | }); | |
| 710 | ||
| 711 | test("a document still reads through the same Markdown screen", async () => { | |
| 712 | const entry = docEntry("guide-first-app.md") ?? docEntry("ARCHITECTURE.md"); | |
| 713 | expect(entry).toBeDefined(); | |
| 714 | const terminal = headlessTerminal(120, 40); | |
| 715 | const { app: tui } = createForgeApp(app, identity(alice), { terminal, exitHooks: false }); | |
| 716 | tui.start(); | |
| 717 | try { | |
| 718 | tui.ctx.push(docScreen(tui.ctx, entry!, false)); | |
| 719 | await settleApp(tui); | |
| 720 | const text = tui.screen.toText(); | |
| 721 | expect(text).toContain(entry!.title); | |
| 722 | expect(text.trim().split("\n").length).toBeGreaterThan(5); | |
| 723 | } finally { | |
| 724 | tui.stop(); | |
| 725 | } | |
| 726 | }); | |
| 727 | }); |
test/mcp-forge-protocol.test.ts +1
| @@ -235,6 +235,7 @@ describe("the forge over MCP: protocol", () => { | ||
| 235 | 235 | "feed_chips", |
| 236 | 236 | "feed_dismiss", |
| 237 | 237 | "feed_like", |
| 238 | "fetch_url", | |
| 238 | 239 | "find_tool", |
| 239 | 240 | "maintenance", |
| 240 | 241 | "make_it_yours", |
test/outbound-guard.test.ts +17
| @@ -31,6 +31,7 @@ import { statusOf } from "../src/apps/parity_probe.ts"; | ||
| 31 | 31 | import { createRepo } from "../src/core/repos.ts"; |
| 32 | 32 | import { createUser, type User } from "../src/core/users.ts"; |
| 33 | 33 | import { createWebhook, deliverDue, pingWebhook } from "../src/core/webhooks.ts"; |
| 34 | import { fetchPage, webPageReach } from "../src/core/web_page.ts"; | |
| 34 | 35 | import { openGatewayDoor } from "../src/crew/gateway_door.ts"; |
| 35 | 36 | import { post } from "../src/crew/notify.ts"; |
| 36 | 37 | import { REFUSED_SENTENCE, type Resolve } from "../src/kernel/outbound.ts"; |
| @@ -106,6 +107,22 @@ let repoId = ""; | ||
| 106 | 107 | let hooks = 0; |
| 107 | 108 | |
| 108 | 109 | const SITES: readonly Site[] = [ |
| 110 | { | |
| 111 | file: "src/core/web_page.ts", | |
| 112 | what: "a page fetch_url reads for Talk or the terminal", | |
| 113 | fetches: true, | |
| 114 | names: true, | |
| 115 | judgesRedirects: true, | |
| 116 | async refused(t) { | |
| 117 | webPageReach.override = { resolve: t.resolve }; | |
| 118 | try { | |
| 119 | const r = await fetchPage(app.db, { url: `https://${t.host}/page`, who: `guard-${++hooks}`, fresh: true }); | |
| 120 | return !r.ok && r.error.code === "refused"; | |
| 121 | } finally { | |
| 122 | webPageReach.override = undefined; | |
| 123 | } | |
| 124 | }, | |
| 125 | }, | |
| 109 | 126 | { |
| 110 | 127 | file: "src/core/webhooks.ts", |
| 111 | 128 | what: "a repository's webhook, delivered", |
test/outbound.test.ts +7
| @@ -21,6 +21,13 @@ describe("vetHost", () => { | ||
| 21 | 21 | "ff02::1", |
| 22 | 22 | "::ffff:127.0.0.1", |
| 23 | 23 | "::ffff:10.0.0.1", |
| 24 | // #16365: IETF protocol assignments, benchmarking, SIIT, Teredo. | |
| 25 | "192.0.0.8", | |
| 26 | "198.18.0.1", | |
| 27 | "198.19.255.254", | |
| 28 | "::ffff:0:10.0.0.1", | |
| 29 | "::ffff:0:5db8:d822", | |
| 30 | "2001:0:4136:e378:8000:63bf:3fff:fdd2", | |
| 24 | 31 | ]) |
| 25 | 32 | test(`refuses ${addr}`, async () => { |
| 26 | 33 | const r = await vetHost(addr); |
test/palette-roster.test.ts +3
| @@ -111,6 +111,7 @@ test("a site-admin person is offered the whole roster", () => { | ||
| 111 | 111 | ["runners", "Runners", "the machines that take this forge's checks; x removes a hand-made one"], |
| 112 | 112 | ["conversations", "Conversations", "your talks with the forge's agent; n starts one, r renames, x archives"], |
| 113 | 113 | ["build-app", "Build an app", "say what to build; versions, diff, restore and publish. n starts one"], |
| 114 | ["fetch-page", "Read a web page", "paste an https link; the page as Markdown, as Talk's agent reads it"], | |
| 114 | 115 | ["ssh-keys", "Computer keys", "list, add and remove the keys that sign in as you"], |
| 115 | 116 | ["passkeys", "Passkeys", "the passkeys that sign in as you"], |
| 116 | 117 | ["account", "Account settings", undefined], |
| @@ -294,6 +295,7 @@ test("a site-admin agent is offered the roster without the person-only entries", | ||
| 294 | 295 | ["asked", "Asked", "your thoughts and what became of them"], |
| 295 | 296 | ["thought-notes", "Notes", "write an idea and watch it become shipped work"], |
| 296 | 297 | ["decider", "Decider", "what it closed, deferred and asked you about today"], |
| 298 | ["fetch-page", "Read a web page", "paste an https link; the page as Markdown, as Talk's agent reads it"], | |
| 297 | 299 | ["ssh-keys", "Computer keys", "list, add and remove the keys that sign in as you"], |
| 298 | 300 | ["account", "Account settings", undefined], |
| 299 | 301 | ["signins", "Signed in", "your browsers and tokens; d signs a browser out"], |
| @@ -413,6 +415,7 @@ test("a member person is offered the signed-in roster without the admin entries" | ||
| 413 | 415 | ["receipts", "Receipts", "what you confirmed in /talk; u undoes it once"], |
| 414 | 416 | ["conversations", "Conversations", "your talks with the forge's agent; n starts one, r renames, x archives"], |
| 415 | 417 | ["build-app", "Build an app", "say what to build; versions, diff, restore and publish. n starts one"], |
| 418 | ["fetch-page", "Read a web page", "paste an https link; the page as Markdown, as Talk's agent reads it"], | |
| 416 | 419 | ["ssh-keys", "Computer keys", "list, add and remove the keys that sign in as you"], |
| 417 | 420 | ["passkeys", "Passkeys", "the passkeys that sign in as you"], |
| 418 | 421 | ["account", "Account settings", undefined], |
new above
offline
Medium: this terminal entry has no behavioural test, only the roster line. Cover the success path, the refusal toast and the guest case (no entry).