aiwaf 1.2.5 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +178 -40
- package/index.js +4 -0
- package/lib/bodyPeek.js +40 -0
- package/lib/injectionAnalysis.js +29 -4
- package/lib/inputSchema.js +301 -0
- package/lib/nativePipeline.js +50 -39
- package/lib/routeRisks.js +76 -11
- package/lib/sqlInjection.js +59 -10
- package/lib/wafMiddleware.js +11 -8
- package/lib/wasmAdapter.js +18 -3
- package/lib/webSocketGuard.js +97 -0
- package/package.json +9 -3
- package/utils/db.js +82 -6
package/lib/sqlInjection.js
CHANGED
|
@@ -3,7 +3,12 @@
|
|
|
3
3
|
// SQL injection checks. The check runs in aiwaf-wasm (sql_inspect), which walks the query and
|
|
4
4
|
// body, decodes values, parses JSON, applies the size limits and runs the SQL tokenizer.
|
|
5
5
|
// Findings never include request values.
|
|
6
|
+
const zlib = require('zlib');
|
|
6
7
|
const wasmChecks = require('./wasmChecks');
|
|
8
|
+
const { peekBody, isMultipart } = require('./bodyPeek');
|
|
9
|
+
|
|
10
|
+
// The start of a multipart body, read by peekUpload before a body parser has run.
|
|
11
|
+
const UPLOAD = Symbol('aiwaf.upload-prefix');
|
|
7
12
|
|
|
8
13
|
const EMPTY = new Uint8Array(0);
|
|
9
14
|
|
|
@@ -30,25 +35,63 @@ function headerPairs(headers) {
|
|
|
30
35
|
if (value === undefined || value === null) continue;
|
|
31
36
|
for (const item of Array.isArray(value) ? value : [value]) {
|
|
32
37
|
found.push([String(name), String(item)]);
|
|
33
|
-
|
|
38
|
+
// One past what aiwaf-wasm checks, so it refuses a request with too many, not skips them.
|
|
39
|
+
if (found.length > 256) return found;
|
|
34
40
|
}
|
|
35
41
|
}
|
|
36
42
|
return found;
|
|
37
43
|
}
|
|
38
44
|
|
|
45
|
+
// A raw body in the encoding it was sent in. aiwaf-wasm reads gzip and deflate itself; br is
|
|
46
|
+
// decoded here, to at most maxBytes + 1 bytes, so the check refuses a larger one. Null for an
|
|
47
|
+
// encoding that can't be read.
|
|
48
|
+
function decoded(body, encoding, maxBytes) {
|
|
49
|
+
const name = String(encoding || 'identity').trim().toLowerCase();
|
|
50
|
+
if (['', 'identity', 'gzip', 'x-gzip', 'deflate'].includes(name)) return body;
|
|
51
|
+
if (name !== 'br') return null;
|
|
52
|
+
try {
|
|
53
|
+
return zlib.brotliDecompressSync(body, { maxOutputLength: maxBytes + 1 });
|
|
54
|
+
} catch (_) {
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Reads the start of an unparsed multipart body, then puts it back on the stream, so the
|
|
61
|
+
* inspector checks its text fields, file names and file headers before an upload parser runs.
|
|
62
|
+
* A body that isn't multipart, or was already read, is left alone.
|
|
63
|
+
*/
|
|
64
|
+
async function peekUpload(req, maxBytes) {
|
|
65
|
+
if (req.body !== undefined || req[UPLOAD] || !isMultipart(req) || typeof req.read !== 'function'
|
|
66
|
+
|| typeof req.unshift !== 'function' || req.readableEnded) return;
|
|
67
|
+
const declared = Number(req.headers?.['content-length'] || 0) > 0 || !!req.headers?.['transfer-encoding'];
|
|
68
|
+
if (declared) req[UPLOAD] = await peekBody(req, maxBytes);
|
|
69
|
+
}
|
|
70
|
+
|
|
39
71
|
function createInspector(options = {}) {
|
|
40
72
|
const mode = String(options.AIWAF_SQL_INJECTION_MODE ?? process.env.AIWAF_SQL_INJECTION_MODE ?? 'block').toLowerCase();
|
|
41
73
|
if (!['block', 'monitor', 'off'].includes(mode)) throw new Error('Invalid AIWAF_SQL_INJECTION_MODE');
|
|
42
74
|
const maxBytes = Number(options.AIWAF_PAYLOAD_MAX_BYTES ?? process.env.AIWAF_PAYLOAD_MAX_BYTES ?? 65536);
|
|
43
75
|
if (!Number.isInteger(maxBytes) || maxBytes < 1 || maxBytes > 1048576) throw new Error('AIWAF_PAYLOAD_MAX_BYTES must be 1..1048576');
|
|
44
|
-
/** Checks a request. Await wasmChecks.load() before the
|
|
45
|
-
|
|
76
|
+
/** Checks a request. Await wasmChecks.load(), and inspect.prepare(req), before the call. */
|
|
77
|
+
inspect.prepare = req => (mode === 'off' ? Promise.resolve() : peekUpload(req, maxBytes));
|
|
78
|
+
inspect.maxBytes = maxBytes;
|
|
79
|
+
return inspect;
|
|
80
|
+
function inspect(req) {
|
|
46
81
|
if (mode === 'off') return null;
|
|
47
82
|
const wasm = wasmChecks.get();
|
|
48
|
-
const body = bodyBytes(req.body);
|
|
49
|
-
if (body === null) return { rule: 'payload_inspection_limit', status: 413, mode };
|
|
50
83
|
// Raw Node requests have only a URL. Frameworks may also have parsed the query.
|
|
51
84
|
const raw = String(req.originalUrl || req.url || '').split('?').slice(1).join('?');
|
|
85
|
+
let body = req.body === undefined && req[UPLOAD]
|
|
86
|
+
// A large upload is checked by its start: its text fields and file headers come first.
|
|
87
|
+
? req[UPLOAD].subarray(0, Math.max(0, maxBytes - Buffer.byteLength(raw)))
|
|
88
|
+
: bodyBytes(req.body);
|
|
89
|
+
// Only a raw body is still encoded: a parsed one was decoded by its parser.
|
|
90
|
+
const unparsed = Buffer.isBuffer(req.body) || req.body instanceof Uint8Array || typeof req.body === 'string';
|
|
91
|
+
if (body !== null && body.length && unparsed) body = decoded(body, req.headers?.['content-encoding'], maxBytes);
|
|
92
|
+
if (body === null) return { rule: 'payload_inspection_limit', status: 413, mode };
|
|
93
|
+
// Where the finding came from, so the route's saved inputs can review it.
|
|
94
|
+
let source = 'payload';
|
|
52
95
|
let found = JSON.parse(wasm.sql_inspect(Buffer.from(raw), body, maxBytes));
|
|
53
96
|
if (!found && !raw && req.query && typeof req.query === 'object') {
|
|
54
97
|
const query = bodyBytes(req.query);
|
|
@@ -56,12 +99,18 @@ function createInspector(options = {}) {
|
|
|
56
99
|
? { rule: 'payload_inspection_limit', status: 413 }
|
|
57
100
|
: JSON.parse(wasm.sql_inspect(EMPTY, query, maxBytes));
|
|
58
101
|
}
|
|
59
|
-
if (!found)
|
|
102
|
+
if (!found) {
|
|
103
|
+
source = 'headers';
|
|
104
|
+
found = JSON.parse(wasm.sql_inspect_headers(JSON.stringify(headerPairs(req.headers)), maxBytes));
|
|
105
|
+
}
|
|
60
106
|
// The URL path, one segment at a time, as in /post/1 OR 1=1.
|
|
61
107
|
const path = String(req.originalUrl || req.url || '').split('?')[0];
|
|
62
|
-
if (!found && path)
|
|
63
|
-
|
|
64
|
-
|
|
108
|
+
if (!found && path) {
|
|
109
|
+
source = 'path';
|
|
110
|
+
found = JSON.parse(wasm.sql_inspect_path(path, maxBytes));
|
|
111
|
+
}
|
|
112
|
+
return found ? { rule: found.rule, status: found.status, mode, source } : null;
|
|
113
|
+
}
|
|
65
114
|
}
|
|
66
115
|
|
|
67
|
-
module.exports = { createInspector, bodyBytes };
|
|
116
|
+
module.exports = { createInspector, bodyBytes, peekUpload };
|
package/lib/wafMiddleware.js
CHANGED
|
@@ -161,13 +161,9 @@ function applyAutoMiddlewareDefaults(opts, enabled, rawOpts = {}) {
|
|
|
161
161
|
const NATIVE_DEFAULT_WASM = '0.2.9';
|
|
162
162
|
|
|
163
163
|
function installedWasmVersion() {
|
|
164
|
-
const
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
() => require.resolve('aiwaf-wasm/package.json')]) {
|
|
168
|
-
try { return JSON.parse(fs.readFileSync(typeof file === 'function' ? file() : file, 'utf8')).version; } catch (_) { /* next */ }
|
|
169
|
-
}
|
|
170
|
-
return null;
|
|
164
|
+
const dir = require('./wasmAdapter').wasmPackageDir();
|
|
165
|
+
if (!dir) return null;
|
|
166
|
+
try { return JSON.parse(require('fs').readFileSync(require('path').join(dir, 'package.json'), 'utf8')).version; } catch (_) { return null; }
|
|
171
167
|
}
|
|
172
168
|
function atLeast(version, minimum) {
|
|
173
169
|
const parse = v => String(v).split('-')[0].split('.').map(Number);
|
|
@@ -344,7 +340,14 @@ module.exports = function aiwaf(rawOpts = {}) {
|
|
|
344
340
|
await checksReady;
|
|
345
341
|
const riskFinding = observeRisks ? observeRisks(req) : null;
|
|
346
342
|
if (riskFinding) return riskFinding;
|
|
347
|
-
|
|
343
|
+
await inspectSql.prepare(req);
|
|
344
|
+
let finding = inspectSql(req);
|
|
345
|
+
// The route's saved inputs review the general check's answer: see AIWAF_ROUTE_SCHEMA_MODE.
|
|
346
|
+
if (observeRisks?.review && finding?.status !== 413 && finding?.source !== 'headers') {
|
|
347
|
+
finding = finding?.source === 'path'
|
|
348
|
+
? observeRisks.reviewPath(req, finding, inspectSql.maxBytes)
|
|
349
|
+
: observeRisks.review(req, finding, inspectSql.maxBytes);
|
|
350
|
+
}
|
|
348
351
|
if (finding?.mode === 'monitor') {
|
|
349
352
|
(opts.logger || console).warn?.({ event: 'aiwaf.payload', rule: finding.rule, mode: finding.mode });
|
|
350
353
|
return null;
|
package/lib/wasmAdapter.js
CHANGED
|
@@ -6,8 +6,21 @@ let wasmModule = null;
|
|
|
6
6
|
let wasmLoadAttempted = false;
|
|
7
7
|
let wasmLoadError = null;
|
|
8
8
|
|
|
9
|
+
/**
|
|
10
|
+
* The installed aiwaf-wasm folder, found the way require() finds it, so it works wherever npm
|
|
11
|
+
* put it (in aiwaf's own node_modules or hoisted to the app's), or null when it isn't installed.
|
|
12
|
+
*/
|
|
13
|
+
function wasmPackageDir() {
|
|
14
|
+
try {
|
|
15
|
+
return path.dirname(require.resolve('aiwaf-wasm/package.json'));
|
|
16
|
+
} catch (_) {
|
|
17
|
+
return null;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
9
21
|
async function loadWasmFromDisk() {
|
|
10
|
-
const pkgDir =
|
|
22
|
+
const pkgDir = wasmPackageDir();
|
|
23
|
+
if (!pkgDir) return null;
|
|
11
24
|
const wasmPath = path.join(pkgDir, 'aiwaf_wasm_bg.wasm');
|
|
12
25
|
const bgPath = path.join(pkgDir, 'aiwaf_wasm_bg.js');
|
|
13
26
|
|
|
@@ -58,7 +71,8 @@ async function loadWasmFromDisk() {
|
|
|
58
71
|
}
|
|
59
72
|
|
|
60
73
|
async function loadWasmFromPackageModule() {
|
|
61
|
-
const pkgDir =
|
|
74
|
+
const pkgDir = wasmPackageDir();
|
|
75
|
+
if (!pkgDir) return null;
|
|
62
76
|
const modulePath = path.join(pkgDir, 'aiwaf_wasm.js');
|
|
63
77
|
if (!fs.existsSync(modulePath)) return null;
|
|
64
78
|
try {
|
|
@@ -596,5 +610,6 @@ module.exports = {
|
|
|
596
610
|
rustPayloadFromRecords,
|
|
597
611
|
pythonFeatureFromRecord,
|
|
598
612
|
pythonFeaturesBatched,
|
|
599
|
-
getWasmStatus
|
|
613
|
+
getWasmStatus,
|
|
614
|
+
wasmPackageDir
|
|
600
615
|
};
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// WebSocket messages, checked like request bodies. HTTP checks never see what a WebSocket
|
|
4
|
+
// carries after its handshake, so this checks each message a client sends with the payload
|
|
5
|
+
// check in aiwaf-wasm: SQL injection, remote code execution and their disguises, and JSON
|
|
6
|
+
// messages by their values. A message with a finding closes the socket with 1008 (policy
|
|
7
|
+
// violation), or 1009 when it's too large to check, and never reaches the application's
|
|
8
|
+
// handlers. It follows AIWAF_SQL_INJECTION_MODE: monitor logs the rule and passes the message,
|
|
9
|
+
// off checks nothing. Log events carry the rule and path only, never message content.
|
|
10
|
+
const wasmChecks = require('./wasmChecks');
|
|
11
|
+
const { bodyBytes } = require('./sqlInjection');
|
|
12
|
+
|
|
13
|
+
const EMPTY = new Uint8Array(0);
|
|
14
|
+
|
|
15
|
+
function settings(options = {}) {
|
|
16
|
+
const mode = String(options.AIWAF_SQL_INJECTION_MODE ?? process.env.AIWAF_SQL_INJECTION_MODE ?? 'block').toLowerCase();
|
|
17
|
+
if (!['block', 'monitor', 'off'].includes(mode)) throw new Error('Invalid AIWAF_SQL_INJECTION_MODE');
|
|
18
|
+
const maxBytes = Number(options.AIWAF_PAYLOAD_MAX_BYTES ?? process.env.AIWAF_PAYLOAD_MAX_BYTES ?? 65536);
|
|
19
|
+
if (!Number.isInteger(maxBytes) || maxBytes < 1 || maxBytes > 1048576) throw new Error('AIWAF_PAYLOAD_MAX_BYTES must be 1..1048576');
|
|
20
|
+
return { mode, maxBytes, logger: options.logger || console };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// A message as bytes: ws gives a Buffer, an array of Buffers or an ArrayBuffer; socket.io gives
|
|
24
|
+
// event arguments, which are checked as JSON.
|
|
25
|
+
function messageBytes(data) {
|
|
26
|
+
if (Buffer.isBuffer(data) || data instanceof Uint8Array) return data;
|
|
27
|
+
if (Array.isArray(data) && data.every(item => Buffer.isBuffer(item))) return Buffer.concat(data);
|
|
28
|
+
if (data instanceof ArrayBuffer) return Buffer.from(data);
|
|
29
|
+
return bodyBytes(data);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** The finding for one message, or null. Await wasmChecks.load() first. Ignores the mode. */
|
|
33
|
+
function inspectMessage(data, options = {}) {
|
|
34
|
+
const { maxBytes } = settings(options);
|
|
35
|
+
const bytes = messageBytes(data);
|
|
36
|
+
if (bytes === null) return { rule: 'payload_inspection_limit', status: 413 };
|
|
37
|
+
return JSON.parse(wasmChecks.get().sql_inspect(EMPTY, bytes, maxBytes));
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function report(logger, mode, path, finding) {
|
|
41
|
+
try {
|
|
42
|
+
logger.warn?.({ event: 'aiwaf.websocket', mode, path: String(path || ''), rule: finding.rule });
|
|
43
|
+
} catch (_) { /* Logging must not decide the outcome. */ }
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Checks every message clients send to a `ws` WebSocketServer. Resolves once the checks are
|
|
48
|
+
* loaded; messages are checked from then on.
|
|
49
|
+
*/
|
|
50
|
+
async function guardWebSocketServer(wss, options = {}) {
|
|
51
|
+
const config = settings(options);
|
|
52
|
+
if (config.mode === 'off') return wss;
|
|
53
|
+
await wasmChecks.load();
|
|
54
|
+
wss.on('connection', (socket, req) => {
|
|
55
|
+
const path = String(req?.url || '').split('?')[0];
|
|
56
|
+
let closed = false;
|
|
57
|
+
const emit = socket.emit;
|
|
58
|
+
socket.emit = function emitChecked(event, ...args) {
|
|
59
|
+
if (event === 'message') {
|
|
60
|
+
if (closed) return false;
|
|
61
|
+
const finding = inspectMessage(args[0], options);
|
|
62
|
+
if (finding) {
|
|
63
|
+
report(config.logger, config.mode, path, finding);
|
|
64
|
+
if (config.mode === 'block') {
|
|
65
|
+
closed = true;
|
|
66
|
+
socket.close(finding.status === 413 ? 1009 : 1008, 'aiwaf');
|
|
67
|
+
return false;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return emit.call(this, event, ...args);
|
|
72
|
+
};
|
|
73
|
+
});
|
|
74
|
+
return wss;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Checks every event clients send to a socket.io server, with per-socket packet middleware. */
|
|
78
|
+
async function guardSocketIo(io, options = {}) {
|
|
79
|
+
const config = settings(options);
|
|
80
|
+
if (config.mode === 'off') return io;
|
|
81
|
+
await wasmChecks.load();
|
|
82
|
+
io.on('connection', socket => {
|
|
83
|
+
const path = String(socket.handshake?.url || '').split('?')[0];
|
|
84
|
+
socket.use(([event, ...args], next) => {
|
|
85
|
+
// The event name and its arguments, except an acknowledgement callback.
|
|
86
|
+
const finding = inspectMessage([event, ...args.filter(item => typeof item !== 'function')], options);
|
|
87
|
+
if (!finding) return next();
|
|
88
|
+
report(config.logger, config.mode, path, finding);
|
|
89
|
+
if (config.mode !== 'block') return next();
|
|
90
|
+
next(new Error(finding.rule));
|
|
91
|
+
socket.disconnect(true);
|
|
92
|
+
});
|
|
93
|
+
});
|
|
94
|
+
return io;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
module.exports = { guardSocketIo, guardWebSocketServer, inspectMessage };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "aiwaf",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.3.0",
|
|
4
4
|
"description": "AIWAF Web Application Firewall for JavaScript applications and major Node.js frameworks",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"files": [
|
|
@@ -22,8 +22,11 @@
|
|
|
22
22
|
"scripts": {
|
|
23
23
|
"retrain": "AIWAF_LOG_PATH=/var/log/nginx/access.log npm run train",
|
|
24
24
|
"train": "node train.js",
|
|
25
|
+
"pretest": "node scripts/check-local-wasm.js",
|
|
25
26
|
"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js --runInBand",
|
|
27
|
+
"pretest:coverage": "node scripts/check-local-wasm.js",
|
|
26
28
|
"test:coverage": "node --experimental-vm-modules node_modules/jest/bin/jest.js --runInBand --coverage",
|
|
29
|
+
"pretest:wasm": "node scripts/check-local-wasm.js",
|
|
27
30
|
"test:wasm": "node --experimental-vm-modules node_modules/jest/bin/jest.js --runInBand --runTestsByPath test/wasmAdapter.test.js test/wasm-header-config.test.js test/wasm-header-input.test.js test/wasm-retrain-behavior.test.js test/wasm-waf-integration.test.js && node test/wasm-real.js",
|
|
28
31
|
"aiwaf": "node bin/aiwaf.js",
|
|
29
32
|
"test:wasm-real": "node test/wasm-real.js",
|
|
@@ -34,7 +37,7 @@
|
|
|
34
37
|
},
|
|
35
38
|
"dependencies": {
|
|
36
39
|
"@babel/parser": "^7.29.2",
|
|
37
|
-
"aiwaf-wasm": "^0.2.
|
|
40
|
+
"aiwaf-wasm": "^0.2.11",
|
|
38
41
|
"express": "^4.21.2",
|
|
39
42
|
"glob": "^14.0.6",
|
|
40
43
|
"knex": "^2.4.2",
|
|
@@ -55,7 +58,10 @@
|
|
|
55
58
|
"@nestjs/core": "^11.1.18",
|
|
56
59
|
"@nestjs/platform-express": "^11.1.18",
|
|
57
60
|
"reflect-metadata": "^0.2.2",
|
|
58
|
-
"rxjs": "^7.8.1"
|
|
61
|
+
"rxjs": "^7.8.1",
|
|
62
|
+
"ws": "8.22.1",
|
|
63
|
+
"socket.io": "4.8.4",
|
|
64
|
+
"socket.io-client": "4.8.4"
|
|
59
65
|
},
|
|
60
66
|
"optionalDependencies": {
|
|
61
67
|
"maxmind": "^4.3.0"
|
package/utils/db.js
CHANGED
|
@@ -2,10 +2,86 @@ const knex = require('knex');
|
|
|
2
2
|
|
|
3
3
|
const isTest = process.env.NODE_ENV === 'test';
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
5
|
+
// npm 12 no longer runs dependencies' install scripts unless the app allows them, and sqlite3's
|
|
6
|
+
// install script is what fetches or builds its native binary. Without it, sqlite3 can't load.
|
|
7
|
+
// So the database connects on first use rather than when aiwaf is required: when sqlite3 can't
|
|
8
|
+
// load, each use throws SqliteUnavailableError, and the stores fall back to their CSV files.
|
|
9
|
+
const FIX = 'To store data in SQLite instead, run: npm approve-scripts sqlite3 && npm rebuild sqlite3';
|
|
10
|
+
|
|
11
|
+
class SqliteUnavailableError extends Error {
|
|
12
|
+
constructor(cause) {
|
|
13
|
+
super(`AIWAF can't load sqlite3's native binary, so it stores data in CSV files under logs/storage. `
|
|
14
|
+
+ `npm 12 skips install scripts unless they're approved, and sqlite3 needs its install script. ${FIX}`);
|
|
15
|
+
this.name = 'SqliteUnavailableError';
|
|
16
|
+
this.code = 'AIWAF_SQLITE_UNAVAILABLE';
|
|
17
|
+
this.cause = cause;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
let instance = null;
|
|
22
|
+
let failure = null;
|
|
23
|
+
let warned = false;
|
|
24
|
+
|
|
25
|
+
function loadDriver() {
|
|
26
|
+
// Required for its side effect: it throws when the native binary is missing.
|
|
27
|
+
// eslint-disable-next-line global-require
|
|
28
|
+
require('sqlite3');
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function connect() {
|
|
32
|
+
if (instance) return instance;
|
|
33
|
+
if (failure) throw failure;
|
|
34
|
+
try {
|
|
35
|
+
loadDriver();
|
|
36
|
+
} catch (err) {
|
|
37
|
+
failure = new SqliteUnavailableError(err);
|
|
38
|
+
if (!warned && !isTest) {
|
|
39
|
+
warned = true;
|
|
40
|
+
console.warn(`[aiwaf] ${failure.message}`);
|
|
41
|
+
}
|
|
42
|
+
throw failure;
|
|
43
|
+
}
|
|
44
|
+
instance = knex({
|
|
45
|
+
client: 'sqlite3',
|
|
46
|
+
connection: {
|
|
47
|
+
filename: isTest ? ':memory:' : './aiwaf.sqlite'
|
|
48
|
+
},
|
|
49
|
+
useNullAsDefault: true,
|
|
50
|
+
});
|
|
51
|
+
return instance;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// Properties that inspection and module tooling read; answering them must not connect.
|
|
55
|
+
const PASSIVE = new Set(['then', '__esModule', 'default', 'inspect', 'toJSON', 'constructor', 'prototype']);
|
|
56
|
+
|
|
57
|
+
// Calling db('table') runs this function; reading a property goes through the get trap below.
|
|
58
|
+
function aiwafDb(...args) {
|
|
59
|
+
return connect()(...args);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const db = new Proxy(aiwafDb, {
|
|
63
|
+
get(target, prop) {
|
|
64
|
+
if (prop === 'available') return available;
|
|
65
|
+
if (prop === 'SqliteUnavailableError') return SqliteUnavailableError;
|
|
66
|
+
if (typeof prop === 'symbol' || PASSIVE.has(prop)) return Reflect.get(target, prop);
|
|
67
|
+
const conn = connect();
|
|
68
|
+
const value = conn[prop];
|
|
69
|
+
return typeof value === 'function' ? value.bind(conn) : value;
|
|
9
70
|
},
|
|
10
|
-
|
|
11
|
-
});
|
|
71
|
+
has(_target, prop) {
|
|
72
|
+
try { return prop in connect(); } catch (_) { return false; }
|
|
73
|
+
}
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
/** Whether sqlite3 loads. False means the stores use their CSV files. */
|
|
77
|
+
function available() {
|
|
78
|
+
try {
|
|
79
|
+
connect();
|
|
80
|
+
return true;
|
|
81
|
+
} catch (err) {
|
|
82
|
+
if (err instanceof SqliteUnavailableError) return false;
|
|
83
|
+
throw err;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
module.exports = db;
|