@maiyunnet/kebab 9.29.6 → 10.0.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.
Files changed (52) hide show
  1. package/abox/proxy.js +24 -2
  2. package/abox/response.js +36 -17
  3. package/abox/session-login.js +1 -13
  4. package/doc/kebab-rag.md +1522 -1034
  5. package/index.d.ts +12 -1
  6. package/index.js +1 -1
  7. package/lib/ai.d.ts +4 -0
  8. package/lib/ai.js +32 -16
  9. package/lib/cookie.d.ts +2 -0
  10. package/lib/cookie.js +47 -45
  11. package/lib/core.d.ts +26 -0
  12. package/lib/core.js +36 -13
  13. package/lib/cron.js +1 -8
  14. package/lib/crypto.js +20 -6
  15. package/lib/db/conn.js +1 -0
  16. package/lib/fs.js +78 -31
  17. package/lib/kv.d.ts +182 -79
  18. package/lib/kv.js +518 -214
  19. package/lib/s3.d.ts +2 -0
  20. package/lib/s3.js +14 -27
  21. package/lib/session.d.ts +7 -0
  22. package/lib/session.js +23 -2
  23. package/lib/socket.d.ts +4 -1
  24. package/lib/socket.js +1 -0
  25. package/lib/sql.d.ts +0 -5
  26. package/lib/sql.js +48 -12
  27. package/lib/text.d.ts +10 -5
  28. package/lib/text.js +22 -12
  29. package/lib/turnstile.d.ts +6 -0
  30. package/lib/turnstile.js +16 -9
  31. package/lib/undici.d.ts +7 -1
  32. package/lib/undici.js +72 -36
  33. package/lib/ws.d.ts +1 -1
  34. package/lib/ws.js +85 -128
  35. package/lib/zip.js +46 -45
  36. package/package.json +2 -2
  37. package/sys/child.js +178 -146
  38. package/sys/cmd.js +196 -197
  39. package/sys/ctr.d.ts +14 -14
  40. package/sys/ctr.js +145 -59
  41. package/sys/master.js +111 -80
  42. package/sys/mod.d.ts +8 -2
  43. package/sys/mod.js +23 -11
  44. package/sys/monitor/files.d.ts +2 -1
  45. package/sys/monitor/files.js +77 -21
  46. package/sys/monitor/watchdog.d.ts +7 -0
  47. package/sys/monitor/watchdog.js +311 -203
  48. package/sys/monitor.d.ts +59 -54
  49. package/sys/monitor.js +742 -681
  50. package/sys/route.d.ts +4 -4
  51. package/sys/route.js +93 -52
  52. package/www/example/ctr/test.js +8 -8
package/sys/ctr.js CHANGED
@@ -1,3 +1,6 @@
1
+ import * as path from 'path';
2
+ import * as crypto from 'crypto';
3
+ // --- 第三方 ---
1
4
  import ejs from 'ejs';
2
5
  import * as lCore from '#kebab/lib/core.js';
3
6
  import * as lFs from '#kebab/lib/fs.js';
@@ -11,6 +14,38 @@ let loadedData = {};
11
14
  let localeFiles = [];
12
15
  /** --- 已经加载的语言包(全局) --- */
13
16
  let localeData = {};
