1
1
const 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 + ) ? $ /
2
5
3
6
/**
4
7
* Assert that the query is safe
@@ -10,7 +13,7 @@ const SQL_COMMANDS = /SELECT|INSERT|UPDATE|DELETE|DROP|ALTER/i
10
13
* @returns True if the query is safe, false otherwise
11
14
*/
12
15
export 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 )
14
17
if ( ! match ) {
15
18
throw new Error ( 'Invalid query' )
16
19
}
@@ -22,8 +25,8 @@ export function assertSafeQuery(sql: string, collection: string) {
22
25
if ( columns . length === 1 ) {
23
26
if (
24
27
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 + " $ / )
27
30
) {
28
31
throw new Error ( 'Invalid query' )
29
32
}
@@ -42,7 +45,7 @@ export function assertSafeQuery(sql: string, collection: string) {
42
45
if ( ! where . startsWith ( ' WHERE (' ) || ! where . endsWith ( ')' ) ) {
43
46
throw new Error ( 'Invalid query' )
44
47
}
45
- const noString = where ?. replace ( / ( [ ' " ` ] ) (?: \\ . | [ ^ \\ ] ) * ?\1 / g , '' )
48
+ const noString = where ?. replace ( SQL_CLEANUN_REGEX , '' )
46
49
if ( noString . match ( SQL_COMMANDS ) ) {
47
50
throw new Error ( 'Invalid query' )
48
51
}
0 commit comments