From c7efe96825058014a5f6ae6cd4873feb0c706440 Mon Sep 17 00:00:00 2001 From: Perception Date: Mon, 28 Dec 2020 09:44:25 -0800 Subject: [PATCH] Try to prevent search queries from crashing --- routes/search.js | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/routes/search.js b/routes/search.js index 8938756..721198a 100644 --- a/routes/search.js +++ b/routes/search.js @@ -9,6 +9,22 @@ const db = ds.db() const PER_PAGE = 100 +/** + * Wrap search queries that might crash FTS5 with double quotes. + * @param {String} q - search query + * @returns {String} a search query that probably won't crash SQLite's FTS5 + */ +function safeQuery(q) { + let q2 = q.trim() + if (q2.match(/[-./]/)) { + q2 = `"${q2}"` + } + if (q2.match(/\+/)) { + q2 = q2.replace(/\+/g, ' ') + } + return q2 +} + module.exports.GET = async (req, res) => { const url = urlite.parse(req.url) const q = unescape(url.search.q) @@ -22,8 +38,9 @@ module.exports.GET = async (req, res) => { // Search, if we have a query. const path = `/search?q=${url.search.q}&` const {limit, offset} = pagination.getValuesToPaginate({ currentPage: p, perPage: PER_PAGE }) - const results = await ds.search(db, q, limit, offset) - const count = await ds.searchCount(db, q) + const q2 = safeQuery(q) + const results = await ds.search(db, q2, limit, offset) + const count = await ds.searchCount(db, q2) const totalPages = pagination.getTotalPages({ totalItems: count, perPage: PER_PAGE }) const out = await page.render('search', { path, q, p, results, count, totalPages }) return send(res, 200, out)