The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Security: pages and skill files from other sites can't freeze the server
Adarshed7b5f80298f
diff --git a/src/lib/assist.ts b/src/lib/assist.tsindex d395a4bd..5af2327f 100644--- a/src/lib/assist.ts+++ b/src/lib/assist.ts@@ -333,7 +333,9 @@ export function parseFrontmatter(src: string): Record<string, Yamlish> {}return t.slice(1, -1).replace(/\\(["\\])/g, "$1").replace(/\\n/g, "\n");}- return t.replace(/\s+#.*$/, "");+ // A " # comment" goes. (Not /\s+#.*$/: from every space of a long run it reads to the run's end, which grows with+ // the square of the run, and a skill's file comes from anywhere.)+ return t.replace(/\s#.*$/, "").trimEnd();};for (let i = 0; i < lines.length; i++) {const line = lines[i];diff --git a/src/lib/html-scan.ts b/src/lib/html-scan.tsnew file mode 100644index 00000000..2c24dc03--- /dev/null+++ b/src/lib/html-scan.ts@@ -0,0 +1,126 @@+/**+ * Pieces of a web page found in time that grows with the page, never with its square: these readers run on pages and+ * files from other sites, on the server's one thread. A pattern like `<a[^>]*>` or `<b>[\s\S]*?</b>` tries again from+ * every opening and reads on to the end each time an opening never closes, so a page of a few MB made of openings+ * would hold the server for an hour. Here a tag stops at the next "<", and each closing tag is looked for once.+ */++export interface Element {+ name: string;+ /** The opening tag, as written (`<script type="…">`). */+ open: string;+ /** What is between the opening and the closing tag. */+ inner: string;+ start: number;+ end: number;+}++const escape = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");++/**+ * Each `<name …>…</name>` of these names, in order (names are matched in any case). An element ends at the first+ * closing tag of its name after it, as `<name\b[^>]*>[\s\S]*?</name>` would; an opening that never closes is skipped.+ */+export function elements(html: string, names: string | readonly string[], limit = Infinity): Element[] {+ const list = (typeof names === "string" ? [names] : [...names]).map((n) => n.toLowerCase());+ const out: Element[] = [];+ if (!list.length || limit <= 0) return out;+ const open = new RegExp(`<(${list.map(escape).join("|")})\\b[^<>]*>`, "gi");+ // Per name: where its next closing tag is (searched forward only, so each name's search reads the page once).+ const closes = new Map<string, { re: RegExp; at: number; end: number }>();+ for (let m = open.exec(html); m && out.length < limit; m = open.exec(html)) {+ const name = m[1].toLowerCase();+ const from = m.index + m[0].length;+ const close = nextClose(closes, html, name, from);+ if (!close) continue;+ out.push({ name, open: m[0], inner: html.slice(from, close.at), start: m.index, end: close.end });+ open.lastIndex = close.end;+ }+ return out;+}++function nextClose(closes: Map<string, { re: RegExp; at: number; end: number }>, html: string, name: string, from: number): { at: number; end: number } | null {+ let c = closes.get(name);+ if (!c) {+ c = { re: new RegExp(`</${escape(name)}\\s*>`, "gi"), at: -1, end: -1 };+ closes.set(name, c);+ }+ if (c.at === Infinity) return null;+ if (c.at < from) {+ c.re.lastIndex = from;+ const m = c.re.exec(html);+ if (!m) {+ c.at = Infinity;+ return null;+ }+ c.at = m.index;+ c.end = m.index + m[0].length;+ }+ return { at: c.at, end: c.end };+}++/** The page without these elements (each replaced by `by`). */+export function stripElements(html: string, names: readonly string[], by = " "): string {+ const found = elements(html, names);+ if (!found.length) return html;+ let out = "";+ let at = 0;+ for (const e of found) {+ out += html.slice(at, e.start) + by;+ at = e.end;+ }+ return out + html.slice(at);+}++/** The page without its comments (`<!-- … -->`); a comment that never ends is left as it is. */+export function stripComments(html: string, by = " "): string {+ let out = "";+ let at = 0;+ for (;;) {+ const start = html.indexOf("<!--", at);+ if (start < 0) break;+ const end = html.indexOf("-->", start + 4);+ if (end < 0) break;+ out += html.slice(at, start) + by;+ at = end + 3;+ }+ return at === 0 ? html : out + html.slice(at);+}++/** The text of the first `<name>…</name>`, or null. */+export const firstInner = (html: string, name: string): string | null => elements(html, name, 1)[0]?.inner ?? null;++/** What is inside `<body>`: from the first opening to the last closing tag (the whole page when there is none). */+export function bodyOf(html: string): string {+ const open = /<body\b[^<>]*>/i.exec(html);+ if (!open) return html;+ const from = open.index + open[0].length;+ const close = /<\/body\s*>/gi;+ close.lastIndex = from;+ let last = -1;+ for (let m = close.exec(html); m; m = close.exec(html)) last = m.index;+ return last < 0 ? html : html.slice(from, last);+}++/** Every `<name …>` tag's attributes, names lower-cased, values as written (quotes removed). */+export function tagAttrs(html: string, name: string): Record<string, string>[] {+ return [...html.matchAll(new RegExp(`<${escape(name)}\\b[^<>]*>`, "gi"))].map((m) => attrsOf(m[0]));+}++function attrsOf(tag: string): Record<string, string> {+ const out: Record<string, string> = {};+ const body = tag.replace(/^<[\w:-]+/, "").replace(/\/?>$/, "");+ for (const m of body.matchAll(/([^\s=/>"']+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?/g)) out[m[1].toLowerCase()] ??= m[2] ?? m[3] ?? m[4] ?? "";+ return out;+}++/** The content of the first `<meta>` whose name or property is one of these keys (in the keys' order), or "". */+export function metaContent(html: string, keys: readonly string[]): string {+ const all = tagAttrs(html, "meta");+ for (const k of keys) {+ const key = k.toLowerCase();+ const hit = all.find((a) => (a.name ?? a.property ?? a.itemprop ?? "").toLowerCase() === key && a.content);+ if (hit) return hit.content;+ }+ return "";+}diff --git a/src/server/assist/projects.ts b/src/server/assist/projects.tsindex 53435ba9..d25dcf8f 100644--- a/src/server/assist/projects.ts+++ b/src/server/assist/projects.ts@@ -1,6 +1,7 @@import "server-only";import { nanoid } from "nanoid";import { MAX_PROJECT_SOURCES, PROJECT_COLORS, PROJECT_LIMITS, type AssistProject, type ProjectColor, type ProjectSource, type SourceKind } from "@/lib/assist";+import { bodyOf, firstInner, metaContent, stripComments, stripElements } from "@/lib/html-scan";import { db } from "../db";import { getElement } from "../elements";import { PdfError, pdfText } from "./pdf";@@ -177,16 +178,14 @@ const decode = (s: string) =>/** Readable text from a web page: the title, the description, then the body without scripts, styles or navigation chrome. */export function htmlToText(html: string): { title: string; text: string } {- const title = decode(/<title[^>]*>([\s\S]*?)<\/title>/i.exec(html)?.[1] ?? "").replace(/\s+/g, " ").trim();- const desc = decode(/<meta[^>]+(?:name|property)=["'](?:og:)?description["'][^>]*content=["']([^"']*)["']/i.exec(html)?.[1] ?? "").trim();- let body = /<body[^>]*>([\s\S]*)<\/body>/i.exec(html)?.[1] ?? html;- body = body- .replace(/<!--[\s\S]*?-->/g, " ")- .replace(/<(script|style|noscript|svg|template|iframe|nav|footer|form)\b[\s\S]*?<\/\1>/gi, " ")+ // Linear scans only (src/lib/html-scan.ts): the page is someone else's, and the server reads it on its one thread.+ const title = decode(firstInner(html, "title") ?? "").replace(/\s+/g, " ").trim();+ const desc = decode(metaContent(html, ["description", "og:description"])).trim();+ const body = stripElements(stripComments(bodyOf(html)), ["script", "style", "noscript", "svg", "template", "iframe", "nav", "footer", "form"]).replace(/<(br|hr)\s*\/?>/gi, "\n").replace(/<\/(p|div|section|article|li|h[1-6]|tr|blockquote|pre|ul|ol|table|header|main)>/gi, "\n")- .replace(/<li[^>]*>/gi, "- ")- .replace(/<[^>]+>/g, " ");+ .replace(/<li\b[^<>]*>/gi, "- ")+ .replace(/<[^<>]+>/g, " ");const text = decode(body).split("\n").map((l) => l.replace(/[ \t ]+/g, " ").trim())diff --git a/src/server/brand.ts b/src/server/brand.tsindex a967e0b3..e5c6f6cb 100644--- a/src/server/brand.ts+++ b/src/server/brand.ts@@ -20,6 +20,7 @@ import { llmText } from "./enhance";import { fetchRemote } from "./remote-fetch";import { saveFile } from "./storage";import { normalizeWebsite } from "@/lib/website";+import { elements, firstInner, stripComments, stripElements } from "@/lib/html-scan";/*** Brand kits and products, shared by Marketing Studio, Ads Studio and Click to Ad.@@ -56,23 +57,24 @@ export function attrs(tag: string): Record<string, string> {return out;}+// Every pattern here reads in time that grows with the page, never with its square (src/lib/html-scan.ts): a tag stops+// at the next "<", and elements and comments are found by scans that read the page once.function tags(html: string, name: string): Record<string, string>[] {- return [...html.matchAll(new RegExp(`<${name}\\b[^>]*>`, "gi"))].map((m) => attrs(m[0]));+ return [...html.matchAll(new RegExp(`<${name}\\b[^<>]*>`, "gi"))].map((m) => attrs(m[0]));}const strip = (html: string) =>decodeEntities(- html- .replace(/<(script|style|noscript|svg|template|iframe)\b[\s\S]*?<\/\1>/gi, " ")- .replace(/<!--[\s\S]*?-->/g, " ")+ stripComments(stripElements(html, ["script", "style", "noscript", "svg", "template", "iframe"])).replace(/<br\s*\/?>/gi, "\n").replace(/<\/(p|div|li|h[1-6]|section|article|tr)>/gi, "\n")- .replace(/<[^>]+>/g, " "),+ .replace(/<[^<>]+>/g, " "),).replace(/[ \t\f\v\r]+/g, " ")- .replace(/\s*\n\s*/g, "\n")- .replace(/\n{2,}/g, "\n")- .trim();+ .split("\n")+ .map((line) => line.trim())+ .filter(Boolean)+ .join("\n");const clean = (s: string | undefined | null, max = 400) => (s ? decodeEntities(s).replace(/\s+/g, " ").trim().slice(0, max) : "");@@ -118,9 +120,10 @@ export function jsonLd(html: string): Json[] {if (o.item && typeof o.item === "object") walk(o.item);}};- for (const m of html.matchAll(/<script\b[^>]*type\s*=\s*["']?application\/ld\+json["']?[^>]*>([\s\S]*?)<\/script>/gi)) {+ for (const e of elements(html, "script")) {+ if (!/\btype\s*=\s*["']?application\/ld\+json/i.test(e.open)) continue;try {- walk(JSON.parse(m[1].trim()));+ walk(JSON.parse(e.inner.trim()));} catch {// Malformed blocks are common; skip them.}@@ -479,7 +482,7 @@ export function parseSite(html: string, url: string): SiteFacts {sameAs: urlsOf(orgRaw.sameAs),}: null;- const title = clean(/<title\b[^>]*>([\s\S]*?)<\/title>/i.exec(html)?.[1], 200);+ const title = clean(firstInner(html, "title"), 200);const ogSite = meta(html, "og:site_name", "application-name", "apple-mobile-web-app-title");const titleParts = title.split(/\s+[|–—·:-]\s+/).map((s) => s.trim()).filter(Boolean);const name = organization?.name || ogSite || clean(str(site?.name), 80) || shortestBrandPart(titleParts, host) || hostName(host);@@ -499,11 +502,18 @@ export function parseSite(html: string, url: string): SiteFacts {const logos = [...new Set([organization?.logo, ...logoImgs, ...icons.filter((i) => i.size >= 96).map((i) => i.href), ...icons.map((i) => i.href)].filter((x): x is string => !!x))];// An inline <svg> logo: the first svg after an element whose class or id names a logo.let svgLogo: string | null = null;- const at = html.search(/(class|id|aria-label)\s*=\s*["'][^"']*logo[^"']*["']/i);+ let at = -1;+ for (const m of html.matchAll(/(?:class|id|aria-label)\s*=\s*(?:"([^"]*)"|'([^']*)')/gi)) {+ if (/logo/i.test(m[1] ?? m[2] ?? "")) {+ at = m.index;+ break;+ }+ }if (at >= 0) {const tail = html.slice(at, at + 40_000);- const m = /<svg\b[\s\S]*?<\/svg>/i.exec(tail);- if (m && m.index < 2000 && m[0].length < 30_000) svgLogo = m[0].includes("xmlns") ? m[0] : m[0].replace(/<svg\b/i, '<svg xmlns="http://www.w3.org/2000/svg"');+ const e = elements(tail, "svg", 1)[0];+ const svg = e && tail.slice(e.start, e.end);+ if (e && e.start < 2000 && svg.length < 30_000) svgLogo = svg.includes("xmlns") ? svg : svg.replace(/<svg\b/i, '<svg xmlns="http://www.w3.org/2000/svg"');}const images = [@@ -535,18 +545,18 @@ export function parseSite(html: string, url: string): SiteFacts {title,description,themeColor: meta(html, "theme-color", "msapplication-TileColor") || null,- lang: (/<html\b[^>]*\blang\s*=\s*["']?([a-zA-Z-]+)/i.exec(html)?.[1] ?? null)?.toLowerCase() ?? null,+ lang: (/<html\b[^<>]*\blang\s*=\s*["']?([a-zA-Z-]+)/i.exec(html)?.[1] ?? null)?.toLowerCase() ?? null,logos,svgLogo,images: [...new Set(images)].slice(0, 16),- headings: [...html.matchAll(/<h([1-3])\b[^>]*>([\s\S]*?)<\/h\1>/gi)].map((m) => clean(strip(m[2]), 140)).filter(Boolean).slice(0, 20),+ headings: elements(html, ["h1", "h2", "h3"], 200).map((e) => clean(strip(e.inner), 140)).filter(Boolean).slice(0, 20),text: text.slice(0, 20_000),socials,stylesheets: links.filter((l) => /stylesheet/i.test(l.rel ?? "") && l.href).map((l) => resolve(l.href, url)).filter((x): x is string => !!x && !/fonts\.googleapis\.com/.test(x)),- inlineCss: [...html.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)].map((m) => m[1]),+ inlineCss: elements(html, "style").map((e) => e.inner),products: jsonLdProducts(ld, url),shopify: isShopify(html),organization,@@ -575,7 +585,7 @@ function shortestBrandPart(parts: string[], host: string): string {export function productsFromPage(html: string, url: string): ProductDraft[] {const facts = parseSite(html, url);if (facts.products.length) return facts.products.map((p) => ({ ...p, url: p.url ?? url, images: p.images.length ? p.images : facts.images.slice(0, 5) }));- const h1 = /<h1\b[^>]*>([\s\S]*?)<\/h1>/i.exec(html)?.[1];+ const h1 = firstInner(html, "h1");const name = meta(html, "og:title", "twitter:title") || (h1 ? clean(strip(h1), 140) : "") || facts.title;if (!name) return [];return [diff --git a/src/server/faceless.ts b/src/server/faceless.tsindex afcb9c66..e605e25c 100644--- a/src/server/faceless.ts+++ b/src/server/faceless.ts@@ -100,6 +100,7 @@ import { provider } from "./providers";import type { JsonSpec } from "./llm";import { llmBackends, probeLocal } from "./providers/llm";import { fetchRemote } from "./remote-fetch";+import { firstInner, metaContent, stripElements } from "@/lib/html-scan";import { engineMode, getSetting } from "./settings";import { fileUrl, saveFile } from "./storage";import { firstOn, offeredModel } from "./model-access";@@ -1746,13 +1747,14 @@ const ENTITIES: Record<string, string> = { amp: "&", lt: "<", gt: ">", quot: '"'/** Readable text of an HTML page: title plus paragraphs, scripts and styles dropped. */export function pageText(html: string): { title: string | null; text: string } {- const title = /<title[^>]*>([\s\S]*?)<\/title>/i.exec(html)?.[1] ?? /<meta[^>]+property=["']og:title["'][^>]+content=["']([^"']+)/i.exec(html)?.[1] ?? null;- const body = html- .replace(/<(head|script|style|noscript|svg|nav|footer|header|form)[\s\S]*?<\/\1>/gi, " ")+ // Linear scans only (src/lib/html-scan.ts): the page is someone else's, and the server reads it on its one thread.+ const title = firstInner(html, "title") ?? (metaContent(html, ["og:title"]) || null);+ const point = (n: number, m: string) => (Number.isInteger(n) && n > 0 && n < 0x110000 ? String.fromCodePoint(n) : m);+ const body = stripElements(html, ["head", "script", "style", "noscript", "svg", "nav", "footer", "header", "form"]).replace(/<br\s*\/?>|<\/(p|div|li|h[1-6]|section|article|tr)>/gi, "\n")- .replace(/<[^>]+>/g, " ")+ .replace(/<[^<>]+>/g, " ").replace(/&(#\d+|#x[\da-f]+|\w+);/gi, (m, e: string) =>- e.startsWith("#x") ? String.fromCodePoint(parseInt(e.slice(2), 16)) : e.startsWith("#") ? String.fromCodePoint(Number(e.slice(1))) : (ENTITIES[e.toLowerCase()] ?? m),+ e.startsWith("#x") || e.startsWith("#X") ? point(parseInt(e.slice(2), 16), m) : e.startsWith("#") ? point(Number(e.slice(1)), m) : (ENTITIES[e.toLowerCase()] ?? m),).split("\n").map((l) => l.replace(/\s+/g, " ").trim())diff --git a/tests/text-readers-linear.test.ts b/tests/text-readers-linear.test.tsnew file mode 100644index 00000000..dc114781--- /dev/null+++ b/tests/text-readers-linear.test.ts@@ -0,0 +1,136 @@+import { describe, expect, it, vi } from "vitest";+import { tempDir } from "./helpers/temp-dir";++vi.mock("server-only", () => ({}));+process.env.FUOBE_DATA_DIR = tempDir("fuobe-linear-");++/**+ * The readers that turn a page, a skill file or pasted text from somewhere else into text run on the server's one+ * thread: a pattern whose time grows with the square of its input would stop every request while it runs. Each reader+ * gets inputs built to make such a pattern backtrack (many openings with no closing, long runs of spaces) and must+ * finish them quickly. A linear reader does each in milliseconds; a quadratic one takes seconds.+ */++const N = Number(process.env.LINEAR_TEST_N) || 120_000;+const BUDGET_MS = Number(process.env.LINEAR_TEST_BUDGET_MS) || 600;++const fill = (token: string) => token.repeat(Math.ceil(N / token.length));++const HTML_TOKENS = [+ "<",+ "<a ",+ "<<",+ "</",+ "<!--",+ "<!-- ",+ "<script",+ "<script>",+ "<style>",+ "<svg ",+ "<nav>",+ "<head>",+ "<header ",+ "<form ",+ "<title",+ "<title>",+ "<meta ",+ "<meta name='description' ",+ "<meta property=\"og:description\" content=\"",+ "<meta property='og:title' ",+ "<body",+ "<body>",+ "<li",+ "<br",+ "<br ",+ "<h1>",+ "<h2 ",+ "<link ",+ "<img ",+ "<a href='",+ "<script type=\"application/ld+json\">",+ "&",+ "&#",+ "&#x",+ "&",+ " ",+ "\u00a0",+ " ",+ "\t",+ " \n",+ "\n",+ "=\"",+ "'",+ "a",+ " ",+ " \n",+];++/** One long opening tag (a single "<"), whose attributes would each start a scan to the end. */+const LONG_TAGS = [+ `<meta ${fill("name='description' ")}`,+ `<meta ${fill("property='og:title' ")}>`,+ `<div class="${fill("logo")}`,+ `<html ${fill("lang=x ")}`,+ `<script ${fill("type=application/ld+json ")}`,+ `<title>${fill(" ")}x</title>`,+];++const slow: string[] = [];+function within(label: string, run: () => unknown) {+ const t = performance.now();+ run();+ const ms = performance.now() - t;+ if (ms >= BUDGET_MS) slow.push(`${label}: ${Math.round(ms)} ms`);+}+const noneSlow = () => expect(slow.splice(0)).toEqual([]);++describe("readers of outside text take time in step with their input", () => {+ it("a web page added as an Assist project source", async () => {+ const { htmlToText } = await import("@/server/assist/projects");+ for (const t of HTML_TOKENS) {+ within(`htmlToText ${JSON.stringify(t)}`, () => htmlToText(fill(t)));+ within(`htmlToText x+${JSON.stringify(t)}`, () => htmlToText(`<html><body><p>x</p>${fill(t)}`));+ }+ for (const [i, t] of LONG_TAGS.entries()) within(`htmlToText long tag ${i}`, () => htmlToText(t));+ noneSlow();+ });++ it("a page an Explainer reads from a link", async () => {+ const { pageText } = await import("@/server/faceless");+ for (const t of HTML_TOKENS) {+ within(`pageText ${JSON.stringify(t)}`, () => pageText(fill(t)));+ within(`pageText x+${JSON.stringify(t)}`, () => pageText(`<html><body><p>x</p>${fill(t)}`));+ }+ for (const [i, t] of LONG_TAGS.entries()) within(`pageText long tag ${i}`, () => pageText(t));+ noneSlow();+ });++ it("a brand's website and a product link", async () => {+ const { parseSite, productsFromPage } = await import("@/server/brand");+ for (const t of HTML_TOKENS) {+ within(`parseSite ${JSON.stringify(t)}`, () => parseSite(fill(t), "https://brand.example/"));+ within(`productsFromPage ${JSON.stringify(t)}`, () => productsFromPage(fill(t), "https://brand.example/p"));+ }+ for (const [i, t] of LONG_TAGS.entries()) within(`parseSite long tag ${i}`, () => productsFromPage(t, "https://brand.example/"));+ noneSlow();+ });++ it("a skill's SKILL.md and pasted memories", async () => {+ const { parseSkillMd, parseMemoryImport } = await import("@/lib/assist");+ const spaces = " ".repeat(N);+ const cases: [string, string][] = [+ ["value with spaces", `---\nname: a\ndescription: a${spaces}b\n---\nbody`],+ ["quoted value", `---\nname: a\ndescription: "${"\\".repeat(N)}\n---\nbody`],+ ["key with spaces", `---\nname${spaces}\n---\nbody`],+ ["comment marks", `---\nname: a\ndescription: ${fill("a #")}\n---\nbody`],+ ["many dashes lines", `---\n${fill("--- x\n")}`],+ ["block", `---\nname: a\ndescription: |\n${fill(" line\n")}---\nbody`],+ ["list", `---\nname: a\ntags:\n${fill(" - t\n")}---\nbody`],+ ["no end", `---\n${fill("a: b\n")}`],+ ["spaces only", spaces],+ ];+ for (const [label, text] of cases) within(`parseSkillMd ${label}`, () => parseSkillMd(text));+ for (const t of [" ", "\n", "- ", "* ", "#", "1. ", "\u00a0", "a", "{", "[", '"']) within(`parseMemoryImport ${JSON.stringify(t)}`, () => parseMemoryImport(fill(t)));+ noneSlow();+ });+});