17
+ /**
18
+ * --- 将相对路径安全解析到指定基目录内,禁止目录穿越、空字符与绝对路径 ---
19
+ * @param baseDir 允许的基目录
20
+ * @param relPath 相对路径
21
+ * @returns 位于基目录内的绝对路径;越界或非法返回 null
22
+ */
23
+ function resolveInsideBase(baseDir, relPath) {
24
+ if (!relPath || relPath.includes('\0') || relPath.includes('\\') || path.isAbsolute(relPath)) {
25
+ return null;
26
+ }
27
+ const base = path.resolve(baseDir);
28
+ const target = path.resolve(base, relPath);
29
+ const diff = path.relative(base, target);
30
+ if (!diff || diff === '..' || diff.startsWith(`..${path.sep}`) || path.isAbsolute(diff)) {
31
+ return null;
32
+ }
33
+ return target;
34
+ }
35
+ /**
36
+ * --- 恒定时间字符串比较,避免时序侧信道泄露令牌 ---
37
+ * @param a 字符串 A
38
+ * @param b 字符串 B
39
+ * @returns 是否完全相等
40
+ */
41
+ function safeEqualString(a, b) {
42
+ const ba = Buffer.from(a);
43
+ const bb = Buffer.from(b);
44
+ if (ba.length !== bb.length) {
45
+ return false;
46
+ }
47
+ return crypto.timingSafeEqual(ba, bb);
48
+ }
14
49
  /**
15
50
  * --- 清除已经加载的 data 与语言包文件缓存 ---
16
51
  */
