@@ -4,11 +4,13 @@ const flags = require("flags");
44flags . defineString ( "db" , "" , "DB File path" ) ;
55flags . defineBoolean ( "readonly" , false , "Open the database for readonly" ) ;
66flags . defineNumber ( "port" , 2048 , "TCP Port to listen on" ) ;
7+ flags . defineMultiString ( "cors" , [ ] , "CORS URLs to allow requests from" ) ;
78flags . parse ( ) ;
89
910console . log ( "db" , "=" , flags . get ( "db" ) ) ;
1011console . log ( "readonly" , "=" , flags . get ( "readonly" ) ) ;
1112console . log ( "port" , "=" , flags . get ( "port" ) ) ;
13+ console . log ( "cors" , "=" , flags . get ( "cors" ) . join ( ", " ) || "false" ) ;
1214
1315const Database = require ( "better-sqlite3" ) ;
1416
@@ -19,14 +21,30 @@ const app = express();
1921app . use ( require ( "compression" ) ( ) ) ;
2022app . use ( bodyParser . urlencoded ( { extended : false , limit : "1mb" } ) ) ;
2123app . use ( bodyParser . json ( { limit : "1mb" } ) ) ;
22- app . use ( function ( req , res , next ) {
24+ app . use ( function ( req , res , next ) {
2325 req . connection . setTimeout ( 2 * 60 * 1000 ) ; // 2 minutes
2426 res . connection . setTimeout ( 2 * 60 * 1000 ) ; // 2 minutes
2527 next ( ) ;
2628} ) ;
2729
30+ if ( flags . get ( "cors" ) . length > 0 ) {
31+ const cors = require ( "cors" ) ;
32+ const corsWhitelist = new Set ( flags . get ( "cors" ) ) ;
33+ const corsOptions = {
34+ origin : function ( origin , callback ) {
35+ //https://www.w3.org/TR/cors/#access-control-allow-origin-response-header
36+ if ( ! origin || corsWhitelist . has ( origin ) || corsWhitelist . has ( "*" ) ) {
37+ return callback ( null , true ) ;
38+ }
39+
40+ callback ( new Error ( "Not allowed by CORS" ) ) ;
41+ } ,
42+ } ;
43+ app . use ( cors ( corsOptions ) ) ;
44+ }
45+
2846function getSqlExecutor ( httpRequestFieldName ) {
29- return function ( req , res ) {
47+ return function ( req , res ) {
3048 const sql = req [ httpRequestFieldName ] . sql ;
3149 if ( ! sql ) {
3250 return res . send ( [ ] ) ;
0 commit comments