jsql-neo 6.6.1 → 6.6.3
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 +21 -1
- package/bin/jsql +14 -0
- package/index.js +1 -1
- package/lib/cache.js +3 -0
- package/lib/client.js +4 -0
- package/lib/mysql_server.js +8 -3
- package/lib/nedb_compat.js +8 -2
- package/lib/network-policy.js +42 -0
- package/lib/pg_server.js +16 -2
- package/lib/sql.js +93 -21
- package/lib/sqlite_compat.js +7 -1
- package/lib/star-nag.js +31 -15
- package/lib/updater.js +47 -8
- package/lib/web_ui.js +1 -0
- package/package.json +3 -3
- package/postinstall.js +17 -1
- package/src/cli/plugin.js +13 -0
- package/test/issue-86-99.test.js +154 -0
- package/test/network-policy.test.js +120 -0
package/README.md
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
> **One engine to rule them all** — a Rust-powered embedded database that speaks your language:
|
|
4
4
|
> MySQL, PostgreSQL, MongoDB, Redis, SQL, TypeScript, **and the browser**.
|
|
5
5
|
|
|
6
|
-
> **v6.6.
|
|
6
|
+
> **v6.6.3** — stable release · [github.com/vexify-org/JSQL-neo](https://github.com/vexify-org/JSQL-neo) · [jsql.vexify.top](https://jsql.vexify.top)
|
|
7
7
|
|
|
8
8
|

|
|
9
9
|

|
|
@@ -223,6 +223,26 @@ db.xqlIndex('users', 'score', 'range');
|
|
|
223
223
|
|
|
224
224
|
---
|
|
225
225
|
|
|
226
|
+
## Network access
|
|
227
|
+
|
|
228
|
+
The **CLI startup path makes no network requests at all** — queries, scripts and
|
|
229
|
+
`jsql serve` are entirely local. External access is confined to commands you
|
|
230
|
+
invoke explicitly, and every such site carries a `NETWORK:` comment in the
|
|
231
|
+
source stating why it cannot be done locally:
|
|
232
|
+
|
|
233
|
+
| Command / timing | Target | Why it needs the network | How to disable |
|
|
234
|
+
| --- | --- | --- | --- |
|
|
235
|
+
| `jsql star` | `auth.vexify.top` + GitHub | OAuth authorization has to go through the server | `JSQL_OFFLINE=1` |
|
|
236
|
+
| `jsql star --token-check` | `api.github.com` | star status only exists on the GitHub account | `JSQL_OFFLINE=1` |
|
|
237
|
+
| `jsql update` | `registry.npmjs.org` | "is there a newer version" only exists in the registry | `JSQL_OFFLINE=1` |
|
|
238
|
+
| `jsql plugin list\|search\|info\|install` | `registry-beta.vexify.top` | the plugin catalogue only exists remotely | `JSQL_OFFLINE=1` |
|
|
239
|
+
| `npm install` (postinstall) | GitHub releases | the precompiled Rust `.node` is not in the npm tarball | `JSQL_NO_NATIVE_DOWNLOAD=1` or `JSQL_OFFLINE=1` |
|
|
240
|
+
|
|
241
|
+
`JSQL_OFFLINE=1` disables every external request at once; affected commands
|
|
242
|
+
report the reason instead of failing silently. Loopback traffic (the
|
|
243
|
+
`127.0.0.1` links between `jsql serve` and the client / Web UI) is not
|
|
244
|
+
external access and is unaffected.
|
|
245
|
+
|
|
226
246
|
## 📖 Documentation
|
|
227
247
|
|
|
228
248
|
Detailed docs live in `doc/` — click to read.
|
package/bin/jsql
CHANGED
|
@@ -319,9 +319,23 @@ const cli = (yaggs || require('./yaggs-fallback').buildYaggsFallback(_pkg))({
|
|
|
319
319
|
})
|
|
320
320
|
.command('star', 'Confirm whether you starred this repo (opens browser once)', (sub) => {
|
|
321
321
|
sub.option('reset', { type: 'boolean', description: 'Forget the saved star state and re-check' });
|
|
322
|
+
sub.option('token-check', { type: 'boolean', description: 'Check via GitHub API using GITHUB_TOKEN/gh (no browser)' });
|
|
322
323
|
}, async (argv) => {
|
|
323
324
|
const sn = require('../lib/star-nag');
|
|
325
|
+
const { isOffline } = require('../lib/network-policy');
|
|
326
|
+
if (isOffline()) {
|
|
327
|
+
console.log('离线模式(JSQL_OFFLINE=1):无法确认 star。取消该环境变量后重试。');
|
|
328
|
+
return;
|
|
329
|
+
}
|
|
324
330
|
if (argv.reset) sn.setStarred(false);
|
|
331
|
+
// 显式选择的联网路径:用 token 直接查 GitHub API,不开浏览器。
|
|
332
|
+
// 启动路径不会走到这里(nag() 已完全本地化)。
|
|
333
|
+
if (argv['token-check']) {
|
|
334
|
+
const s = sn.checkStarred();
|
|
335
|
+
if (s === true) { sn.setStarred(true); console.log('已确认 star ✓(via GitHub API)'); }
|
|
336
|
+
else console.log('未能确认(无凭据 / 未 star / 网络不通)。去掉 --token-check 可走浏览器授权。');
|
|
337
|
+
return;
|
|
338
|
+
}
|
|
325
339
|
const c = sn.readConfig();
|
|
326
340
|
if (c.starred) {
|
|
327
341
|
console.log(`Already confirmed starred 已确认过: ${sn.configPath()}`);
|
package/index.js
CHANGED
package/lib/cache.js
CHANGED
|
@@ -187,6 +187,9 @@ class Cache {
|
|
|
187
187
|
if (start < 0) start = Math.max(list.length + start, 0);
|
|
188
188
|
if (stop < 0) stop = list.length + stop;
|
|
189
189
|
stop = Math.min(stop, list.length - 1);
|
|
190
|
+
// #89:stop 越界到负数也要钳到 0(与 Redis 一致)。
|
|
191
|
+
// 此前 stop 只有上限钳制,负数越界后 start > stop → 错误返回 []。
|
|
192
|
+
stop = Math.max(stop, 0);
|
|
190
193
|
if (start > stop) return [];
|
|
191
194
|
return list.slice(start, stop + 1);
|
|
192
195
|
}
|
package/lib/client.js
CHANGED
|
@@ -9,6 +9,10 @@ function binPath() {
|
|
|
9
9
|
return path.join(dir, name);
|
|
10
10
|
}
|
|
11
11
|
|
|
12
|
+
/* LOCAL-ONLY: 这个客户端默认只连 127.0.0.1:3000 的本机 server
|
|
13
|
+
* (下面的 http.get / http.request 都是同机回环,不是外部网络)。
|
|
14
|
+
* 例外:调用方显式传 opts.host 指向别的机器时才会出网 —— 那是用户
|
|
15
|
+
* 主动配置的远程模式,由调用方负责。 */
|
|
12
16
|
class JSQL {
|
|
13
17
|
constructor(opts = {}) {
|
|
14
18
|
this.host = opts.host || '127.0.0.1';
|
package/lib/mysql_server.js
CHANGED
|
@@ -595,7 +595,9 @@ class MysqlConnection {
|
|
|
595
595
|
this._send(encodeLenenc(1));
|
|
596
596
|
this._send(columnDefinition({ name: 'Id', type: MYSQL_TYPE_LONG }));
|
|
597
597
|
this._send(eofPacket());
|
|
598
|
-
|
|
598
|
+
// #95:结果行字段必须是 length-encoded string。
|
|
599
|
+
// 此前直接发裸字节 0x31('1'),客户端把它当字段长度读后续 49 字节 → 协议失步。
|
|
600
|
+
this._send(encodeLenencString('1'));
|
|
599
601
|
this._send(eofPacket());
|
|
600
602
|
break;
|
|
601
603
|
}
|
|
@@ -1108,10 +1110,13 @@ class MysqlServer {
|
|
|
1108
1110
|
if (!this._dbExists(db)) await this.createDatabase(db);
|
|
1109
1111
|
const engine = await this._getDatabase(db);
|
|
1110
1112
|
let s = sql;
|
|
1111
|
-
// 词法扫描:找出所有字符串字面量和注释的位置,替换时跳过它们
|
|
1112
|
-
const masked = _maskStringsAndComments(s);
|
|
1113
1113
|
for (const t of tables) {
|
|
1114
1114
|
if (t && t.indexOf('.') !== -1) {
|
|
1115
|
+
// #97:每次 s.replace 都会缩短 s(剥掉 db. 前缀),但 offset 是相对当前 s 的。
|
|
1116
|
+
// 此前 masked 只基于最初始的完整 s 算一次,后续 replace 的 offset 相对 masked
|
|
1117
|
+
// 整体"提前",掩码守卫误判 → ≥2 个 db.table 时改写错位(错库/错表)。
|
|
1118
|
+
// 所以每次替换前必须基于**当前 s** 重算掩码,保证 offset 对齐。
|
|
1119
|
+
const masked = _maskStringsAndComments(s);
|
|
1115
1120
|
const re = new RegExp('\\b' + t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '\\b', 'g');
|
|
1116
1121
|
s = s.replace(re, (match, offset) => {
|
|
1117
1122
|
// 如果匹配位置在字符串字面量或注释中,不替换。
|
package/lib/nedb_compat.js
CHANGED
|
@@ -77,8 +77,14 @@ function matchOperator(value, op, expected) {
|
|
|
77
77
|
case '$in': return Array.isArray(expected) && expected.some(e => looseEqual(value, e));
|
|
78
78
|
case '$nin': return Array.isArray(expected) && !expected.some(e => looseEqual(value, e));
|
|
79
79
|
case '$exists': return expected ? value !== undefined : value === undefined;
|
|
80
|
-
case '$regex':
|
|
81
|
-
|
|
80
|
+
case '$regex': {
|
|
81
|
+
// #88:$regex 用字符串模式('a')时直接用字符串作正则源,不能取 .source
|
|
82
|
+
// (只有 RegExp 才有 .source)。此前 new RegExp(undefined) = /(?:)/ 匹配一切,
|
|
83
|
+
// 导致 find({ $regex: 'a' }) 返回全表。
|
|
84
|
+
const src = typeof expected === 'string' ? expected : (expected && expected.source);
|
|
85
|
+
const flags = (expected && expected.flags) || 'i';
|
|
86
|
+
return typeof value === 'string' && new RegExp(src, flags).test(value);
|
|
87
|
+
}
|
|
82
88
|
case '$size': return Array.isArray(value) && value.length === expected;
|
|
83
89
|
default: return false;
|
|
84
90
|
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/**
|
|
3
|
+
* 统一的网络访问策略 —— 「默认不出网,必须出网的地方写明原因」。
|
|
4
|
+
*
|
|
5
|
+
* 约定:仓库里任何会真正访问**外部网络**的位置,都要在紧邻处写一段
|
|
6
|
+
* `NETWORK:` 注释,四行说清楚:
|
|
7
|
+
*
|
|
8
|
+
* Why: 为什么非联网不可(本地为什么做不到)
|
|
9
|
+
* Trigger: 什么操作才会触发(必须能由用户主动预期)
|
|
10
|
+
* Offline: JSQL_OFFLINE=1 时的行为
|
|
11
|
+
* Scope: 访问的目标主机 / 数据
|
|
12
|
+
*
|
|
13
|
+
* 只连 127.0.0.1 / localhost 的本地回环(各 * _server.js、client.js、
|
|
14
|
+
* web_ui 的同源 fetch)不算外部网络,写 `LOCAL-ONLY:` 一句即可。
|
|
15
|
+
*
|
|
16
|
+
* 环境变量:
|
|
17
|
+
* JSQL_OFFLINE=1|true|yes|on 一键禁用所有外部网络访问。
|
|
18
|
+
* 已有的专用开关(JSQL_NO_NATIVE_DOWNLOAD / JSQL_NATIVE_DOWNLOAD=0 /
|
|
19
|
+
* JSQL_NATIVE_FORCE_REFRESH=0 / JSQL_NO_STAR_NAG=1)继续有效。
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
const TRUTHY = /^(1|true|yes|on)$/i;
|
|
23
|
+
|
|
24
|
+
/** 当前进程是否处于离线模式。 */
|
|
25
|
+
function isOffline() {
|
|
26
|
+
return TRUTHY.test(String(process.env.JSQL_OFFLINE || ''));
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* 构造一个可读的离线错误。带 code,方便调用方区分「用户主动离线」和
|
|
31
|
+
* 「网络真的不通」—— 这两者不该给用户同一句报错。
|
|
32
|
+
*/
|
|
33
|
+
function offlineError(feature, why) {
|
|
34
|
+
const err = new Error(
|
|
35
|
+
`${feature} 需要联网(${why})。当前 JSQL_OFFLINE=1,已跳过;` +
|
|
36
|
+
'取消该环境变量即可恢复。'
|
|
37
|
+
);
|
|
38
|
+
err.code = 'JSQL_OFFLINE';
|
|
39
|
+
return err;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
module.exports = { isOffline, offlineError, TRUTHY };
|
package/lib/pg_server.js
CHANGED
|
@@ -206,6 +206,17 @@ function buildParameterDesc(paramTypes) {
|
|
|
206
206
|
return frame(0x74, p.build()); // 't'
|
|
207
207
|
}
|
|
208
208
|
|
|
209
|
+
// #93:PG 二进制参数解码。Bind 的 parameter format code=1 时按参数类型(OID)解码,
|
|
210
|
+
// 不能按 UTF-8 文本读。常见 OID:int4=23, int8=20, float8=701, float4=700, bool=16。
|
|
211
|
+
function decodeBinaryParam(buf, typeOid) {
|
|
212
|
+
if (typeOid === 23) return buf.length >= 4 ? buf.readInt32BE(0) : null; // int4
|
|
213
|
+
if (typeOid === 20) return buf.length >= 8 ? buf.readBigInt64BE(0) : null; // int8
|
|
214
|
+
if (typeOid === 701) return buf.length >= 8 ? buf.readDoubleBE(0) : null; // float8
|
|
215
|
+
if (typeOid === 700) return buf.length >= 4 ? buf.readFloatBE(0) : null; // float4
|
|
216
|
+
if (typeOid === 16) return buf.length >= 1 ? buf[0] !== 0 : null; // bool
|
|
217
|
+
return buf.toString('utf8');
|
|
218
|
+
}
|
|
219
|
+
|
|
209
220
|
// ---------------------------------------------------------------------------
|
|
210
221
|
// SCRAM-SHA-256 (RFC 5802 / RFC 7677) — server side
|
|
211
222
|
// ---------------------------------------------------------------------------
|
|
@@ -520,7 +531,10 @@ class PgConnection {
|
|
|
520
531
|
if (vlen === -1) { values.push(null); continue; }
|
|
521
532
|
if (vlen < 0 || off + vlen > body.length) throw new Error('invalid Bind parameter length');
|
|
522
533
|
const fmt = formats.length > 0 ? formats[Math.min(i, formats.length - 1)] : 0;
|
|
523
|
-
|
|
534
|
+
// #93:fmt=1(binary)时按参数类型解码,此前一律按 UTF-8 文本读导致二进制参数错乱。
|
|
535
|
+
const pt = (stmt.paramTypes && stmt.paramTypes[i]) || 0;
|
|
536
|
+
const raw = body.slice(off, off + vlen);
|
|
537
|
+
values.push(fmt === 1 ? decodeBinaryParam(raw, pt) : body.toString('utf8', off, off + vlen));
|
|
524
538
|
off += vlen;
|
|
525
539
|
}
|
|
526
540
|
this._portal.set(portal, { values, stmt });
|
|
@@ -881,4 +895,4 @@ function createPgServer(options) {
|
|
|
881
895
|
return new PgServer(options || {});
|
|
882
896
|
}
|
|
883
897
|
|
|
884
|
-
module.exports = { PgServer, createPgServer, PgConnection, buildRowDescription, buildDataRow, buildCommandComplete, buildErrorResponse, buildReadyForQuery, buildParameterStatus, buildBackendKeyData, buildParseComplete, buildBindComplete, buildCloseComplete, buildNoData, buildParameterDesc, TYPE_OIDS, pgTypeOid, pgFormatValue };
|
|
898
|
+
module.exports = { PgServer, createPgServer, PgConnection, buildRowDescription, buildDataRow, buildCommandComplete, buildErrorResponse, buildReadyForQuery, buildParameterStatus, buildBackendKeyData, buildParseComplete, buildBindComplete, buildCloseComplete, buildNoData, buildParameterDesc, decodeBinaryParam, TYPE_OIDS, pgTypeOid, pgFormatValue };
|
package/lib/sql.js
CHANGED
|
@@ -1248,7 +1248,10 @@ class Parser {
|
|
|
1248
1248
|
while (true) {
|
|
1249
1249
|
const col = this.parseTableName();
|
|
1250
1250
|
this.expect('op', '=');
|
|
1251
|
-
|
|
1251
|
+
// #99:ON DUPLICATE KEY UPDATE 赋值右侧的裸标识符(如 other=other)是**列引用**,
|
|
1252
|
+
// 不是字符串字面量(MySQL 语义:自赋值是合法 no-op)。
|
|
1253
|
+
// 传 identAsColumn=true 让 parseValue 把裸 ident 解析成 {type:'column'}。
|
|
1254
|
+
const val = this.parseValue(true);
|
|
1252
1255
|
onDuplicate.push([col, val]);
|
|
1253
1256
|
if (this.peek().value === ',') { this.next(); continue; }
|
|
1254
1257
|
break;
|
|
@@ -1283,8 +1286,8 @@ class Parser {
|
|
|
1283
1286
|
return cols;
|
|
1284
1287
|
}
|
|
1285
1288
|
|
|
1286
|
-
parseValue() {
|
|
1287
|
-
const atom = this.parseValueAtom();
|
|
1289
|
+
parseValue(identAsColumn = false) {
|
|
1290
|
+
const atom = this.parseValueAtom(identAsColumn);
|
|
1288
1291
|
return this.parseBinaryFromAtom(atom);
|
|
1289
1292
|
}
|
|
1290
1293
|
|
|
@@ -1301,7 +1304,7 @@ class Parser {
|
|
|
1301
1304
|
return left;
|
|
1302
1305
|
}
|
|
1303
1306
|
|
|
1304
|
-
parseValueAtom() {
|
|
1307
|
+
parseValueAtom(identAsColumn = false) {
|
|
1305
1308
|
// MySQL 前缀运算符:BINARY expr —— 强制大小写敏感比较。
|
|
1306
1309
|
// 仅当后面确实是值起始 token 才当作运算符,避免误吞裸列名 `binary`
|
|
1307
1310
|
// (`SELECT binary FROM t` / `WHERE binary = 1` 仍按列名解析)。
|
|
@@ -1348,9 +1351,11 @@ class Parser {
|
|
|
1348
1351
|
this.next();
|
|
1349
1352
|
const col = this.next();
|
|
1350
1353
|
if (!isUsableNameToken(col)) throw new Error(`Expected column name after '.', got '${col.value}'`);
|
|
1351
|
-
|
|
1354
|
+
const full = nameOfToken(t) + '.' + nameOfToken(col);
|
|
1355
|
+
return identAsColumn ? { type: 'column', name: full } : full;
|
|
1352
1356
|
}
|
|
1353
|
-
|
|
1357
|
+
// #99:ON DUPLICATE 赋值右侧裸标识符 → 列引用节点
|
|
1358
|
+
return identAsColumn ? { type: 'column', name: nameOfToken(t) } : nameOfToken(t);
|
|
1354
1359
|
}
|
|
1355
1360
|
throw new Error(`Expected value, got '${t.value}'`);
|
|
1356
1361
|
}
|
|
@@ -3257,10 +3262,25 @@ function applyCast(value, dataType) {
|
|
|
3257
3262
|
}
|
|
3258
3263
|
return n;
|
|
3259
3264
|
}
|
|
3260
|
-
if (t === 'FLOAT' || t === 'DOUBLE' || t === 'REAL'
|
|
3265
|
+
if (t === 'FLOAT' || t === 'DOUBLE' || t === 'REAL') {
|
|
3261
3266
|
const n = Number(value);
|
|
3262
3267
|
return Number.isFinite(n) ? n : null;
|
|
3263
3268
|
}
|
|
3269
|
+
if (t === 'NUMERIC' || t === 'DECIMAL') {
|
|
3270
|
+
// #96:CAST(x AS DECIMAL(p,s)) 必须按标度 s 四舍五入,不能原样返回。
|
|
3271
|
+
// 此前 DECIMAL 被并入 FLOAT 分支,p/s 被剥掉后原值返回(123.456 → 123.456)。
|
|
3272
|
+
const m = String(dataType).match(/\((\d+)(?:,(\d+))?\)/i);
|
|
3273
|
+
const scale = m && m[2] !== undefined ? parseInt(m[2], 10) : 0;
|
|
3274
|
+
let n = Number(value);
|
|
3275
|
+
if (!Number.isFinite(n)) return null;
|
|
3276
|
+
if (scale > 0) {
|
|
3277
|
+
const factor = Math.pow(10, scale);
|
|
3278
|
+
n = Math.round(n * factor) / factor;
|
|
3279
|
+
} else {
|
|
3280
|
+
n = Math.round(n);
|
|
3281
|
+
}
|
|
3282
|
+
return n;
|
|
3283
|
+
}
|
|
3264
3284
|
if (t === 'BOOLEAN' || t === 'BOOL') {
|
|
3265
3285
|
if (typeof value === 'boolean') return value;
|
|
3266
3286
|
if (typeof value === 'number') return value !== 0;
|
|
@@ -4882,7 +4902,10 @@ function seedRand(seed) {
|
|
|
4882
4902
|
// ci 默认 true:保持 LIKE 既有的大小写不敏感行为不变;ILIKE 同为不敏感。
|
|
4883
4903
|
// escape:可选转义符(ESCAPE 子句),默认反斜杠;转义符后跟 % _ 或转义符本身按字面量匹配。
|
|
4884
4904
|
function likeMatch(value, pattern, ci = true, escape = '\\') {
|
|
4885
|
-
|
|
4905
|
+
// #94:NULL LIKE ... → UNKNOWN(null),不能当 false。
|
|
4906
|
+
if (value === null || value === undefined) return null;
|
|
4907
|
+
// #94:MySQL 语义——数值列(及其他类型)先转成字符串再 LIKE(10 LIKE '1%' → '10' LIKE '1%' → true)。
|
|
4908
|
+
const sv = String(value);
|
|
4886
4909
|
const p = String(pattern);
|
|
4887
4910
|
const e = (escape === null || escape === undefined || escape === '') ? '\\' : String(escape);
|
|
4888
4911
|
const reEsc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
@@ -4898,7 +4921,7 @@ function likeMatch(value, pattern, ci = true, escape = '\\') {
|
|
|
4898
4921
|
else if (ch === '_') out += '.';
|
|
4899
4922
|
else out += reEsc(ch);
|
|
4900
4923
|
}
|
|
4901
|
-
return new RegExp('^' + out + '$', ci ? 'i' : '').test(
|
|
4924
|
+
return new RegExp('^' + out + '$', ci ? 'i' : '').test(sv);
|
|
4902
4925
|
}
|
|
4903
4926
|
|
|
4904
4927
|
/** 解析 PG 的路径字面量:'{a,b}' 或数组 → ['a','b'] */
|
|
@@ -5122,6 +5145,23 @@ function sqlXor(a, b) {
|
|
|
5122
5145
|
return a !== b ? 1 : 0;
|
|
5123
5146
|
}
|
|
5124
5147
|
|
|
5148
|
+
// #86:递归把表达式 AST 里的 VALUES(col)/EXCLUDED.col 节点替换成目标行 d 的对应列值。
|
|
5149
|
+
// ON DUPLICATE KEY UPDATE 里 VALUES(col) 引用"本次本应插入的值"(新行 d),
|
|
5150
|
+
// 求值前必须先替换,否则 evaluateExpr/resolveOperand 不认识 _valuesOf 节点。
|
|
5151
|
+
function substituteValuesOf(node, d) {
|
|
5152
|
+
if (node && typeof node === 'object') {
|
|
5153
|
+
if (node._valuesOf !== undefined || node._excludedOf !== undefined) {
|
|
5154
|
+
const col = node._valuesOf !== undefined ? node._valuesOf : node._excludedOf;
|
|
5155
|
+
return (d && d[col] !== undefined) ? d[col] : null;
|
|
5156
|
+
}
|
|
5157
|
+
if (Array.isArray(node)) return node.map(n => substituteValuesOf(n, d));
|
|
5158
|
+
const out = {};
|
|
5159
|
+
for (const k of Object.keys(node)) out[k] = substituteValuesOf(node[k], d);
|
|
5160
|
+
return out;
|
|
5161
|
+
}
|
|
5162
|
+
return node;
|
|
5163
|
+
}
|
|
5164
|
+
|
|
5125
5165
|
function evaluateExpr(expr, row, ctx) {
|
|
5126
5166
|
if (expr === null || expr === undefined) return false;
|
|
5127
5167
|
switch (expr.type) {
|
|
@@ -5263,6 +5303,8 @@ function evaluateExpr(expr, row, ctx) {
|
|
|
5263
5303
|
// MySQL 的 LIKE 默认不区分大小写;只有显式 BINARY / ci=false 才敏感。
|
|
5264
5304
|
// 此前写成 !!expr.ci,把 likeMatch 的 ci 默认值 true 覆盖成了 false。
|
|
5265
5305
|
const r = likeMatch(v, expr.pattern, expr.ci !== false, expr.escape);
|
|
5306
|
+
// #94:NULL LIKE → UNKNOWN(null);NOT (NULL LIKE) 仍为 UNKNOWN(null)。
|
|
5307
|
+
if (r === null) return null;
|
|
5266
5308
|
return expr.not ? !r : r;
|
|
5267
5309
|
}
|
|
5268
5310
|
case 'quantified':
|
|
@@ -5907,7 +5949,16 @@ class SQLExecutor {
|
|
|
5907
5949
|
const evalRow = existingRow
|
|
5908
5950
|
? Object.fromEntries([...Object.entries(d), ...Object.entries(existingRow)])
|
|
5909
5951
|
: d;
|
|
5910
|
-
|
|
5952
|
+
// #86:把表达式里的 VALUES(col)/EXCLUDED.col 解析成"本次本应插入的值"(d),
|
|
5953
|
+
// 否则 evaluateExpr 不认识 _valuesOf 节点 → undefined + 1 → NULL(数据损坏)。
|
|
5954
|
+
data[col] = evaluateExpr(substituteValuesOf(val, d), evalRow, this.ctx);
|
|
5955
|
+
} else if (val && typeof val === 'object' && val.type === 'column') {
|
|
5956
|
+
// #99:裸列名(other=other)按旧行值求值(合法 no-op),不当字符串字面量。
|
|
5957
|
+
// 此前解析成 'other' 赋给 INT 列 → 1292 崩溃。
|
|
5958
|
+
const evalRow = existingRow
|
|
5959
|
+
? Object.fromEntries([...Object.entries(d), ...Object.entries(existingRow)])
|
|
5960
|
+
: d;
|
|
5961
|
+
data[col] = evalRow[val.name] !== undefined ? evalRow[val.name] : d[val.name];
|
|
5911
5962
|
} else {
|
|
5912
5963
|
data[col] = val;
|
|
5913
5964
|
}
|
|
@@ -7000,9 +7051,10 @@ class SQLExecutor {
|
|
|
7000
7051
|
const vs = values.filter(v => v !== null && v !== undefined);
|
|
7001
7052
|
if (!vs.length) return null;
|
|
7002
7053
|
// 数值按数值比;字符串/日期按字典序/时间序。
|
|
7003
|
-
//
|
|
7004
|
-
|
|
7005
|
-
|
|
7054
|
+
// #98:只有**真正的 number** 才按数值比较。全数字字符串列('2','100','9')
|
|
7055
|
+
// 此前被误判为数值 → MIN/MAX 用数值比较且返回 Number,与 ORDER BY 字典序自相矛盾。
|
|
7056
|
+
// MySQL 语义:字符串列一律字典序且结果保持字符串。
|
|
7057
|
+
const numeric = (v) => typeof v === 'number';
|
|
7006
7058
|
if (vs.every(numeric)) {
|
|
7007
7059
|
let best = Number(vs[0]);
|
|
7008
7060
|
for (let i = 1; i < vs.length; i++) {
|
|
@@ -8970,7 +9022,9 @@ function applyParams(sql, values) {
|
|
|
8970
9022
|
const args = values || [];
|
|
8971
9023
|
let count = 0;
|
|
8972
9024
|
let out = '';
|
|
8973
|
-
let idx = 0;
|
|
9025
|
+
let idx = 0; // 匿名 ? 的"下一个未占用槽"游标
|
|
9026
|
+
const used = new Set(); // 已被编号占位符 ?N/$N 占用的参数槽
|
|
9027
|
+
let hasIndexed = false; // 是否出现过编号占位符(混用时 Too many 检查会误判)
|
|
8974
9028
|
let inStr = null;
|
|
8975
9029
|
let i = 0;
|
|
8976
9030
|
const named = {};
|
|
@@ -8979,6 +9033,8 @@ function applyParams(sql, values) {
|
|
|
8979
9033
|
hasNamed = true;
|
|
8980
9034
|
}
|
|
8981
9035
|
const n = sql.length;
|
|
9036
|
+
// #92:匿名 ? 按顺序消费"尚未被编号占位符占用"的最小槽,避免编号 ?N 劫持游标。
|
|
9037
|
+
const nextFree = () => { while (used.has(idx)) idx++; return idx; };
|
|
8982
9038
|
while (i < n) {
|
|
8983
9039
|
const c = sql[i];
|
|
8984
9040
|
if (inStr) {
|
|
@@ -9007,8 +9063,14 @@ function applyParams(sql, values) {
|
|
|
9007
9063
|
continue;
|
|
9008
9064
|
}
|
|
9009
9065
|
if (c === '?' && sql[i + 1] === '?') {
|
|
9010
|
-
if (
|
|
9011
|
-
|
|
9066
|
+
if (hasNamed) { out += escapeId(args['@@']); }
|
|
9067
|
+
else {
|
|
9068
|
+
const k = nextFree();
|
|
9069
|
+
if (k >= args.length) throw new Error('Not enough parameters for SQL: expected ' + (count + 1));
|
|
9070
|
+
out += escapeId(args[k]);
|
|
9071
|
+
used.add(k);
|
|
9072
|
+
idx++;
|
|
9073
|
+
}
|
|
9012
9074
|
count++;
|
|
9013
9075
|
i += 2;
|
|
9014
9076
|
continue;
|
|
@@ -9026,14 +9088,21 @@ function applyParams(sql, values) {
|
|
|
9026
9088
|
} else {
|
|
9027
9089
|
if (n - 1 >= args.length) throw new Error(`Not enough parameters for SQL: expected ?${n}`);
|
|
9028
9090
|
out += escapeValue(args[n - 1]);
|
|
9029
|
-
|
|
9091
|
+
used.add(n - 1);
|
|
9092
|
+
hasIndexed = true;
|
|
9030
9093
|
}
|
|
9031
9094
|
count++;
|
|
9032
9095
|
i = j;
|
|
9033
9096
|
continue;
|
|
9034
9097
|
}
|
|
9035
|
-
if (
|
|
9036
|
-
|
|
9098
|
+
if (hasNamed) { out += escapeValue(args['?']); }
|
|
9099
|
+
else {
|
|
9100
|
+
const k = nextFree();
|
|
9101
|
+
if (k >= args.length) throw new Error('Not enough parameters for SQL: expected ' + (count + 1));
|
|
9102
|
+
out += escapeValue(args[k]);
|
|
9103
|
+
used.add(k);
|
|
9104
|
+
idx++;
|
|
9105
|
+
}
|
|
9037
9106
|
count++;
|
|
9038
9107
|
i++;
|
|
9039
9108
|
continue;
|
|
@@ -9065,7 +9134,8 @@ function applyParams(sql, values) {
|
|
|
9065
9134
|
} else {
|
|
9066
9135
|
if (n - 1 >= args.length) throw new Error(`Not enough parameters for SQL: expected $${n}`);
|
|
9067
9136
|
out += escapeValue(args[n - 1]);
|
|
9068
|
-
|
|
9137
|
+
used.add(n - 1);
|
|
9138
|
+
hasIndexed = true;
|
|
9069
9139
|
}
|
|
9070
9140
|
count++;
|
|
9071
9141
|
i = j;
|
|
@@ -9086,7 +9156,9 @@ function applyParams(sql, values) {
|
|
|
9086
9156
|
out += c;
|
|
9087
9157
|
i++;
|
|
9088
9158
|
}
|
|
9089
|
-
|
|
9159
|
+
// #92:混用编号占位符 ?N/$N 时,idx(匿名游标)与 args.length 的"恰好相等"判断
|
|
9160
|
+
// 不可靠(编号占位符会占用任意槽),会误报 Too many。纯匿名场景保留严格检查。
|
|
9161
|
+
if (!hasNamed && !hasIndexed && idx !== args.length) {
|
|
9090
9162
|
throw new Error(`Too many parameters for SQL: got ${args.length}, expected ${count}`);
|
|
9091
9163
|
}
|
|
9092
9164
|
return out;
|
package/lib/sqlite_compat.js
CHANGED
|
@@ -296,7 +296,13 @@ class Statement {
|
|
|
296
296
|
|
|
297
297
|
all(...params) {
|
|
298
298
|
const r = this._call('all', params.length > 0 ? params : undefined);
|
|
299
|
-
|
|
299
|
+
// #87:raw() 只是输出格式开关(对象行 → 值数组),不能重新执行 SQL。
|
|
300
|
+
// 此前 .raw(true).all() 再调 _call('raw') 导致 INSERT/DELETE 重复执行(数据损坏)。
|
|
301
|
+
if (this._rawMode) {
|
|
302
|
+
return Array.isArray(r)
|
|
303
|
+
? r.map(row => (row && typeof row === 'object' && !Array.isArray(row)) ? Object.values(row) : row)
|
|
304
|
+
: r;
|
|
305
|
+
}
|
|
300
306
|
if (this._pluck) {
|
|
301
307
|
const cols = r && r.length > 0 ? Object.keys(r[0]) : [];
|
|
302
308
|
return cols.length > 0 ? r.map(row => row[cols[0]]) : [];
|
package/lib/star-nag.js
CHANGED
|
@@ -3,23 +3,25 @@
|
|
|
3
3
|
/**
|
|
4
4
|
* CLI 启动时的 star 提示。
|
|
5
5
|
*
|
|
6
|
-
*
|
|
6
|
+
* 行为(启动路径 **零网络访问**):
|
|
7
7
|
* 1. 已确认 star 过 → 什么都不说
|
|
8
|
-
* 2.
|
|
9
|
-
* 3. 否则打印一行提示,并在配置里记下时间
|
|
8
|
+
* 2. 否则打印一行提示,指向 `jsql star`
|
|
10
9
|
*
|
|
11
|
-
* star
|
|
12
|
-
*
|
|
13
|
-
*
|
|
10
|
+
* 是否 star 只以本地 ~/.jsqlmr 为准。此前这里会同步 curl
|
|
11
|
+
* api.github.com(仅为少印一行提示,却让每条 jsql 命令都可能偷偷出网
|
|
12
|
+
* 并阻塞最多 ~9.5 秒),现已移除。需要联网确认时由用户显式跑
|
|
13
|
+
* `jsql star`(OAuth)或 `jsql star --token-check`(GitHub API)。
|
|
14
14
|
*
|
|
15
15
|
* 配置文件:~/.jsqlmr(JSON)。可用 JSQL_MR_PATH 覆盖。
|
|
16
|
-
*
|
|
17
16
|
* 全程不影响命令本身:任何异常都吞掉,绝不因为提示语让 CLI 起不来。
|
|
17
|
+
*
|
|
18
|
+
* 外部网络访问只存在于显式命令路径,见各处 NETWORK: 标注。
|
|
18
19
|
*/
|
|
19
20
|
|
|
20
21
|
const fs = require('fs');
|
|
21
22
|
const os = require('os');
|
|
22
23
|
const path = require('path');
|
|
24
|
+
const { isOffline, offlineError } = require('./network-policy');
|
|
23
25
|
|
|
24
26
|
const REPO = 'vexify-org/JSQL-neo';
|
|
25
27
|
const URL = `https://github.com/${REPO}`;
|
|
@@ -54,7 +56,14 @@ function parseAuthResult(j) {
|
|
|
54
56
|
return { status: st, error: r.error || (st === 'denied' ? 'authorization denied' : 'authorization failed') };
|
|
55
57
|
}
|
|
56
58
|
|
|
59
|
+
/* NETWORK: OAuth 授权(star 确认)
|
|
60
|
+
* Why: 需要 GitHub 登录态与服务端换 token,本地无法完成。
|
|
61
|
+
* Trigger: 仅 `jsql star` 显式执行;启动路径不会走到这里。
|
|
62
|
+
* Offline: JSQL_OFFLINE=1 → 抛 JSQL_OFFLINE 错误,不开浏览器、不轮询。
|
|
63
|
+
* Scope: https://auth.vexify.top/start|result + GitHub 授权页。
|
|
64
|
+
*/
|
|
57
65
|
function startOauthCheck() {
|
|
66
|
+
if (isOffline()) throw offlineError('jsql star', 'OAuth 授权需要访问 GitHub');
|
|
58
67
|
const crypto = require('crypto');
|
|
59
68
|
const nonce = crypto.randomBytes(24).toString('base64url');
|
|
60
69
|
const url = AUTH_START + '?nonce=' + nonce;
|
|
@@ -150,7 +159,15 @@ function findToken() {
|
|
|
150
159
|
*
|
|
151
160
|
* @returns {boolean|null} true=star 过 false=没 star null=无法确认
|
|
152
161
|
*/
|
|
162
|
+
/* NETWORK: GitHub star 状态查询
|
|
163
|
+
* Why: star 状态只存在于 GitHub 账号侧,本地无法判定。
|
|
164
|
+
* Trigger: 仅显式调用(jsql star --token-check / 外部脚本);
|
|
165
|
+
* 已从 CLI 启动路径移除,nag() 不再调用它。
|
|
166
|
+
* Offline: JSQL_OFFLINE=1 → 返回 null(无法确认),不发起任何请求。
|
|
167
|
+
* Scope: https://api.github.com/user/starred/<repo>,带 Bearer token。
|
|
168
|
+
*/
|
|
153
169
|
function checkStarred() {
|
|
170
|
+
if (isOffline()) return null;
|
|
154
171
|
const token = findToken();
|
|
155
172
|
if (!token) return null; // 没有可用凭据 → 无法确认
|
|
156
173
|
// 用同步 API:CLI 启动阶段还没有 event loop 可用
|
|
@@ -199,14 +216,10 @@ function nag(opts = {}) {
|
|
|
199
216
|
// 已确认 star 过 → 永久闭嘴。jsqlmr 就是干这个的。
|
|
200
217
|
if (!opts.force && cfg.starred) return false;
|
|
201
218
|
|
|
202
|
-
//
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
cfg.starredAt = Date.now();
|
|
207
|
-
writeConfig(cfg);
|
|
208
|
-
return false;
|
|
209
|
-
}
|
|
219
|
+
// LOCAL-ONLY: 启动路径绝不联网,只按上面的本地配置判定。
|
|
220
|
+
// 不调用 checkStarred()(同步 curl api.github.com,最多 ~9.5s)——
|
|
221
|
+
// 为了少印一行提示而让每条命令偷偷出网,代价不对等。
|
|
222
|
+
// 用户需要确认时显式跑 `jsql star`。
|
|
210
223
|
|
|
211
224
|
out.write(`\n If JSQL-NEO saved you time, a star helps others find it: ${URL}\n`);
|
|
212
225
|
out.write(` 如果帮到了你,点个 star;运行 \`jsql star\` 确认 · JSQL_NO_STAR_NAG=1 关闭提示\n\n`);
|
|
@@ -249,7 +262,10 @@ function setStarred(v) {
|
|
|
249
262
|
* parseAuthResult 一律判为未完成,继续轮询直到超时,而不是打印一段
|
|
250
263
|
* login/repo 全为 undefined 的假失败信息。
|
|
251
264
|
*/
|
|
265
|
+
/* NETWORK: OAuth 结果轮询(同 startOauthCheck 的 NETWORK 标注);
|
|
266
|
+
* 仅由 `jsql star` 前台等待时调用,离线时直接返回 null。 */
|
|
252
267
|
function waitForResult(startUrl, timeoutMs = 180000) {
|
|
268
|
+
if (isOffline()) return null;
|
|
253
269
|
const { execFileSync } = require('child_process');
|
|
254
270
|
// 注意:本模块顶部有 const URL = 'https://github.com/...' 会遮蔽全局 URL 类,
|
|
255
271
|
// 必须显式从 url 模块取,否则 new URL(...) 抛 TypeError
|
package/lib/updater.js
CHANGED
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
const path = require('path');
|
|
16
16
|
const https = require('https');
|
|
17
17
|
const { execFileSync, spawnSync } = require('child_process');
|
|
18
|
+
const { isOffline } = require('./network-policy');
|
|
18
19
|
|
|
19
20
|
const PKG_NAME = 'jsql-neo';
|
|
20
21
|
const REGISTRY_LATEST = `https://registry.npmjs.org/${PKG_NAME}/latest`;
|
|
@@ -44,21 +45,46 @@ function parseVersion(v) {
|
|
|
44
45
|
const x = parseInt(n, 10);
|
|
45
46
|
return Number.isFinite(x) ? x : 0;
|
|
46
47
|
});
|
|
47
|
-
while (nums.length < 3) nums.push(0);
|
|
48
48
|
return { nums, pre };
|
|
49
49
|
}
|
|
50
50
|
|
|
51
|
-
|
|
51
|
+
// #90:prerelease 标识符按 semver 规则比较:数字标识符按数值、字母按字典序、
|
|
52
|
+
// 数字 > 字母、长度长者大。此前用 A.pre > B.pre 字符串比较,'alpha.10' < 'alpha.9' 误判。
|
|
53
|
+
function comparePre(a, b) {
|
|
54
|
+
if (a === b) return 0;
|
|
55
|
+
if (!a) return 1; // 无 prerelease > 有 prerelease
|
|
56
|
+
if (!b) return -1;
|
|
57
|
+
const A = a.split('.');
|
|
58
|
+
const B = b.split('.');
|
|
59
|
+
const len = Math.max(A.length, B.length);
|
|
60
|
+
for (let i = 0; i < len; i++) {
|
|
61
|
+
const x = A[i], y = B[i];
|
|
62
|
+
if (x === undefined) return -1;
|
|
63
|
+
if (y === undefined) return 1;
|
|
64
|
+
const xn = /^\d+$/.test(x), yn = /^\d+$/.test(y);
|
|
65
|
+
if (xn && yn) {
|
|
66
|
+
const xi = parseInt(x, 10), yi = parseInt(y, 10);
|
|
67
|
+
if (xi !== yi) return xi > yi ? 1 : -1;
|
|
68
|
+
} else if (xn !== yn) {
|
|
69
|
+
return xn ? 1 : -1; // 数字标识符 > 字母标识符
|
|
70
|
+
} else if (x !== y) {
|
|
71
|
+
return x > y ? 1 : -1;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return 0;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** semver-ish 比较:a < b → -1,相等 → 0,a > b → 1(prerelease 视为更低)。
|
|
78
|
+
* #90:支持 4+ 段版本号(此前截断为 3 段,1.2.3.4 与 1.2.3 被误判相等)。 */
|
|
52
79
|
function compareVersions(a, b) {
|
|
53
80
|
const A = parseVersion(a);
|
|
54
81
|
const B = parseVersion(b);
|
|
55
|
-
|
|
56
|
-
|
|
82
|
+
const len = Math.max(A.nums.length, B.nums.length);
|
|
83
|
+
for (let i = 0; i < len; i++) {
|
|
84
|
+
const x = A.nums[i] || 0, y = B.nums[i] || 0;
|
|
85
|
+
if (x !== y) return x > y ? 1 : -1;
|
|
57
86
|
}
|
|
58
|
-
|
|
59
|
-
if (!A.pre) return 1;
|
|
60
|
-
if (!B.pre) return -1;
|
|
61
|
-
return A.pre > B.pre ? 1 : -1;
|
|
87
|
+
return comparePre(A.pre, B.pre);
|
|
62
88
|
}
|
|
63
89
|
|
|
64
90
|
function isNewer(latest, current) {
|
|
@@ -67,6 +93,12 @@ function isNewer(latest, current) {
|
|
|
67
93
|
|
|
68
94
|
// ─── 网络 ───────────────────────────────────────────────────
|
|
69
95
|
|
|
96
|
+
/* NETWORK: 查询 npm registry 上的最新版本号
|
|
97
|
+
* Why: 「有没有新版本」只存在于 registry,本地包里没有这个信息。
|
|
98
|
+
* Trigger: 仅 `jsql update` / `jsql update --check` 显式调用。
|
|
99
|
+
* Offline: JSQL_OFFLINE=1 → runUpdate 直接返回离线结果,不发请求。
|
|
100
|
+
* Scope: https://registry.npmjs.org/jsql-neo/latest(只读,无认证)。
|
|
101
|
+
*/
|
|
70
102
|
function httpGetText(url, redirects = 0) {
|
|
71
103
|
return new Promise((resolve, reject) => {
|
|
72
104
|
if (redirects > 5) {
|
|
@@ -227,6 +259,13 @@ function installCommand(version) {
|
|
|
227
259
|
*/
|
|
228
260
|
async function runUpdate(opts = {}) {
|
|
229
261
|
const current = currentVersion();
|
|
262
|
+
if (isOffline()) {
|
|
263
|
+
return {
|
|
264
|
+
ok: false, current, latest: null,
|
|
265
|
+
error: '离线模式(JSQL_OFFLINE=1):jsql update 需要访问 npm registry',
|
|
266
|
+
hints: ['取消 JSQL_OFFLINE 后重试;或手动执行 npm install -g jsql-neo@latest'],
|
|
267
|
+
};
|
|
268
|
+
}
|
|
230
269
|
let latestInfo;
|
|
231
270
|
try {
|
|
232
271
|
latestInfo = await fetchLatestVersion({ fetchImpl: opts.fetchImpl, npmView: opts.npmView });
|
package/lib/web_ui.js
CHANGED
|
@@ -68,6 +68,7 @@ tr:nth-child(even) td { background: #0d1117; }
|
|
|
68
68
|
</div>
|
|
69
69
|
<script>
|
|
70
70
|
let dbs = [], cur = null;
|
|
71
|
+
// LOCAL-ONLY: 浏览器同源请求(/api/*),不访问任何外部网络。
|
|
71
72
|
const q = async (u, o) => { const r = await fetch(u, o); return r.json(); };
|
|
72
73
|
function esc(s) { return String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>'); }
|
|
73
74
|
async function load() {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "jsql-neo",
|
|
3
|
-
"version": "6.6.
|
|
3
|
+
"version": "6.6.3",
|
|
4
4
|
"description": "JSQL-NEO — Rust-powered embedded database with WASM, REST API, B-Tree indexes, WAL, crash recovery",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"types": "index.d.ts",
|
|
@@ -50,12 +50,12 @@
|
|
|
50
50
|
"scripts": {
|
|
51
51
|
"postinstall": "node postinstall.js",
|
|
52
52
|
"build:native": "node scripts/build-native.js",
|
|
53
|
-
"test": "node test/smoke.js && node test/result-raw.test.js && node test/native-install.test.js && node test/native-cli.test.js && node test/finalize-bigint.test.js && node test/native.test.js && node test/json-functions.test.js && node test/sql-parser.test.js && node test/readme-audit.test.js && node test/query-opt.test.js && node test/wal-recovery.test.js && node test/mysql-compat-hijack.test.js && node test/dml-constraints.test.js && node test/star-nag.test.js && node test/plugin-xql.test.js && node test/bug-regression-2.test.js && node test/issue-34-35-36.test.js && node test/issue-g4.test.js && node test/issue-38.test.js && node test/issue-39.test.js && node test/issue-40.test.js && node test/issue-44.test.js && node test/issue-45.test.js && node test/issue-46.test.js && node test/issue-47.test.js && node test/issue-48.test.js && node test/issue-50.test.js && node test/issue-51.test.js && node test/issue-52.test.js && node test/issue-53.test.js && node test/issue-54.test.js && node test/issue-55.test.js && node test/issue-56.test.js && node test/issue-57.test.js && node test/issue-58.test.js && node test/issue-59.test.js && node test/issue-60.test.js && node test/issue-63-68.test.js && node test/issue-69-70.test.js && node test/issue-71-72.test.js && node test/issue-73-76.test.js && node test/issue-77-84.test.js",
|
|
53
|
+
"test": "node test/smoke.js && node test/result-raw.test.js && node test/native-install.test.js && node test/native-cli.test.js && node test/finalize-bigint.test.js && node test/native.test.js && node test/json-functions.test.js && node test/sql-parser.test.js && node test/readme-audit.test.js && node test/query-opt.test.js && node test/wal-recovery.test.js && node test/mysql-compat-hijack.test.js && node test/dml-constraints.test.js && node test/star-nag.test.js && node test/plugin-xql.test.js && node test/bug-regression-2.test.js && node test/issue-34-35-36.test.js && node test/issue-g4.test.js && node test/issue-38.test.js && node test/issue-39.test.js && node test/issue-40.test.js && node test/issue-44.test.js && node test/issue-45.test.js && node test/issue-46.test.js && node test/issue-47.test.js && node test/issue-48.test.js && node test/issue-50.test.js && node test/issue-51.test.js && node test/issue-52.test.js && node test/issue-53.test.js && node test/issue-54.test.js && node test/issue-55.test.js && node test/issue-56.test.js && node test/issue-57.test.js && node test/issue-58.test.js && node test/issue-59.test.js && node test/issue-60.test.js && node test/issue-63-68.test.js && node test/network-policy.test.js && node test/issue-69-70.test.js && node test/issue-71-72.test.js && node test/issue-73-76.test.js && node test/issue-77-84.test.js && node test/issue-86-99.test.js",
|
|
54
54
|
"test:parser": "node test/sql-parser.test.js",
|
|
55
55
|
"test:btree": "node test/btree.test.js",
|
|
56
56
|
"test:native": "node test/native.test.js",
|
|
57
57
|
"test:regress": "node test/regress-5.1.0.js",
|
|
58
|
-
"test:all": "node test/smoke.js && node test/result-raw.test.js && node test/native-install.test.js && node test/native-cli.test.js && node test/finalize-bigint.test.js && node test/sql-parser.test.js && node test/readme-audit.test.js && node test/native.test.js && node test/native-multi-instance.test.js && node test/wal-recovery.test.js && node test/mysql-compat-hijack.test.js && node test/wasm.test.js && node test/coverage.js && node test/regress-5.1.0.js && node test/join.test.js && node test/btree.test.js && node test/dml-constraints.test.js && node test/savepoint.test.js && node test/alter-table.test.js && node test/null-semantics.test.js && node test/identifier-keywords.test.js && node test/issue-34-35-36.test.js && node test/sql-semantics.test.js && node test/extra-coverage.test.js && node test/filter-compile.test.js && node test/recursive-cte.test.js && node test/index-ddl.test.js && node test/mongo-group.test.js && node test/multiprotocol.test.js && node test/issue-g4.test.js && node test/issue-38.test.js && node test/issue-39.test.js && node test/issue-40.test.js && node test/issue-44.test.js && node test/issue-45.test.js && node test/issue-46.test.js && node test/issue-47.test.js && node test/issue-48.test.js && node test/issue-50.test.js && node test/issue-51.test.js && node test/issue-52.test.js && node test/issue-53.test.js && node test/issue-54.test.js && node test/issue-55.test.js && node test/issue-56.test.js && node test/issue-57.test.js && node test/issue-58.test.js && node test/issue-59.test.js && node test/issue-60.test.js && node test/issue-63-68.test.js && node test/issue-69-70.test.js && node test/issue-71-72.test.js && node test/issue-77-84.test.js",
|
|
58
|
+
"test:all": "node test/smoke.js && node test/result-raw.test.js && node test/native-install.test.js && node test/native-cli.test.js && node test/finalize-bigint.test.js && node test/sql-parser.test.js && node test/readme-audit.test.js && node test/native.test.js && node test/native-multi-instance.test.js && node test/wal-recovery.test.js && node test/mysql-compat-hijack.test.js && node test/wasm.test.js && node test/coverage.js && node test/regress-5.1.0.js && node test/join.test.js && node test/btree.test.js && node test/dml-constraints.test.js && node test/savepoint.test.js && node test/alter-table.test.js && node test/null-semantics.test.js && node test/identifier-keywords.test.js && node test/issue-34-35-36.test.js && node test/sql-semantics.test.js && node test/extra-coverage.test.js && node test/filter-compile.test.js && node test/recursive-cte.test.js && node test/index-ddl.test.js && node test/mongo-group.test.js && node test/multiprotocol.test.js && node test/issue-g4.test.js && node test/issue-38.test.js && node test/issue-39.test.js && node test/issue-40.test.js && node test/issue-44.test.js && node test/issue-45.test.js && node test/issue-46.test.js && node test/issue-47.test.js && node test/issue-48.test.js && node test/issue-50.test.js && node test/issue-51.test.js && node test/issue-52.test.js && node test/issue-53.test.js && node test/issue-54.test.js && node test/issue-55.test.js && node test/issue-56.test.js && node test/issue-57.test.js && node test/issue-58.test.js && node test/issue-59.test.js && node test/issue-60.test.js && node test/issue-63-68.test.js && node test/network-policy.test.js && node test/issue-69-70.test.js && node test/issue-71-72.test.js && node test/issue-77-84.test.js && node test/issue-86-99.test.js",
|
|
59
59
|
"test:coverage": "c8 --all --include='lib/**' --exclude='lib/web_ui.js' --reporter=text --reporter=lcov node test/coverage.js",
|
|
60
60
|
"test:orms": "node examples/orms/run-all.js",
|
|
61
61
|
"test:dml": "node test/dml-constraints.test.js",
|
package/postinstall.js
CHANGED
|
@@ -5,10 +5,20 @@ const path = require('path');
|
|
|
5
5
|
const http = require('http');
|
|
6
6
|
const https = require('https');
|
|
7
7
|
const { detectLibc, nativeTargetSuffix, nativeNapiVersion, supportsNativeNapi, MIN_NAPI_VERSION } = require('./lib/native_target');
|
|
8
|
+
const { isOffline } = require('./lib/network-policy');
|
|
8
9
|
|
|
9
10
|
const ROOT = __dirname;
|
|
10
11
|
const pkg = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8'));
|
|
11
12
|
|
|
13
|
+
/* NETWORK: 安装期拉取预编译的 native .node 二进制
|
|
14
|
+
* Why: Rust 编译产物不在 npm tarball 里;不下载就只能本地 cargo 编译
|
|
15
|
+
* (要求用户装 Rust toolchain),或直接降级到 WASM/JS 引擎。
|
|
16
|
+
* Trigger: 仅 `npm install` 触发的 postinstall,或手动 `node postinstall.js`。
|
|
17
|
+
* 运行时 / CLI 启动绝不会走到这里。
|
|
18
|
+
* Offline: JSQL_OFFLINE=1 或 JSQL_NO_NATIVE_DOWNLOAD=1 → 完全跳过下载;
|
|
19
|
+
* 有本地 .node 就用,没有则走源码编译 / WASM 降级。
|
|
20
|
+
* Scope: GitHub releases 的固定 tag 资源 + SHA256SUMS(强制校验)。
|
|
21
|
+
*/
|
|
12
22
|
// Server CLI binary (bin/jsql-neo-server)
|
|
13
23
|
const BIN_NAME = process.platform === 'win32' ? 'jsql-neo-server.exe' : 'jsql-neo-server';
|
|
14
24
|
const BP = path.join(ROOT, 'bin', BIN_NAME);
|
|
@@ -53,7 +63,8 @@ const GHPROXY_TOKEN = process.env.JSQL_GHPROXY_TOKEN || '';
|
|
|
53
63
|
//
|
|
54
64
|
// 供应链安全(issue #25):不内置任何加速站/token,代理仍需显式 JSQL_GHPROXY,
|
|
55
65
|
// 且下载必须通过 SHA256SUMS 校验(除非用户显式 JSQL_ALLOW_UNVERIFIED_NATIVE=1)。
|
|
56
|
-
const DOWNLOAD_DISABLED =
|
|
66
|
+
const DOWNLOAD_DISABLED = isOffline()
|
|
67
|
+
|| process.env.JSQL_NO_NATIVE_DOWNLOAD === '1'
|
|
57
68
|
|| process.env.JSQL_NATIVE_DOWNLOAD === '0'
|
|
58
69
|
|| process.env.JSQL_AUTO_DOWNLOAD_NATIVE === '0';
|
|
59
70
|
const FORCE_REFRESH = process.env.JSQL_NATIVE_FORCE_REFRESH !== '0';
|
|
@@ -101,7 +112,12 @@ function sameOrigin(a, b) {
|
|
|
101
112
|
* 解析 JSQL_NATIVE_TAG=latest:跟随 GitHub `/releases/latest` 的 302 跳转,
|
|
102
113
|
* 从 Location 里取出真实 tag(vX.Y.Z)。失败返回 null —— 调用方回退到当前版本 tag。
|
|
103
114
|
*/
|
|
115
|
+
/* NETWORK: 解析 JSQL_NATIVE_TAG=latest(GET GitHub /releases/latest 的 302)
|
|
116
|
+
* Why: "latest" 指向哪个 tag 只有远端知道。
|
|
117
|
+
* Trigger: 仅用户显式设置 JSQL_NATIVE_TAG=latest 时;默认用 v<pkg.version> 不发请求。
|
|
118
|
+
* Offline: JSQL_OFFLINE=1 → 返回 null,调用方回退到当前版本 tag。 */
|
|
104
119
|
function resolveLatestTag() {
|
|
120
|
+
if (isOffline()) return Promise.resolve(null);
|
|
105
121
|
return new Promise((resolve) => {
|
|
106
122
|
const url = `https://github.com/${REPO}/releases/latest`;
|
|
107
123
|
let settled = false;
|
package/src/cli/plugin.js
CHANGED
|
@@ -12,6 +12,7 @@ const fs = require('fs');
|
|
|
12
12
|
const os = require('os');
|
|
13
13
|
const path = require('path');
|
|
14
14
|
const { execFileSync } = require('child_process');
|
|
15
|
+
const { isOffline, offlineError } = require('../../lib/network-policy');
|
|
15
16
|
|
|
16
17
|
const REGISTRY_BASE = 'https://registry-beta.vexify.top';
|
|
17
18
|
const PLUGIN_DIR = path.join(os.homedir(), '.jsql', 'plugins');
|
|
@@ -94,8 +95,15 @@ function extractJson(text) {
|
|
|
94
95
|
}
|
|
95
96
|
}
|
|
96
97
|
|
|
98
|
+
/* NETWORK: 插件 registry 的元数据查询(plugins / search)
|
|
99
|
+
* Why: 可安装插件的目录只在远端,本地只有「已安装」列表。
|
|
100
|
+
* Trigger: 仅 `jsql plugin list|search|info` 显式调用。
|
|
101
|
+
* Offline: JSQL_OFFLINE=1 → 抛 JSQL_OFFLINE 错误,不发起 fetch。
|
|
102
|
+
* Scope: https://registry-beta.vexify.top/?action=...(只读)。
|
|
103
|
+
*/
|
|
97
104
|
/** 发起 registry API 请求,返回解析后的 JSON */
|
|
98
105
|
async function apiRequest(action, params = {}) {
|
|
106
|
+
if (isOffline()) throw offlineError('jsql plugin', '插件目录在远端 registry');
|
|
99
107
|
const url = new URL(REGISTRY_BASE);
|
|
100
108
|
url.searchParams.set('action', action);
|
|
101
109
|
for (const [k, v] of Object.entries(params)) {
|
|
@@ -151,7 +159,12 @@ async function getPluginInfo(name) {
|
|
|
151
159
|
* 带重试的 fetch(P1 修复:install 网络间歇性失败 30-40%)
|
|
152
160
|
* 3 次重试 + 指数退避(500ms, 1s, 2s)
|
|
153
161
|
*/
|
|
162
|
+
/* NETWORK: 下载插件压缩包(同 apiRequest 的 NETWORK 标注)
|
|
163
|
+
* Why: 包体只在远端;Trigger: 仅 `jsql plugin install <name>`;
|
|
164
|
+
* Offline: JSQL_OFFLINE=1 → 抛 JSQL_OFFLINE 错误;
|
|
165
|
+
* Scope: registry-beta.vexify.top 的 download action。 */
|
|
154
166
|
async function fetchWithRetry(url, retries = 3, baseDelay = 500) {
|
|
167
|
+
if (isOffline()) throw offlineError('jsql plugin install', '插件包需要下载');
|
|
155
168
|
for (let i = 0; i < retries; i++) {
|
|
156
169
|
try {
|
|
157
170
|
const res = await fetch(url.toString());
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
// 回归测试:Issue #86-#99
|
|
2
|
+
const Database = require('../lib/database');
|
|
3
|
+
const { executeSQL, applyParams, splitStatements, parseSQL } = require('../lib/sql');
|
|
4
|
+
const { Datastore } = require('../lib/nedb_compat');
|
|
5
|
+
const Cache = require('../lib/cache');
|
|
6
|
+
const updater = require('../lib/updater');
|
|
7
|
+
const { decodeBinaryParam } = require('../lib/pg_server');
|
|
8
|
+
const { createMysqlServer, MysqlConnection } = require('../lib/mysql_server');
|
|
9
|
+
const sqliteCompat = require('../lib/sqlite_compat');
|
|
10
|
+
|
|
11
|
+
let pass = 0, fail = 0;
|
|
12
|
+
function ok(name, cond, extra) {
|
|
13
|
+
if (cond) { pass++; console.log('[OK] ', name); }
|
|
14
|
+
else { fail++; console.log('[FAIL]', name, extra !== undefined ? ' -> ' + JSON.stringify(extra).slice(0, 240) : ''); }
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
(async () => {
|
|
18
|
+
// #86 ON DUPLICATE VALUES(a)+1 表达式
|
|
19
|
+
{
|
|
20
|
+
const db = new Database(':memory:');
|
|
21
|
+
await executeSQL(db, "CREATE TABLE t (id INT PRIMARY KEY, a INT, b INT)");
|
|
22
|
+
await executeSQL(db, "INSERT INTO t VALUES (1,10,3)");
|
|
23
|
+
await executeSQL(db, "INSERT INTO t (id,a,b) VALUES (1,100,200) ON DUPLICATE KEY UPDATE a=VALUES(a)+1, b=VALUES(b)");
|
|
24
|
+
const r = await executeSQL(db, "SELECT * FROM t");
|
|
25
|
+
ok('#86 VALUES(a)+1 → a=101', r.rows[0][1] === 101, r.rows[0]);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// #87 sqlite raw(true).all() 不重复执行
|
|
29
|
+
{
|
|
30
|
+
const db = new sqliteCompat.Database(':memory:');
|
|
31
|
+
db.exec('CREATE TABLE t (a INT)');
|
|
32
|
+
db.prepare('INSERT INTO t(a) VALUES (1)').raw(true).all();
|
|
33
|
+
const n = db.prepare('SELECT COUNT(*) c FROM t').get();
|
|
34
|
+
ok('#87 raw(true).all() 只执行一次', n.c === 1, n);
|
|
35
|
+
const rows = db.prepare('SELECT a FROM t').raw(true).all();
|
|
36
|
+
ok('#87 raw 输出数组格式', JSON.stringify(rows) === '[[1]]', rows);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// #88 $regex 字符串模式
|
|
40
|
+
{
|
|
41
|
+
const ds = new Datastore({ inMemoryOnly: true });
|
|
42
|
+
await ds.loadDatabase();
|
|
43
|
+
await ds.insert({ name: 'alice' }); await ds.insert({ name: 'bob' }); await ds.insert({ name: 'charlie' });
|
|
44
|
+
const r = await ds.find({ name: { $regex: '^al' } });
|
|
45
|
+
ok('#88 $regex ^al 只返回 alice', r.length === 1, r.length);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// #89 lrange 负索引越界
|
|
49
|
+
{
|
|
50
|
+
const c = new Cache();
|
|
51
|
+
c.rpush('k', 'a', 'b', 'c');
|
|
52
|
+
const out = c.lrange('k', 0, -5);
|
|
53
|
+
ok('#89 lrange(0,-5) → ["a"]', out.join(',') === 'a', out);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// #90 updater 版本比较
|
|
57
|
+
{
|
|
58
|
+
ok('#90 alpha.10 > alpha.9', updater.isNewer('1.0.0-alpha.10', '1.0.0-alpha.9') === true, updater.isNewer('1.0.0-alpha.10', '1.0.0-alpha.9'));
|
|
59
|
+
ok('#90 1.2.3.4 > 1.2.3', updater.compareVersions('1.2.3.4', '1.2.3') > 0, updater.compareVersions('1.2.3.4', '1.2.3'));
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// #91 多语句协议(fake connection 应产生 2 个结果集)
|
|
63
|
+
{
|
|
64
|
+
const server = createMysqlServer({ safety: false });
|
|
65
|
+
await server._getEngine();
|
|
66
|
+
const socket = { write: () => {}, destroy: () => {}, remoteAddress: 'x', on: () => {} };
|
|
67
|
+
const conn = new MysqlConnection(socket, server);
|
|
68
|
+
conn.authenticated = true; conn.multiStatements = true;
|
|
69
|
+
await new Promise((res) => { conn._handleQuery('SELECT 1; SELECT 2;'); setTimeout(res, 800); });
|
|
70
|
+
ok('#91 多语句无异常', true);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// #92 applyParams 混用 ?N 与 ?
|
|
74
|
+
{
|
|
75
|
+
const a = applyParams("SELECT * FROM t WHERE a=? AND b=?2", [10, 20, 30]);
|
|
76
|
+
ok('#92 a=? AND b=?2 → a=10 b=20', a.includes('a=10') && a.includes('b=20'), a);
|
|
77
|
+
const b = applyParams("SELECT * FROM t WHERE b=?2 AND a=?", [10, 20, 30]);
|
|
78
|
+
ok('#92 b=?2 AND a=? → b=20 a=10', b.includes('b=20') && b.includes('a=10'), b);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// #93 pg 二进制参数解码
|
|
82
|
+
{
|
|
83
|
+
const i4 = Buffer.from([0, 0, 0, 42]);
|
|
84
|
+
ok('#93 int4 binary=42', decodeBinaryParam(i4, 23) === 42, decodeBinaryParam(i4, 23));
|
|
85
|
+
const i8 = Buffer.alloc(8); i8.writeBigInt64BE(1234567890123n);
|
|
86
|
+
ok('#93 int8 binary', decodeBinaryParam(i8, 20) === 1234567890123n, decodeBinaryParam(i8, 20));
|
|
87
|
+
const f8 = Buffer.alloc(8); f8.writeDoubleBE(3.14);
|
|
88
|
+
ok('#93 float8 binary', decodeBinaryParam(f8, 701) === 3.14, decodeBinaryParam(f8, 701));
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// #94 数值 LIKE
|
|
92
|
+
{
|
|
93
|
+
const db = new Database(':memory:');
|
|
94
|
+
await executeSQL(db, "CREATE TABLE t (id INT PRIMARY KEY, a INT)");
|
|
95
|
+
await executeSQL(db, "INSERT INTO t VALUES (1,10),(2,20)");
|
|
96
|
+
const r = await executeSQL(db, "SELECT id FROM t WHERE a LIKE '1%'");
|
|
97
|
+
ok('#94 a LIKE \'1%\' → id=1', r.rows.map(x => x[0]).join(',') === '1', r.rows);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// #95 COM_PROCESS_INFO 用 lenenc string
|
|
101
|
+
{
|
|
102
|
+
const server = createMysqlServer({ safety: false });
|
|
103
|
+
await server._getEngine();
|
|
104
|
+
const socket = { write: () => {}, destroy: () => {}, remoteAddress: 'x', on: () => {} };
|
|
105
|
+
const conn = new MysqlConnection(socket, server);
|
|
106
|
+
conn.authenticated = true;
|
|
107
|
+
const sent = [];
|
|
108
|
+
conn._send = (b) => { sent.push(Buffer.from(b)); };
|
|
109
|
+
conn._handlePacket(Buffer.from([0x0a]), 0);
|
|
110
|
+
let found = false;
|
|
111
|
+
for (const p of sent) for (let i = 0; i < p.length - 1; i++) if (p[i] === 0x01 && p[i + 1] === 0x31) found = true;
|
|
112
|
+
ok('#95 数据行含 lenenc 0x01 0x31', found);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// #96 CAST DECIMAL 精度
|
|
116
|
+
{
|
|
117
|
+
const db = new Database(':memory:');
|
|
118
|
+
const r = await executeSQL(db, "SELECT CAST(123.456 AS DECIMAL(10,2))");
|
|
119
|
+
ok('#96 CAST DECIMAL(10,2) → 123.46', r.rows[0][0] === 123.46, r.rows[0][0]);
|
|
120
|
+
const r2 = await executeSQL(db, "SELECT CAST(123.456 AS DECIMAL(10,0))");
|
|
121
|
+
ok('#96 CAST DECIMAL(10,0) → 123', r2.rows[0][0] === 123, r2.rows[0][0]);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// #97 _route 多限定表
|
|
125
|
+
{
|
|
126
|
+
const server = createMysqlServer({ safety: false });
|
|
127
|
+
await server._getEngine();
|
|
128
|
+
const sql = "SELECT * FROM db1.t JOIN db1.u ON t.id=u.id WHERE name='db1.t'";
|
|
129
|
+
const routed = await server._route(parseSQL(sql), sql, null, null);
|
|
130
|
+
ok('#97 多表改写 + 字符串保留', routed.sql === "SELECT * FROM t JOIN u ON t.id=u.id WHERE name='db1.t'", routed.sql);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// #98 字符串列 MIN/MAX 字典序
|
|
134
|
+
{
|
|
135
|
+
const db = new Database(':memory:');
|
|
136
|
+
await executeSQL(db, "CREATE TABLE s (x STRING)");
|
|
137
|
+
await executeSQL(db, "INSERT INTO s VALUES ('2'),('100'),('9')");
|
|
138
|
+
const r = await executeSQL(db, "SELECT MIN(x), MAX(x) FROM s");
|
|
139
|
+
ok('#98 MIN=100 MAX=9 字典序', r.rows[0][0] === '100' && r.rows[0][1] === '9', r.rows[0]);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// #99 ON DUPLICATE 裸列名
|
|
143
|
+
{
|
|
144
|
+
const db = new Database(':memory:');
|
|
145
|
+
await executeSQL(db, "CREATE TABLE t (id INT PRIMARY KEY, cnt INT, other INT)");
|
|
146
|
+
await executeSQL(db, "INSERT INTO t VALUES (1,5,7)");
|
|
147
|
+
await executeSQL(db, "INSERT INTO t (id,cnt,other) VALUES (1,5,7) ON DUPLICATE KEY UPDATE cnt=cnt+1, other=other");
|
|
148
|
+
const r = await executeSQL(db, "SELECT * FROM t");
|
|
149
|
+
ok('#99 other=other 不崩溃且 cnt=6', r.rows[0][1] === 6 && r.rows[0][2] === 7, r.rows[0]);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
console.log(`\n${pass} passed, ${fail} failed`);
|
|
153
|
+
process.exit(fail === 0 ? 0 : 1);
|
|
154
|
+
})().catch(e => { console.error('FATAL', e); process.exit(1); });
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
/* ---- 网络访问策略:启动路径零出网 + JSQL_OFFLINE 统一开关 ---- */
|
|
2
|
+
/*
|
|
3
|
+
* 背景:CLI 启动路径曾会同步 curl api.github.com(只为少印一行 star 提示),
|
|
4
|
+
* 让每条 jsql 命令都可能偷偷出网并阻塞最多 ~9.5 秒。本测试把「启动不联网」
|
|
5
|
+
* 钉死,并验证 JSQL_OFFLINE=1 能拦住所有显式联网入口。
|
|
6
|
+
*
|
|
7
|
+
* 全程用临时目录:JSQL_MR_PATH 指向临时路径,绝不碰真实的 ~/.jsqlmr。
|
|
8
|
+
*/
|
|
9
|
+
const path = require('path');
|
|
10
|
+
const fs = require('fs');
|
|
11
|
+
const os = require('os');
|
|
12
|
+
|
|
13
|
+
const ROOT = path.join(__dirname, '..');
|
|
14
|
+
const TMP = fs.mkdtempSync(path.join(os.tmpdir(), 'jsql-netpolicy-'));
|
|
15
|
+
process.env.JSQL_MR_PATH = path.join(TMP, 'jsqlmr'); // 必须在 require 之前
|
|
16
|
+
|
|
17
|
+
const { isOffline, offlineError } = require(path.join(ROOT, 'lib', 'network-policy'));
|
|
18
|
+
const sn = require(path.join(ROOT, 'lib', 'star-nag'));
|
|
19
|
+
const updater = require(path.join(ROOT, 'lib', 'updater'));
|
|
20
|
+
const plugin = require(path.join(ROOT, 'src', 'cli', 'plugin'));
|
|
21
|
+
|
|
22
|
+
let pass = 0, fail = 0;
|
|
23
|
+
function ok(name, cond, got) {
|
|
24
|
+
if (cond) { pass++; console.log('[OK] ' + name); }
|
|
25
|
+
else { fail++; console.log('[FAIL] ' + name + ' -> ' + JSON.stringify(got)); }
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// 记录所有子进程调用(curl / gh / npm),用来证明「没有出网」
|
|
29
|
+
const cp = require('child_process');
|
|
30
|
+
const realExecFileSync = cp.execFileSync;
|
|
31
|
+
const realExecFile = cp.execFile;
|
|
32
|
+
const realSpawn = cp.spawn;
|
|
33
|
+
const calls = [];
|
|
34
|
+
cp.execFileSync = function (cmd, ...rest) { calls.push('execFileSync:' + cmd); return realExecFileSync.call(this, cmd, ...rest); };
|
|
35
|
+
cp.execFile = function (cmd, ...rest) { calls.push('execFile:' + cmd); return realExecFile.call(this, cmd, ...rest); };
|
|
36
|
+
cp.spawn = function (cmd, ...rest) { calls.push('spawn:' + cmd); return realSpawn.call(this, cmd, ...rest); };
|
|
37
|
+
|
|
38
|
+
function resetCalls() { calls.length = 0; }
|
|
39
|
+
|
|
40
|
+
(async () => {
|
|
41
|
+
// ---------- 环境变量解析 ----------
|
|
42
|
+
const saved = process.env.JSQL_OFFLINE;
|
|
43
|
+
delete process.env.JSQL_OFFLINE;
|
|
44
|
+
ok('默认不离线', isOffline() === false, process.env.JSQL_OFFLINE);
|
|
45
|
+
for (const v of ['1', 'true', 'yes', 'on', 'TRUE']) {
|
|
46
|
+
process.env.JSQL_OFFLINE = v;
|
|
47
|
+
ok('JSQL_OFFLINE=' + v + ' → 离线', isOffline() === true, v);
|
|
48
|
+
}
|
|
49
|
+
for (const v of ['0', 'false', '', 'no']) {
|
|
50
|
+
process.env.JSQL_OFFLINE = v;
|
|
51
|
+
ok('JSQL_OFFLINE=' + JSON.stringify(v) + ' → 不离线', isOffline() === false, v);
|
|
52
|
+
}
|
|
53
|
+
process.env.JSQL_OFFLINE = '1';
|
|
54
|
+
const oe = offlineError('jsql update', '需要访问 npm registry');
|
|
55
|
+
ok('offlineError 带 code=JSQL_OFFLINE', oe && oe.code === 'JSQL_OFFLINE', oe && oe.code);
|
|
56
|
+
ok('offlineError 文案含功能名与原因', /jsql update/.test(oe.message) && /npm registry/.test(oe.message), oe && oe.message);
|
|
57
|
+
|
|
58
|
+
// ---------- 启动路径零出网 ----------
|
|
59
|
+
process.env.JSQL_OFFLINE = '';
|
|
60
|
+
delete process.env.JSQL_OFFLINE;
|
|
61
|
+
process.env.GITHUB_TOKEN = 'fake-token-should-never-be-used';
|
|
62
|
+
const out = [];
|
|
63
|
+
resetCalls();
|
|
64
|
+
const printed = sn.nag({ out: { write: (s) => out.push(s) } });
|
|
65
|
+
ok('nag() 正常打印提示', printed === true && out.join('').includes('star helps others find it'), out.join(''));
|
|
66
|
+
ok('nag() 不发起任何子进程网络调用', calls.length === 0, calls);
|
|
67
|
+
ok('nag() 不写 lastNagAt', (() => {
|
|
68
|
+
try { const c = sn.readConfig(); return c.lastNagAt === undefined; } catch (e) { return true; }
|
|
69
|
+
})(), null);
|
|
70
|
+
delete process.env.GITHUB_TOKEN;
|
|
71
|
+
|
|
72
|
+
// 已标记 starred 时应彻底沉默,且同样不出网
|
|
73
|
+
sn.setStarred(true);
|
|
74
|
+
const out2 = [];
|
|
75
|
+
resetCalls();
|
|
76
|
+
const printed2 = sn.nag({ out: { write: (s) => out2.push(s) } });
|
|
77
|
+
ok('已 starred 时不打印', printed2 === false && out2.length === 0, out2.join(''));
|
|
78
|
+
ok('已 starred 时不出网', calls.length === 0, calls);
|
|
79
|
+
sn.setStarred(false);
|
|
80
|
+
|
|
81
|
+
// ---------- 离线时各联网入口都被拦住 ----------
|
|
82
|
+
process.env.JSQL_OFFLINE = '1';
|
|
83
|
+
resetCalls();
|
|
84
|
+
ok('checkStarred() 离线返回 null', sn.checkStarred() === null, null);
|
|
85
|
+
ok('checkStarred() 离线不出网', calls.length === 0, calls);
|
|
86
|
+
resetCalls();
|
|
87
|
+
let threw = null;
|
|
88
|
+
try { sn.startOauthCheck(); } catch (e) { threw = e; }
|
|
89
|
+
ok('startOauthCheck() 离线抛 JSQL_OFFLINE', threw && threw.code === 'JSQL_OFFLINE', threw && threw.code);
|
|
90
|
+
ok('startOauthCheck() 离线不开浏览器', calls.length === 0, calls);
|
|
91
|
+
resetCalls();
|
|
92
|
+
ok('waitForResult() 离线返回 null', sn.waitForResult('https://auth.vexify.top/start?nonce=x') === null, null);
|
|
93
|
+
ok('waitForResult() 离线不轮询', calls.length === 0, calls);
|
|
94
|
+
|
|
95
|
+
resetCalls();
|
|
96
|
+
const up = await updater.runUpdate({ checkOnly: true });
|
|
97
|
+
ok('jsql update 离线返回 ok=false', up && up.ok === false, up);
|
|
98
|
+
ok('jsql update 离线给出可读原因', up && /JSQL_OFFLINE|离线/.test(up.error || ''), up && up.error);
|
|
99
|
+
ok('jsql update 离线不出网', calls.length === 0, calls);
|
|
100
|
+
|
|
101
|
+
resetCalls();
|
|
102
|
+
let perr = null;
|
|
103
|
+
try { await plugin.listPlugins({}); } catch (e) { perr = e; }
|
|
104
|
+
ok('jsql plugin list 离线抛 JSQL_OFFLINE', perr && perr.code === 'JSQL_OFFLINE', perr && perr.code);
|
|
105
|
+
ok('jsql plugin list 离线不出网', calls.length === 0, calls);
|
|
106
|
+
|
|
107
|
+
// ---------- 恢复 ----------
|
|
108
|
+
process.env.JSQL_OFFLINE = saved === undefined ? '' : saved;
|
|
109
|
+
if (saved === undefined) delete process.env.JSQL_OFFLINE;
|
|
110
|
+
cp.execFileSync = realExecFileSync;
|
|
111
|
+
cp.execFile = realExecFile;
|
|
112
|
+
cp.spawn = realSpawn;
|
|
113
|
+
try { fs.rmSync(TMP, { recursive: true, force: true }); } catch (_) {}
|
|
114
|
+
|
|
115
|
+
console.log(`\n${pass} passed, ${fail} failed`);
|
|
116
|
+
process.exit(fail === 0 ? 0 : 1);
|
|
117
|
+
})().catch(e => {
|
|
118
|
+
console.log('[FAIL] unexpected exception: ' + e.stack.split('\n').slice(0, 3).join('\n'));
|
|
119
|
+
process.exit(1);
|
|
120
|
+
});
|