Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

markdown: Use RE2JS for linkifier rendering.

Alex Vandiver753082fd057b
diff --git a/web/e2e-tests/realm-linkifier.test.ts b/web/e2e-tests/realm-linkifier.test.ts
index d5fbd00f81b..fcfa7622753 100644
--- a/web/e2e-tests/realm-linkifier.test.ts
+++ b/web/e2e-tests/realm-linkifier.test.ts
@@ -60,10 +60,13 @@ async function test_add_invalid_linkifier_pattern(page: Page): Promise<void> {
});
await page.click(".dialog_submit_button");
- await page.waitForSelector("div#add-linkifier-status", {visible: true});
+ // Invalid patterns are rejected client-side by RE2JS compilation before
+ // the form is submitted; the error appears in the pattern-specific status
+ // element and includes RE2JS's description of the compilation failure.
+ await page.waitForSelector("div#linkifier-pattern-status", {visible: true});
assert.strictEqual(
- await common.get_text_from_selector(page, "div#add-linkifier-status"),
- "Failed: Bad regular expression: missing ): (foo",
+ await common.get_text_from_selector(page, "div#linkifier-pattern-status"),
+ "Failed: Bad regular expression: missing closing )",
);
await page.click(".dialog_exit_button");
@@ -108,24 +111,27 @@ async function test_edit_invalid_linkifier(page: Page): Promise<void> {
});
await page.click(".dialog_submit_button");
- const edit_linkifier_pattern_status_selector = "div#dialog_error";
+ // Invalid patterns are rejected client-side by RE2JS, so the form
+ // does not submit and the URL template is never checked server-side.
+ const edit_linkifier_pattern_status_selector = "div#linkifier-pattern-status";
await page.waitForSelector(edit_linkifier_pattern_status_selector, {visible: true});
- const edit_linkifier_pattern_status = await common.get_text_from_selector(
- page,
- edit_linkifier_pattern_status_selector,
- );
assert.strictEqual(
- edit_linkifier_pattern_status,
- "Failed: Bad regular expression: bad repetition operator: ????",
+ await common.get_text_from_selector(page, edit_linkifier_pattern_status_selector),
+ "Failed: Bad regular expression: invalid nested repetition operator",
);
+ // Fix the pattern; the invalid URL template now surfaces from the server.
+ await common.fill_form(page, "form.linkifier-edit-form", {
+ pattern: "#(?P<id>[0-9]+)",
+ });
+ await page.click(".dialog_submit_button");
+
const edit_linkifier_template_status_selector = "div#linkifier-template-status";
await page.waitForSelector(edit_linkifier_template_status_selector, {visible: true});
- const edit_linkifier_template_status = await common.get_text_from_selector(
- page,
- edit_linkifier_template_status_selector,
+ assert.strictEqual(
+ await common.get_text_from_selector(page, edit_linkifier_template_status_selector),
+ "Failed: Invalid URL template.",
);
- assert.strictEqual(edit_linkifier_template_status, "Failed: Invalid URL template.");
await page.click(".dialog_exit_button");
await common.wait_for_micromodal_to_close(page);
diff --git a/web/src/compose_ui.ts b/web/src/compose_ui.ts
index 83d7a6644a5..2ad61ad83fc 100644
--- a/web/src/compose_ui.ts
+++ b/web/src/compose_ui.ts
@@ -11,7 +11,6 @@ import {
setFieldText,
wrapFieldSelection,
} from "text-field-edit";
-import type Template from "uri-template-lite";
import * as z from "zod/mini";
import type {Typeahead} from "./bootstrap_typeahead.ts";
@@ -728,28 +727,11 @@ function expand_reverse_template(
return output.join("");
}
-function expand_url_template_from_match(
- match: RegExpExecArray,
- url_template: Template,
- group_number_to_name: Record<number, string>,
-): string | null {
- const context: Record<string, string> = {};
- const capturing_groups = match.slice(1).entries();
- for (const [index, capturing_group] of capturing_groups) {
- const name = group_number_to_name[index + 1];
- if (!name) {
- return null;
- }
- context[name] = capturing_group;
- }
- return url_template.expand(context);
-}
-
function reverse_linkify_segment(segment: string): string | null {
const linkifier_map = linkifiers.get_linkifier_map();
for (const [
pattern,
- {url_template, group_number_to_name, reverse_template, alternative_url_templates},
+ {url_template, reverse_template, alternative_url_templates},
] of linkifier_map) {
if (!reverse_template) {
continue;
@@ -763,18 +745,19 @@ function reverse_linkify_segment(segment: string): string | null {
}
const reversed_text = expand_reverse_template(reverse_template, template_context);
- pattern.lastIndex = 0;
- const match = pattern.exec(reversed_text);
- if (!match) {
+ // Use the RE2JS matcher to verify the reversed text matches the pattern.
+ const matcher = pattern.matcher(reversed_text);
+ if (!matcher.find()) {
continue;
}
// Validate that expanding the captured groups round-trips to the original URL.
- const expanded_url = expand_url_template_from_match(
- match,
- template,
- group_number_to_name,
- );
+ const named_groups = pattern.namedGroups();
+ const context: Record<string, string> = {};
+ for (const name of Object.keys(named_groups)) {
+ context[name] = matcher.group(name)!;
+ }
+ const expanded_url = template.expand(context);
if (expanded_url !== segment) {
continue;
}
diff --git a/web/src/echo.ts b/web/src/echo.ts
index 9846baeba56..0ee33cf5b80 100644
--- a/web/src/echo.ts
+++ b/web/src/echo.ts
@@ -273,7 +273,7 @@ export function insert_local_message(
id: local_id_float,
resend: false,
is_me_message: false,
- topic_links: topic ? markdown.get_topic_links(topic) : [],
+ topic_links: markdown.get_topic_links(topic),
reactions: [],
};
diff --git a/web/src/linkifiers.ts b/web/src/linkifiers.ts
index c6f785a77cf..56983608c97 100644
--- a/web/src/linkifiers.ts
+++ b/web/src/linkifiers.ts
@@ -1,18 +1,17 @@
+import {RE2JS} from "re2js";
import Template from "uri-template-lite";
import type * as z from "zod/mini";
import * as blueslip from "./blueslip.ts";
import type {realm_linkifier_schema} from "./state_data.ts";
-type LinkifierMap = Map<
- RegExp,
- {
- url_template: Template;
- group_number_to_name: Record<number, string>;
- reverse_template: string | null;
- alternative_url_templates: Template[];
- }
->;
+export type LinkifierMapValue = {
+ url_template: Template;
+ reverse_template: string | null;
+ alternative_url_templates: Template[];
+};
+
+type LinkifierMap = Map<RE2JS, LinkifierMapValue>;
const linkifier_map: LinkifierMap = new Map();
type Linkifier = z.output<typeof realm_linkifier_schema>;
@@ -21,100 +20,40 @@ export function get_linkifier_map(): LinkifierMap {
return linkifier_map;
}
-export function python_to_js_linkifier(
- pattern: string,
- url: string,
- alternative_urls: string[] = [],
-): [RegExp | null, Template, Record<number, string>, Template[]] {
- // Converts a python named-group regex to a javascript-compatible numbered
- // group regex... with a regex!
- const named_group_re = /\(?P<([^>]+?)>/g;
- let match = named_group_re.exec(pattern);
- let current_group = 1;
- const group_number_to_name: Record<number, string> = {};
- while (match) {
- const name = match[1]!;
- // Replace named group with regular matching group
- pattern = pattern.replace("(?P<" + name + ">", "(");
- // Map numbered reference to named reference for template expansion
- group_number_to_name[current_group] = name;
-
- // Reset the RegExp state
- named_group_re.lastIndex = 0;
- match = named_group_re.exec(pattern);
-
- current_group += 1;
- }
- // Convert any python in-regex flags to RegExp flags
- let js_flags = "g";
- const inline_flag_re = /\(\?([Limsux]+)\)/;
- match = inline_flag_re.exec(pattern);
-
- // JS regexes only support i (case insensitivity) and m (multiline)
- // flags, so keep those and ignore the rest
- if (match) {
- const py_flags = match[1]!;
-
- for (const flag of py_flags) {
- if ("im".includes(flag)) {
- js_flags += flag;
- }
- }
-
- pattern = pattern.replace(inline_flag_re, "");
- }
- // Ideally we should have been checking that linkifiers
- // begin with certain characters but since there is no
- // support for negative lookbehind in javascript, we check
- // for this condition in `contains_backend_only_syntax()`
- // function. If the condition is satisfied then the message
- // is rendered locally, otherwise, we return false there and
- // message is rendered on the backend which has proper support
- // for negative lookbehind.
- pattern = pattern + /(?!\w)/.source;
- let final_regex = null;
- try {
- final_regex = new RegExp(pattern, js_flags);
- } catch (error) {
- // We have an error computing the generated regex syntax.
- // We'll ignore this linkifier for now, but log this
- // failure for debugging later.
- if (error instanceof SyntaxError) {
- blueslip.error("python_to_js_linkifier failure!", {pattern}, error);
- } else {
- // Don't swallow any other (unexpected) exceptions.
- /* istanbul ignore next */
- throw error;
- }
- }
+export function compile_linkifier(pattern: string, url: string): [RE2JS, Template] {
+ // This boundary-matching must be kept in sync with prepare_linkifier_pattern
+ // in zerver/lib/markdown/__init__.py. It does not use look-ahead or
+ // look-behind, because re2 does not support either.
+ // RE2 uses \x{NNNN} for Unicode escapes, not \uNNNN.
+ pattern = "(^|\\s|\\x{0085}|\\pZ|['\"(,:<])(" + pattern + ")($|[^\\pL\\pN])";
+ const compiled_regex = RE2JS.compile(pattern);
const url_template = new Template(url);
- const alternative_url_templates = alternative_urls.map(
- (template_string) => new Template(template_string),
- );
- return [final_regex, url_template, group_number_to_name, alternative_url_templates];
+ return [compiled_regex, url_template];
}
export function update_linkifier_rules(linkifiers: Linkifier[]): void {
linkifier_map.clear();
for (const linkifier of linkifiers) {
- const [regex, url_template, group_number_to_name, alternative_url_templates] =
- python_to_js_linkifier(
+ try {
+ const [regex, url_template] = compile_linkifier(
linkifier.pattern,
linkifier.url_template,
- linkifier.alternative_url_templates ?? [],
);
- if (!regex) {
- // Skip any linkifiers that could not be converted
- continue;
+ const alternative_url_templates = (linkifier.alternative_url_templates ?? []).map(
+ (template_string) => new Template(template_string),
+ );
+ linkifier_map.set(regex, {
+ url_template,
+ reverse_template: linkifier.reverse_template ?? null,
+ alternative_url_templates,
+ });
+ } catch (error) {
+ // We have an error computing the generated regex syntax.
+ // We'll ignore this linkifier for now, but log this
+ // failure for debugging later.
+ blueslip.error("Failed to compile linkifier!", linkifier, error);
}
-
- linkifier_map.set(regex, {
- url_template,
- group_number_to_name,
- reverse_template: linkifier.reverse_template ?? null,
- alternative_url_templates,
- });
}
}
diff --git a/web/src/markdown.ts b/web/src/markdown.ts
index 9e1411c2985..a76382e0a9a 100644
--- a/web/src/markdown.ts
+++ b/web/src/markdown.ts
@@ -2,14 +2,15 @@ import {getUnixTime, isValid} from "date-fns";
import katex from "katex";
import _ from "lodash";
import assert from "minimalistic-assert";
-import type Template from "uri-template-lite";
+import type {Matcher, RE2JS} from "re2js";
import render_channel_message_link from "../templates/channel_message_link.hbs";
import render_topic_link from "../templates/topic_link.hbs";
import marked from "../third/marked/lib/marked.cjs";
-import type {LinkifierMatch, ParseOptions, RegExpOrStub} from "../third/marked/lib/marked.cjs";
+import type {ParseOptions, RegExpOrStub} from "../third/marked/lib/marked.cjs";
import * as fenced_code from "./fenced_code.ts";
+import type {LinkifierMapValue} from "./linkifiers.ts";
import * as util from "./util.ts";
// This contains zulip's frontend Markdown implementation; see
@@ -37,6 +38,21 @@ function contains_preview_link(content: string): boolean {
return preview_regexes.some((re) => re.test(content));
}
+function contains_topic_wildcard_mention(content: string): boolean {
+ // If the content has topic wildcard mention (@**topic**) then don't
+ // render it locally. We have only server-side restriction check for
+ // @topic mention. This helps to show the error message (no permission)
+ // via the compose banner and not to local-echo then fail due to restriction.
+ return content.includes("@**topic**");
+}
+
+export function contains_backend_only_syntax(content: string): boolean {
+ // Try to guess whether or not a message contains syntax that only the
+ // backend Markdown processor can correctly handle.
+ // If it doesn't, we can immediately render it client-side for local echo.
+ return contains_preview_link(content) || contains_topic_wildcard_mention(content);
+}
+
export let web_app_helpers: MarkdownHelpers | undefined;
export type AbstractMap<K, V> = {
@@ -45,10 +61,7 @@ export type AbstractMap<K, V> = {
get: (k: K) => V | undefined;
};
-export type AbstractLinkifierMap = AbstractMap<
- RegExp,
- {url_template: Template; group_number_to_name: Record<number, string>}
->;
+export type AbstractLinkifierMap = AbstractMap<RE2JS, LinkifierMapValue>;
type GetLinkifierMap = () => AbstractLinkifierMap;
@@ -133,46 +146,6 @@ export function translate_emoticons_to_names({
return translated;
}
-function contains_problematic_linkifier(
- content: string,
- get_linkifier_map: GetLinkifierMap,
-): boolean {
- // If a linkifier doesn't start with some specified characters
- // then don't render it locally. It is workaround for the fact that
- // javascript regex doesn't support lookbehind.
- for (const re of get_linkifier_map().keys()) {
- const pattern = /[^\s"'(,:<]/.source + re.source + /(?!\w)/.source;
- const regex = new RegExp(pattern);
- if (regex.test(content)) {
- return true;
- }
- }
-
- return false;
-}
-
-function contains_topic_wildcard_mention(content: string): boolean {
- // If the content has topic wildcard mention (@**topic**) then don't
- // render it locally. We have only server-side restriction check for
- // @topic mention. This helps to show the error message (no permission)
- // via the compose banner and not to local-echo then fail due to restriction.
- return content.includes("@**topic**");
-}
-
-function content_contains_backend_only_syntax(
- content: string,
- get_linkifier_map: GetLinkifierMap,
-): boolean {
- // Try to guess whether or not a message contains syntax that only the
- // backend Markdown processor can correctly handle.
- // If it doesn't, we can immediately render it client-side for local echo.
- return (
- contains_preview_link(content) ||
- contains_problematic_linkifier(content, get_linkifier_map) ||
- contains_topic_wildcard_mention(content)
- );
-}
-
function parse_with_options(
raw_content: string,
helper_config: MarkdownHelpers,
@@ -412,24 +385,45 @@ export function get_topic_links(topic: string): TopicLink[] {
// We export this for testing purposes, and mobile may want to
// use this as well in the future.
const links: Link[] = [];
+ if (!topic) {
+ return links;
+ }
// The lower the precedence is, the more prioritized the pattern is.
let precedence = 0;
assert(web_app_helpers !== undefined);
const get_linkifier_map = web_app_helpers.get_linkifier_map;
- for (const [pattern, {url_template, group_number_to_name}] of get_linkifier_map().entries()) {
- let match;
- while ((match = pattern.exec(topic)) !== null) {
+ for (const [pattern, {url_template}] of get_linkifier_map().entries()) {
+ let pos = 0;
+ while (pos < topic.length) {
+ const matcher = pattern.matcher(topic.slice(pos));
+ if (!matcher.find()) {
+ break;
+ }
+ // After a successful find() on a pattern wrapped by
+ // compile_linkifier, groups 1 (leading boundary), 2 (user
+ // pattern body), and the trailing boundary group are always
+ // matched, as are all named groups inside the user pattern.
+ // Advance position past the leading boundary group.
+ pos += matcher.end(1);
+
const template_context = Object.fromEntries(
- match
- .slice(1)
- .map((matched_group, i) => [group_number_to_name[i + 1]!, matched_group]),
+ Object.keys(pattern.namedGroups()).map((groupname) => [
+ groupname,
+ matcher.group(groupname)!,
+ ]),
);
+
const link_url = url_template.expand(template_context);
// We store the starting index as well, to sort the order of occurrence of the links
// in the topic, similar to the logic implemented in zerver/lib/markdown/__init__.py
- links.push({url: link_url, text: match[0], index: match.index, precedence});
+ const match_text = matcher.group(2)!;
+ links.push({url: link_url, text: match_text, index: pos, precedence});
+
+ // Advance past the user match body, but not the trailing boundary,
+ // so that patterns can overlap their whitespace.
+ pos += match_text.length;
}
precedence += 1;
}
@@ -555,18 +549,21 @@ function handleEmoji({
function handleLinkifier({
pattern,
- matches,
+ matcher,
get_linkifier_map,
}: {
- pattern: RegExp;
- matches: LinkifierMatch[];
+ pattern: RE2JS;
+ matcher: Matcher;
get_linkifier_map: GetLinkifierMap;
}): string {
const item = get_linkifier_map().get(pattern);
assert(item !== undefined);
- const {url_template, group_number_to_name} = item;
+ const {url_template} = item;
const template_context = Object.fromEntries(
- matches.map((match, i) => [group_number_to_name[i + 1]!, match]),
+ Object.keys(pattern.namedGroups()).map((groupname) => [
+ groupname,
+ matcher.group(groupname)!,
+ ]),
);
return url_template.expand(template_context);
}
@@ -698,7 +695,7 @@ export function parse({
content: string;
flags: string[];
} {
- function get_linkifier_regexes(): RegExp[] {
+ function get_linkifier_regexes(): RE2JS[] {
return [...helper_config.get_linkifier_map().keys()];
}
@@ -809,10 +806,10 @@ export function parse({
return handleUnicodeEmoji(unicode_emoji, helper_config.get_emoji_name);
}
- function linkifierHandler(pattern: RegExp, matches: LinkifierMatch[]): string {
+ function linkifierHandler(pattern: RE2JS, matcher: Matcher): string {
return handleLinkifier({
pattern,
- matches,
+ matcher,
get_linkifier_map: helper_config.get_linkifier_map,
});
}
@@ -871,11 +868,6 @@ export function render(
};
}
-export function contains_backend_only_syntax(content: string): boolean {
- assert(web_app_helpers !== undefined);
- return content_contains_backend_only_syntax(content, web_app_helpers.get_linkifier_map);
-}
-
export function parse_non_message(raw_content: string): string {
assert(web_app_helpers !== undefined);
// Occasionally we get markdown from the server that is not technically
diff --git a/web/src/settings_linkifiers.ts b/web/src/settings_linkifiers.ts
index beb9d6cb88b..67061fb59b8 100644
--- a/web/src/settings_linkifiers.ts
+++ b/web/src/settings_linkifiers.ts
@@ -1,5 +1,6 @@
import $ from "jquery";
import assert from "minimalistic-assert";
+import {RE2JSSyntaxException} from "re2js";
import SortableJS from "sortablejs";
import * as z from "zod/mini";
@@ -75,6 +76,30 @@ function read_alternative_url_templates_from_form($modal: JQuery): string[] {
return templates;
}
+// Compile the pattern client-side to catch regex syntax errors before
+// submitting to the server. On failure, reports the error into
+// $pattern_status and returns false.
+function validate_linkifier_pattern(
+ pattern: string,
+ url_template: string,
+ $pattern_status: JQuery,
+): boolean {
+ try {
+ linkifiers.compile_linkifier(pattern, url_template);
+ } catch (error) {
+ const detail = error instanceof RE2JSSyntaxException ? error.getDescription() : undefined;
+ ui_report.error(
+ detail === undefined
+ ? $t_html({defaultMessage: "Failed: Bad regular expression"})
+ : $t_html({defaultMessage: "Failed: Bad regular expression: {detail}"}, {detail}),
+ undefined,
+ $pattern_status,
+ );
+ return false;
+ }
+ return true;
+}
+
function open_linkifier_edit_form(linkifier_id: number): void {
const linkifiers_list = realm.realm_linkifiers;
const linkifier = linkifiers_list.find((linkifier) => linkifier.id === linkifier_id);
@@ -122,6 +147,12 @@ function open_linkifier_edit_form(linkifier_id: number): void {
.find("#linkifier-alternative-url-templates-status")
.expectOne();
const $dialog_error_element = $modal.find("#dialog_error").expectOne();
+
+ if (!validate_linkifier_pattern(pattern, url_template, $pattern_status)) {
+ $change_linkifier_button.prop("disabled", false);
+ return;
+ }
+
const opts = {
success_continuation() {
$change_linkifier_button.prop("disabled", false);
@@ -221,15 +252,8 @@ function open_linkifier_add_form(): void {
.val()!
.trim();
- try {
- linkifiers.python_to_js_linkifier(pattern, url_template);
- } catch {
+ if (!validate_linkifier_pattern(pattern, url_template, $pattern_status)) {
$add_linkifier_button.prop("disabled", false);
- ui_report.error(
- $t_html({defaultMessage: "Failed: Invalid Pattern"}),
- undefined,
- $pattern_status,
- );
return;
}
diff --git a/web/tests/compose.test.cjs b/web/tests/compose.test.cjs
index 947ec69fdf2..ba99c86d47b 100644
--- a/web/tests/compose.test.cjs
+++ b/web/tests/compose.test.cjs
@@ -301,6 +301,7 @@ test_ui("send_message", ({override, override_rewire, mock_template}) => {
const server_message_id = 127;
override(markdown, "render", noop);
+ override(markdown, "get_topic_links", () => []);
override_rewire(echo, "try_deliver_locally", (message_request) => {
const local_id_float = 123.04;
diff --git a/web/tests/echo.test.cjs b/web/tests/echo.test.cjs
index f0043a7528d..5ca7c738b0a 100644
--- a/web/tests/echo.test.cjs
+++ b/web/tests/echo.test.cjs
@@ -391,6 +391,7 @@ run_test("insert_local_message direct message", ({override}) => {
override(markdown, "render", () => {
render_called = true;
});
+ override(markdown, "get_topic_links", () => []);
const message_request = {
private_message_recipient: "[email protected]",
diff --git a/web/tests/linkifiers.test.cjs b/web/tests/linkifiers.test.cjs
index e953a6c9104..f46ad516548 100644
--- a/web/tests/linkifiers.test.cjs
+++ b/web/tests/linkifiers.test.cjs
@@ -14,25 +14,23 @@ function get_linkifier_regexes() {
return [...linkifiers.get_linkifier_map().keys()];
}
-run_test("python_to_js_linkifier", () => {
- // The only way to reach python_to_js_linkifier is indirectly, hence the call
- // to update_linkifier_rules.
+run_test("compile_linkifier", () => {
+ // Verify basic pattern compilation with RE2JS.
linkifiers.update_linkifier_rules([
{
- pattern: "/a(?im)a/g",
- url_template: "http://example1.example.com",
+ pattern: "TICKET-(?P<id>\\d+)",
+ url_template: "http://example1.example.com/{id}",
id: 10,
},
- {
- pattern: "/a(?L)a/g",
- url_template: "http://example2.example.com",
- id: 20,
- },
]);
- let actual_value = get_linkifier_regexes();
- let expected_value = [/\/aa\/g(?!\w)/gim, /\/aa\/g(?!\w)/g];
- assert.deepEqual(actual_value, expected_value);
- // Test case with multiple replacements.
+ let regexes = get_linkifier_regexes();
+ assert.equal(regexes.length, 1);
+ let matcher = regexes[0].matcher(" TICKET-42 ");
+ assert.ok(matcher.find());
+ assert.equal(matcher.group(2), "TICKET-42");
+ assert.equal(matcher.group("id"), "42");
+
+ // Test case with multiple named groups.
linkifiers.update_linkifier_rules([
{
pattern: "#cf(?P<contest>\\d+)(?P<problem>[A-Z][\\dA-Z]*)",
@@ -40,11 +38,25 @@ run_test("python_to_js_linkifier", () => {
id: 30,
},
]);
- actual_value = get_linkifier_regexes();
- expected_value = [/#cf(\d+)([A-Z][\dA-Z]*)(?!\w)/g];
- assert.deepEqual(actual_value, expected_value);
- // Test incorrect syntax.
- blueslip.expect("error", "python_to_js_linkifier failure!");
+ regexes = get_linkifier_regexes();
+ assert.equal(regexes.length, 1);
+ matcher = regexes[0].matcher(" #cf100Z ");
+ assert.ok(matcher.find());
+ assert.equal(matcher.group(2), "#cf100Z");
+ assert.equal(matcher.group("contest"), "100");
+ assert.equal(matcher.group("problem"), "Z");
+
+ // Boundary matching: linkifier only matches after boundary characters.
+ matcher = regexes[0].matcher("x#cf100Z ");
+ assert.ok(!matcher.find());
+ matcher = regexes[0].matcher("(#cf100Z)");
+ assert.ok(matcher.find());
+ assert.equal(matcher.group(2), "#cf100Z");
+
+ // Test incorrect syntaxes
+
+ // Just absolute garbage:
+ blueslip.expect("error", "Failed to compile linkifier!", 1);
linkifiers.update_linkifier_rules([
{
pattern: "!@#@(!#&((!&(@#(",
@@ -52,7 +64,18 @@ run_test("python_to_js_linkifier", () => {
id: 40,
},
]);
- actual_value = get_linkifier_regexes();
- expected_value = [];
- assert.deepEqual(actual_value, expected_value);
+ blueslip.reset();
+ assert.deepEqual(get_linkifier_regexes(), []);
+
+ // Python-only inline flags like (?L) are rejected by RE2JS.
+ blueslip.expect("error", "Failed to compile linkifier!", 1);
+ linkifiers.update_linkifier_rules([
+ {
+ pattern: "(?L)foo",
+ url_template: "http://example2.example.com",
+ id: 20,
+ },
+ ]);
+ blueslip.reset();
+ assert.deepEqual(get_linkifier_regexes(), []);
});
diff --git a/web/tests/markdown.test.cjs b/web/tests/markdown.test.cjs
index 4596ed43e51..5e49944f159 100644
--- a/web/tests/markdown.test.cjs
+++ b/web/tests/markdown.test.cjs
@@ -525,9 +525,6 @@ test("marked", ({override}) => {
expected:
'<blockquote>\n<p>User group mention in quote: <span class="user-group-mention silent" data-user-group-id="2">Backend</span></p>\n</blockquote>\n<blockquote>\n<p>Another user group mention in quote: <span class="user-group-mention silent" data-user-group-id="1">hamletcharacters</span></p>\n</blockquote>',
},
- // Test only those linkifiers which don't return True for
- // `contains_backend_only_syntax()`. Those which return True
- // are tested separately.
{
input: "This is a linkifier #1234 with text after it",
expected:
@@ -548,6 +545,14 @@ test("marked", ({override}) => {
expected:
'<p>This is a linkifier with <a href="https://zone_45.zulip.net/ticket/123" title="https://zone_45.zulip.net/ticket/123">ZGROUP_123:45</a> groups</p>',
},
+ {
+ input: "Here is the PR-#123.",
+ expected: `<p>Here is the PR-<a href="https://trac.example.com/ticket/123" title="https://trac.example.com/ticket/123">#123</a>.</p>`,
+ },
+ {
+ input: "Function abc() was introduced in (PR)#123.",
+ expected: `<p>Function abc() was introduced in (PR)<a href="https://trac.example.com/ticket/123" title="https://trac.example.com/ticket/123">#123</a>.</p>`,
+ },
{input: "Test *italic*", expected: "<p>Test <em>italic</em></p>"},
{
input: "T\n#**Denmark**",
@@ -992,16 +997,6 @@ test("message_flags", () => {
assert.equal(message.flags.includes("mentioned"), false);
});
-test("backend_only_linkifiers", () => {
- const backend_only_linkifiers = [
- "Here is the PR-#123.",
- "Function abc() was introduced in (PR)#123.",
- ];
- for (const content of backend_only_linkifiers) {
- assert.equal(markdown.contains_backend_only_syntax(content), true);
- }
-});
-
test("translate_emoticons_to_names", () => {
const get_emoticon_translations = emoji.get_emoticon_translations;
diff --git a/web/tests/markdown_parse.test.cjs b/web/tests/markdown_parse.test.cjs
index d3b6cae6762..3d85310e0ac 100644
--- a/web/tests/markdown_parse.test.cjs
+++ b/web/tests/markdown_parse.test.cjs
@@ -2,6 +2,7 @@
const assert = require("node:assert/strict");
+const {RE2JS} = require("re2js");
const Template = require("uri-template-lite");
const {zrequire} = require("./lib/namespace.cjs");
@@ -113,13 +114,16 @@ function get_realm_emoji_url(emoji_name) {
return realm_emoji_map.get(emoji_name);
}
-const regex = /#foo(\d+)(?!\w)/g;
+const regex = RE2JS.compile(
+ "(^|\\s|\\x{0085}|\\p{Z}|['\"(,:<])(#foo(?P<id>\\d+))($|[^\\p{L}\\p{N}])",
+);
const linkifier_map = new Map([
[
regex,
{
url_template: new Template("http://foo.com/{id}"),
- group_number_to_name: {1: "id"},
+ reverse_template: null,
+ alternative_url_templates: [],
},
],
]);
diff --git a/web/third/marked/lib/marked.cjs b/web/third/marked/lib/marked.cjs
index 8e573198214..973f383808f 100644
--- a/web/third/marked/lib/marked.cjs
+++ b/web/third/marked/lib/marked.cjs
@@ -611,19 +611,20 @@ InlineLexer.output = function(src, links, options) {
*/
InlineLexer.prototype.inlineReplacement = function(regex, src, replace_func) {
- var cap, out = "";
- regex.lastIndex = 0;
- if (cap = regex.exec(src)) {
+ var out = "";
+ var matcher = regex.matcher(src);
+ if (matcher.find()) {
// Split before-match into its own segment and handle it separately
- var match_idx = regex.lastIndex;
- var before = src.substring(0, match_idx - cap[0].length);
+ var match_start = matcher.start(0);
+ var match_end = matcher.end(0);
+ var before = src.substring(0, match_start);
before = this.output(before);
out += before;
// Consume all of the matched text
- src = src.substring(match_idx);
+ src = src.substring(match_end);
- out += replace_func(regex, cap.slice(1), cap[0]);
+ out += replace_func(regex, matcher);
}
return [src, out];
@@ -649,14 +650,17 @@ InlineLexer.prototype.output = function(src) {
const regexes = this.options.get_linkifier_regexes ? this.options.get_linkifier_regexes() : [];
regexes.forEach(function (regex) {
- var ret = self.inlineReplacement(regex, src, function(regex, groups, match) {
+ var ret = self.inlineReplacement(regex, src, function(regex, matcher) {
// Insert the created URL
- href = self.linkifier(regex, groups, match);
+ href = self.linkifier(regex, matcher);
if (href !== undefined) {
href = escape(href);
- return self.renderer.link(href, href, match);
+ var leading = matcher.group(1);
+ var link_text = matcher.group(2);
+ var trailing = matcher.group(matcher.groupCount());
+ return leading + self.renderer.link(href, href, link_text) + trailing;
} else {
- return match;
+ return matcher.group(0);
}
});
@@ -898,11 +902,11 @@ InlineLexer.prototype.timestamp = function (time) {
return this.options.timestampHandler(time);
};
-InlineLexer.prototype.linkifier = function (linkifier, matches, orig) {
+InlineLexer.prototype.linkifier = function (linkifier, matcher) {
if (typeof this.options.linkifierHandler !== 'function')
return;
- return this.options.linkifierHandler(linkifier, matches);
+ return this.options.linkifierHandler(linkifier, matcher);
};
InlineLexer.prototype.usermention = function (username, orig, silent) {
diff --git a/web/third/marked/lib/marked.d.cts b/web/third/marked/lib/marked.d.cts
index 5da788db317..8c51a8d9494 100644
--- a/web/third/marked/lib/marked.d.cts
+++ b/web/third/marked/lib/marked.d.cts
@@ -4,6 +4,7 @@ we only use parts of the marked API and are using a fork
of the upstream library.
*/
+import type {Matcher, RE2JS} from "re2js";
declare class Renderer {
code: (code: string) => string;
@@ -17,12 +18,10 @@ declare namespace marked {
| {
exec(string: string): RegExpExecArray | null;
};
- // uri-template-lite has this type set as unknown.
- type LinkifierMatch = unknown;
type ParseOptions = {
- get_linkifier_regexes: () => RegExp[];
- linkifierHandler: (pattern: RegExp, matches: LinkifierMatch[]) => string;
+ get_linkifier_regexes: () => RE2JS[];
+ linkifierHandler: (pattern: RE2JS, matcher: Matcher) => string;
emojiHandler: (emoji_name: string) => string;
unicodeEmojiHandler: (unicode_emoji: string) => string;
streamHandler: (stream_name: string) => string | undefined;
diff --git a/zerver/lib/markdown/__init__.py b/zerver/lib/markdown/__init__.py
index b46ed834e5b..cd5eaec3375 100644
--- a/zerver/lib/markdown/__init__.py
+++ b/zerver/lib/markdown/__init__.py
@@ -1646,6 +1646,9 @@ def prepare_linkifier_pattern(source: str) -> str:
# We use an extended definition of 'whitespace' which is
# equivalent to \p{White_Space} -- since \s in re2 only matches
# ASCII spaces, and re2 does not support \p{White_Space}.
+ #
+ # This implementation should be kept in sync with the one in
+ # web/src/linkifiers.ts.
return rf"""(?P<{BEFORE_CAPTURE_GROUP}>^|\s|{next_line}|\pZ|['"(,:<])(?P<{OUTER_CAPTURE_GROUP}>{source})(?P<{AFTER_CAPTURE_GROUP}>$|[^\pL\pN])"""