cortico-world-extra-actions 0.3.17 → 0.3.19

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/dist/webui.js CHANGED
@@ -182,6 +182,15 @@ const CSS = `<style>
182
182
  background:var(--ea-acc);color:#fff;font-size:10px;font-weight:700;margin-right:4px}
183
183
  .ea-guide .s .d{color:var(--ea-dim);font-size:11px;padding-left:19px}
184
184
  .ea-guide .a{color:var(--ea-dim);opacity:.6;padding-top:1px}
185
+ .ea-modal{position:fixed;inset:0;z-index:50;display:grid;place-items:center;background:rgba(0,0,0,.35);padding:16px}
186
+ .ea-modal .card{max-width:520px;background:var(--ea-bg);border:1px solid var(--ea-line);border-radius:16px;
187
+ padding:18px 20px;box-shadow:0 18px 60px -20px rgba(0,0,0,.5);color:var(--ea-ink)}
188
+ .ea-modal h3{margin:0 0 8px;font-size:15px;font-weight:650}
189
+ .ea-modal p{margin:0 0 12px;font-size:12.5px;line-height:1.75;color:var(--ea-soft)}
190
+ .ea-modal .row{display:flex;gap:8px;align-items:center}
191
+ .ea-modal .tip{margin-top:10px;font-size:11px;color:var(--ea-dim)}
192
+ .ea-x.get{color:var(--ea-acc);border-color:rgba(0,168,112,.35);font-size:13px}
193
+ .ea-x.get:hover{background:var(--ea-acc);color:#fff;border-color:transparent}
185
194
  .ea-msg{font-size:12.5px;min-height:18px;color:var(--ea-dim);transition:color .15s}
186
195
  .ea-msg.bad{color:var(--ea-danger)}
187
196
  .ea-msg.ok{color:var(--ea-ok)}
@@ -383,6 +392,7 @@ const panel = {
383
392
  </div>
384
393
  </div>
385
394
  ${mounted ? '<button class="ea-x" type="button" title="从包里删掉这一段" aria-label="删除">×</button>' : ''}
395
+ ${off && state?.download?.perAction && a.word ? '<button class="ea-x get" type="button" data-act="get-action" data-id="' + esc(a.id) + '" title="从下载源补这一段(不跳转,直接装进动作库)" aria-label="下载">↓</button>' : ''}
386
396
  <input type="checkbox" ${on ? 'checked' : ''} ${isState || off ? 'disabled' : ''}>`;