@@ -244,8 +279,12 @@ export class Ctr {
244
279
  * @param path
245
280
  * @param data
246
281
  */
247
- async _loadView(path, data = {}) {
248
- const content = await lFs.getContent(this._config.const.viewPath + path + '.ejs', 'utf8');
282
+ async _loadView(viewPath, data = {}) {
283
+ const target = resolveInsideBase(this._config.const.viewPath, `${viewPath}.ejs`);
284
+ if (!target) {
285
+ return '';
286
+ }
287
+ const content = await lFs.getContent(target, 'utf8');
249
288
  if (!content) {
250
289
  return '';
251
290
  }
@@ -271,14 +310,17 @@ export class Ctr {
271
310
  * @param opt 可选配置
272
311
  */
273
312
  async _loadReactPage(path, props = {}, opt = {}) {
274
- // --- 校验服务端组件与客户端水合产物 ---
313
+ // --- 校验服务端组件与客户端水合产物(防止路径穿越出 stc/) ---
275
314
  const hydrate = opt.hydrate !== false;
276
- const pagePath = `${this._config.const.rootPath}stc/${path}.page`;
277
- const componentPath = `${pagePath}.js`;
315
+ const stcRoot = `${this._config.const.rootPath}stc/`;
316
+ const componentPath = resolveInsideBase(stcRoot, `${path}.page.js`);
317
+ const bundlePath = resolveInsideBase(stcRoot, `${path}.page.bundle.js`);
318
+ if (!componentPath || !bundlePath) {
319
+ return this._reactPageError(`invalid page path: ${path}`);
320
+ }
278
321
  if (!await lFs.isFile(componentPath)) {
279
322
  return this._reactPageError(`componentPath ${componentPath} is not a file`);
280
323
  }
281
- const bundlePath = `${pagePath}.bundle.js`;
282
324
  if (hydrate && !await lFs.isFile(bundlePath)) {
283
325
  return this._reactPageError(`bundlePath ${bundlePath} is not a file; run "npx kebab build -d ${this._config.const.rootPath}stc"`);
284
326
  }
@@ -327,9 +369,23 @@ export class Ctr {
327
369
  }
328
370
  const propsJson = lText.stringifyJson(fullProps).replace(/</g, '\\u003c');
329
371
  const clientUrl = `${staticPath}${path}.page.bundle.js?v=${this._config.set.staticVer}`;
372
+ // --- 转义单引号、反斜杠、换行和 <,避免注入跳出 import 语句或 script 标签 ---
373
+ const safeClientUrl = clientUrl
374
+ .replace(/\\/g, '\\\\')
375
+ .replace(/'/g, '\\\'')
376
+ .replace(/</g, '\\u003c')
377
+ .replace(/\r/g, '\\r')
378
+ .replace(/\n/g, '\\n')
379
+ .replace(/\u2028/g, '\\u2028')
380
+ .replace(/\u2029/g, '\\u2029');
330
381
  const propsScript = `<script id="__kebab_props__" type="application/json">${propsJson}</script>`;
331
- const hydrateScript = `<script type="module">import'${clientUrl}';</script>`;
332
- return html.replace('</body>', `${propsScript}${hydrateScript}</body>`);
382
+ const hydrateScript = `<script type="module">import'${safeClientUrl}';</script>`;
383
+ // --- 使用切片拼接而非 replace,避免 props 中包含 $` / $& / $' 导致 XSS 或水合破坏 ---
384
+ const bodyClose = html.lastIndexOf('</body>');
385
+ if (bodyClose === -1) {
386
+ return html;
387
+ }
388
+ return `${html.slice(0, bodyClose)}${propsScript}${hydrateScript}${html.slice(bodyClose)}`;
333
389
  }
334
390
  catch (e) {
335
391
  return this._reactPageError(e.message ?? '', lText.stringifyError(e));
@@ -436,9 +492,8 @@ export class Ctr {
436
492
  * @returns 可判别的校验结果
437
493
  */
438
494
  _valibotx(schema, input, options) {
439
- /** --- 用户提交的 XSRF token --- */
495
+ // --- 从输入对象中提取并剥离 _xsrf,避免污染业务 schema ---
440
496
  let submittedXsrf;
441
- /** --- 移除 XSRF 传输字段后交给业务 schema 的输入 --- */
442
497
  let schemaInput = input;
443
498
  if ((typeof input === 'object') && (input !== null) && !Array.isArray(input)) {
444
499
  const inputRecord = input;
@@ -446,10 +501,10 @@ export class Ctr {
446
501
  schemaInput = { ...inputRecord };
447
502
  delete schemaInput['_xsrf'];
448
503
  }
504
+ // --- 校验 XSRF token ---
449
505
  if (!options?.ignoreXsrf) {
450
- /** --- Cookie 中应匹配的 XSRF token --- */
451
506
  const expectedXsrf = this._cookie['XSRF-TOKEN'];
452
- if (!expectedXsrf || (submittedXsrf !== expectedXsrf)) {
507
+ if (typeof expectedXsrf !== 'string' || !expectedXsrf || typeof submittedXsrf !== 'string' || !safeEqualString(submittedXsrf, expectedXsrf)) {
453
508
  const issue = {
454
509
  'kind': 'validation',
455
510
  'type': 'xsrf',
@@ -557,19 +612,21 @@ export class Ctr {
557
612
  case 'int':
558
613
  case 'integer': {
559
614
  // --- 必须是数字型且是整数 ---
560
- needReturn = input[key] && !Number.isSafeInteger(input[key]);
615
+ needReturn = input[key] !== null && input[key] !== '' && !Number.isSafeInteger(input[key]);
561
616
  break;
562
617
  }
563
618
  case 'float':
564
619
  case 'double': {
565
620
  // --- 必须是数字型 ---
566
- needReturn = input[key] && (typeof input[key] !== 'number');
621
+ needReturn = input[key] !== null && input[key] !== '' && (typeof input[key] !== 'number' || !Number.isFinite(input[key]));
567
622
  break;
568
623
  }
569
624
  case 'num':
570
625
  case 'number': {
571
626
  // --- 可字符串数字 ---
572
- needReturn = input[key] && (typeof input[key] !== 'number') && !/^[0-9]+\.?[0-9]*$/.test(input[key]);
627
+ needReturn = input[key] !== null && input[key] !== '' &&
628
+ (typeof input[key] !== 'number' || !Number.isFinite(input[key])) &&
629
+ !(typeof input[key] === 'string' && /^[0-9]+\.?[0-9]*$/.test(input[key]));
573
630
  break;
574
631
  }
575
632
  case 'array': {
@@ -601,38 +658,45 @@ export class Ctr {
601
658
  needReturn = !(new RegExp(v.slice(1, -1))).test(input[key]);
602
659
  }
603
660
  else {
604
- const match = /^([><=]+) *([0-9]+)$/.exec(v);
661
+ const match = /^([><=!]+) *([0-9]+)$/.exec(v);
605
662
  if (match) {
606
- // --- 判断表达式 ---
607
- const inputNum = Number(input[key]);
663
+ // --- 判断表达式:先确保输入是有限数值,防止 NaN 绕过大小比较 ---
664
+ const rawVal = input[key];
665
+ const validNum = typeof rawVal === 'number' || (typeof rawVal === 'string' && rawVal.trim() !== '');
666
+ const inputNum = validNum ? Number(rawVal) : NaN;
608
667
  const num = Number(match[2]);
609
- switch (match[1]) {
610
- case '>': {
611
- needReturn = inputNum <= num;
612
- break;
613
- }
614
- case '<': {
615
- needReturn = inputNum >= num;
616
- break;
617
- }
618
- case '>=': {
619
- needReturn = inputNum < num;
620
- break;
621
- }
622
- case '<=': {
623
- needReturn = inputNum > num;
624
- break;
625
- }
626
- case '=':
627
- case '==':
628
- case '===': {
629
- needReturn = inputNum !== num;
630
- break;
631
- }
632
- case '!=':
633
- case '<>': {
634
- needReturn = inputNum === num;
635
- break;
668
+ if (!Number.isFinite(inputNum)) {
669
+ needReturn = true;
670
+ }
671
+ else {
672
+ switch (match[1]) {
673
+ case '>': {
674
+ needReturn = inputNum <= num;
675
+ break;
676
+ }
677
+ case '<': {
678
+ needReturn = inputNum >= num;
679
+ break;
680
+ }
681
+ case '>=': {
682
+ needReturn = inputNum < num;
683
+ break;
684
+ }
685
+ case '<=': {
686
+ needReturn = inputNum > num;
687
+ break;
688
+ }
689
+ case '=':
690
+ case '==':
691
+ case '===': {
692
+ needReturn = inputNum !== num;
693
+ break;
694
+ }
695
+ case '!=':
696
+ case '<>': {
697
+ needReturn = inputNum === num;
698
+ break;
699
+ }
636
700
  }
637
701
  }
638
702
  }
@@ -659,8 +723,14 @@ export class Ctr {
659
723
  * @param ignore 忽略 xsrf 判断
660
724
  */
661
725
  _checkXInput(input, rule, rtn, ignore = false) {
662
- if (!ignore) {
663
- rule['_xsrf'] ??= ['require', this._cookie['XSRF-TOKEN'], [0, 'Bad request, no permission.']];
726
+ if (!ignore && !Object.hasOwn(rule, '_xsrf')) {
727
+ // --- 直接严格比对 XSRF Token,不把 Cookie 值塞入规则引擎,避免关键字/正则绕过与 ReDoS ---
728
+ const expected = this._cookie['XSRF-TOKEN'];
729
+ const submitted = input['_xsrf'];
730
+ if (typeof expected !== 'string' || !expected || typeof submitted !== 'string' || !safeEqualString(submitted, expected)) {
731
+ this._setCheckError(rtn, [0, 'Bad request, no permission.']);
732
+ return false;
733
+ }
664
734
  }
665
735
  return this._checkInput(input, rule, rtn);
666
736
  }
@@ -670,12 +740,14 @@ export class Ctr {
670
740
  */
671
741
  _enabledXsrf(opt) {
672
742
  // --- 设置 XSRF 值 ---
673
- if (this._cookie['XSRF-TOKEN'] === undefined) {
743
+ if (!this._cookie['XSRF-TOKEN']) {
674
744
  const xsrf = lCore.random(16, lCore.RANDOM_LUN);
675
745
  this._xsrf = xsrf;
676
746
  lCore.setCookie(this, 'XSRF-TOKEN', xsrf, {
677
747
  'path': '/',
748
+ 'ssl': this._config.const.https,
678
749
  'httponly': true,
750
+ 'samesite': 'Lax',
679
751
  'domain': opt?.domain,
680
752
  });
681
753
  this._cookie['XSRF-TOKEN'] = xsrf;
@@ -763,8 +835,11 @@ export class Ctr {
763
835
  * --- 获取 data JSON 数据 ---
764
836
  * @param path 文件路径(不含扩展名)
765
837
  */
766
- async _loadData(path) {
767
- const realPath = this._config.const.dataPath + path + '.json';
838
+ async _loadData(dataPath) {
839
+ const realPath = resolveInsideBase(this._config.const.dataPath, `${dataPath}.json`);
840
+ if (!realPath) {
841
+ return null;
842
+ }
768
843
  if (loadedData[realPath]) {
769
844
  return loadedData[realPath];
770
845
  }
@@ -799,9 +874,11 @@ export class Ctr {
799
874
  * @param opt Session 选项,cookie 为 false 时不读取或写入 Cookie
800
875
  * @returns 是否初始化成功,匿名会话也返回 true
801
876
  */
802
- _startSession(link, auth = false, opt = {}) {
803
- this._sess = new lSession.Session();
804
- return this._sess.init(this, link, auth, opt);
877
+ async _startSession(link, auth = false, opt = {}) {
878
+ const sess = new lSession.Session();
879
+ const ok = await sess.init(this, link, auth, opt);
880
+ this._sess = ok ? sess : null;
881
+ return ok;
805
882
  }
806
883
  // --- 本地化 ---
807
884
  /**
@@ -810,6 +887,13 @@ export class Ctr {
810
887
  * @param pkg 包名,为空自动填充为 default
811
888
  */
812
889
  async _loadLocale(loc, pkg = 'default') {
890
+ // --- 校验语言码与包名,防止目录穿越与原型污染 ---
891
+ if (!/^[a-zA-Z0-9_-]+$/.test(loc) || !/^[a-zA-Z0-9_.-]+$/.test(pkg) || pkg.includes('..')) {
892
+ return false;
893
+ }
894
+ if (loc === '__proto__' || loc === 'constructor' || loc === 'prototype') {
895
+ return false;
896
+ }
813
897
  const lName = loc + '.' + pkg;
814
898
  this._locale = loc;
815
899
  if (!this._localeFiles.includes(lName)) {
@@ -880,19 +964,21 @@ export class Ctr {
880
964
  const reqOrigin = this._headers['origin'] ?? '';
881
965
  if (opt.origins.includes(reqOrigin)) {
882
966
  this._res.setHeader('access-control-allow-origin', reqOrigin);
883
- this._res.setHeader('vary', 'Origin');
884
967
  }
885
- else {
886
- this._res.setHeader('access-control-allow-origin', opt.origins[0]);
887
- this._res.setHeader('vary', 'Origin');
968
+ const vary = this._res.getHeader('vary');
969
+ const rawVary = Array.isArray(vary) ? vary.join(',') : String(vary ?? '');
970
+ const varyList = rawVary.split(',').map(item => item.trim()).filter(Boolean);
971
+ if (!varyList.some(item => item === '*' || item.toLowerCase() === 'origin')) {
972
+ varyList.push('Origin');
973
+ this._res.setHeader('vary', varyList.join(', '));
888
974
  }
889
975
  }
890
- else {
976
+ else if (!opt.credentials) {
891
977
  this._res.setHeader('access-control-allow-origin', '*');
892
978
  }
893
979
  this._res.setHeader('access-control-allow-headers', opt.headers ?? '*');
894
980
  this._res.setHeader('access-control-allow-methods', opt.methods ?? '*');
895
- if (opt.credentials) {
981
+ if (opt.credentials && this._res.getHeader('access-control-allow-origin')) {
896
982
  this._res.setHeader('access-control-allow-credentials', 'true');
897
983
  }
898
984
  if (this._req.method === 'OPTIONS') {