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
58 changes: 56 additions & 2 deletions apps/server/src/provider/documentTextWorker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -782,6 +782,47 @@ const RTF_CODE_PAGES = new Map([
const rtfCodePage = (value: number) =>
RTF_CODE_PAGES.get(value) ?? (value >= 1250 && value <= 1258 ? `windows-${value}` : undefined);

const MAX_RTF_DEPTH = 128;

function rtfGroupEnd(source: string, start: number, outerDepth: number) {
// Match group boundaries without counting escaped braces or braces in binary data.
const structure = /[{}]|\\(?:(bin)(?![a-z])(-?\d+)? ?|[\\{}])/gi;
structure.lastIndex = start;
let depth = outerDepth + 1;
let token: RegExpExecArray | null;
while (depth <= MAX_RTF_DEPTH && (token = structure.exec(source))) {
if (token[0] === "{") depth++;
else if (token[0] === "}") {
if (--depth === outerDepth) return structure.lastIndex;
} else if (token[1] === "bin") {
const size = Number(token[2]);
if (!Number.isSafeInteger(size) || size < 0) return;
structure.lastIndex += size;
}
}
}

function rtfUnicodeDestination(
source: string,
start: number,
outerDepth: number,
verifiedThrough: number,
) {
const ansiStart = /[\r\n]*\{/y;
ansiStart.lastIndex = start;
if (!ansiStart.test(source)) return;
const ansiEnd = rtfGroupEnd(source, ansiStart.lastIndex, outerDepth);
if (ansiEnd === undefined) return;

const unicodeStart = /[\r\n]*\{[\r\n]*\\\*[\r\n]*\\ud(?![a-zA-Z]|-?\d) ?/y;
unicodeStart.lastIndex = ansiEnd;
if (!unicodeStart.test(source)) return;
const body = unicodeStart.lastIndex;
// An enclosing group already checked for balance also proves its nested groups close.
const end = body < verifiedThrough ? verifiedThrough : rtfGroupEnd(source, body, outerDepth);
if (end !== undefined) return { body, end };
}

function* rtf(source: string): Generator<string, void> {
if (!source.startsWith("{\\rtf")) throw new Error("Invalid RTF document");
let state = {
Expand All @@ -795,6 +836,10 @@ function* rtf(source: string): Generator<string, void> {
decoder: new TextDecoder("windows-1252"),
};
const stack: Array<typeof state> = [];
const openGroup = () => {
stack.push({ ...state });
if (stack.length > MAX_RTF_DEPTH) throw new Truncation("RTF depth limit");
};
// A font's \cpg, else its \fcharset, not the document code page, encodes the bytes written in
// that font. A \cpg inside \fontfile encodes the font's file name instead.
const fonts = new Map<number, typeof state.decoder>();
Expand Down Expand Up @@ -841,15 +886,15 @@ function* rtf(source: string): Generator<string, void> {
["-", ""],
]);
let fallback = 0;
let verifiedThrough = 0;
for (let i = 0; i < source.length; i++) {
const char = source[i]!;
if (char === "{" || char === "}") {
yield* flushBytes();
fallback = 0;
}
if (char === "{") {
stack.push({ ...state });
if (stack.length > 128) throw new Truncation("RTF depth limit");
openGroup();
} else if (char === "}") state = stack.pop() ?? state;
else if (char === "\\") {
const rest = source.slice(i + 1, i + 80);
Expand All @@ -873,6 +918,15 @@ function* rtf(source: string): Generator<string, void> {
continue;
}
yield* flushBytes();
if (control === "upr") {
const unicode = rtfUnicodeDestination(source, i + 1, stack.length, verifiedThrough);
if (unicode) {
openGroup();
verifiedThrough = unicode.end;
i = unicode.body - 1;
}
continue;
}
if (
[
"fonttbl",
Expand Down
10 changes: 10 additions & 0 deletions apps/server/src/provider/userInputAttachments.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,16 @@ describe("question answer paths", () => {
],
["hyphen symbol fallback", String.raw`{\rtf1\ansi\uc3\u945\~\_\-Z}`, "αZ"],
["control word", String.raw`{\rtf1\ansi A\u9\tab X}`, "A\tX"],
[
"Unicode alternate destination",
String.raw`{\rtf1\ansi\uc1 Price: {\upr{\{??\}\bin2 {}}{\*\ud{\u20320?{\upr{?}{\*\ud{\u22909?}}}}}} confirmed.{\*\ud Hidden}{\*\unknown{\upr{Hidden}{\*\ud Also hidden}}}}`,
"Price: 你好 confirmed.",
],
[
"ANSI alternate with a truncated Unicode destination",
String.raw`{\rtf1\ansi Price: {\upr{fallback}{\*\ud{\u20320?}`,
"Price: fallback",
],
["line break paragraphs", "{\\rtf1\\ansi First\\\nSecond\\\r\nThird}", "First\nSecond\nThird"],
[
"tracked deletion",
Expand Down
Loading