Public: anyone can read this; the crew can change it.
Every link in a Talk reply clicks, and nothing that reads as a link is dead #16212
Check · Review · Land · Live done — Landed and live in production.
talk/fix-links-click → main 2 commits 3 threads · 3 unresolved
5 files
changed +591
−6
docs/features/talk.md +4
| @@ -122,6 +122,10 @@ Prior art read: Vercel AI Elements (Apache-2.0 React on shadcn; anatomy and beha | ||
| 122 | 122 | |
| 123 | 123 | **The terminal** (`ssh <forge> talk <words>`, `forge talk`) sends one line and prints the answer; it has no log, so who/when, copy, tool cards, starters and the jump button do not apply to it. `forge talk` prints a thought as one `thinking:` line, then the reply, the steps line and the links as paths (the API's agent turns carry `work: {steps, links}`). The steps line says "opened" for a read issue or pull and "changed" for a tool that writes one (`CHANGES` in `core/talk_work.ts`, held to the MCP tools' `writes` by a test); numbers carry their repo when a turn touched more than one. A reply first on an older page, or first in a stream batch, reads its calls from the turns before the page (`worksOf`), so it says the same on every door. The conversation's whole history is read through `GET /api/v1/conversation/turns`, where every turn carries its role and time. |
| 124 | 124 | |
| 125 | ## Every link in a reply clicks | |
| 126 | ||
| 127 | A reply is drawn by the README renderer and then, for Talk alone, by `linkTalk` (`src/text/talk_link_words.ts`): a Markdown link stays a link only if it goes somewhere (an `http(s)` address with no user part, or a path rooted on this forge: one leading slash, never `//` or `/\\`, no encoded control character), and a relative path, which would resolve against the conversation's own address, is set back to its words. A bare `http(s)` address in the words is a link, its trailing punctuation left out. A forge path written as words (`owner/repo`, `owner/repo#12`, `owner/repo/pulls/4`, `owner/repo/src/a.ts`) is a link when you may read that repository and, for a number, when it is there; anything else stays words, so a private repository's existence is never shown. Each repository a page of replies names is read once. An address of one of this forge's apps you may read goes to it while it runs, and to its page on the forge, said "not running yet", while it does not. READMEs keep their rules (no bare-address or path links); both now refuse a `/\\host` link, which a browser reads as `//host`. | |
| 128 | ||
| 125 | 129 | ## Code, tables and Copy in a reply (#8816) |
| 126 | 130 | |
| 127 | 131 | An agent reply is Markdown, drawn on the server by the same renderer as a README: fenced code is highlighted, tables and links render, and everything else is escaped (a `<script>` in a reply shows as text). A table wider than the column scrolls inside it; the page does not. The reply sits in the column like a person's turn, with none of the README's padding or line measure. |
src/text/talk_link_words.ts added +232
| @@ -0,0 +1,232 @@ | ||
| 1 | /** | |
| 2 | * Every link a Talk reply shows clicks, and nothing that reads as a link is dead (#10262). The | |
| 3 | * owner met "a link that didn't click": a reply's words named a repository, a file or an address | |
| 4 | * that the page drew as plain text, or as a link going nowhere. This works on the HTML the markdown | |
| 5 | * renderer already escaped, like `linkRefs`, touching only text outside tags, links, code and pre, | |
| 6 | * and putting in only hrefs it built itself: | |
| 7 | * | |
| 8 | * - A link the renderer made stays only if it goes somewhere: an `http(s)` address with no user | |
| 9 | * part (`https://[email protected]` is not one), or a path rooted on this forge (one | |
| 10 | * leading slash, never `//` or `/\`, no encoded control character). A relative path, which | |
| 11 | * would resolve against the conversation's own address, is set back to its words. | |
| 12 | * - A bare `http(s)` address in the words is a link, trailing punctuation left out of it. | |
| 13 | * - A forge path written as words (`owner/repo`, `owner/repo#12`, `owner/repo/pulls/4`, | |
| 14 | * `owner/repo/src/a.ts`) is a link when the viewer may read it (`TalkLook`): unknown or | |
| 15 | * unreadable stays words, so a private repository's existence is never shown. | |
| 16 | * - An address of one of this forge's apps the viewer may read is a link to it while it runs, and | |
| 17 | * to its page on the forge, said "not running yet", while it does not. | |
| 18 | * | |
| 19 | * README rendering never passes through here. | |
| 20 | */ | |
| 21 | import type { Database } from "bun:sqlite"; | |
| 22 | import type { App } from "../app.ts"; | |
| 23 | import { parseAppHost } from "../apps/proxy.ts"; | |
| 24 | import { appsRuntime } from "../apps/runtime.ts"; | |
| 25 | import { getAppBySlug } from "../core/apps.ts"; | |
| 26 | import { getIssue } from "../core/issues.ts"; | |
| 27 | import { canRead, getRepo, getRepoById, type Repo } from "../core/repos.ts"; | |
| 28 | import type { User } from "../core/users.ts"; | |
| 29 | import { raw, type Html } from "../web/html.ts"; | |
| 30 | ||
| 31 | const SKIP = new Set(["a", "code", "pre"]); | |
| 32 | /** A name segment of a repository path: what the forge allows, never ending in a dot. */ | |
| 33 | const SEG = "[A-Za-z0-9_](?:[A-Za-z0-9_.-]{0,98}[A-Za-z0-9_-])?"; | |
| 34 | /** `owner/repo`, then `#12`, `/pulls/4`, `/issues/4`, or a file with an extension. */ | |
| 35 | const FORGE_PATH = new RegExp( | |
| 36 | `(?<![\\w/.:@&;-])(${SEG})/(${SEG})(?:#(\\d{1,7})|/(pulls|issues)/(\\d{1,7})|/((?:${SEG}/){0,20}[A-Za-z0-9_-][A-Za-z0-9_.-]{0,99}\\.[A-Za-z0-9]{1,10}))?(?![\\w/])`, | |
| 37 | "g", | |
| 38 | ); | |
| 39 | /** | |
| 40 | * A bare address in the words; `&` is escaped already, so the address stops at a quote or a tag. | |
| 41 | */ | |
| 42 | const BARE_URL = /\bhttps?:\/\/[^\s<"']+/gi; | |
| 43 | /** Punctuation that ends a sentence, not an address. */ | |
| 44 | const TRAILING = /[.,;:!?)\]]+$/; | |
| 45 | ||
| 46 | /** What the links need to know about the forge, asked once per page of turns. */ | |
| 47 | export interface TalkLook { | |
| 48 | /** The repository at `owner/name` when the viewer may read it. */ | |
| 49 | readonly repo: (owner: string, name: string) => Repo | undefined; | |
| 50 | /** Whether issue or pull `n` of a readable repository exists, and which it is. */ | |
| 51 | readonly kindOf: (repo: Repo, n: number) => "issue" | "pull" | undefined; | |
| 52 | /** An app address (`https://notes.forge.example/…`) the viewer may read, with where to go. */ | |
| 53 | readonly app: ( | |
| 54 | url: string, | |
| 55 | ) => { readonly href: string; readonly running: boolean } | undefined; | |
| 56 | } | |
| 57 | ||
| 58 | /** | |
| 59 | * Whether an href the renderer made goes somewhere: http(s) without a user part, or a safe rooted | |
| 60 | * path. | |
| 61 | */ | |
| 62 | export function safeHref(href: string): boolean { | |
| 63 | if (/^https?:\/\//i.test(href)) | |
| 64 | return !/^https?:\/\/[^/?#]*@/i.test(href) && !/[\s\\]/.test(href); | |
| 65 | return ( | |
| 66 | /^\/(?![/\\])/.test(href) && | |
| 67 | !/[\\\s]/.test(href) && | |
| 68 | !/%(?:[01][0-9a-f]|7f)/i.test(href) | |
| 69 | ); | |
| 70 | } | |
| 71 | ||
| 72 | /** An address off this forge carries what the README renderer gives one: no follow, no opener. */ | |
| 73 | const anchor = (href: string, words: string): string => | |
| 74 | /^https?:\/\//i.test(href) | |
| 75 | ? `<a href="${href}" rel="nofollow noopener">${words}</a>` | |
| 76 | : `<a href="${href}">${words}</a>`; | |
| 77 | ||
| 78 | /** Link what reads as a link in an escaped Talk reply, by the rules above. */ | |
| 79 | export function linkTalk(rendered: Html, look: TalkLook): Html { | |
| 80 | // A link the renderer made that goes nowhere becomes its words again. | |
| 81 | const text = rendered.text.replace( | |
| 82 | /<a href="([^"]*)"[^>]*>([\s\S]*?)<\/a>/g, | |
| 83 | (whole, href: string, words: string) => { | |
| 84 | if (!safeHref(href)) return words; | |
| 85 | const app = /^https?:\/\//i.test(href) ? look.app(href) : undefined; | |
| 86 | return app === undefined || app.running | |
| 87 | ? whole | |
| 88 | : `${anchor(app.href, words)} (not running yet)`; | |
| 89 | }, | |
| 90 | ); | |
| 91 | const parts = text.split(/(<[^>]*>)/); | |
| 92 | let skipping = 0; | |
| 93 | for (let i = 0; i < parts.length; i += 1) { | |
| 94 | const part = parts[i]!; | |
| 95 | if (part.startsWith("<")) { | |
| 96 | const tag = /^<(\/?)([a-z0-9]+)/i.exec(part); | |
| 97 | if (tag !== null && SKIP.has(tag[2]!.toLowerCase())) | |
| 98 | skipping = Math.max(0, skipping + (tag[1] === "/" ? -1 : 1)); | |
| 99 | continue; | |
| 100 | } | |
| 101 | if (skipping > 0 || part === "") continue; | |
| 102 | parts[i] = linkWords(part, look); | |
| 103 | } | |
| 104 | return raw(parts.join("")); | |
| 105 | } | |
| 106 | ||
| 107 | /** One run of escaped text: its bare addresses, then its forge paths, each linked once. */ | |
| 108 | function linkWords(part: string, look: TalkLook): string { | |
| 109 | // Addresses first, set aside, so a path inside one is not read again. | |
| 110 | const kept: string[] = []; | |
| 111 | const hold = (html: string): string => | |
| 112 | `\u0000${String(kept.push(html) - 1)}\u0000`; | |
| 113 | let out = part.replace(BARE_URL, (found) => { | |
| 114 | const tail = TRAILING.exec(found)?.[0] ?? ""; | |
| 115 | const url = found.slice(0, found.length - tail.length); | |
| 116 | if (!safeHref(url)) return found; | |
| 117 | const app = look.app(url); | |
| 118 | if (app !== undefined && !app.running) | |
| 119 | return `${hold(anchor(app.href, url))} (not running yet)${tail}`; | |
| 120 | return `${hold(anchor(url, url))}${tail}`; | |
| 121 | }); | |
| 122 | out = out.replace( | |
| 123 | FORGE_PATH, | |
| 124 | ( | |
| 125 | whole, | |
| 126 | owner: string, | |
| 127 | name: string, | |
| 128 | hash?: string, | |
| 129 | kind?: string, | |
| 130 | n?: string, | |
| 131 | file?: string, | |
| 132 | ) => { | |
| 133 | const repo = look.repo(owner, name); | |
| 134 | if (repo === undefined) return whole; | |
| 135 | const base = `/${repo.ownerName}/${repo.name}`; | |
| 136 | const number = hash ?? n; | |
| 137 | if (number !== undefined) { | |
| 138 | const found = look.kindOf(repo, Number(number)); | |
| 139 | if (found === undefined || (kind !== undefined && kind !== `${found}s`)) | |
| 140 | return whole; | |
| 141 | return hold(anchor(`${base}/${found}s/${number}`, whole)); | |
| 142 | } | |
| 143 | if (file !== undefined) | |
| 144 | return hold( | |
| 145 | anchor( | |
| 146 | `${base}/blob/${encodeURIComponent(repo.defaultBranch)}/${file.split("/").map(encodeURIComponent).join("/")}`, | |
| 147 | whole, | |
| 148 | ), | |
| 149 | ); | |
| 150 | return hold(anchor(base, whole)); | |
| 151 | }, | |
| 152 | ); | |
| 153 | return out.replace( | |
| 154 | /\u0000(\d+)\u0000/g, | |
| 155 | (_m, k: string) => kept[Number(k)] ?? "", | |
| 156 | ); | |
| 157 | } | |
| 158 | ||
| 159 | /** The owner/repo pairs a page of replies names, each once. */ | |
| 160 | export function namedRepos(texts: readonly string[]): string[] { | |
| 161 | const seen = new Set<string>(); | |
| 162 | for (const t of texts) | |
| 163 | for (const m of t.matchAll(FORGE_PATH)) | |
| 164 | seen.add(`${m[1]!}/${m[2]!}`.toLowerCase()); | |
| 165 | return [...seen]; | |
| 166 | } | |
| 167 | ||
| 168 | /** | |
| 169 | * The look for a page of replies: each repository the replies name read once (and its readability | |
| 170 | * decided once), each number looked up once, however many times the words repeat them. | |
| 171 | */ | |
| 172 | export function talkLook( | |
| 173 | db: Database, | |
| 174 | viewer: User | undefined, | |
| 175 | texts: readonly string[], | |
| 176 | app: TalkLook["app"] = () => undefined, | |
| 177 | ): TalkLook { | |
| 178 | const repos = new Map<string, Repo | undefined>(); | |
| 179 | for (const pair of namedRepos(texts)) { | |
| 180 | const [owner = "", name = ""] = pair.split("/"); | |
| 181 | const found = getRepo(db, owner, name); | |
| 182 | repos.set( | |
| 183 | pair, | |
| 184 | found !== undefined && canRead(db, found, viewer) ? found : undefined, | |
| 185 | ); | |
| 186 | } | |
| 187 | const kinds = new Map<string, "issue" | "pull" | undefined>(); | |
| 188 | return { | |
| 189 | repo: (owner, name) => repos.get(`${owner}/${name}`.toLowerCase()), | |
| 190 | kindOf: (repo, n) => { | |
| 191 | const key = `${repo.id}#${String(n)}`; | |
| 192 | if (!kinds.has(key)) kinds.set(key, getIssue(db, repo.id, n)?.kind); | |
| 193 | return kinds.get(key); | |
| 194 | }, | |
| 195 | app, | |
| 196 | }; | |
| 197 | } | |
| 198 | ||
| 199 | /** | |
| 200 | * Where an address of one of this forge's apps goes for `viewer`: to it while that environment | |
| 201 | * runs, to the app's page on the forge while it does not; undefined for an address that is no app | |
| 202 | * of ours, or one the viewer may not read. | |
| 203 | */ | |
| 204 | export function appLook(app: App, viewer: User | undefined): TalkLook["app"] { | |
| 205 | const runtime = appsRuntime(app); | |
| 206 | if (runtime === undefined) return () => undefined; | |
| 207 | return (url) => { | |
| 208 | let host: string; | |
| 209 | try { | |
| 210 | host = new URL(url).host; | |
| 211 | } catch { | |
| 212 | return undefined; | |
| 213 | } | |
| 214 | const at = parseAppHost(host, runtime.options.domain); | |
| 215 | // A nested host is an app of a forge hosted here: that forge's to answer, not ours. | |
| 216 | const record = | |
outdated
Untested and unformatted. Cover readable and unreadable apps, running and not running, nested hosts. Wrap the long lines (gate --fix). |
||
| 217 | at === undefined || at.nested ? undefined : getAppBySlug(app.db, at.slug); | |
| 218 | const repo = | |
| 219 | record === undefined ? undefined : getRepoById(app.db, record.repoId); | |
| 220 | if ( | |
| 221 | at === undefined || | |
| 222 | record === undefined || | |
| 223 | repo === undefined || | |
| 224 | !canRead(app.db, repo, viewer) | |
| 225 | ) | |
| 226 | return undefined; | |
| 227 | const running = runtime | |
| 228 | .status(record) | |
| 229 | .some((e) => e.env === at.env && e.state === "running"); | |
| 230 | return { href: `/${repo.ownerName}/${repo.name}`, running }; | |
| 231 | }; | |
| 232 | } |
src/web/markdown.ts +7 −1
| @@ -113,7 +113,13 @@ function inline(escaped: string, repo?: MarkdownRepo): string { | ||
| 113 | 113 | // what keeps javascript:, data: and vbscript: out. What is left is a |
| 114 | 114 | // relative path (`docs/keeping.md`), a rooted one, or an anchor — |
| 115 | 115 | // all of which stay on this origin by construction. |
| 116 | if (url.startsWith("//")) return match; | |
| 116 | // A browser reads "/\\host" and "\\host" as "//host" too. | |
| 117 | if ( | |
| 118 | url.startsWith("//") || | |
| 119 | url.startsWith("/\\") || | |
| 120 | url.startsWith("\\") | |
| 121 | ) | |
| 122 | return match; | |
| 117 | 123 | if (repo !== undefined) { |
| 118 | 124 | const at = resolveRelative(url, repo); |
| 119 | 125 | if (at === "inert") return `${bang}${text}`; |
src/web/pages/talk.ts +20 −5
| @@ -61,6 +61,7 @@ import { readForm } from "../form.ts"; | ||
| 61 | 61 | import { html, raw, type Html } from "../html.ts"; |
| 62 | 62 | import { flashTo, page, redirect } from "../layout.ts"; |
| 63 | 63 | import { linkRefs, refTarget } from "../../text/talk_links.ts"; |
| 64 | import { appLook, linkTalk, talkLook, type TalkLook } from "../../text/talk_link_words.ts"; | |
| 64 | 65 | import { liveCrewRows } from "../../actions/crew_now.ts"; |
| 65 | 66 | import { crewLineHtml } from "../crew_now.ts"; |
| 66 | 67 | import { renderMarkdown } from "../markdown.ts"; |
| @@ -230,8 +231,19 @@ const totalLine = (usd: number | undefined): Html => | ||
| 230 | 231 | /** The cost line under a reply. */ |
| 231 | 232 | const costLine = (spend: Spend): Html => html`<p class="talk-cost small muted">${spendWords(spend)}</p>`; |
| 232 | 233 | |
| 234 | /** | |
| 235 | * What a reply's drawn Markdown becomes on the page: its cited numbers linked, and every link one | |
| 236 | * that clicks. | |
| 237 | */ | |
| 238 | const linkedOf = | |
| 239 | (refs?: (n: number) => string | undefined, look?: TalkLook) => | |
| 240 | (md: Html): Html => { | |
| 241 | const cited = refs === undefined ? md : linkRefs(md, refs); | |
| 242 | return look === undefined ? cited : linkTalk(cited, look); | |
| 243 | }; | |
| 244 | ||
| 233 | 245 | /** One turn as the page and the stream both draw it; `waiting` is the confirms still open. */ |
| 234 | export function turnHtml(turn: Turn, waiting: ReadonlySet<string>, cost?: Spend, act?: Html, work?: Work, files: readonly ConversationFile[] = [], expired: ReadonlySet<string> = new Set(), undone: ReadonlySet<string> = new Set(), refs?: (n: number) => string | undefined, voice?: Voice): Html { | |
| 246 | export function turnHtml(turn: Turn, waiting: ReadonlySet<string>, cost?: Spend, act?: Html, work?: Work, files: readonly ConversationFile[] = [], expired: ReadonlySet<string> = new Set(), undone: ReadonlySet<string> = new Set(), refs?: (n: number) => string | undefined, voice?: Voice, look?: TalkLook): Html { | |
| 235 | 247 | const id = `t-${turn.id}`; |
| 236 | 248 | const set = turn.replaced ? " talk-replaced" : ""; |
| 237 | 249 | const acts = act === undefined ? null : html`<div class="talk-acts">${act}</div>`; |
| @@ -249,7 +261,7 @@ export function turnHtml(turn: Turn, waiting: ReadonlySet<string>, cost?: Spend, | ||
| 249 | 261 | </li>`; |
| 250 | 262 | if (turn.role === "agent") |
| 251 | 263 | return html`<li class="talk-turn talk-agent${set}" id="${id}"> |
| 252 | <div class="talk-body prose">${agentHtml(turn, voice, (md) => (refs === undefined ? md : linkRefs(md, refs)))}</div> | |
| 264 | <div class="talk-body prose">${agentHtml(turn, voice, linkedOf(refs, look))}</div> | |
| 253 | 265 | ${work === undefined ? null : workHtml(work)} |
| 254 | 266 | ${label("Forge")} |
| 255 | 267 | ${cost === undefined ? null : costLine(cost)}${acts} |
| @@ -437,6 +449,8 @@ async function talkPage(ctx: Ctx, conversation: Conversation, before0: string | | ||
| 437 | 449 | const cited = repoOf(turns); |
| 438 | 450 | const refs = refTarget(ctx.app.db, user, cited); |
| 439 | 451 | const voice = voiceOf(ctx.app.db, user.id, conversation.id, turns, ctx.url.origin); |
| 452 | // The forge paths the replies name, each read once for the page however often they repeat. | |
| 453 | const look = talkLook(ctx.app.db, user, turns.filter((t) => t.role === "agent").map((t) => t.text), appLook(ctx.app, user)); | |
| 440 | 454 | const pane = talkPane(ctx, user, cited, works, view); |
| 441 | 455 | const body = html`<div class="talk-page"><h1 class="sr-only">Talk</h1> |
| 442 | 456 | ${box} |
| @@ -456,7 +470,7 @@ async function talkPage(ctx: Ctx, conversation: Conversation, before0: string | | ||
| 456 | 470 | ${turns.length === 0 |
| 457 | 471 | ? html`<li class="muted talk-turn">Ask the forge anything, or tell it what to change. It acts as you, with your permissions, and asks before anything hard to undo. |
| 458 | 472 | <div class="talk-suggest">${STARTER_PROMPTS.map((q) => html`<form method="post" action="${here}" data-starter><input type="hidden" name="text" value="${q}" />${btn(q)}</form>`)}</div></li>` |
| 459 | : turns.map((t) => turnHtml(t, waiting, costs.get(t.id), acts.get(t.id), works.get(t.id), sent.get(t.id), expired, undone, refs, voice))} | |
| 473 | : turns.map((t) => turnHtml(t, waiting, costs.get(t.id), acts.get(t.id), works.get(t.id), sent.get(t.id), expired, undone, refs, voice, look))} | |
| 460 | 474 | ${!paged && running ? queuedTalk(ctx.app, user, conversation.id).map(queuedHtml) : null} |
| 461 | 475 | </ol> |
| 462 | 476 | <div id="end"></div> |
| @@ -718,7 +732,7 @@ export function talkStream(ctx: Ctx): Response { | ||
| 718 | 732 | const block = liveBlock(app.db, conversation.id); |
| 719 | 733 | const refs = refTarget(app.db, user, cited); |
| 720 | 734 | const frame = { |
| 721 | html: block === undefined || block.text === "" ? "" : html`<div class="talk-body prose">${linkRefs(renderMarkdown(block.text), refs)}</div>`.text, | |
| 735 | html: block === undefined || block.text === "" ? "" : html`<div class="talk-body prose">${linkedOf(refs, talkLook(app.db, user, [block.text], appLook(app, user)))(renderMarkdown(block.text))}</div>`.text, | |
| 722 | 736 | thinking: block?.thinking === true, |
| 723 | 737 | tool: block?.tool === undefined ? "" : runningStep(block.tool), |
| 724 | 738 | }; |
| @@ -748,8 +762,9 @@ export function talkStream(ctx: Ctx): Response { | ||
| 748 | 762 | if (named !== undefined) cited = named; |
| 749 | 763 | const refs = refTarget(app.db, user, cited); |
| 750 | 764 | const voice = voiceOf(app.db, user.id, conversation.id, fresh, ctx.url.origin); |
| 765 | const look = talkLook(app.db, user, fresh.filter((t) => t.role === "agent").map((t) => t.text), appLook(app, user)); | |
| 751 | 766 | for (const turn of fresh) { |
| 752 | emit("turn", { id: turn.id, role: turn.role, html: turnHtml(turn, waiting, undefined, undefined, works.get(turn.id), sent.get(turn.id), expired, undone, refs, voice).text }, turn.id); | |
| 767 | emit("turn", { id: turn.id, role: turn.role, html: turnHtml(turn, waiting, undefined, undefined, works.get(turn.id), sent.get(turn.id), expired, undone, refs, voice, look).text }, turn.id); | |
| 753 | 768 | cursor = turn.id; |
| 754 | 769 | } |
| 755 | 770 | // The page is told at once what the block holds after these turns, empty once it is |
test/talk-links-click.test.ts added +328
| @@ -0,0 +1,328 @@ | ||
| 1 | /** | |
| 2 | * Every link in a Talk reply clicks (#10262). The owner met "a link that didn't click". A rooted | |
| 3 | * forge path and a bare address are links; a forge path written as words links when the viewer | |
| 4 | * may read it; an app's address goes to the app while it runs and to its page while it does not; | |
| 5 | * a link the renderer made that would go nowhere is set back to its words; hostile forms stay | |
| 6 | * text. README rendering keeps its rules, and a page of replies reads each named repository once. | |
| 7 | */ | |
| 8 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 9 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 10 | import { tmpdir } from "node:os"; | |
| 11 | import { join } from "node:path"; | |
| 12 | import { createRepo } from "../src/actions/repos.ts"; | |
| 13 | import { createApp, type App } from "../src/app.ts"; | |
| 14 | import { appendTurn, createConversation } from "../src/core/conversations.ts"; | |
| 15 | import { createIssue } from "../src/core/issues.ts"; | |
| 16 | import { createSession } from "../src/core/sessions.ts"; | |
| 17 | import { createUser, type User } from "../src/core/users.ts"; | |
| 18 | import type { Repo } from "../src/core/repos.ts"; | |
| 19 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 20 | import { newApp } from "../src/actions/apps.ts"; | |
| 21 | import { AppsRuntime } from "../src/apps/runtime.ts"; | |
| 22 | import { getAppBySlug, type AppRecord } from "../src/core/apps.ts"; | |
| 23 | import { | |
| 24 | appLook, | |
| 25 | linkTalk, | |
| 26 | safeHref, | |
| 27 | talkLook, | |
| 28 | type TalkLook, | |
| 29 | } from "../src/text/talk_link_words.ts"; | |
| 30 | import { renderMarkdown } from "../src/web/markdown.ts"; | |
| 31 | import { promote } from "./helpers/members.ts"; | |
| 32 | import { once } from "./helpers/statements.ts"; | |
| 33 | ||
| 34 | let dir: string; | |
| 35 | let app: App; | |
| 36 | let servers: Servers; | |
| 37 | let alice: User; | |
| 38 | let bob: User; | |
| 39 | /** A real repository, `marin/lighthouse`, for the fixed world below. */ | |
| 40 | let marin: Repo; | |
| 41 | ||
| 42 | /** | |
| 43 | * A look over a fixed world: one readable repository, `marin/lighthouse`, with issue 12 and pull 4. | |
| 44 | */ | |
| 45 | const fake = (apps: TalkLook["app"] = () => undefined): TalkLook => ({ | |
| 46 | repo: (o, n) => | |
| 47 | `${o}/${n}`.toLowerCase() === "marin/lighthouse" | |
| 48 | ? marin | |
| 49 | : undefined, | |
| 50 | kindOf: (_r, n) => (n === 12 ? "issue" : n === 4 ? "pull" : undefined), | |
| 51 | app: apps, | |
| 52 | }); | |
| 53 | const talk = (md: string, look = fake()) => | |
| 54 | linkTalk(renderMarkdown(md), look).text; | |
| 55 | const hrefs = (html: string) => | |
| 56 | [...html.matchAll(/<a href="([^"]*)"/g)].map((m) => m[1]); | |
| 57 | ||
| 58 | describe("what links", () => { | |
| 59 | test("a rooted forge path in Markdown and a bare address are links, the sentence's stop outside", () => { | |
| 60 | expect( | |
| 61 | hrefs( | |
| 62 | talk( | |
| 63 | "Open [the app](/marin/lighthouse) or [pull 4](/marin/lighthouse/pulls/4).", | |
| 64 | ), | |
| 65 | ), | |
| 66 | ).toEqual(["/marin/lighthouse", "/marin/lighthouse/pulls/4"]); | |
| 67 | const bare = talk("See https://example.com/a?b=1&c=2. Then go."); | |
| 68 | expect(hrefs(bare)).toEqual(["https://example.com/a?b=1&c=2"]); | |
| 69 | expect(bare).toContain("</a>. Then go."); | |
| 70 | }); | |
| 71 | ||
| 72 | test("forge paths written as words link to what they name, when readable", () => { | |
| 73 | const html = talk( | |
| 74 | "Look at marin/lighthouse, marin/lighthouse#12, marin/lighthouse/pulls/4 and marin/lighthouse/src/beacon.ts.", | |
| 75 | ); | |
| 76 | expect(hrefs(html)).toEqual([ | |
| 77 | "/marin/lighthouse", | |
| 78 | "/marin/lighthouse/issues/12", | |
| 79 | "/marin/lighthouse/pulls/4", | |
| 80 | "/marin/lighthouse/blob/main/src/beacon.ts", | |
| 81 | ]); | |
| 82 | // Unknown or unreadable: words. A number that is not there, or the wrong kind: words. | |
| 83 | expect( | |
| 84 | hrefs( | |
| 85 | talk( | |
| 86 | "and ghost/private, marin/lighthouse#99, marin/lighthouse/issues/4", | |
| 87 | ), | |
| 88 | ), | |
| 89 | ).toEqual([]); | |
| 90 | }); | |
| 91 | ||
| 92 | test("an app's address goes to it while it runs, to its page while it does not", () => { | |
| 93 | const apps = | |
| 94 | (running: boolean): TalkLook["app"] => | |
| 95 | (u) => | |
| 96 | u.startsWith("https://beacon.forge.example") | |
| 97 | ? { href: "/marin/lighthouse", running } | |
| 98 | : undefined; | |
| 99 | expect( | |
| 100 | hrefs(talk("Live at https://beacon.forge.example/", fake(apps(true)))), | |
| 101 | ).toEqual(["https://beacon.forge.example/"]); | |
| 102 | const asleep = talk( | |
| 103 | "Live at https://beacon.forge.example/", | |
| 104 | fake(apps(false)), | |
| 105 | ); | |
| 106 | expect(hrefs(asleep)).toEqual(["/marin/lighthouse"]); | |
| 107 | expect(asleep).toContain("(not running yet)"); | |
| 108 | expect( | |
| 109 | hrefs( | |
| 110 | talk("[the app](https://beacon.forge.example/)", fake(apps(false))), | |
| 111 | ), | |
| 112 | ).toEqual(["/marin/lighthouse"]); | |
| 113 | }); | |
| 114 | }); | |
| 115 | ||
| 116 | describe("what stays words", () => { | |
| 117 | test("hostile and dead forms never become a link", () => { | |
| 118 | for (const md of [ | |
| 119 | "[x](//evil.example/a)", | |
| 120 | "[x](/\\evil.example/a)", | |
| 121 | "[x](javascript:alert(1))", | |
| 122 | "[x](/a%0Ab)", | |
| 123 | "[x](src/a.ts)", | |
| 124 | "[x](https://[email protected]/)", | |
| 125 | "https://[email protected]/", | |
| 126 | "javascript:alert(1)", | |
| 127 | "data:text/html,hi", | |
| 128 | ]) | |
| 129 | expect(hrefs(talk(md))).toEqual([]); | |
| 130 | expect(safeHref("/marin/lighthouse")).toBe(true); | |
| 131 | expect(safeHref("/\\evil")).toBe(false); | |
| 132 | expect(safeHref("https://a.example/x")).toBe(true); | |
| 133 | }); | |
| 134 | ||
| 135 | test("words inside code stay as they are", () => { | |
| 136 | expect( | |
| 137 | hrefs(talk("`marin/lighthouse` and\n\n```\nhttps://example.com\n```")), | |
| 138 | ).toEqual([]); | |
| 139 | }); | |
| 140 | }); | |
| 141 | ||
| 142 | describe("README rendering", () => { | |
| 143 | test("keeps its own rules: no bare-address or forge-path links, and a slash-backslash path is words", () => { | |
| 144 | expect( | |
| 145 | renderMarkdown("See https://example.com and marin/lighthouse.").text, | |
| 146 | ).toBe("<p>See https://example.com and marin/lighthouse.</p>"); | |
| 147 | expect( | |
| 148 | renderMarkdown("[x](/docs/a.md) and [y](https://example.com)").text, | |
| 149 | ).toBe( | |
| 150 | '<p><a href="/docs/a.md" rel="nofollow noopener">x</a> and <a href="https://example.com" rel="nofollow noopener">y</a></p>', | |
| 151 | ); | |
| 152 | // A browser reads "/\host" as "//host": no README or reply may link one. | |
| 153 | expect(renderMarkdown("[x](/\\evil.example)").text).not.toContain("<a "); | |
| 154 | }); | |
| 155 | }); | |
| 156 | ||
| 157 | beforeAll(async () => { | |
| 158 | dir = await mkdtemp(join(tmpdir(), "forge-links-click-")); | |
| 159 | app = createApp({ dataDir: dir, port: 0 }); | |
| 160 | servers = await serve(app); | |
| 161 | const mk = async (username: string, first: boolean) => { | |
| 162 | const u = await createUser(app.db, { | |
| 163 | origin: "seed", | |
| 164 | trusted: true, | |
| 165 | username, | |
| 166 | email: `${username}@forge.local`, | |
| 167 | password: "a-good-passphrase", | |
| 168 | adminIfFirst: first, | |
| 169 | }); | |
| 170 | if (!u.ok) throw new Error(u.error); | |
| 171 | promote(app.db, u.value); | |
| 172 | return u.value; | |
| 173 | }; | |
| 174 | alice = await mk("alice", true); | |
| 175 | bob = await mk("bob", false); | |
| 176 | const m = await mk("marin", false); | |
| 177 | const made = await createRepo(app, m, { name: "lighthouse", visibility: "public" }); | |
| 178 | if (!made.ok) throw new Error(String(made.error)); | |
| 179 | marin = made.value; | |
| 180 | const open = await createRepo(app, alice, { | |
| 181 | name: "lighthouse", | |
| 182 | visibility: "public", | |
| 183 | }); | |
| 184 | const hidden = await createRepo(app, alice, { | |
| 185 | name: "secret", | |
| 186 | visibility: "private", | |
| 187 | }); | |
| 188 | if (!open.ok || !hidden.ok) throw new Error("repo"); | |
| 189 | const i = createIssue(app.db, { | |
| 190 | repoId: open.value.id, | |
| 191 | authorId: alice.id, | |
| 192 | title: "One", | |
| 193 | body: "x", | |
| 194 | }); | |
| 195 | if (!i.ok) throw new Error(i.error); | |
| 196 | }, 30_000); | |
| 197 | ||
| 198 | afterAll(async () => { | |
| 199 | servers.stop(); | |
| 200 | app.close(); | |
| 201 | await rm(dir, { recursive: true, force: true }); | |
| 202 | }); | |
| 203 | ||
| 204 | describe("on the page", () => { | |
| 205 | test("a reply links what bob may read, and never names what he may not", async () => { | |
| 206 | const c = createConversation(app.db, bob.id); | |
| 207 | if (!c.ok) throw new Error(c.error); | |
| 208 | appendTurn(app.db, bob.id, c.value.id, { role: "person", text: "where?" }); | |
| 209 | appendTurn(app.db, bob.id, c.value.id, { | |
| 210 | role: "agent", | |
| 211 | text: "It is in alice/lighthouse#1, not in alice/secret.", | |
| 212 | }); | |
| 213 | const page = await ( | |
| 214 | await fetch(`${servers.url}/talk/${c.value.id}`, { | |
| 215 | headers: { | |
| 216 | cookie: `forge_session=${createSession(app.db, bob.id).token}`, | |
| 217 | }, | |
| 218 | }) | |
| 219 | ).text(); | |
| 220 | expect(page).toContain( | |
| 221 | '<a href="/alice/lighthouse/issues/1">alice/lighthouse#1</a>', | |
| 222 | ); | |
| 223 | expect(page).not.toContain('href="/alice/secret'); | |
| 224 | expect(page).toContain("alice/secret"); | |
| 225 | }); | |
| 226 | ||
| 227 | test("a page of replies reads each named repository once, however often it is named", async () => { | |
| 228 | const cost = async (times: number) => | |
| 229 | once(app.db, () => { | |
| 230 | const text = Array.from( | |
| 231 | { length: times }, | |
| 232 | () => "alice/lighthouse#1 alice/lighthouse", | |
| 233 | ).join(" "); | |
| 234 | const look = talkLook(app.db, bob, [text]); | |
| 235 | linkTalk(renderMarkdown(text), look); | |
| 236 | }); | |
| 237 | expect(await cost(20)).toBe(await cost(1)); | |
| 238 | }); | |
| 239 | }); | |
| 240 | ||
| 241 | describe("appLook, over a real app on a real runtime", () => { | |
| 242 | const DOMAIN = "apps.test"; | |
| 243 | let forge: App; | |
| 244 | let owner: User; | |
| 245 | let stranger: User; | |
| 246 | let look: (viewer: User) => TalkLook["app"]; | |
| 247 | let runtime: AppsRuntime; | |
| 248 | let beacon: AppRecord; | |
| 249 | ||
| 250 | /** Production of `record` as the runtime reports it while it serves. */ | |
| 251 | const serving = (record: AppRecord): void => { | |
| 252 | (runtime as unknown as { envs: Map<string, unknown> }).envs.set(`${record.id}/production`, { | |
| 253 | app: record, | |
| 254 | env: "production", | |
| 255 | chain: Promise.resolve(), | |
| 256 | restarts: [], | |
| 257 | live: { commitOid: "c0ffee", handle: { port: 4321 }, runId: "r", since: new Date().toISOString(), manifest: { tty: null } }, | |
| 258 | }); | |
| 259 | }; | |
| 260 | ||
| 261 | beforeAll(async () => { | |
| 262 | forge = createApp({ dataDir: join(dir, "apps"), port: 0, host: "forge.test" }); | |
| 263 | const mk = async (username: string, first: boolean) => { | |
| 264 | const u = await createUser(forge.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase", adminIfFirst: first }); | |
| 265 | if (!u.ok) throw new Error(u.error); | |
| 266 | promote(forge.db, u.value); | |
| 267 | return u.value; | |
| 268 | }; | |
| 269 | await mk("olive", true); | |
| 270 | owner = await mk("ada", false); | |
| 271 | stranger = await mk("sam", false); | |
| 272 | const pub = await newApp(forge, owner, { name: "beacon", description: "x", visibility: "public" }); | |
| 273 | const priv = await newApp(forge, owner, { name: "vault", description: "x", visibility: "private" }); | |
| 274 | if (!pub.ok || !priv.ok) throw new Error("apps"); | |
| 275 | runtime = new AppsRuntime(forge, { domain: DOMAIN, scheme: "http", publicPort: 80, forgeUrl: "http://forge.test", concurrency: 1 }); | |
| 276 | beacon = getAppBySlug(forge.db, "beacon")!; | |
| 277 | look = (viewer) => appLook(forge, viewer); | |
| 278 | }, 30_000); | |
| 279 | ||
| 280 | afterAll(() => forge.close()); | |
| 281 | ||
| 282 | test("a readable app not running goes to its page on the forge, said not running", () => { | |
| 283 | // Stopped, whatever ran before. | |
| 284 | (runtime as unknown as { envs: Map<string, unknown> }).envs.delete(`${beacon.id}/production`); | |
| 285 | expect(look(stranger)(`http://beacon.${DOMAIN}/`)).toEqual({ href: "/ada/beacon", running: false }); | |
| 286 | expect(linkTalk(renderMarkdown(`Live at http://beacon.${DOMAIN}/ now.`), { ...fake(), app: look(stranger) }).text).toContain( | |
| 287 | `<a href="/ada/beacon">http://beacon.${DOMAIN}/</a> (not running yet)`, | |
| 288 | ); | |
| 289 | }); | |
| 290 | ||
| 291 | test("a readable app running is a link to itself, off the forge with the README's rel", () => { | |
| 292 | serving(beacon); | |
| 293 | expect(look(stranger)(`http://beacon.${DOMAIN}/menu`)).toEqual({ href: "/ada/beacon", running: true }); | |
| 294 | expect(linkTalk(renderMarkdown(`Live at http://beacon.${DOMAIN}/menu now.`), { ...fake(), app: look(stranger) }).text).toContain( | |
| 295 | `<a href="http://beacon.${DOMAIN}/menu" rel="nofollow noopener">http://beacon.${DOMAIN}/menu</a> now.`, | |
| 296 | ); | |
| 297 | }); | |
| 298 | ||
| 299 | test("a private app is no app to someone who may not read it, and its owner's to open", () => { | |
| 300 | expect(look(stranger)(`http://vault.${DOMAIN}/`)).toBeUndefined(); | |
| 301 | const said = linkTalk(renderMarkdown(`See http://vault.${DOMAIN}/ there.`), { ...fake(), app: look(stranger) }).text; | |
| 302 | expect(said).not.toContain("/ada/vault"); | |
| 303 | expect(said).not.toContain("not running"); | |
| 304 | expect(look(owner)(`http://vault.${DOMAIN}/`)).toEqual({ href: "/ada/vault", running: false }); | |
| 305 | }); | |
| 306 | ||
| 307 | test("a nested host is a hosted forge's own app, never ours; a host off the domain is nothing", () => { | |
| 308 | expect(look(owner)(`http://theirs--beacon.${DOMAIN}/`)).toBeUndefined(); | |
| 309 | expect(look(owner)("http://beacon.elsewhere.test/")).toBeUndefined(); | |
| 310 | expect(look(owner)("not a url")).toBeUndefined(); | |
| 311 | }); | |
| 312 | }); | |
| 313 | ||
| 314 | describe("the live stream", () => { | |
| 315 | test("a streamed turn links what the reply names, as the page does", async () => { | |
| 316 | const c = createConversation(app.db, bob.id); | |
| 317 | if (!c.ok) throw new Error(c.error); | |
| 318 | const asked = appendTurn(app.db, bob.id, c.value.id, { role: "person", text: "where?" }); | |
| 319 | if (!asked.ok) throw new Error(asked.error); | |
| 320 | appendTurn(app.db, bob.id, c.value.id, { role: "agent", text: "It is alice/lighthouse#1, at https://example.com/a." }); | |
| 321 | const text = await ( | |
| 322 | await fetch(`${servers.url}/talk/stream?after=${asked.value.id}`, { headers: { cookie: `forge_session=${createSession(app.db, bob.id).token}` } }) | |
| 323 | ).text(); | |
| 324 | const turns = [...text.matchAll(/^event: turn\ndata: (.*)$/gm)].map((m) => (JSON.parse(m[1]!) as { html: string }).html); | |
| 325 | expect(turns.join("")).toContain('<a href="/alice/lighthouse/issues/1">alice/lighthouse#1</a>'); | |
| 326 | expect(turns.join("")).toContain('<a href="https://example.com/a" rel="nofollow noopener">https://example.com/a</a>.'); | |
| 327 | }); | |
| 328 | }); |
new above
offline
anchoremits no rel. Off-forge hrefs needrel="nofollow noopener", as the README renderer does. Rooted paths don't need it.