Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 2 additions & 4 deletions apps/web/lib/api.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import "server-only";
import { outboundApiUrl } from "./outbound-api-url";
export { outboundApiUrl } from "./outbound-api-url";
import { cookies } from "next/headers";

export interface Session {
Expand Down Expand Up @@ -3919,10 +3921,6 @@ export async function archiveChannelCampaign(
});
}

export function outboundApiUrl(pathname: string): URL {
return new URL(pathname, process.env.OUTBOUND_API_URL ?? "http://127.0.0.1:3001");
}

async function apiFetch(
pathname: string,
options: {
Expand Down
27 changes: 27 additions & 0 deletions apps/web/lib/outbound-api-url.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
export function outboundApiUrl(pathname: string): URL {
if (
!pathname.startsWith("/api/")
|| pathname.startsWith("//")
|| pathname.includes("#")
|| /[\\\u0000-\u001f\u007f]/.test(pathname)
) {
throw new Error("INVALID_OUTBOUND_API_PATH");
}

const base = new URL(process.env.OUTBOUND_API_URL ?? "http://127.0.0.1:3001");
if (
(base.protocol !== "http:" && base.protocol !== "https:")
|| base.username
|| base.password
|| base.search
|| base.hash
) {
throw new Error("INVALID_OUTBOUND_API_URL");
}

const queryOffset = pathname.indexOf("?");
const target = new URL(base.origin);
target.pathname = queryOffset === -1 ? pathname : pathname.slice(0, queryOffset);
target.search = queryOffset === -1 ? "" : pathname.slice(queryOffset + 1);
return target;
}
5 changes: 4 additions & 1 deletion bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@
"lucide-react": "^1.26.0",
"mammoth": "^1.12.1",
"next": "^16.2.11",
"node-html-parser": "^7.0.1",
"node-html-markdown": "^2.0.0",
"pdf-lib": "^1.17.1",
"postgres": "^3.4.9",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import mammoth from "mammoth";
import { unzipSync, type UnzipFileInfo, type Unzipped } from "fflate";
import { XMLParser } from "fast-xml-parser";
import { NodeHtmlMarkdown } from "node-html-markdown";
import { parse } from "node-html-parser";
import { extractText } from "unpdf";
import type {
DocumentExtractionSection,
Expand Down Expand Up @@ -444,10 +445,27 @@ function normalizeZipPath(base: string, target: string): string {
}

function stripUnsafeHtml(value: string): string {
return value
.replace(/<(script|style|iframe|object|embed)[^>]*>[\s\S]*?<\/\1>/gi, "")
.replace(/\son\w+\s*=\s*(["']).*?\1/gi, "")
.replace(/\s(href|src)\s*=\s*(["'])\s*(javascript|data):.*?\2/gi, "");
const root = parse(value, {
comment: false,
blockTextElements: { script: false, style: false, pre: true },
});
for (const element of root.querySelectorAll("script,style,iframe,object,embed,svg,math,template")) {
element.remove();
}
for (const element of root.querySelectorAll("*")) {
for (const [name, rawValue] of Object.entries(element.attributes)) {
const attribute = name.toLowerCase();
if (attribute.startsWith("on") || attribute === "style") {
element.removeAttribute(name);
continue;
}
if (["href", "src", "xlink:href", "formaction"].includes(attribute)) {
const normalized = rawValue.replace(/[\u0000-\u0020\u007f]+/g, "").toLowerCase();
if (/^(javascript|data|vbscript):/.test(normalized)) element.removeAttribute(name);
}
}
}
return root.toString();
}

function baseMetrics(bytes: Uint8Array, markdown: string, sections: readonly DocumentExtractionSection[]) {
Expand All @@ -466,15 +484,29 @@ function assertHasText(value: string): void {
}

function visibleText(value: string): string {
return value.replace(/<!--.*?-->/gs, "").replace(/[#|*_`\s-]+/g, " ").trim();
return stripHtmlComments(value).replace(/[#|*_`\s-]+/g, " ").trim();
}

function stripHtmlComments(value: string): string {
let output = "";
let offset = 0;
while (offset < value.length) {
const start = value.indexOf("<!--", offset);
if (start === -1) return output + value.slice(offset);
output += value.slice(offset, start);
const end = value.indexOf("-->", start + 4);
if (end === -1) return output;
offset = end + 3;
}
return output;
}

function normalize(value: string): string {
return value.replace(/\u0000/g, "").replace(/\r\n/g, "\n").replace(/[ \t]+\n/g, "\n").replace(/\n{3,}/g, "\n\n").trim();
}

function escapeTableCell(value: string): string {
return value.replace(/\|/g, "\\|").replace(/\r?\n/g, "<br>");
return value.replace(/\\/g, "\\\\").replace(/\|/g, "\\|").replace(/\r\n?|\n/g, "<br>");
}

function escapeRegExp(value: string): string {
Expand Down
18 changes: 18 additions & 0 deletions packages/infrastructure/src/inbox/html-to-text.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { parse } from "node-html-parser";

export function htmlToText(value: string | null): string | null {
if (!value) return null;
const root = parse(value, {
comment: false,
blockTextElements: { script: false, style: false, pre: true },
});
for (const element of root.querySelectorAll("script,style,iframe,object,embed,svg,math,template")) {
element.remove();
}
const text = root.structuredText
.replace(/\u00a0/g, " ")
.replace(/[ \t]+/g, " ")
.replace(/\n{3,}/g, "\n\n")
.trim();
return text || null;
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { ProspectingChannel } from "@outbound/domain/campaigns/prospecting-
import { normalizeEmail } from "@outbound/domain/crm/normalization";
import type { Database } from "@outbound/infrastructure/database/client";
import { captureProspectMemoryMutation } from "@outbound/infrastructure/prospect-memory/capture-prospect-memory-mutation";
import { htmlToText } from "@outbound/infrastructure/inbox/html-to-text";
import {
automatedReplies,
connectedAccounts,
Expand Down Expand Up @@ -807,26 +808,6 @@ function recordList(value: unknown): Record<string, unknown>[] {
: [];
}

function htmlToText(value: string | null): string | null {
if (!value) return null;
const text = value
.replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi, " ")
.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi, " ")
.replace(/<br\s*\/?>/gi, "\n")
.replace(/<\/p>/gi, "\n")
.replace(/<[^>]+>/g, " ")
.replace(/&nbsp;/gi, " ")
.replace(/&amp;/gi, "&")
.replace(/&lt;/gi, "<")
.replace(/&gt;/gi, ">")
.replace(/&quot;/gi, '"')
.replace(/&#39;/gi, "'")
.replace(/[ \t]+/g, " ")
.replace(/\n{3,}/g, "\n\n")
.trim();
return text || null;
}

function batches<T>(items: readonly T[], size: number): T[][] {
const result: T[][] = [];
for (let offset = 0; offset < items.length; offset += size) result.push(items.slice(offset, offset + size));
Expand Down
19 changes: 19 additions & 0 deletions tests/unit/html-to-text.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { describe, expect, test } from "bun:test";
import { htmlToText } from "@outbound/infrastructure/inbox/html-to-text";

describe("inbox HTML to text", () => {
test("keeps readable structure while discarding executable elements", () => {
expect(htmlToText("<p>Bonjour<br>Salim</p><script>alert('x')</script><p>Suite</p>"))
.toBe("Bonjour\nSalim\nSuite");
});

test("decodes entities once without turning encoded markup into HTML", () => {
expect(htmlToText("&amp;lt;script&amp;gt;preuve&amp;lt;/script&amp;gt;"))
.toBe("&lt;script&gt;preuve&lt;/script&gt;");
});

test("fails closed on malformed executable markup", () => {
expect(htmlToText("<script>danger</script ><p>visible</p>"))
.toBeNull();
});
});
42 changes: 42 additions & 0 deletions tests/unit/outbound-api-url.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { afterEach, describe, expect, test } from "bun:test";
import { outboundApiUrl } from "../../apps/web/lib/outbound-api-url";

const originalUrl = process.env.OUTBOUND_API_URL;

afterEach(() => {
if (originalUrl === undefined) delete process.env.OUTBOUND_API_URL;
else process.env.OUTBOUND_API_URL = originalUrl;
});

describe("outbound API URL", () => {
test("keeps API paths and queries on the configured internal origin", () => {
process.env.OUTBOUND_API_URL = "https://api.internal.example:3443";
expect(outboundApiUrl("/api/v1/conversations?cursor=next").href)
.toBe("https://api.internal.example:3443/api/v1/conversations?cursor=next");
});

test("rejects paths that could override or escape the internal origin", () => {
for (const pathname of [
"https://attacker.example/api/v1/data",
"//attacker.example/api/v1/data",
"/api\\\\attacker.example/data",
"/health",
"/api/v1/data#fragment",
"/api/v1/data\nX-Test: injected",
]) {
expect(() => outboundApiUrl(pathname)).toThrow("INVALID_OUTBOUND_API_PATH");
}
});

test("rejects unsafe backend base URLs", () => {
for (const base of [
"file:///tmp/socket",
"https://user:secret@api.internal.example",
"https://api.internal.example?redirect=1",
"https://api.internal.example#fragment",
]) {
process.env.OUTBOUND_API_URL = base;
expect(() => outboundApiUrl("/api/v1/data")).toThrow("INVALID_OUTBOUND_API_URL");
}
});
});
13 changes: 13 additions & 0 deletions tests/unit/structured-document-text-extractor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,19 @@ describe("structured document text extractor", () => {
expect(result.sections[0]?.locator).toBe("section:1");
});

test("removes active HTML attributes and unsafe links before Markdown conversion", async () => {
const result = await extractor.extract({
filename: "hostile.html",
contentType: "text/html",
bytes: new TextEncoder().encode('<h1 onmouseover="steal()">Titre</h1><a href="java\nscript:steal()">Lien</a><img src="data:text/html,evil"><p>Preuve sûre</p>'),
});
expect(result.markdown).toContain("Titre");
expect(result.markdown).toContain("Preuve sûre");
expect(result.markdown).not.toContain("javascript:");
expect(result.markdown).not.toContain("data:text");
expect(result.markdown).not.toContain("steal()");
});

test("preserves physical PDF pages and marks image-only PDFs for OCR", async () => {
const textPdf = await createTextPdf();
const text = await extractor.extract({ filename: "offre.pdf", contentType: "application/pdf", bytes: textPdf });
Expand Down
Loading