UNPKG

@small-tech/jsdb

Version:

A zero-dependency, transparent, in-memory, streaming write-on-update JavaScript database for Small Web applications that persists to a JavaScript transaction log.

60 lines (51 loc) 2.27 kB
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Util class. // // Miscellaneous small generic utilities. // // Like this? Fund us! // https://small-tech.org/fund-us // // Copyright ⓒ 2020-2021 Aral Balkan. Licensed under AGPLv3 or later. // Shared with ♥ by the Small Technology Foundation. // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// import { types } from 'util' const isProxy = types.isProxy const onlyContainsDigitsAndDoesNotStartWithZero = value => { const _valueAsString = value.toString() return /^\d+$/.exec(value) !== null && (_valueAsString.length === 1 || _valueAsString[0] !== '0') } /** Sanitises string value. Must be used anywhere sting values are stored in the database. It is important that we sanitise string input before storing it to thwart arbitrary code execution via injection attacks. So we: • Escape all backslashes (why? See https://source.small-tech.org/site.js/lib/jsdb/-/issues/9#note_15844) • Escape all backticks (why? See https://source.small-tech.org/site.js/lib/jsdb/-/issues/9#note_15848) • Escape all dollar signs (why? See https://source.small-tech.org/site.js/lib/jsdb/-/issues/9) */ export function sanitisedString (value) { return `\`${value.replace(/\\/g, '\\\\').replace(/`/g, '\\`').replace(/\$/g, '\\$')}\`` } export function quoteKeyIfNotSafeInteger (key) { // If a key is not a safe integer, surround it in quotes. // Otherwise, leave it be. const _key = parseFloat(key) return onlyContainsDigitsAndDoesNotStartWithZero(key) && !isNaN(_key) && Number.isSafeInteger(_key) ? _key : `[${sanitisedString(key)}]` } export function needsToBeProxified (object) { return (object !== null && !isProxy(object) && typeof object === 'object') } // Conditionally log to console. export function log (...args) { // Note: we have unit tests for the else clause but since // ===== we’re monkeypatching console.log() to test invocation // Istanbul/nyc’s coverage is not picking them up properly. // istanbul ignore else if (process.env.QUIET) { return } /* c8 ignore next */ console.log(...args) }