11const SQL_COMMANDS = / S E L E C T | I N S E R T | U P D A T E | D E L E T E | D R O P | A L T E R / i
2+ const SQL_CLEANUN_REGEX = / ( [ ' " ` ] ) (?: \\ .| [ ^ \\ ] ) * ?\1| \/ \* [ \s \S ] * ?\* \/ / g
3+ const SQL_COUNT_REGEX = / C O U N T \( ( D I S T I N C T ) ? [ a - z _ ] \w + \) / i
4+ const SQL_SELECT_REGEX = / ^ S E L E C T ( .* ) F R O M ( \w + ) ( W H E R E .* ) ? O R D E R B Y ( [ " \w , \s ] + ) ( A S C | D E S C ) ( L I M I T \d + ) ? ( O F F S E T \d + ) ? $ /
25
36/**
47 * Assert that the query is safe
@@ -10,7 +13,7 @@ const SQL_COMMANDS = /SELECT|INSERT|UPDATE|DELETE|DROP|ALTER/i
1013 * @returns True if the query is safe, false otherwise
1114 */
1215export function assertSafeQuery ( sql : string , collection : string ) {
13- const match = sql . match ( / ^ S E L E C T ( . * ) F R O M ( \w + ) ( W H E R E . * ) ? O R D E R B Y ( [ " \w , \s ] + ) ( A S C | D E S C ) ( L I M I T \d + ) ? ( O F F S E T \d + ) ? $ / )
16+ const match = sql . match ( SQL_SELECT_REGEX )
1417 if ( ! match ) {
1518 throw new Error ( 'Invalid query' )
1619 }
@@ -22,8 +25,8 @@ export function assertSafeQuery(sql: string, collection: string) {
2225 if ( columns . length === 1 ) {
2326 if (
2427 columns [ 0 ] !== '*'
25- && ! columns [ 0 ] . startsWith ( 'COUNT(' )
26- && ! columns [ 0 ] . match ( / ^ C O U N T \( ( D I S T I N C T ) ? [ a - z _ ] \w + \) a s c o u n t $ / )
28+ && ! columns [ 0 ] . match ( SQL_COUNT_REGEX )
29+ && ! columns [ 0 ] . match ( / ^ " [ a - z _ ] \w + " $ / )
2730 ) {
2831 throw new Error ( 'Invalid query' )
2932 }
@@ -42,7 +45,7 @@ export function assertSafeQuery(sql: string, collection: string) {
4245 if ( ! where . startsWith ( ' WHERE (' ) || ! where . endsWith ( ')' ) ) {
4346 throw new Error ( 'Invalid query' )
4447 }
45- const noString = where ?. replace ( / ( [ ' " ` ] ) (?: \\ . | [ ^ \\ ] ) * ?\1 / g , '' )
48+ const noString = where ?. replace ( SQL_CLEANUN_REGEX , '' )
4649 if ( noString . match ( SQL_COMMANDS ) ) {
4750 throw new Error ( 'Invalid query' )
4851 }
0 commit comments