From 6b255f2a4e6874d9bd9d20bd0dfd0e6be2cbf8d3 Mon Sep 17 00:00:00 2001 From: Leokuma Date: Thu, 2 Nov 2023 03:30:50 -0300 Subject: [PATCH] fix: prevent hanging when the first character is invalid (#31) --- parse_test.ts | 15 +++++++++++++++ utils/parser.ts | 12 ++++++++---- 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/parse_test.ts b/parse_test.ts index f165e8db..369fc0f0 100644 --- a/parse_test.ts +++ b/parse_test.ts @@ -494,6 +494,21 @@ Deno.test("parse: xml syntax attributes properly quoted", () => `) )) +Deno.test("parse: xml syntax first character", () => { + assertThrows(() => + parse(`a>1`) + ) + assertThrows(() => + parse(`xml`) + ) + assertThrows(() => + parse(`""`) + ) + assertThrows(() => + parse(`{a: 1}`) + ) +}) + //Example below were taken from https://www.w3schools.com/xml/default.asp Deno.test("parse: xml example w3schools.com#1", () => diff --git a/utils/parser.ts b/utils/parser.ts index 2515af95..8c0ee56c 100644 --- a/utils/parser.ts +++ b/utils/parser.ts @@ -57,7 +57,7 @@ export class Parser { } //Extract prolog, stylesheets and doctype - if ((this.#peek(tokens.prolog.start)) && (!this.#peek(tokens.stylesheet.start))) { + else if ((this.#peek(tokens.prolog.start)) && (!this.#peek(tokens.stylesheet.start))) { if (document.xml) { throw Object.assign(new SyntaxError("Multiple prolog declaration found"), { stack: false }) } @@ -65,13 +65,13 @@ export class Parser { Object.assign(document, this.#prolog({ path })) continue } - if (this.#peek(tokens.stylesheet.start)) { + else if (this.#peek(tokens.stylesheet.start)) { clean = false const stylesheets = (document[schema.stylesheets] ??= []) as unknown[] stylesheets.push(this.#stylesheet({ path }).stylesheet) continue } - if (this.#peek(tokens.doctype.start)) { + else if (this.#peek(tokens.doctype.start)) { if (document.doctype) { throw Object.assign(new SyntaxError("Multiple doctype declaration found"), { stack: false }) } @@ -81,7 +81,7 @@ export class Parser { } //Extract root node - if (this.#peek(tokens.tag.start)) { + else if (this.#peek(tokens.tag.start)) { if (root) { throw Object.assign(new SyntaxError("Multiple root elements found"), { stack: false }) } @@ -91,6 +91,10 @@ export class Parser { root = true continue } + + else { + throw Object.assign(new SyntaxError("Invalid XML structure"), { stack: false }) + } } } catch (error) { if ((error instanceof Deno.errors.UnexpectedEof) && (clean)) {