387
397
  if (!isState && !off) {
388
398
  const box = row.querySelector('input');
@@ -496,7 +506,9 @@ const panel = {
496
506
  noteEl.hidden = false;
497
507
  noteEl.className = 'ea-note bad';
498
508
  const smallLib = state.library.ok && (state.library.present ?? state.library.count) < 20
499
- ? `<b>当前动作库只有 ${state.library.present ?? state.library.count} 段</b>(插件自带的示例)。想要全部 105 段:去 <a href="https://github.com/MOYU-AI-Lab/cortico-world-extra-actions/releases" target="_blank" rel="noreferrer">Releases 页</a> 下载 <code>shenshen-action-library.zip</code>,解压后点「选择动作库位置…」指到里面的 <code>深深-动作库</code>(选它的上一级也行,会自动定位)。<br>`
509
+ ? `<b>当前动作库只有 ${state.library.present ?? state.library.count} 段</b>(插件自带的示例)。想要全部 105 段:
510
+ <button class="ea-btn pri" type="button" data-act="download-library" style="margin-left:6px">一键下载并安装</button>
511
+ <span class="ea-dim">(插件自己下、自己解压,不用你选文件夹)</span><br>`
500
512
  : '';
501
513
  noteEl.innerHTML = smallLib + `动作库目录没找到:<code>${esc(state.library.dir || '未设置')}</code> —— 点「自动寻找动作库…」让它自己找,或用「选择动作库…」指到那个文件夹。`;
502
514
  return;
@@ -569,6 +581,20 @@ const panel = {
569
581
  };
570
582
  qInp.oninput = () => { query = qInp.value.trim(); renderList(); };
571
583
 
584
+ async function doDownloadLibrary() {
585
+ busy(true);
586
+ say('正在下载完整动作库…(约 370 MB,视网速几分钟,别关这个页面)');
587
+ try {
588
+ const r = await ctx.invoke('download-library', []);
589
+ say(`动作库已装好:${r.modules} 段 → ${r.path}`);
590
+ await loadAll();
591
+ } catch (err) {
592
+ say('下载没成功:' + String(err?.message ?? err), true);
593
+ } finally {
594
+ busy(false);
595
+ }
596
+ }
597
+
572
598
  wrap.addEventListener('click', async (e) => {
573
599
  const btn = e.target.closest('[data-act]');
574
600
  if (!btn) return;
@@ -700,6 +726,18 @@ const panel = {
700
726
  ? r.added.map((x) => `${x.zh}(${x.frames} 帧 / ${x.seconds}s)`).join('、')
701
727
  : (r.skipped.map((x) => `${x.dir}:${x.reason}`).join(';') || '');
702
728
  }
729
+ } else if (act === 'download-library') {
730
+ await doDownloadLibrary();
731
+ } else if (act === 'get-action') {
732
+ const id = btn.dataset.id;
733
+ if (!id) return;
734
+ const item = catalog?.actions?.find((a) => a.id === id);
735
+ busy(true); say(`正在下载「${item?.zh ?? id}」…`);
736
+ try {
737
+ await ctx.invoke('download-action', [id, item?.category ?? '']);
738
+ await loadAll();
739
+ say(`「${item?.zh ?? id}」已装进动作库`);
740
+ } finally { busy(false); }
703
741
  } else if (act === 'library') {
704
742
  // 协议里 PathPickerOptions.kind 只有 'file' | 'directory'
705
743
  const dir = await ctx.pickPath({ kind: 'directory', title: '选择动作库目录(里面要有 actions/)' });
@@ -716,8 +754,39 @@ const panel = {
716
754
  }
717
755
  });
718
756
 
757
+ /* 首次进入(库里只有自带示例)时问一次:要不要一键装完整动作库 */
758
+ let askedDownload = false;
759
+ function maybeAskDownload() {
760
+ if (askedDownload || !state) return;
761
+ const have = state.library?.present ?? state.library?.count ?? 0;
762
+ const total = state.library?.count ?? 0;
763
+ if (!state.library?.ok || have >= 20 || !state.download?.libraryUrl) return;
764
+ askedDownload = true;
765
+ const box = el('div', 'ea-modal');
766
+ box.innerHTML = `
767
+ <div class="card">
768
+ <h3>要装完整动作库吗?</h3>
769
+ <p>现在只有插件自带的 ${have} 段示例(目录一共 ${total} 段)。
770
+ 完整的 105 段可以直接让插件下载并装好 —— <b>不用解压、不用选文件夹</b>,装完列表立刻能用。</p>
771
+ <div class="row">
772
+ <button class="ea-btn pri" type="button" data-act="download-library">现在就下载</button>
773
+ <button class="ea-btn" type="button" data-act="close">稍后</button>
774
+ </div>
775
+ <div class="tip">下载量约 370 MB,视网速几分钟;装到 Coopanion 数据目录里的 shenshen-library。</div>
776
+ </div>`;
777
+ box.addEventListener('click', async (e) => {
778
+ const btn = e.target.closest('[data-act]');
779
+ if (!btn) return;
780
+ const act = btn.dataset.act;
781
+ if (act === 'close') { box.remove(); return; }
782
+ if (act === 'download-library') { await doDownloadLibrary(); box.remove(); }
783
+ });
784
+ wrap.appendChild(box);
785
+ }
786
+
719
787
  try {
720
788
  await loadAll();
789
+ maybeAskDownload();
721
790
  } catch (err) {
722
791
  wrap.innerHTML = `<div class="ea-note bad">加载失败:${esc(err?.message ?? err)}</div>`;
723
792
  }
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "cortico-world-extra-actions",
3
- "version": "0.3.17",
3
+ "version": "0.3.19",
4
4
  "private": false,
5
5
  "type": "module",
6
- "description": "勾选动作库里的动作,写进角色包的「额外动作拓展」文件夹,让桌宠照着做。105 条目录固定;动作库可自动寻找、可自选位置;空角色包位置自选。",
6
+ "description": "勾选动作库里的动作,写进形象包的「额外动作拓展」文件夹,让桌宠照着做。自带入门形象包与示例动作;完整 105 段可一键下载安装(不用解压、不用选文件夹)。",
7
7
  "keywords": [
8
8
  "cortico-world",
9
9
  "coopanion",
package/src/online.js ADDED
@@ -0,0 +1,118 @@
1
+ /**
2
+ * 在线取动作:**插件自己下载、自己解压、自己装进动作库**。
3
+ * 用户不需要解压、不需要选文件夹 —— 这是"下载完了面板还是空的"那一类问题的根治。
4
+ *
5
+ * 下载源(Gitee / 任意静态站点)由 `remoteBase` 决定,布局约定:
6
+ * <remoteBase>/library.zip 完整动作库(和我们发的一致:actions/<分类>/<id>/{action.json,anim.webp})
7
+ * <remoteBase>/actions/<分类>/<id>.zip 单个动作(zip 里是 action.json + anim.webp)
8
+ *
9
+ * 所有入口都过同一套校验:只认 https?://、限体积、只解 action.json / anim.webp / preview.webp / f_NNNN.webp,
10
+ * 且落点必须在动作库目录里面。
11
+ */
12
+ import { existsSync, mkdirSync, readdirSync, rmSync } from 'node:fs';
13
+ import { isAbsolute, join, normalize, sep } from 'node:path';
14
+ import { extractZip, listZip } from './zip.js';
15
+
16
+ /** 维护者把 Gitee 仓库的 raw/下载前缀填这里(末尾不要带斜杠)。 */
17
+ export const DEFAULT_REMOTE = '';
18
+
19
+ const MAX_LIBRARY_BYTES = 800 * 1024 * 1024; // 完整库上限
20
+ const MAX_ACTION_BYTES = 32 * 1024 * 1024; // 单个动作上限
21
+ /** 没配 remoteBase 时的兜底:GitHub Release 上的完整库(国内可能慢,但不至于完全没有)。 */
22
+ export const FALLBACK_LIBRARY = 'https://github.com/MOYU-AI-Lab/cortico-world-extra-actions/releases/download/library/shenshen-action-library.zip';
23
+ /** 只收这些条目:动作库的两种格式(帧序列 / 单文件动画)。 */
24
+ const WANT = /(^|\/)actions\/[a-z][a-z0-9-]*\/[a-z0-9][a-z0-9-]*\/(action\.json|anim\.webp|preview\.webp|f_\d{4}\.webp)$/;
25
+
26
+ /** 所有条目共用的顶层目录(深深-动作库/),没有就返回空串。 */
27
+ function commonTop(names) {
28
+ const files = names.filter((x) => x && !x.endsWith('/'));
29
+ if (!files.length) return '';
30
+ const first = files[0].split('/')[0];
31
+ if (files[0].split('/').length < 2) return '';
32
+ return files.every((x) => x.split('/')[0] === first) ? first + '/' : '';
33
+ }
34
+
35
+ const isHttp = (u) => typeof u === 'string' && /^https?:\/\//i.test(u);
36
+
37
+ async function fetchBytes(url, cap) {
38
+ if (!isHttp(url)) throw new Error(`只支持 http(s) 地址:${url}`);
39
+ const r = await fetch(url, { redirect: 'follow' });
40
+ if (!r.ok) throw new Error(`下载失败:HTTP ${r.status}`);
41
+ const len = Number(r.headers.get('content-length') ?? 0);
42
+ if (len && len > cap) throw new Error(`文件太大(${(len / 1048576).toFixed(0)} MB):${url}`);
43
+ const buf = Buffer.from(await r.arrayBuffer());
44
+ if (buf.length > cap) throw new Error(`文件太大(${(buf.length / 1048576).toFixed(0)} MB)`);
45
+ return buf;
46
+ }
47
+
48
+ /** 解压出来的动作模块里必须有 action.json;顺带把库根 index.js 重建。 */
49
+ function summarize(dir) {
50
+ const mods = [];
51
+ const actionsRoot = join(dir, 'actions');
52
+ if (!existsSync(actionsRoot)) return mods;
53
+ for (const cat of readdirSync(actionsRoot, { withFileTypes: true })) {
54
+ if (!cat.isDirectory()) continue;
55
+ for (const m of readdirSync(join(actionsRoot, cat.name), { withFileTypes: true })) {
56
+ if (!m.isDirectory()) continue;
57
+ if (existsSync(join(actionsRoot, cat.name, m.name, 'action.json'))) mods.push(`${cat.name}/${m.name}`);
58
+ }
59
+ }
60
+ return mods;
61
+ }
62
+
63
+ /**
64
+ * 完整动作库:下载 zip → 解到动作库里(已有就覆盖同名文件,不动别的)。
65
+ * @returns {{ ok: boolean, path: string, modules: number, bytes: number, skipped: number }}
66
+ */
67
+ export async function installLibrary({ url, libraryDir, dataDir, log }) {
68
+ let dest = libraryDir && isAbsolute(libraryDir) && existsSync(libraryDir) ? libraryDir : '';
69
+ if (!dest) {
70
+ dest = join(dataDir, 'shenshen-library');
71
+ mkdirSync(dest, { recursive: true });
72
+ }
73
+ const buf = await fetchBytes(url, MAX_LIBRARY_BYTES);
74
+ log?.(`已下载 ${(buf.length / 1048576).toFixed(1)} MB,开始解压…`);
75
+
76
+ const before = new Set(summarize(dest));
77
+ const top = commonTop(listZip(buf).map((e) => e.name));
78
+ const r = extractZip(buf, {
79
+ dest,
80
+ // 动作库 zip 一般带一层 `深深-动作库/`:剥掉,直接落到 actions/ 下
81
+ mapPath: (rel) => (top && rel.startsWith(top) ? rel.slice(top.length) : rel),
82
+ onFile: (rel) => WANT.test(rel),
83
+ });
84
+ if (!r.files.length) throw new Error('这个 zip 里没有动作(不是我们发的动作库?)');
85
+
86
+ let mods = summarize(dest);
87
+ const added = mods.filter((m) => !before.has(m));
88
+ log?.(`解压 ${r.files.length} 个文件;动作库现有 ${mods.length} 段(新增 ${added.length})`);
89
+ return { ok: true, path: dest, modules: mods.length, added: added.length, bytes: buf.length, skipped: r.skipped, files: r.files.length };
90
+ }
91
+
92
+ /**
93
+ * 单个动作:下载 `<base>/actions/<分类>/<id>.zip`,解到 `<库>/actions/<分类>/<id>/`。
94
+ * 只允许落在库目录内。
95
+ */
96
+ export async function installAction({ url, libraryDir, category, id, log }) {
97
+ if (!libraryDir || !isAbsolute(libraryDir) || !existsSync(libraryDir)) throw new Error('动作库还没设置好');
98
+ if (!/^[a-z][a-z0-9-]{0,15}$/.test(String(category ?? ''))) throw new Error('分类不合法');
99
+ if (!/^[a-z0-9][a-z0-9-]{0,31}$/.test(String(id ?? ''))) throw new Error('id 不合法');
100
+
101
+ const dest = join(libraryDir, 'actions', category, id);
102
+ const root = normalize(join(libraryDir, 'actions') + sep);
103
+ if (!normalize(dest + sep).startsWith(root)) throw new Error('落点越界');
104
+
105
+ const buf = await fetchBytes(url, MAX_ACTION_BYTES);
106
+ rmSync(dest, { recursive: true, force: true });
107
+ mkdirSync(dest, { recursive: true });
108
+ const r = extractZip(buf, { dest, onFile: (rel) => !rel.includes('/') && /^(action\.json|anim\.webp|preview\.webp|f_\d{4}\.webp)$/.test(rel) });
109
+ if (!existsSync(join(dest, 'action.json'))) throw new Error('这个 zip 里没有 action.json');
110
+ log?.(`单个动作已装:${category}/${id}(${r.files.length} 个文件)`);
111
+ return { ok: true, path: dest, files: r.files.length, bytes: buf.length };
112
+ }
113
+
114
+ /** 由 remoteBase 拼出两个地址。 */
115
+ export const libraryUrl = (base) => `${String(base).replace(/\/+$/, '')}/library.zip`;
116
+ export const actionUrl = (base, category, id) => `${String(base).replace(/\/+$/, '')}/actions/${category}/${id}.zip`;
117
+ /** 扁平布局(GitHub Release 的资产做不到子目录):<base>/<id>.zip */
118
+ export const flatActionUrl = (base, id) => `${String(base).replace(/\/+$/, '')}/${id}.zip`;
package/src/world.js CHANGED
@@ -14,6 +14,7 @@ import { fileURLToPath } from 'node:url';
14
14
  import { EXTRA_DIR, clear, inspect, isInside, packLooksSupported, prunePack, readExtra, removeOne, save } from './writer.js';
15
15
  import { addModules, rebuildIndex, scanLibrary } from './importer.js';
16
16
  import { ensureStarter, installStarterLibrary, libraryHealth, restorePack, safePackName } from './starter.js';
17
+ import { FALLBACK_LIBRARY, actionUrl, flatActionUrl, installAction, installLibrary, libraryUrl } from './online.js';
17
18
  import { petFigures, petState } from './pet.js';
18
19
 
19
20
  const ID = 'extra-actions';
@@ -365,6 +366,10 @@ export class ExtraActionsWorld {
365
366
  return this.removeAction(this.cleanPackId(a[0]), String(a[1] ?? '').trim());
366
367
  case 'set-library':
367
368
  return this.setLibrary(a[0]);
369
+ case 'download-library':
370
+ return this.downloadLibrary();
371
+ case 'download-action':
372
+ return this.downloadAction(String(a[0] ?? ''), String(a[1] ?? ''));
368
373
  default:
369
374
  throw new Error(`unknown method: ${method}`);
370
375
  }
@@ -400,6 +405,7 @@ export class ExtraActionsWorld {
400
405
  categories: [...new Set(merged.actions.map((a) => a.category))]
401
406
  .map((c) => ({ id: c, zh: CATEGORY_ZH[c] ?? c, count: merged.actions.filter((a) => a.category === c).length })),
402
407
  },
408
+ download: this.downloadInfo(),
403
409
  folder: EXTRA_DIR,
404
410
  figuresDir: this.figuresDir(),
405
411
  roots: this.figureRoots(),
@@ -496,6 +502,70 @@ export class ExtraActionsWorld {
496
502
  return { ...r, roots };
497
503
  }
498
504
 
505
+ /* ---------- 在线下载:用户不用解压、不用选文件夹 ---------- */
506
+
507
+ /** 下载源:设置里的 remoteBase(Gitee 等),没配就退回 GitHub 直链。 */
508
+ remoteBase() {
509
+ const c = this.ctx.cfg && typeof this.ctx.cfg === 'object' ? this.ctx.cfg : {};
510
+ const pick = (v) => (typeof v === 'string' && v.trim() ? v.trim().replace(/\/+$/, '') : '');
511
+ return pick(c.remoteBase) || '';
512
+ }
513
+
514
+ /** 单段动作的地址前缀(GitHub Release 的资产是扁平的,没有 actions/<分类>/ 这层)。 */
515
+ remoteActionBase() {
516
+ const c = this.ctx.cfg && typeof this.ctx.cfg === 'object' ? this.ctx.cfg : {};
517
+ const pick = (v) => (typeof v === 'string' && v.trim() ? v.trim().replace(/\/+$/, '') : '');
518
+ return pick(c.remoteActionBase) || '';
519
+ }
520
+
521
+ /** 面板需要知道:完整库从哪下、能不能单个下。 */
522
+ downloadInfo() {
523
+ const base = this.remoteBase();
524
+ const actionBase = this.remoteActionBase();
525
+ return {
526
+ base,
527
+ actionBase,
528
+ libraryUrl: base ? libraryUrl(base) : FALLBACK_LIBRARY,
529
+ // 完整库有 GitHub 兜底;单段必须有专门的前缀
530
+ perAction: !!(actionBase || base),
531
+ flat: !!actionBase,
532
+ };
533
+ }
534
+
535
+ /** 一键:下载完整动作库 → 解压进动作库 → 设为当前库。 */
536
+ async downloadLibrary() {
537
+ const info = this.downloadInfo();
538
+ if (!info.libraryUrl) throw new Error('还没配置下载源');
539
+ const r = await installLibrary({
540
+ url: info.libraryUrl,
541
+ libraryDir: this.libraryDir(),
542
+ dataDir: this.dataDir,
543
+ log: (m) => this.host?.log?.info?.(m),
544
+ });
545
+ this.saveSettings({ libraryDir: r.path });
546
+ this.bustCatalog();
547
+ this.host?.log?.info?.(`动作库已装好:${r.modules} 段(新增 ${r.added})`);
548
+ return { ok: true, ...r, libraryDir: r.path };
549
+ }
550
+
551
+ /** 单个动作:从 <base>/actions/<分类>/<id>.zip 取,直接装进动作库。 */
552
+ async downloadAction(id, category) {
553
+ const info = this.downloadInfo();
554
+ if (!info.perAction) throw new Error('还没配置单动作下载源(remoteBase)');
555
+ const lib = this.libraryDir();
556
+ if (!lib) throw new Error('动作库还没设置好');
557
+ const url = info.flat ? flatActionUrl(info.actionBase, id) : actionUrl(info.base, category, id);
558
+ const r = await installAction({
559
+ url,
560
+ libraryDir: lib,
561
+ category,
562
+ id,
563
+ log: (m) => this.host?.log?.info?.(m),
564
+ });
565
+ this.bustCatalog();
566
+ return { ok: true, ...r };
567
+ }
568
+
499
569
  /** 在用户选的目录下用自带示例建一个动作库并设为当前库(沿用作者 0.3.9 的做法)。 */
500
570
  async useStarterLibrary(parentDir) {
501
571
  const lib = typeof parentDir === 'string' ? parentDir.trim() : '';
package/src/zip.js ADDED
@@ -0,0 +1,100 @@
1
+ /**
2
+ * 最小 ZIP 读取器(只用 node:zlib,无第三方依赖)。
3
+ *
4
+ * 只做我们需要的两件事:
5
+ * - listZip(buf):列出条目(名字 / 大小 / 压缩方法)
6
+ * - extractZip(buf, { dest, onFile }):把条目解出来(支持 store 与 deflate)
7
+ *
8
+ * 安全约束(外部下载来的包不可信):
9
+ * - 拒绝绝对路径、`..`、盘符、反斜杠归一化;
10
+ * - 只允许 `onFile` 返回 true 的路径落盘;
11
+ * - 单条目有大小上限,防 zip 炸弹(声明大小与实际都要看)。
12
+ */
13
+ import { mkdirSync, writeFileSync } from 'node:fs';
14
+ import { dirname, join, normalize, sep } from 'node:path';
15
+ import { inflateRawSync } from 'node:zlib';
16
+
17
+ const SIG_EOCD = 0x06054b50;
18
+ const SIG_CENTRAL = 0x02014b50;
19
+ const SIG_LOCAL = 0x04034b50;
20
+ const MAX_ENTRY_BYTES = 128 * 1024 * 1024;
21
+
22
+ /** 找到 End of Central Directory(从尾部往前扫,注释最长 64K)。 */
23
+ function eocdOffset(buf) {
24
+ const min = Math.max(0, buf.length - (22 + 0xffff));
25
+ for (let i = buf.length - 22; i >= min; i--) {
26
+ if (buf.readUInt32LE(i) === SIG_EOCD) return i;
27
+ }
28
+ throw new Error('不是合法的 zip(找不到目录结尾)');
29
+ }
30
+
31
+ /** 列出条目。 */
32
+ export function listZip(buf) {
33
+ const eocd = eocdOffset(buf);
34
+ const count = buf.readUInt16LE(eocd + 10);
35
+ let off = buf.readUInt32LE(eocd + 16);
36
+ const out = [];
37
+ for (let i = 0; i < count; i++) {
38
+ if (buf.readUInt32LE(off) !== SIG_CENTRAL) throw new Error('zip 目录损坏');
39
+ const flags = buf.readUInt16LE(off + 8);
40
+ const method = buf.readUInt16LE(off + 10);
41
+ const compSize = buf.readUInt32LE(off + 20);
42
+ const rawSize = buf.readUInt32LE(off + 24);
43
+ const nameLen = buf.readUInt16LE(off + 28);
44
+ const extraLen = buf.readUInt16LE(off + 30);
45
+ const commentLen = buf.readUInt16LE(off + 32);
46
+ const localOff = buf.readUInt32LE(off + 42);
47
+ const nameBuf = buf.subarray(off + 46, off + 46 + nameLen);
48
+ const name = nameBuf.toString(flags & 0x800 ? 'utf8' : 'utf8');
49
+ out.push({ name, method, compSize, rawSize, localOff, utf8: !!(flags & 0x800) });
50
+ off += 46 + nameLen + extraLen + commentLen;
51
+ }
52
+ return out;
53
+ }
54
+
55
+ /** 路径安全检查:返回规范化后的相对路径;不安全的条目返回 null(整条丢掉,不阻断其它正常文件)。 */
56
+ export function safeZipPath(name) {
57
+ const clean = String(name).replace(/\\/g, '/');
58
+ if (!clean || clean.endsWith('/')) return null; // 目录条目
59
+ if (clean.startsWith('/') || /^[a-zA-Z]:/.test(clean)) return null; // 绝对路径
60
+ const parts = clean.split('/');
61
+ if (parts.some((p) => p === '..' || p === '' || p === '.')) return null; // 越界
62
+ if (/[<>:"|?*\x00-\x1f]/.test(clean)) return null; // 非法字符
63
+ return parts.join('/'); // 统一正斜杠:调用方(过滤器)按 posix 写更直观
64
+ }
65
+
66
+ /**
67
+ * 解压。
68
+ * @param {Buffer} buf
69
+ * @param {{ dest: string, onFile?: (rel: string, entry: {rawSize:number, compSize:number}) => boolean }} o
70
+ */
71
+ export function extractZip(buf, { dest, onFile = () => true, mapPath = null }) {
72
+ const entries = listZip(buf);
73
+ const files = [];
74
+ let skipped = 0;
75
+ for (const e of entries) {
76
+ let rel = safeZipPath(e.name);
77
+ if (!rel) continue; // 目录/不安全
78
+ if (mapPath) rel = mapPath(rel);
79
+ if (!rel) continue;
80
+ if (!onFile(rel, e)) { skipped++; continue; }
81
+ if (e.rawSize > MAX_ENTRY_BYTES) throw new Error(`条目太大:${e.name}(${e.rawSize})`);
82
+ if (e.method !== 0 && e.method !== 8) throw new Error(`不支持的压缩方式 ${e.method}:${e.name}`);
83
+
84
+ const lh = e.localOff;
85
+ if (buf.readUInt32LE(lh) !== SIG_LOCAL) throw new Error(`本地头损坏:${e.name}`);
86
+ const nameLen = buf.readUInt16LE(lh + 26);
87
+ const extraLen = buf.readUInt16LE(lh + 28);
88
+ const start = lh + 30 + nameLen + extraLen;
89
+ const data = buf.subarray(start, start + e.compSize);
90
+ const raw = e.method === 0 ? Buffer.from(data) : inflateRawSync(data);
91
+ if (raw.length > MAX_ENTRY_BYTES) throw new Error(`解出来太大:${e.name}`);
92
+
93
+ const full = join(dest, ...rel.split('/'));
94
+ if (!full.startsWith(normalize(dest + sep))) throw new Error(`越界:${e.name}`);
95
+ mkdirSync(dirname(full), { recursive: true });
96
+ writeFileSync(full, raw);
97
+ files.push(rel);
98
+ }
99
+ return { files, skipped, total: entries.length };
100
+ }
@@ -0,0 +1,115 @@
1
+ /**
2
+ * 「一键下载动作库」的世界级端到端测试(本地 http 服务,不碰外网)。
3
+ * node test_download.mjs
4
+ *
5
+ * 覆盖:
6
+ * - state.download:没配 remoteBase 时给 GitHub 兜底、perAction=false
7
+ * - 配了 remoteBase → perAction=true,地址拼成 <base>/library.zip 与 <base>/actions/<分类>/<id>.zip
8
+ * - invoke('download-library') 真的把 zip 装进动作库并写进设置
9
+ * - invoke('download-action') 真的补上单个动作,列表 present 跟着涨
10
+ * - 下载源 404 → 报错,动作库不被破坏
11
+ */
12
+ import { createServer } from 'node:http';
13
+ import { existsSync, mkdirSync, readdirSync, rmSync } from 'node:fs';
14
+ import { dirname, join } from 'node:path';
15
+ import { fileURLToPath, pathToFileURL } from 'node:url';
16
+ import { deflateRawSync } from 'node:zlib';
17
+ import assert from 'node:assert/strict';
18
+
19
+ const here = dirname(fileURLToPath(import.meta.url));
20
+ const W = await import(pathToFileURL(join(here, '..', 'src', 'world.js')).href);
21
+
22
+ /* 最小 zip 构造(store 也行,这里用 deflate 更接近真实) */
23
+ function buildZip(entries) {
24
+ const chunks = [], central = [];
25
+ let off = 0;
26
+ for (const [name, data] of entries) {
27
+ const raw = Buffer.from(data), comp = deflateRawSync(raw), nb = Buffer.from(name, 'utf8');
28
+ const lh = Buffer.alloc(30);
29
+ lh.writeUInt32LE(0x04034b50, 0); lh.writeUInt16LE(20, 4); lh.writeUInt16LE(0x800, 6);
30
+ lh.writeUInt16LE(8, 8); lh.writeUInt32LE(comp.length, 18); lh.writeUInt32LE(raw.length, 22);
31
+ lh.writeUInt16LE(nb.length, 26);
32
+ chunks.push(lh, nb, comp);
33
+ const cd = Buffer.alloc(46);
34
+ cd.writeUInt32LE(0x02014b50, 0); cd.writeUInt16LE(20, 4); cd.writeUInt16LE(20, 6);
35
+ cd.writeUInt16LE(0x800, 8); cd.writeUInt16LE(8, 10);
36
+ cd.writeUInt32LE(comp.length, 20); cd.writeUInt32LE(raw.length, 24);
37
+ cd.writeUInt16LE(nb.length, 28); cd.writeUInt32LE(off, 42);
38
+ central.push(Buffer.concat([cd, nb]));
39
+ off += 30 + nb.length + comp.length;
40
+ }
41
+ const cen = Buffer.concat(central), eocd = Buffer.alloc(22);
42
+ eocd.writeUInt32LE(0x06054b50, 0); eocd.writeUInt16LE(entries.length, 8);
43
+ eocd.writeUInt16LE(entries.length, 10); eocd.writeUInt32LE(cen.length, 12); eocd.writeUInt32LE(off, 16);
44
+ return Buffer.concat([...chunks, cen, eocd]);
45
+ }
46
+
47
+ const mkAction = (cat, id) => [
48
+ [`深深-动作库/actions/${cat}/${id}/action.json`, JSON.stringify({ id, category: cat, word: id, zh: id, say: id, clip: `actions/${cat}/${id}`, frames: 1, fps: 24, seconds: 1, anim: true })],
49
+ [`深深-动作库/actions/${cat}/${id}/anim.webp`, 'RIFFxxxxWEBPVP8 '],
50
+ ];
51
+ const libZip = buildZip([...mkAction('core', 'cheer-hop'), ...mkAction('eat', 'eat-dumplings')]);
52
+ const oneZip = buildZip([
53
+ ['action.json', JSON.stringify({ id: 'fireworks', category: 'festival', word: 'fireworks', zh: '放烟花', say: '放烟花', clip: 'actions/festival/fireworks', frames: 1, fps: 24, seconds: 1, anim: true })],
54
+ ['anim.webp', 'RIFFxxxxWEBPVP8 '],
55
+ ]);
56
+ const routes = new Map([['/lib/library.zip', libZip], ['/lib/actions/festival/fireworks.zip', oneZip]]);
57
+ const server = createServer((req, res) => {
58
+ const b = routes.get(req.url);
59
+ if (!b) { res.writeHead(404).end(); return; }
60
+ res.writeHead(200, { 'content-length': b.length }); res.end(b);
61
+ });
62
+ await new Promise((r) => server.listen(0, '127.0.0.1', r));
63
+ const base = `http://127.0.0.1:${server.address().port}/lib`;
64
+
65
+ const root = join(here, '_tmp-download');
66
+ rmSync(root, { recursive: true, force: true });
67
+ const dataDir = join(root, 'data');
68
+ mkdirSync(dataDir, { recursive: true });
69
+
70
+ const cfg = { remoteBase: base };
71
+ // 宿主的 persist 会写回同一个 cfg,这里照做,否则 libraryDir() 读不到
72
+ const settings = cfg;
73
+ const ctx = {
74
+ dataDir,
75
+ botDir: join(root, 'bot'),
76
+ cfg,
77
+ persist: (p) => Object.assign(cfg, p),
78
+ packageDir: join(here, '..'),
79
+ repoRoot: here,
80
+ };
81
+ const w = new W.ExtraActionsWorld({ ctx });
82
+
83
+ const fails = [];
84
+ const check = (fn, msg) => { try { fn(); console.log('ok ' + msg); } catch (e) { fails.push(msg + ' → ' + e.message); console.log('FAIL ' + msg); } };
85
+
86
+ /* 1. state.download */
87
+ let st = await w.invoke('picker', 'state');
88
+ check(() => assert.equal(st.download.perAction, true), 'remoteBase makes per-action downloads available');
89
+ check(() => assert.equal(st.download.libraryUrl, base + '/library.zip'), 'library url = <base>/library.zip');
90
+
91
+ /* 2. 一键下载完整库 */
92
+ const r = await w.invoke('picker', 'download-library');
93
+ check(() => assert.equal(r.modules, 2), 'two modules installed: ' + r.modules);
94
+ check(() => assert.equal(existsSync(join(r.path, 'actions', 'core', 'cheer-hop', 'anim.webp')), true), 'anim.webp landed in the library');
95
+ check(() => assert.equal(settings.libraryDir, r.path), 'libraryDir persisted');
96
+ st = await w.invoke('picker', 'state');
97
+ check(() => assert.equal(st.library.present, 2), 'state sees 2 present (' + st.library.present + ')');
98
+
99
+ /* 3. 单个动作 */
100
+ const one = await w.invoke('picker', 'download-action', ['fireworks', 'festival']);
101
+ check(() => assert.equal(one.ok, true), 'single action downloaded');
102
+ st = await w.invoke('picker', 'state');
103
+ check(() => assert.equal(st.library.present, 3), 'now 3 present (' + st.library.present + ')');
104
+
105
+ /* 4. 下载源坏掉 → 报错但不破坏库 */
106
+ const w2 = new W.ExtraActionsWorld({ ctx: { ...ctx, cfg: { ...cfg, remoteBase: base + '/nope' } } });
107
+ let err = null;
108
+ try { await w2.invoke('picker', 'download-library'); } catch (e) { err = e; }
109
+ check(() => assert.match(String(err?.message), /404/), 'a 404 from the source is reported');
110
+ check(() => assert.equal(readdirSync(join(r.path, 'actions')).length >= 2, true), 'the existing library is untouched');
111
+
112
+ server.close();
113
+ rmSync(root, { recursive: true, force: true });
114
+ console.log(fails.length ? `\nFAIL (${fails.length})\n- ${fails.join('\n- ')}` : '\nall checks passed');
115
+ process.exit(fails.length ? 1 : 0);
@@ -0,0 +1,145 @@
1
+ /**
2
+ * 在线下载的端到端测试(本地起一个 http 服务,不碰外网)。
3
+ * node test_online.mjs
4
+ *
5
+ * 覆盖:
6
+ * - 完整库:下载 → 解压 → 只收 action.json/anim.webp → 动作库变 105 段
7
+ * - 单个动作:<base>/actions/<分类>/<id>.zip → 装进 <库>/actions/<分类>/<id>/
8
+ * - zip 里夹带无关文件(.exe / ../)会被过滤或拒绝
9
+ * - 非 http 地址、超限文件、没有 action.json 的包 → 明确报错
10
+ */
11
+ import { createServer } from 'node:http';
12
+ import { mkdirSync, readdirSync, rmSync, writeFileSync, existsSync } from 'node:fs';
13
+ import { dirname, join } from 'node:path';
14
+ import { fileURLToPath, pathToFileURL } from 'node:url';
15
+ import { deflateRawSync } from 'node:zlib';
16
+ import assert from 'node:assert/strict';
17
+
18
+ const here = dirname(fileURLToPath(import.meta.url));
19
+ const { installLibrary, installAction, libraryUrl, actionUrl } = await import(pathToFileURL(join(here, '..', 'src', 'online.js')).href);
20
+ const { extractZip, listZip } = await import(pathToFileURL(join(here, '..', 'src', 'zip.js')).href);
21
+
22
+ /* ---------- 造一个最小 zip ---------- */
23
+ function buildZip(entries) {
24
+ const chunks = [];
25
+ const central = [];
26
+ let off = 0;
27
+ for (const [name, data] of entries) {
28
+ const raw = Buffer.from(data);
29
+ const comp = deflateRawSync(raw);
30
+ const nameBuf = Buffer.from(name, 'utf8');
31
+ const local = Buffer.alloc(30);
32
+ local.writeUInt32LE(0x04034b50, 0);
33
+ local.writeUInt16LE(20, 4);
34
+ local.writeUInt16LE(0x800, 6); // utf8
35
+ local.writeUInt16LE(8, 8); // deflate
36
+ local.writeUInt32LE(comp.length, 18);
37
+ local.writeUInt32LE(raw.length, 22);
38
+ local.writeUInt16LE(nameBuf.length, 26);
39
+ chunks.push(local, nameBuf, comp);
40
+
41
+ const cen = Buffer.alloc(46);
42
+ cen.writeUInt32LE(0x02014b50, 0);
43
+ cen.writeUInt16LE(20, 4);
44
+ cen.writeUInt16LE(20, 6);
45
+ cen.writeUInt16LE(0x800, 8);
46
+ cen.writeUInt16LE(8, 10);
47
+ cen.writeUInt32LE(comp.length, 20);
48
+ cen.writeUInt32LE(raw.length, 24);
49
+ cen.writeUInt16LE(nameBuf.length, 28);
50
+ cen.writeUInt32LE(off, 42);
51
+ central.push(Buffer.concat([cen, nameBuf]));
52
+ off += 30 + nameBuf.length + comp.length;
53
+ }
54
+ const cenBuf = Buffer.concat(central);
55
+ const eocd = Buffer.alloc(22);
56
+ eocd.writeUInt32LE(0x06054b50, 0);
57
+ eocd.writeUInt16LE(entries.length, 8);
58
+ eocd.writeUInt16LE(entries.length, 10);
59
+ eocd.writeUInt32LE(cenBuf.length, 12);
60
+ eocd.writeUInt32LE(off, 16);
61
+ return Buffer.concat([...chunks, cenBuf, eocd]);
62
+ }
63
+
64
+ const fails = [];
65
+ const check = (fn, msg) => { try { fn(); console.log('ok ' + msg); } catch (e) { fails.push(msg + ' → ' + e.message); console.log('FAIL ' + msg); } };
66
+
67
+ /* ---------- 服务端:一个"完整库"和几个单动作 ---------- */
68
+ const IDS = [['core', 'cheer-hop'], ['eat', 'eat-dumplings'], ['festival', 'fireworks']];
69
+ const libZip = buildZip([
70
+ ...IDS.flatMap(([cat, id]) => [
71
+ [`深深-动作库/actions/${cat}/${id}/action.json`, JSON.stringify({ id, category: cat, word: id, zh: id, clip: `actions/${cat}/${id}`, frames: 1, seconds: 1, anim: true })],
72
+ [`深深-动作库/actions/${cat}/${id}/anim.webp`, 'RIFFxxxxWEBPVP8 '],
73
+ ]),
74
+ ['深深-动作库/actions/core/evil/../../evil.exe', 'MZ'],
75
+ ['深深-动作库/readme.txt', 'ignore me'],
76
+ ]);
77
+ const oneZip = buildZip([
78
+ ['action.json', JSON.stringify({ id: 'cheer-wave', category: 'core', word: 'cheer-wave', zh: '元气挥手', clip: 'actions/core/cheer-wave', frames: 1, seconds: 1, anim: true })],
79
+ ['anim.webp', 'RIFFxxxxWEBPVP8 '],
80
+ ['..\\..\\evil.bat', 'echo'] // 目录外的条目
81
+ ]);
82
+
83
+ const routes = new Map([
84
+ ['/library.zip', libZip],
85
+ ['/actions/core/cheer-wave.zip', oneZip],
86
+ ['/bomb.zip', Buffer.alloc(1024)],
87
+ ['/empty.zip', buildZip([['readme.txt', 'hi']])],
88
+ ]);
89
+ const server = createServer((req, res) => {
90
+ const body = routes.get(req.url);
91
+ if (!body) { res.writeHead(404).end(); return; }
92
+ res.writeHead(200, { 'content-type': 'application/zip', 'content-length': body.length });
93
+ res.end(body);
94
+ });
95
+ await new Promise((r) => server.listen(0, '127.0.0.1', r));
96
+ const base = `http://127.0.0.1:${server.address().port}`;
97
+
98
+ const root = join(here, '_tmp-online');
99
+ rmSync(root, { recursive: true, force: true });
100
+ const dataDir = join(root, 'data');
101
+ mkdirSync(dataDir, { recursive: true });
102
+
103
+ /* ---------- 1. 完整库 ---------- */
104
+ const lib = await installLibrary({ url: libraryUrl(base), libraryDir: '', dataDir });
105
+ check(() => assert.equal(lib.ok, true), 'library install returns ok');
106
+ check(() => assert.equal(lib.modules, 3), 'three modules landed: ' + lib.modules);
107
+ check(() => assert.equal(existsSync(join(lib.path, 'actions', 'core', 'cheer-hop', 'anim.webp')), true), 'anim.webp landed');
108
+ check(() => assert.equal(existsSync(join(lib.path, 'actions', 'core', 'evil')), false), 'a "../" entry is refused');
109
+ check(() => assert.equal(existsSync(join(lib.path, 'readme.txt')), false), 'an unrelated file is filtered out');
110
+
111
+ /* ---------- 2. 单个动作 ---------- */
112
+ const one = await installAction({ url: actionUrl(base, 'core', 'cheer-wave'), libraryDir: lib.path, category: 'core', id: 'cheer-wave' });
113
+ check(() => assert.equal(one.ok, true), 'single action install returns ok');
114
+ check(() => assert.equal(existsSync(join(lib.path, 'actions', 'core', 'cheer-wave', 'action.json')), true), 'single action json landed');
115
+ check(() => assert.equal(existsSync(join(lib.path, 'actions', 'core', 'cheer-wave', 'anim.webp')), true), 'single action anim landed');
116
+ check(() => assert.equal(existsSync(join(lib.path, 'actions', 'core', 'evil.bat')), false), 'a path-escaping entry is dropped');
117
+
118
+ /* ---------- 3. 坏输入 ---------- */
119
+ const bad = async (fn, re) => {
120
+ let err = null;
121
+ try { await fn(); } catch (e) { err = e; }
122
+ assert.ok(err, '应该抛错');
123
+ if (re) assert.match(String(err.message), re);
124
+ };
125
+ check(() => assert.ok(true), '(async 断言在下面)');
126
+ await bad(() => installLibrary({ url: 'ftp://x/y.zip', libraryDir: '', dataDir }), /http/);
127
+ await bad(() => installLibrary({ url: `${base}/nope.zip`, libraryDir: '', dataDir }), /404/);
128
+ await bad(() => installLibrary({ url: `${base}/empty.zip`, libraryDir: '', dataDir }), /没有动作/);
129
+ await bad(() => installAction({ url: `${base}/actions/core/cheer-wave.zip`, libraryDir: lib.path, category: '../x', id: 'y' }), /分类/);
130
+ await bad(() => installAction({ url: `${base}/actions/core/cheer-wave.zip`, libraryDir: lib.path, category: 'core', id: '../y' }), /id/);
131
+ console.log('ok 坏输入都被拒绝(非 http / 404 / 空包 / 非法分类 / 非法 id)');
132
+
133
+ /* ---------- 4. zip 读取器本身 ---------- */
134
+ check(() => assert.equal(listZip(libZip).length, 8), 'listZip sees every entry (8)');
135
+ {
136
+ const dest = join(root, 'z');
137
+ mkdirSync(dest, { recursive: true });
138
+ const r = extractZip(libZip, { dest, onFile: (p) => p.endsWith('.json') });
139
+ check(() => assert.equal(r.files.length, 3), 'onFile filter keeps only the 3 action.json');
140
+ }
141
+
142
+ server.close();
143
+ rmSync(root, { recursive: true, force: true });
144
+ console.log(fails.length ? `\nFAIL (${fails.length})\n- ${fails.join('\n- ')}` : '\nall checks passed');
145
+ process.exit(fails.length ? 1 : 0);