Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

feat(plugins): 收编 penguin-plugins 的 csu-mail 与 wechat-miniprogram,发布到 npm

lmliheng0003f63ba67f
diff --git a/FORK-PROGRESS.md b/FORK-PROGRESS.md
index 5c969609..af68bbe5 100644
--- a/FORK-PROGRESS.md
+++ b/FORK-PROGRESS.md
@@ -975,3 +975,41 @@ registry 上还不存在的名字没有配置可查,OIDC 换不到 token,流
仓库里)。
- **口径**:3003 那台静态站只当开发区内部交付用(用户原话「不用给别人用」),任何对外文本
(Release 正文、README、发布正文、文档)都不写它的地址;安装包对外只走 GitHub Release。
+
+## 两个外部插件入库并发布到 npm(2026-10-05,用户点单)
+
+### 用户说的
+
+「你怎么没把我的插件仓库的两插件传到 npm」—— `lmliheng/penguin-plugins` 里的 `csu-mail` 与
+`wechat-miniprogram`。上一轮首发布时它们**根本不在这棵树里**(在另一个仓库),所以没发。
+
+### 做了什么
+
+- 两个插件从 `lmliheng/penguin-plugins` 搬进 `plugins/`,按 fork 的插件规矩对齐:`package.json`
+ 改名 `@lmliheng/<name>`、版本跟当前 dev 版本 `0.2.13`、补 `repository.directory` 与 `LICENSE`;
+ 删掉误入库的 `__pycache__`。
+- `SKILL.md` 的 frontmatter 按本仓库约定瘦身(文件里只留 `name` + `description`;`version` 与
+ `short_description(_zh)` 归 `plugin.json`,安装时盖章),并补上每个内置技能都有的
+ `## Before you start`。
+- `wechat-miniprogram` 补 `category: software-development` —— 原来没有分类会掉进 Other 组,而
+ `plugins.test.ts` 断言库里四个分类都有人、不留 Other。
+- 接进依赖链:`packages/{core,cli,desktop}/package.json` 各加两条 `workspace:*`。内置插件是靠宿主
+ 包的 `dependencies` 经 Node 解析出来的(`builtinRoots()`),不写这两条,插件就在库里看不见。
+- 同步三处「必须提到每个插件」的守卫:`plugins/README.md` 与 `README.zh.md` 的分类表、
+ `packages/docs/content/skills.{zh,en}.md` 的插件表、`packages/core/test/plugins.test.ts` 的 14 → 16。
+- 发布:`pnpm --filter <name> publish --access public --no-git-checks`,`@lmliheng/[email protected]`
+ 与 `@lmliheng/[email protected]` 都 `✅ Published`。
+- 搬进来的 25 个脚本/模板按本仓库 prettier 重新格式化(它们来自另一个仓库,没过这边的门禁)。
+
+### 验证
+
+- `pnpm -r test` 全绿:docs 62 · ui 1000 · core 1350(+5 跳过) · server 2592(+2 跳过) · cli 505 ·
+ web 2891(+2 跳过) · desktop 279 · ui-gallery 131 · 四个沙箱插件 71。
+- `pnpm typecheck` 八包过;`pnpm lint` 0 警告;`pnpm format:check` 干净。
+- registry:两个新名字的版本端点都 200。
+
+### 没做 / 待办
+
+- **没删 `lmliheng/penguin-plugins`**(用户要求"传上去之后删"):放在最后一步,等 npm 与这个仓库
+ 这两份备份都推上去、插件市场不再依赖那个仓库的 URL 之后再删(令牌有 `delete_repo` 权限)。
+- 插件市场、「按需发版 + 邮件汇报」的定时循环都还没做;设计与计划写在 `/root/evolution/PLAN.md`。
diff --git a/README.zh.md b/README.zh.md
index 0e297e45..3f3cce1b 100644
--- a/README.zh.md
+++ b/README.zh.md
@@ -72,8 +72,8 @@ https://github.com/user-attachments/assets/aec49ae9-b743-467b-b247-37bedfeaa36e
| 分类 | 插件 |
| ----------- | ------------------------------------------------------------------------------- |
-| 办公效率 | `data-analysis`、`use-firecrawl`、`browser-automation`、`use-bento-slides`、`humanizer`、`goal`、`continual-learning` |
-| 软件开发 | `software-development`、`use-claude-code` |
+| 办公效率 | `data-analysis`、`use-firecrawl`、`browser-automation`、`use-bento-slides`、`humanizer`、`goal`、`continual-learning`、`csu-mail` |
+| 软件开发 | `software-development`、`use-claude-code`、`wechat-miniprogram` |
| AI 应用开发 | `agent-development`、`model-development`、`skill-porting`、`agent-tuning` |
| Agent 公司 | `agent-company` |
diff --git a/packages/cli/package.json b/packages/cli/package.json
index cb9d02de..52aa1523 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -29,6 +29,7 @@
"@lmliheng/agent-tuning": "workspace:*",
"@lmliheng/browser-automation": "workspace:*",
"@lmliheng/continual-learning": "workspace:*",
+ "@lmliheng/csu-mail": "workspace:*",
"@lmliheng/data-analysis": "workspace:*",
"@lmliheng/goal": "workspace:*",
"@lmliheng/humanizer": "workspace:*",
@@ -38,6 +39,7 @@
"@lmliheng/use-bento-slides": "workspace:*",
"@lmliheng/use-firecrawl": "workspace:*",
"@lmliheng/use-claude-code": "workspace:*",
+ "@lmliheng/wechat-miniprogram": "workspace:*",
"@prismshadow/agenthub": "^0.4.15",
"@lmliheng/penguin-core": "workspace:*",
"@lmliheng/penguin-server": "workspace:*",
diff --git a/packages/core/package.json b/packages/core/package.json
index 895fb9c2..cec08fe6 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -62,6 +62,7 @@
"@lmliheng/agent-tuning": "workspace:*",
"@lmliheng/browser-automation": "workspace:*",
"@lmliheng/continual-learning": "workspace:*",
+ "@lmliheng/csu-mail": "workspace:*",
"@lmliheng/data-analysis": "workspace:*",
"@lmliheng/goal": "workspace:*",
"@lmliheng/humanizer": "workspace:*",
@@ -71,6 +72,7 @@
"@lmliheng/use-bento-slides": "workspace:*",
"@lmliheng/use-firecrawl": "workspace:*",
"@lmliheng/use-claude-code": "workspace:*",
+ "@lmliheng/wechat-miniprogram": "workspace:*",
"@prismshadow/agenthub": "^0.4.15",
"arktype": "^2.2.3",
"smol-toml": "^1.3.0",
diff --git a/packages/core/test/plugins.test.ts b/packages/core/test/plugins.test.ts
index 4da66e7e..e5fa29a2 100644
--- a/packages/core/test/plugins.test.ts
+++ b/packages/core/test/plugins.test.ts
@@ -65,7 +65,7 @@ describe("loadLibraryPlugins", () => {
it("loads every plugin directory sorted by name, each with a date-sequence version and a category", () => {
const plugins = loadLibraryPlugins();
expect(plugins.map((p) => p.name)).toEqual([...plugins.map((p) => p.name)].sort());
- expect(plugins.length).toBe(14);
+ expect(plugins.length).toBe(16);
for (const plugin of plugins) {
expect(plugin.version, plugin.name).toMatch(PLUGIN_VERSION_PATTERN);
expect(
@@ -208,6 +208,7 @@ describe("groupPlugins / loadPluginGroups", () => {
expect(names("office-productivity")).toEqual([
"browser-automation",
"continual-learning",
+ "csu-mail",
"data-analysis",
"goal",
"humanizer",
diff --git a/packages/desktop/package.json b/packages/desktop/package.json
index 884e16e9..19cf66b0 100644
--- a/packages/desktop/package.json
+++ b/packages/desktop/package.json
@@ -21,6 +21,7 @@
"@lmliheng/agent-tuning": "workspace:*",
"@lmliheng/browser-automation": "workspace:*",
"@lmliheng/continual-learning": "workspace:*",
+ "@lmliheng/csu-mail": "workspace:*",
"@lmliheng/data-analysis": "workspace:*",
"@lmliheng/goal": "workspace:*",
"@lmliheng/humanizer": "workspace:*",
@@ -29,7 +30,8 @@
"@lmliheng/software-development": "workspace:*",
"@lmliheng/use-bento-slides": "workspace:*",
"@lmliheng/use-firecrawl": "workspace:*",
- "@lmliheng/use-claude-code": "workspace:*"
+ "@lmliheng/use-claude-code": "workspace:*",
+ "@lmliheng/wechat-miniprogram": "workspace:*"
},
"devDependencies": {
"@lmliheng/penguin-cli": "workspace:*",
diff --git a/packages/docs/content/skills.en.md b/packages/docs/content/skills.en.md
index cc14b0f9..ffba1d5b 100644
--- a/packages/docs/content/skills.en.md
+++ b/packages/docs/content/skills.en.md
@@ -222,8 +222,10 @@ The built-in plugins, by category (`PLUGIN_CATEGORIES` in `packages/core/src/plu
| | `humanizer` | Strip AI-writing tells from prose in any language and rewrite it into the register of books, newspapers and encyclopedias (not preinstalled: install from the library when needed) |
| | `goal` | The stop hook behind [goal mode](/goal-mode): keeps the Session working toward an objective until it is complete, blocked, or out of Token budget (preinstalled) |
| | `continual-learning` | When a Task ends after more than 30 turns, hands its condensed excerpt to a background subagent that folds the durable findings into the agent's Skills (not preinstalled) |
+| | `csu-mail` | Manage a Coremail mailbox (CSU student mail, `mail.csu.edu.cn`): generate a client app password once, then list, search, read and send mail over IMAP/SMTP, with a copy kept in the Sent folder — daily mail work never touches the unified auth portal (not preinstalled) |
| Software Development | `software-development` | Software development end to end, with two Skills: `software-engineering` (investigate, implement and validate with minimal scope) and `web-design` (the Penguin visual language for generated web UIs) |
| | `use-claude-code` | Run Claude Code on a remote host over SSH: a persistent expect session, headless `-p` with the stdin fix, a tmux-driven interactive TUI and multi-turn continuity (not preinstalled: install from the library when needed) |
+| | `wechat-miniprogram` | Take a WeChat mini-program from code to published on a headless Linux server: QR login to mp.weixin.qq.com, switching from a public account to the mini-program backend, the AppID and upload key, IP whitelisting, upload with miniprogram-ci, a verified preview QR, the mandatory user-privacy policy, review and release (not preinstalled) |
| AI App Development | `agent-development` | Agent development on PenguinHarness, with four Skills: `penguin-sdk` (build agent/AI/RAG apps on the SDK), `unified-llm-api` (call model APIs through `@prismshadow/agenthub`), `penguin-config` (manage model keys, defaults and Vault secrets) and `penguin-orchestration` (drive agents, Sessions, costs and schedules from a shell) |
| | `model-development` | Model development on your own hardware, with three Skills: `llamafactory` (fine-tune), `ollama` (run local models) and `vllm` (serve behind an OpenAI-compatible endpoint) |
| | `skill-porting` | Port Skills from external sources (plugin marketplaces, skills.sh registries, GitHub repos or local folders) into the agent after review and normalization |
diff --git a/packages/docs/content/skills.zh.md b/packages/docs/content/skills.zh.md
index f5b6103a..4ad650c5 100644
--- a/packages/docs/content/skills.zh.md
+++ b/packages/docs/content/skills.zh.md
@@ -222,8 +222,10 @@ Agent 可以在 Task 中重写自己的 `SKILL.md`。结合 Benchmark 评估和
| | `humanizer` | 去除任何语言文字中的 AI 写作痕迹,改写成书籍、报纸和百科全书的语体(不预装:需要时从插件库安装) |
| | `goal` | [目标模式](/goal-mode)背后的 stop 钩子:让 Session 持续朝着目标推进,直到完成、受阻或 Token 预算耗尽(预装) |
| | `continual-learning` | Task 运行超过 30 轮才结束时,把 Task 的精简摘录交给后台子 Agent,由它把有长期价值的发现沉淀到 Agent 的 Skill 中(不预装) |
+| | `csu-mail` | 管理中南大学 Coremail 邮箱(`mail.csu.edu.cn`):一次性生成客户端专用密码,之后用 IMAP/SMTP 从命令行查信、检索、读信、发信,并在「已发送」留底——日常收发信完全不碰统一身份认证(不预装) |
| 软件开发 | `software-development` | 端到端的软件开发,包含两个 Skill:`software-engineering`(在最小范围内调查、实现和验证)和 `web-design`(生成 Web UI 用的 Penguin 视觉语言) |
| | `use-claude-code` | 通过 SSH 在远程主机上运行 Claude Code:持久 expect 会话、带 stdin 修复的无头 `-p` 模式、tmux 驱动的交互式 TUI,以及多轮连续性(不预装:需要时从插件库安装) |
+| | `wechat-miniprogram` | 在无桌面的 Linux 服务器上把微信小程序从代码做到发布:扫码登录 mp.weixin.qq.com、从公众号后台切到小程序后台、取 AppID 与上传密钥、加 IP 白名单、用 miniprogram-ci 上传、交付校验过的预览码、填写必填的用户隐私保护指引、提交审核与发布(不预装) |
| AI 应用开发 | `agent-development` | PenguinHarness 上的 Agent 开发,包含四个 Skill:`penguin-sdk`(基于 SDK 构建 Agent/AI/RAG 应用)、`unified-llm-api`(通过 `@prismshadow/agenthub` 调用模型 API)、`penguin-config`(管理模型密钥、默认值和 Vault 机密)和 `penguin-orchestration`(在 shell 里驱动 Agent、Session、成本和定时任务) |
| | `model-development` | 在自己的硬件上做模型开发,包含三个 Skill:`llamafactory`(微调)、`ollama`(运行本地模型)和 `vllm`(在 OpenAI 兼容端点后面提供服务) |
| | `skill-porting` | 把外部来源(插件市场、skills.sh 注册表、GitHub 仓库或本地文件夹)的 Skill 经审查和规范化后移植到 Agent |
diff --git a/plugins/README.md b/plugins/README.md
index aaf53f7c..94878807 100644
--- a/plugins/README.md
+++ b/plugins/README.md
@@ -8,12 +8,12 @@ Included plugins, by category (`PLUGIN_CATEGORIES` in `packages/core/src/plugins
| Category | Plugins |
| --- | --- |
-| Office Productivity | `data-analysis`, `use-firecrawl`, `browser-automation`, `use-bento-slides`, `humanizer`, `goal`, `continual-learning` |
-| Software Development | `software-development`, `use-claude-code` |
+| Office Productivity | `data-analysis`, `use-firecrawl`, `browser-automation`, `use-bento-slides`, `humanizer`, `goal`, `continual-learning`, `csu-mail` |
+| Software Development | `software-development`, `use-claude-code`, `wechat-miniprogram` |
| AI App Development | `agent-development`, `model-development`, `skill-porting`, `agent-tuning` |
| Agent Company | `agent-company` |
-`humanizer`, `use-claude-code`, `continual-learning` and `agent-company` carry `preinstall: false`, so `default_agent` does not get them at initialization — they are installed from the library on demand (`agent-company` by the organization itself, when it creates the CEO and hires employees, or by hand onto any Agent that should be able to create one). `goal` is the stop hook behind goal mode: its `start.mjs`, a `user_prompt` command marked `"trigger": "host"` so that it runs only when a goal starts, writes the Session's `GOAL.json` and composes round 1; its `stop.mjs` reads the Trace after every Task and injects the next round or ends the goal. `continual-learning` hands a long task's condensed excerpt to a background subagent that folds the findings into the agent's skills.
+`humanizer`, `use-claude-code`, `continual-learning`, `agent-company`, `csu-mail` and `wechat-miniprogram` carry `preinstall: false`, so `default_agent` does not get them at initialization — they are installed from the library on demand (`agent-company` by the organization itself, when it creates the CEO and hires employees, or by hand onto any Agent that should be able to create one). `goal` is the stop hook behind goal mode: its `start.mjs`, a `user_prompt` command marked `"trigger": "host"` so that it runs only when a goal starts, writes the Session's `GOAL.json` and composes round 1; its `stop.mjs` reads the Trace after every Task and injects the next round or ends the goal. `continual-learning` hands a long task's condensed excerpt to a background subagent that folds the findings into the agent's skills.
`browser-automation` drives the desktop app's built-in browser through `penguin browser`: GenericAgent's scan → act → check loop over simplified HTML, trusted clicks and typing, and sign-ins imported from the system browser, with Amazon orders as the worked example.
diff --git a/plugins/csu-mail/LICENSE b/plugins/csu-mail/LICENSE
new file mode 100644
index 00000000..261eeb9e
--- /dev/null
+++ b/plugins/csu-mail/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/plugins/csu-mail/icon.svg b/plugins/csu-mail/icon.svg
new file mode 100644
index 00000000..6a8f207b
--- /dev/null
+++ b/plugins/csu-mail/icon.svg
@@ -0,0 +1,7 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="CSU mail">
+ <rect x="6" y="14" width="52" height="36" rx="5" fill="#2f6fed"/>
+ <path d="M8 18.5 32 36 56 18.5" fill="none" stroke="#eaf1ff" stroke-width="3.2" stroke-linecap="round" stroke-linejoin="round"/>
+ <path d="M8 46.5 25 33M56 46.5 39 33" fill="none" stroke="#eaf1ff" stroke-width="3.2" stroke-linecap="round"/>
+ <circle cx="49" cy="47" r="10" fill="#0b3ea8"/>
+ <path d="M44 47h10M49 42v10" stroke="#ffffff" stroke-width="2.6" stroke-linecap="round"/>
+</svg>
diff --git a/plugins/csu-mail/package.json b/plugins/csu-mail/package.json
new file mode 100644
index 00000000..f725cb2f
--- /dev/null
+++ b/plugins/csu-mail/package.json
@@ -0,0 +1,20 @@
+{
+ "name": "@lmliheng/csu-mail",
+ "version": "0.2.13",
+ "description": "Manage a Coremail mailbox (CSU student mail, mail.csu.edu.cn) over IMAP/SMTP with a client app password instead of the unified auth portal — create the app password once, then list, search, read and send mail from the shell, with a copy kept in the Sent folder.",
+ "license": "Apache-2.0",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/lmliheng/Adelie.git",
+ "directory": "plugins/csu-mail"
+ },
+ "files": [
+ "plugin.json",
+ "icon.svg",
+ "skills",
+ "LICENSE"
+ ],
+ "publishConfig": {
+ "access": "public"
+ }
+}
diff --git a/plugins/csu-mail/plugin.json b/plugins/csu-mail/plugin.json
new file mode 100644
index 00000000..ec560285
--- /dev/null
+++ b/plugins/csu-mail/plugin.json
@@ -0,0 +1,9 @@
+{
+ "description": "Manage a Coremail mailbox (CSU student mail, mail.csu.edu.cn) without going through the unified auth portal: create a client app password once, then list, search, read and send mail over IMAP/SMTP from the shell, keeping a copy in the Sent folder.",
+ "description_zh": "绕开统一身份认证管理 Coremail 邮箱(中南大学学生邮箱):生成客户端专用密码,再用 IMAP/SMTP 从命令行查信、检索、读信、发信,并在「已发送」留底。",
+ "short_description": "Coremail mailbox over IMAP/SMTP with an app password, no CAS.",
+ "short_description_zh": "Coremail 邮箱免 CAS 收发信:专用密码 + IMAP/SMTP,发信自动留底。",
+ "version": "2026.10.02.3",
+ "category": "office-productivity",
+ "preinstall": false
+}
diff --git a/plugins/csu-mail/skills/csu-mail/SKILL.md b/plugins/csu-mail/skills/csu-mail/SKILL.md
new file mode 100644
index 00000000..f40d35d6
--- /dev/null
+++ b/plugins/csu-mail/skills/csu-mail/SKILL.md
@@ -0,0 +1,156 @@
+---
+name: csu-mail
+description: Manage a Coremail mailbox (CSU student mail, mail.csu.edu.cn) over IMAP/SMTP with an app password instead of the unified auth portal — create the app password once, then list, search, read and send mail from the shell, with a copy kept in the Sent folder. Use whenever the task involves checking, sending or automating email on a CSU mailbox, or when a CAS login must be avoided.
+---
+
+# 中南大学邮箱管理(Coremail,绕开统一身份认证)
+
+## Before you start
+
+如果消息只是点名这个技能(比如「用 csu-mail」)而没有具体的事,先问清楚要做什么——查信、发信,还是
+做一次性引导。有具体任务时先自检凭据:`CSU_MAIL_ADDR` / `CSU_MAIL_AUTHCODE` 在不在环境里;不在就去
+第一节做引导,那是**起点**不是认证失败,别去重试登录。
+
+## 结论先行
+
+| 事项 | 做法 |
+| --- | --- |
+| 环境里没有 `CSU_MAIL_ADDR` / `CSU_MAIL_AUTHCODE` | 这是**起点**不是异常:先做一次性引导(**必须登录一次网页邮箱**),见第一节——`bash scripts/bootstrap.sh` 一条命令搞定 |
+| 收发信 | **客户端专用密码 + IMAP/SMTP**,不要为了邮件去登录统一身份认证(CAS) |
+| 为什么 | 短时间高频登录 CAS 会触发风控、甚至冻结账号(2026-10-02 真实发生过一次) |
+| 留底 | 用 SMTP 发信并 `APPEND` 到「已发送」;网页接口 `mbox:compose` **不留底** |
+
+## 一、起点:环境里没有 `CSU_MAIL_ADDR` / `CSU_MAIL_AUTHCODE` 时怎么办
+
+**这两个变量不是前提,是引导的产物。** 全新部署、换机器、或者专用密码丢了,环境里当然什么都没有 ——
+这时**必须登录一次网页邮箱**:专用密码只能在登录后的设置页生成,绕不过去。
+
+| 路径 | 需要什么 | 中南大学实测 | 怎么做 |
+| --- | --- | --- | --- |
+| ① CAS SSO(默认) | 统一身份认证账号 + 密码 | ✅ 可用 | `cas_login.py --mode cas` 换 sid,再驱动设置页生成专用密码。**只做这一次** |
+| ② 网页直登 | 邮箱**自己的**密码(≠ 统一密码) | ❌ `FA_UNAUTHORIZED`,还会开始要验证码 | `cas_login.py --mode direct`(POST `/coremail/index.jsp?cus=1`,先把表单隐藏字段原样回传)。只有邮箱有独立密码的部署才走得通 |
+| ③ 人工在浏览器里点 | 用户本人(Coremail 二次验证是**短信**,只有真人能收) | ✅ 最稳 | 用户自己登录 → 设置 → 个人信息 → 邮箱密码 → 生成专用密码 → **由用户自己**写进密钥库(别在聊天里贴密码) |
+
+自动化这两步用一条命令:
+
+```bash
+cd <插件目录>/skills/csu-mail/scripts
+CSU_MAIL_ADDR=学号@csu.edu.cn \
+CSU_CAS_USER=学号 CSU_CAS_PASS=密码 \
+PROJECT_ID=<App Data Dir 的最后一段> \
+PLAYWRIGHT_MODULE=/path/to/node_modules/playwright-core CHROME_PATH=/path/to/chrome \
+ bash bootstrap.sh
+```
+
+`bootstrap.sh` 做四件事:登录换 sid → 生成专用密码 → 把 `CSU_MAIL_ADDR` / `CSU_MAIL_AUTHCODE`
+写进**指定项目**的密钥库 → 销毁临时明文。`NO_VAULT=1` 只打印命令不写库;
+`SECRET_OUT=/path` 额外留一份 600 的明文(systemd 这类读不到密钥库的场景要用)。
+
+**账号密码从哪来**:问用户要,或放进密钥库(`CSU_CAS_USER` / `CSU_CAS_PASS`)——
+绝不写进代码或仓库;引导完成后这两个变量就该删掉,日常收发信用不到它们。
+
+**登录只做一次,失败不要重试**:CAS 短时间高频失败会触发风控甚至冻结账号(2026-10-02 真实发生过一次)。
+
+## 二、系统事实(实测)
+
+| 项 | 值 |
+| --- | --- |
+| 邮件系统 | Coremail XT5,网页入口 `https://mail.csu.edu.cn` |
+| 地址 | `学号@csu.edu.cn`,另有别名 `拼音[email protected]`,两者是同一邮箱 |
+| 二次验证 | 已开启(短信验证),所以第三方客户端只能用**客户端专用密码** |
+| IMAP | `imap.csu.edu.cn:993` SSL(`mail.csu.edu.cn:993` 同样可用) |
+| POP | `pop.csu.edu.cn:995` SSL |
+| SMTP | `smtp.csu.edu.cn:465` SSL;**587 关闭、25 不通** |
+| IMAP 证书 | CN = `mail.csu.edu.cn`,与主机名 `imap.csu.edu.cn` 不匹配,必须跳过证书校验,否则 `SSL: CERTIFICATE_VERIFY_FAILED` |
+
+链路实测(2026-10-02,非校园网出口):
+
+- 两个端口都可达,**TLS1.3** 握手成功;IMAP 问候 `* OK Coremail System IMap Server Ready(...)`,
+ SMTP 问候 `220 csu.edu.cn Anti-spam GT for Coremail System (...)`;`imaplib`/`smtplib` 用跳过校验的 `SSLContext` 可直接建连。
+- 证书严格校验访问 `imap.csu.edu.cn` 必然 `Hostname mismatch`——这不是网络故障,别再往防火墙方向排查。
+
+认证的边界(都实测过):
+
+- 统一身份认证密码**不能**登录 IMAP → `LOGIN Login error or password error`
+- 网页直登 `/coremail/index.jsp?cus=1`(明文 `uid`+`password`)→ `FA_UNAUTHORIZED`,还会弹验证码
+- 结论:第三方客户端只有**客户端专用密码**这一条路
+
+## 三、首次引导:两条路都走完的三步
+
+第一节决定「用哪条路登录」,这里是把结果落到密钥库的三步(`bootstrap.sh` 就是自动化了这三步)。
+
+1. 网页邮箱 → `设置 → 个人信息 → 邮箱密码` →「客户端专用密码」区块 → 点**虚线方框 “+”** → 填密码名称 →「生成」。
+ **不需要短信验证**,但密码串**只在生成时显示一次**;丢了就在同一页面「移除」后重建。
+2. 后端接口(想自动化时用):`user:listAppPwds`(列表)、`user:addAppPwd`(创建,响应里带明文)、
+ `user:deleteAppPwds`(`{"ids":[102]}`)。请求走 `/coremail/s`,**`func` 与 `sid` 必须在 query string**。
+3. 本插件的脚本:
+
+```bash
+# ① CAS 登录换 sid(只做一次)
+CSU_MAIL_ADDR=学号@csu.edu.cn CSU_CAS_USER=学号 CSU_CAS_PASS=密码 \
+ python scripts/cas_login.py --out mail_session.json # 产出 600 权限的 sid + cookies
+
+# ② 驱动网页邮箱生成专用密码(需要 Playwright)
+PLAYWRIGHT_MODULE=/path/to/node_modules/playwright-core \
+CHROME_PATH=/path/to/chrome \
+ node scripts/create_apppw.mjs mail_session.json agent-server --out secret.txt
+
+# ③ 存进密钥库并删掉明文
+# 必须显式带 --project-id / --agent-id:CLI 的默认项目是 default_project,
+# 不带就会写进别的项目的密钥库(密钥库里查得到,环境变量里永远没有)。
+# 项目 id = 运行环境 App Data Dir 的最后一段,如 /root/.penguin/data/asass -> asass
+P="--project-id <项目id> --agent-id default_agent"
+penguin config vault set $P --key CSU_MAIL_AUTHCODE --value "$(cat secret.txt)" && shred -u secret.txt
+penguin config vault set $P --key CSU_MAIL_ADDR --value "学号@csu.edu.cn"
+```
+
+> 写完后**当前会话仍然没有**这两个变量(见踩坑 2);开一个新对话,或等本会话压缩后再用。
+
+> 引导用的 CAS 登录**不要重试**:失败就停下来问用户,别连续试密码。
+
+## 四、日常收发信:`scripts/mail.py`
+
+```bash
+export CSU_MAIL_ADDR=学号@csu.edu.cn CSU_MAIL_AUTHCODE=专用密码 # 或从密钥库注入
+V=python3
+
+$V scripts/mail.py check # IMAP + SMTP 自检
+$V scripts/mail.py list INBOX 10 # 最近 10 封
+$V scripts/mail.py list "Sent Items" 5 # 含空格的文件夹要加引号
+$V scripts/mail.py read 124 # 读一封(正文)
+$V scripts/mail.py search 成绩 # 按标题检索
+$V scripts/mail.py send --to [email protected] --subject "..." --body-file body.txt
+ # 发信,并自动存一份到「已发送」
+```
+
+依赖:`requests`(只有 `mail.py` 的核心收发用标准库 `imaplib`/`smtplib`/`email`,无需三方包)。
+
+**动手前先自检**:`check` 会依次登录 IMAP 与 SMTP,两条都通过才算通。若报「缺少邮箱地址 / 缺少 CSU_MAIL_AUTHCODE」,
+那是凭据没注入,不是认证失败——去查密钥库写没写错项目(见踩坑 9),别去重试登录。
+
+## 五、踩过的坑
+
+1. **「生成」按钮初始是 `disabled`**,弹出框里的密码名称输入框必须用**真实键盘事件**输入
+ (Playwright 的 `fill()` 不行,要 `click()` + `keyboard.type()`),否则点了没反应、也不报错。
+2. **专用密码只显示一次**:生成后立刻写进密钥库。密钥库变量在**会话开始**时注入,所以当前会话新加的变量当场读不到——
+ 开一个新对话即可。若**换了会话**还是空的,那不是注入时机问题,是写错了项目(见踩坑 9)。
+ 验证办法:在当前 shell 里 `echo ${#CSU_MAIL_AUTHCODE}`,非 0 才算注入成功(只输出长度,别打印明文)。
+3. **网页接口发信不留底**:`mbox:compose` 返回 `S_OK`,但「已发送」里查不到,事后无法核实送达。
+ 要留底就用 SMTP 发送 + `IMAP APPEND` 到 `Sent Items`(本插件的 `mail.py send` 就是这么做的)。
+4. **文件夹名含空格要加引号**(`"Sent Items"`),否则 IMAP 报 `BAD Request not ending with ...`。
+5. **中文 `SEARCH SUBJECT` 命中不稳定**:查不到时改用 `list` 翻页,别下结论说「没有这封邮件」。
+6. 网页 API 的 `func` / `sid` 必须放在 **query string**,其余字段放 form body,否则 202/失败。
+7. IMAP 证书 CN 不匹配,连接时必须 `check_hostname=False; verify_mode=CERT_NONE`。
+8. **不要把账号、密码、专用密码写进代码或提交进仓库**——凭证只放密钥库/环境变量。
+9. **`penguin config vault set/list` 的默认项目是 `default_project`**:不带 `--project-id` 就会把凭据写进另一个项目的密钥库,
+ 现象是「密钥库里查得到,Agent 的 shell 里却始终没有这个变量」。2026-10-02 真实踩到:专用密码落进了 `default_project`,
+ 而 Agent 跑在别的项目里,于是 `mail.py check` 只报「缺少邮箱地址」——**别把它当认证失败去重试登录**。
+ 查证方法:`penguin config vault list --project-id <项目id> --agent-id default_agent`,
+ 项目 id = 运行环境 App Data Dir 的最后一段(`/root/.penguin/data/<项目id>`),列表里有、`env` 里没有就是这个问题。
+ 修法:把值重新 set 到正确项目,并清掉写错的那份:`penguin config vault remove --key <KEY> --project-id default_project --agent-id <agent>`。
+
+## 六、边界
+
+- 本技能只覆盖**邮件**本身。Coremail 的通讯录、日程不在范围内。
+- 代用户发信前先确认收件人与措辞;不要群发、不要发垃圾邮件。
+- 邮箱是学校通知与个人信息的入口,读信时注意隐私,不要把邮件内容贴到无关的地方。
diff --git a/plugins/csu-mail/skills/csu-mail/scripts/bootstrap.sh b/plugins/csu-mail/skills/csu-mail/scripts/bootstrap.sh
new file mode 100755
index 00000000..2b5f2b84
--- /dev/null
+++ b/plugins/csu-mail/skills/csu-mail/scripts/bootstrap.sh
@@ -0,0 +1,81 @@
+#!/usr/bin/env bash
+# csu-mail 引导:从「环境里没有 CSU_MAIL_ADDR / CSU_MAIL_AUTHCODE」到「两个变量都在密钥库里」。
+#
+# 这一步**必须登录一次网页邮箱**——专用密码只能在登录后的设置页生成,没有别的办法。
+# 走的是 CAS SSO(Coremail 开着二次验证时唯一可靠的路);登录一次之后就再也不碰统一身份认证了。
+#
+# 用法:
+# CSU_MAIL_ADDR=学号@csu.edu.cn \
+# CSU_CAS_USER=学号 CSU_CAS_PASS=密码 \
+# PROJECT_ID=<App Data Dir 的最后一段> \
+# bash scripts/bootstrap.sh
+#
+# 可选环境变量:
+# AGENT_ID 默认 default_agent
+# PASSWORD_NAME 专用密码名称,默认 agent-server
+# PYTHON python 解释器,默认 python3(需要 requests / bs4 / pycryptodome)
+# PLAYWRIGHT_MODULE / CHROME_PATH Playwright 与本机 Chromium 的路径
+# SECRET_OUT 额外把专用密码写到该文件(600,不删除)——给 systemd 这类读不了密钥库的场景用
+# NO_VAULT=1 不写密钥库,只打印该执行的两条命令
+# CSU_LOGIN_MODE cas(默认)| direct(邮箱有自己的密码时才用;中南大学实测走不通)
+set -euo pipefail
+
+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+PYTHON="${PYTHON:-python3}"
+AGENT_ID="${AGENT_ID:-default_agent}"
+PASSWORD_NAME="${PASSWORD_NAME:-agent-server}"
+MODE="${CSU_LOGIN_MODE:-cas}"
+
+die() { echo "✗ $*" >&2; exit 1; }
+
+[ -n "${CSU_MAIL_ADDR:-}" ] || die "请设置 CSU_MAIL_ADDR(邮箱地址,如 学号@csu.edu.cn)"
+[ -n "${CSU_CAS_USER:-}" ] || die "请设置 CSU_CAS_USER(统一身份认证账号,通常是学号)"
+[ -n "${CSU_CAS_PASS:-}" ] || die "请设置 CSU_CAS_PASS(统一身份认证密码)"
+
+[ -n "${CSU_MAIL_AUTHCODE:-}" ] && { echo "✓ 环境里已经有 CSU_MAIL_AUTHCODE(长度 ${#CSU_MAIL_AUTHCODE}),无需引导。"; echo " 直接自检即可:$PYTHON $HERE/mail.py check"; exit 0; }
+
+# 先验依赖:python 侧 requests/bs4/pycryptodome,node 侧供 create_apppw.mjs 用
+"$PYTHON" -c 'import requests, bs4, Crypto' 2>/dev/null \
+ || die "$PYTHON 缺依赖,先装:$PYTHON -m pip install requests beautifulsoup4 pycryptodome"
+command -v node >/dev/null || die "找不到 node(第②步生成专用密码要它)"
+
+TMP="$(mktemp -d)"
+cleanup() {
+ [ -f "$TMP/secret" ] && { shred -u "$TMP/secret" 2>/dev/null || rm -f "$TMP/secret"; }
+ rm -rf "$TMP"
+}
+trap cleanup EXIT
+
+echo "→ ① 登录网页邮箱换 sid(模式 $MODE,只这一次)"
+CSU_MAIL_ADDR="$CSU_MAIL_ADDR" "$PYTHON" "$HERE/cas_login.py" --mode "$MODE" --out "$TMP/session.json" \
+ || die "登录失败:不要重试,先找用户确认账号密码或账号状态(CAS 会被风控)。"
+
+echo "→ ② 在网页邮箱里生成一条客户端专用密码(名称:$PASSWORD_NAME)"
+PLAYWRIGHT_MODULE="${PLAYWRIGHT_MODULE:-playwright-core}" CHROME_PATH="${CHROME_PATH:-}" \
+ node "$HERE/create_apppw.mjs" "$TMP/session.json" "$PASSWORD_NAME" --out "$TMP/secret" \
+ || die "生成专用密码失败:确认已装 Playwright/Chromium(PLAYWRIGHT_MODULE、CHROME_PATH)。"
+
+echo "→ ③ 写进密钥库(长度校验:$(wc -c < "$TMP/secret" | tr -d ' ') 字节)"
+if [ "${NO_VAULT:-0}" = "1" ]; then
+ echo " NO_VAULT=1,跳过。请自己执行(注意必须指定项目,否则写进 default_project,环境里永远没有):"
+ echo " penguin config vault set --project-id <项目id> --agent-id $AGENT_ID --key CSU_MAIL_ADDR --value '$CSU_MAIL_ADDR'"
+ echo " penguin config vault set --project-id <项目id> --agent-id $AGENT_ID --key CSU_MAIL_AUTHCODE --value \"\$(cat 专用密码文件)\""
+ [ -n "${SECRET_OUT:-}" ] && { install -m 600 "$TMP/secret" "$SECRET_OUT"; echo " 专用密码也写到了 $SECRET_OUT"; }
+ exit 0
+fi
+
+[ -n "${PROJECT_ID:-}" ] || die "请设置 PROJECT_ID(= 运行环境 App Data Dir 的最后一段,如 /root/.penguin/data/sjaaj -> sjaaj);
+ 否则凭据会落进 default_project:密钥库里查得到,Agent 的 shell 里却永远没有这个变量。"
+
+command -v penguin >/dev/null || die "找不到 penguin CLI:请手动写密钥库,或用 NO_VAULT=1 看命令。"
+
+penguin config vault set --project-id "$PROJECT_ID" --agent-id "$AGENT_ID" \
+ --key CSU_MAIL_ADDR --value "$CSU_MAIL_ADDR"
+penguin config vault set --project-id "$PROJECT_ID" --agent-id "$AGENT_ID" \
+ --key CSU_MAIL_AUTHCODE --value "$(cat "$TMP/secret")"
+
+[ -n "${SECRET_OUT:-}" ] && { install -m 600 "$TMP/secret" "$SECRET_OUT"; echo "✓ 专用密码副本写到 $SECRET_OUT(600)"; }
+
+echo "✓ 完成。当前会话里还没有这两个变量(注入发生在会话开始),先这么用:"
+echo " CSU_MAIL_ADDR=$CSU_MAIL_ADDR CSU_MAIL_AUTHCODE=<从密钥库读> python $HERE/mail.py check"
+echo " 下一个新会话起,环境里会自动带上 CSU_MAIL_ADDR / CSU_MAIL_AUTHCODE。"
diff --git a/plugins/csu-mail/skills/csu-mail/scripts/cas_login.py b/plugins/csu-mail/skills/csu-mail/scripts/cas_login.py
new file mode 100755
index 00000000..61039e01
--- /dev/null
+++ b/plugins/csu-mail/skills/csu-mail/scripts/cas_login.py
@@ -0,0 +1,151 @@
+#!/usr/bin/env python3
+"""登录网页邮箱,换取 Coremail 的 sid —— 只用于首次引导。
+
+日常收发信**不需要**这个脚本:有了客户端专用密码就能直接走 IMAP/SMTP(见 mail.py)。
+只有当邮箱里还没有专用密码、又必须进网页邮箱生成一条时才用它。
+
+两条登录路径(`--mode`):
+
+ cas 走统一身份认证 SSO(默认)。Coremail 侧二次验证开着时,这是**唯一可靠**的路。
+ direct 直接用 `学号 + 密码` POST 网页登录表单 `/coremail/index.jsp?cus=1`。
+ 只有当邮箱有自己的密码(≠ 统一身份认证密码)时才会成功。
+ 中南大学实测:用统一身份认证密码直登返回 `FA_UNAUTHORIZED`,并开始要验证码 —— 走不通。
+
+无论哪条路:**不要重试**。失败就停下来问用户,别连续试密码(CAS 会被风控,邮箱会要验证码)。
+
+用法:
+ CSU_MAIL_ADDR=学号@csu.edu.cn CSU_CAS_USER=学号 CSU_CAS_PASS=密码 \
+ python cas_login.py [--mode cas|direct] [--out mail_session.json]
+
+产出:JSON(sid + cookies,权限 600),可直接喂给 create_apppw.mjs。
+"""
+import argparse
+import base64
+import json
+import os
+import random
+import re
+import sys
+
+import requests
+from bs4 import BeautifulSoup
+from Crypto.Cipher import AES
+
+CAS = os.environ.get("CSU_CAS_URL", "https://ca.csu.edu.cn/authserver/login")
+SERVICE = os.environ.get("CSU_MAIL_SSO", "https://mail.csu.edu.cn/coremail/cmcu_addon/sso.jsp")
+MAIL_BASE = os.environ.get("CSU_MAIL_BASE", "https://mail.csu.edu.cn")
+UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
+ "(KHTML, like Gecko) Chrome/126.0 Safari/537.36")
+CHARS = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678"
+
+
+def _rand(n: int) -> str:
+ return "".join(random.choice(CHARS) for _ in range(n))
+
+
+def encrypt_password(password: str, salt: str) -> str:
+ """与 CAS 页面 static/common/encrypt.js 的 encryptAES 一致:
+ 明文 = 64 位随机串 + 密码,AES-CBC(key = pwdEncryptSalt,iv = 16 位随机串),PKCS7,Base64。"""
+ text = _rand(64) + password
+ pad_len = AES.block_size - len(text) % AES.block_size
+ text += pad_len * chr(pad_len)
+ cipher = AES.new(salt.encode(), AES.MODE_CBC, _rand(16).encode())
+ return base64.b64encode(cipher.encrypt(text.encode())).decode()
+
+
+def cas_login(user: str, password: str, service: str = SERVICE) -> requests.Session:
+ s = requests.Session()
+ s.headers["User-Agent"] = UA
+ page = s.get(CAS, params={"service": service}, timeout=20)
+ div = BeautifulSoup(page.text, "lxml").find(id="pwdLoginDiv")
+ if div is None:
+ raise RuntimeError("CAS 页面结构变化,取不到 pwdLoginDiv(可能要求验证码)")
+ resp = s.post(CAS, params={"service": service}, timeout=25, data={
+ "username": user,
+ "password": encrypt_password(password, div.find(id="pwdEncryptSalt")["value"]),
+ "passwordText": "", "_eventId": "submit", "cllt": "userNameLogin",
+ "dllt": "generalLogin", "lt": "",
+ "execution": div.find(id="execution")["value"], "rmShown": "1",
+ })
+ if "/authserver/login" in resp.url and "ticket" not in resp.url:
+ raise RuntimeError("统一身份认证登录失败(账号或密码错误,或触发风控/需要验证码)")
+ return s
+
+
+def direct_login(user: str, password: str):
+ """网页直登,返回 (session, sid):POST /coremail/index.jsp?cus=1(明文的 uid + password + 表单隐藏字段)。
+
+ 要先把登录页上的隐藏字段原样回传(`loginType`、`locale`、`action:login` 等),
+ 少了它们会被判非法请求。Coremail 的失败信息在页面的 #warnOrErrDiv 里,
+ 同时 `CM.config.user.loginResultCode` 会给一个代码(如 FA_UNAUTHORIZED)。
+ """
+ s = requests.Session()
+ s.headers["User-Agent"] = UA
+ page = s.get(MAIL_BASE + "/", timeout=20)
+ html = page.text
+ fi = html.find('class="j-login-form')
+ if fi < 0:
+ raise RuntimeError("取不到登录表单:页面结构可能变了")
+ seg = html[fi: html.find("</form>", fi)]
+ data = {}
+ for m in re.finditer(r"<input([^>]*)>", seg):
+ attrs = m.group(1)
+ n = re.search(r'name="([^"]+)"', attrs)
+ v = re.search(r'value="([^"]*)"', attrs)
+ if n:
+ data[n.group(1)] = v.group(1) if v else ""
+ data["uid"] = user
+ data["password"] = password
+ resp = s.post(MAIL_BASE + "/coremail/index.jsp?cus=1", data=data, timeout=25,
+ headers={"Referer": MAIL_BASE + "/"})
+ # 注意:失败页面里也会出现 "sid=" 字样(SSO 链接),必须先判错再用 sid 判成功
+ err = (re.search(r'id="warnOrErrDiv"[^>]*>\s*<label>([^<]+)', resp.text)
+ or re.search(r'class="[^"]*\berrMsg\b[^"]*"[^>]*>\s*<label>([^<]+)', resp.text))
+ code = re.search(r"loginResultCode:\s*'([^']+)'", resp.text)
+ m = re.search(r"sid=([A-Za-z0-9_\-]+)", resp.url) or re.search(r'sid="([A-Za-z0-9_\-]+)"', resp.text)
+ if err or not m:
+ detail = err.group(1).strip() if err else "没有返回可用的 sid"
+ if code:
+ detail += f"(loginResultCode={code.group(1)})"
+ raise RuntimeError(f"网页直登失败:{detail} —— 邮箱有自己的密码才走得通,中南大学实测走不通;"
+ "请改用默认的 --mode cas,或让用户在浏览器里手动生成专用密码")
+ return s, m.group(1)
+
+
+def mail_sid(s: requests.Session, resp) -> str:
+ m = re.search(r"sid=([A-Za-z0-9_\-]+)", resp.url)
+ if not m:
+ r = s.get("https://mail.csu.edu.cn/coremail/XT5/index.jsp", allow_redirects=True, timeout=25)
+ m = (re.search(r"sid=([A-Za-z0-9_\-]+)", r.url)
+ or re.search(r'name="sid"\s+value="([^"]+)"', r.text))
+ if not m:
+ raise RuntimeError("SSO 回调里没有 sid")
+ return m.group(1)
+
+
+def main():
+ ap = argparse.ArgumentParser(description="登录网页邮箱换 sid(仅引导时使用)")
+ ap.add_argument("--mode", choices=["cas", "direct"], default=os.environ.get("CSU_LOGIN_MODE", "cas"))
+ ap.add_argument("--user", default=os.environ.get("CSU_CAS_USER", ""))
+ ap.add_argument("--password", default=os.environ.get("CSU_CAS_PASS", ""))
+ ap.add_argument("--service", default=SERVICE)
+ ap.add_argument("--out", default="mail_session.json")
+ a = ap.parse_args()
+ if not a.user or not a.password:
+ sys.exit("需要 CSU_CAS_USER / CSU_CAS_PASS(或用 --user/--password)")
+
+ if a.mode == "direct":
+ s, sid = direct_login(a.user, a.password)
+ else:
+ s = cas_login(a.user, a.password, a.service)
+ resp = s.get(a.service, timeout=25)
+ sid = mail_sid(s, resp)
+
+ with open(a.out, "w", encoding="utf-8") as f:
+ json.dump({"sid": sid, "cookies": s.cookies.get_dict()}, f)
+ os.chmod(a.out, 0o600)
+ print(f"sid 已写入 {a.out}({sid[:4]}…{sid[-4:]},模式 {a.mode}),接下来可用 create_apppw.mjs 生成客户端专用密码")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/plugins/csu-mail/skills/csu-mail/scripts/create_apppw.mjs b/plugins/csu-mail/skills/csu-mail/scripts/create_apppw.mjs
new file mode 100644
index 00000000..6f078b97
--- /dev/null
+++ b/plugins/csu-mail/skills/csu-mail/scripts/create_apppw.mjs
@@ -0,0 +1,133 @@
+#!/usr/bin/env node
+// 用 cas_login.py 产出的 mail_session.json 打开网页邮箱,生成一条「客户端专用密码」。
+// 专用密码只在生成时显示一次,生成后请立刻存进密钥库(不要写进代码/仓库)。
+//
+// 用法:
+// PLAYWRIGHT_MODULE=/path/to/node_modules/playwright-core \
+// CHROME_PATH=/path/to/chrome \
+// node create_apppw.mjs mail_session.json <密码名称> [--out secret.txt]
+//
+// 两个坑(本脚本已处理):
+// 1. 弹窗里的「生成」按钮初始带 disabled,输入框必须用**真实键盘事件**输入才会解除,
+// Playwright 的 fill() 不够,要用 click + keyboard.type。
+// 2. 生成结果同时来自 user:addAppPwd 的响应体,正则取 password/pwd 字段最稳。
+
+import fs from "node:fs";
+import { createRequire } from "node:module";
+
+const PW_MODULE = process.env.PLAYWRIGHT_MODULE || "playwright-core";
+const CHROME = process.env.CHROME_PATH || "";
+// PLAYWRIGHT_MODULE 可以是包名(playwright-core),也可以是本机安装目录的绝对路径
+const require = createRequire(import.meta.url);
+let pw;
+try {
+ pw = require(PW_MODULE);
+} catch (e) {
+ pw = require(PW_MODULE.replace(/\/+$/, "") + "/index.js");
+}
+const chromium = pw.chromium;
+if (!chromium) {
+ console.error(
+ `没有从 ${PW_MODULE} 拿到 chromium:检查 PLAYWRIGHT_MODULE 是否指向 playwright / playwright-core`,
+ );
+ process.exit(2);
+}
+
+const [, , sessionFile, name, ...rest] = process.argv;
+if (!sessionFile || !name) {
+ console.error("用法: node create_apppw.mjs <mail_session.json> <密码名称> [--out secret.txt]");
+ process.exit(2);
+}
+const opts = {};
+for (let i = 0; i < rest.length; i += 2) opts[rest[i].replace(/^--/, "")] = rest[i + 1];
+
+(async () => {
+ const sess = JSON.parse(fs.readFileSync(sessionFile, "utf8"));
+ const browser = await chromium.launch({
+ executablePath: CHROME || undefined,
+ args: ["--no-sandbox", "--disable-dev-shm-usage"],
+ });
+ const ctx = await browser.newContext({
+ userAgent:
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126 Safari/537.36",
+ viewport: { width: 1280, height: 800 },
+ });
+ await ctx.addCookies(
+ Object.entries(sess.cookies || {}).map(([k, v]) => ({
+ name: k,
+ value: v,
+ domain: "mail.csu.edu.cn",
+ path: "/",
+ })),
+ );
+
+ const page = await ctx.newPage();
+ const bodies = [];
+ page.on("response", async (r) => {
+ if (!r.url().includes("/coremail/s")) return;
+ const func = decodeURIComponent((r.url().match(/func=([^&]+)/) || [])[1] || "");
+ if (!/AppPwd/i.test(func)) return;
+ try {
+ bodies.push({ func, text: await r.text() });
+ } catch (e) {
+ /* ignore */
+ }
+ });
+
+ await page.goto(`https://mail.csu.edu.cn/coremail/XT5/index.jsp?sid=${sess.sid}#setting`, {
+ waitUntil: "domcontentloaded",
+ timeout: 60000,
+ });
+ await page.waitForTimeout(6000);
+ await page.getByText("个人信息", { exact: true }).first().click({ timeout: 10000 });
+ await page.waitForTimeout(2000);
+ await page.getByText("邮箱密码", { exact: true }).first().click({ timeout: 10000 });
+ await page.waitForTimeout(4000);
+
+ await page.locator("li.j-add-item").first().click({ timeout: 10000 });
+ await page.waitForTimeout(2500);
+ const input = page.locator("input.j-input-name").first();
+ await input.click();
+ await page.keyboard.type(name, { delay: 60 }); // 必须真实键入,否则确认键仍是 disabled
+ await page.waitForTimeout(500);
+ await page
+ .locator(".u-dialog-btns button[data-role=confirm]")
+ .first()
+ .click({ force: true, timeout: 10000 });
+ await page.waitForTimeout(7000);
+
+ let secret = null;
+ for (const b of bodies) {
+ const m = b.text.match(/"(?:password|pwd|appPwd|altpwd|secret)"\s*:\s*"([^"]{6,64})"/i);
+ if (m) {
+ secret = m[1];
+ break;
+ }
+ }
+ if (!secret) {
+ const txt = (await page.innerText("body")).replace(/\s+/g, " ");
+ const m = txt.match(/专用密码[^A-Za-z0-9]{0,20}([A-Za-z0-9]{8,32})/);
+ if (m) secret = m[1];
+ }
+
+ if (!secret) {
+ console.error(
+ "没拿到专用密码:确认已在网页邮箱里点开了「客户端专用密码」区块,且密码名称未被占用。",
+ );
+ await page.screenshot({ path: "apppw-failed.png", fullPage: true });
+ await browser.close();
+ process.exit(1);
+ }
+
+ if (opts.out) {
+ fs.writeFileSync(opts.out, secret, { mode: 0o600 });
+ console.log(`专用密码已写入 ${opts.out}(len=${secret.length},请立刻存进密钥库后删除该文件)`);
+ } else {
+ console.log("专用密码(只显示这一次):", secret);
+ }
+ console.log("已创建的专用密码名称:", name, "| 后端接口:", bodies.map((b) => b.func).join(", "));
+ await browser.close();
+})().catch((e) => {
+ console.error("ERR", e.message);
+ process.exit(1);
+});
diff --git a/plugins/csu-mail/skills/csu-mail/scripts/mail.py b/plugins/csu-mail/skills/csu-mail/scripts/mail.py
new file mode 100755
index 00000000..4e45b549
--- /dev/null
+++ b/plugins/csu-mail/skills/csu-mail/scripts/mail.py
@@ -0,0 +1,195 @@
+"""Coremail 邮箱命令行工具 —— 走 IMAP/SMTP + 客户端专用密码,不经过统一身份认证(CAS)。
+
+凭证(环境变量):
+ CSU_MAIL_ADDR 邮箱地址,如 [email protected] ← 必填,不写死在代码里
+ CSU_MAIL_AUTHCODE 客户端专用密码(App Password) ← 必填,放在密钥库里
+ CSU_MAIL_IMAP_HOST 默认 imap.csu.edu.cn
+ CSU_MAIL_SMTP_HOST 默认 smtp.csu.edu.cn
+
+没有专用密码就去网页邮箱「设置 → 个人信息 → 邮箱密码 → 客户端专用密码」点虚线 "+" 生成一个
+(密码串只在生成时显示一次,不需要短信验证)。
+
+用法:
+ python mail.py check # 连通性自检(IMAP + SMTP 登录)
+ python mail.py list [文件夹] [条数] # 默认 INBOX 最近 10 封
+ python mail.py search <关键词> [文件夹] [条数]
+ python mail.py read <序号> [文件夹] # 打印邮件正文
+ python mail.py send --to [email protected] --subject 主题 [--body 正文 | --body-file f]
+ [--attach 文件] # 发信并留一份到「已发送」
+"""
+import argparse
+import email
+import imaplib
+import os
+import ssl
+import smtplib
+import sys
+import time
+from email.header import decode_header, make_header
+from email.message import EmailMessage
+from email.utils import formatdate
+
+IMAP_HOST = os.environ.get("CSU_MAIL_IMAP_HOST", "imap.csu.edu.cn")
+IMAP_PORT = int(os.environ.get("CSU_MAIL_IMAP_PORT", "993"))
+SMTP_HOST = os.environ.get("CSU_MAIL_SMTP_HOST", "smtp.csu.edu.cn")
+SMTP_PORT = int(os.environ.get("CSU_MAIL_SMTP_PORT", "465"))
+SENT = os.environ.get("CSU_MAIL_SENT_FOLDER", "Sent Items")
+
+_ADDR = ""
+
+
+def addr() -> str:
+ a = _ADDR or os.environ.get("CSU_MAIL_ADDR", "").strip()
+ if not a:
+ sys.exit("缺少邮箱地址:设置环境变量 CSU_MAIL_ADDR,或用 --addr 指定")
+ return a
+
+
+def code() -> str:
+ c = os.environ.get("CSU_MAIL_AUTHCODE", "").strip()
+ if not c:
+ sys.exit("缺少环境变量 CSU_MAIL_AUTHCODE(客户端专用密码)—— 在邮箱「设置 → 个人信息 → 邮箱密码 → 客户端专用密码」生成一条")
+ return c
+
+
+def _ctx() -> ssl.SSLContext:
+ # 学校 IMAP 证书的 CN 与主机名不一致,跳过校验(Coremail 自身仍是 TLS 加密)
+ ctx = ssl.create_default_context()
+ ctx.check_hostname = False
+ ctx.verify_mode = ssl.CERT_NONE
+ return ctx
+
+
+def imap():
+ m = imaplib.IMAP4_SSL(IMAP_HOST, IMAP_PORT, ssl_context=_ctx())
+ m.login(addr(), code())
+ return m
+
+
+def dec(s) -> str:
+ if not s:
+ return ""
+ try:
+ return str(make_header(decode_header(s)))
+ except Exception:
+ return s
+
+
+def _mb(folder: str) -> str:
+ """IMAP 文件夹名含空格时必须加引号。"""
+ if folder.startswith('"') or not any(c in folder for c in " \t"):
+ return folder
+ return '"%s"' % folder
+
+
+def body_text(msg) -> str:
+ if msg.is_multipart():
+ for part in msg.walk():
+ if part.get_content_type() == "text/plain":
+ return part.get_payload(decode=True).decode(part.get_content_charset() or "utf-8", "ignore")
+ for part in msg.walk():
+ if part.get_content_type() == "text/html":
+ return part.get_payload(decode=True).decode(part.get_content_charset() or "utf-8", "ignore")
+ return ""
+ return msg.get_payload(decode=True).decode(msg.get_content_charset() or "utf-8", "ignore")
+
+
+def cmd_check(_):
+ m = imap()
+ print("IMAP ok:", [x.decode().split(' "/" ')[-1] for x in m.list()[1]][:8])
+ typ, d = m.select("INBOX", readonly=True)
+ print("INBOX 封数:", d[0].decode())
+ m.logout()
+ s = smtplib.SMTP_SSL(SMTP_HOST, SMTP_PORT, context=_ctx(), timeout=30)
+ s.login(addr(), code())
+ print("SMTP ok (登录成功,未发信)")
+ s.quit()
+
+
+def cmd_list(a):
+ m = imap()
+ m.select(_mb(a.folder), readonly=True)
+ typ, ids = m.search(None, "ALL")
+ ids = ids[0].split()[-a.limit:][::-1]
+ for i in ids:
+ t, data = m.fetch(i, "(BODY.PEEK[HEADER.FIELDS (DATE FROM SUBJECT)])")
+ raw = data[0][1].decode("utf-8", "ignore")
+ msg = email.message_from_string(raw)
+ print(f"[{i.decode()}] {dec(msg['Date'])} | {dec(msg['From'])} | {dec(msg['Subject'])}")
+ m.logout()
+
+
+def cmd_search(a):
+ m = imap()
+ m.select(_mb(a.folder), readonly=True)
+ typ, ids = m.search("UTF-8", b"SUBJECT", a.keyword.encode("utf-8"))
+ if typ != "OK":
+ print("检索失败:", ids)
+ ids = ids[0].split()[-a.limit:][::-1]
+ print(f"{a.folder} 命中 {len(ids)} 封")
+ for i in ids:
+ t, data = m.fetch(i, "(BODY.PEEK[HEADER.FIELDS (DATE FROM TO SUBJECT)])")
+ msg = email.message_from_string(data[0][1].decode("utf-8", "ignore"))
+ print(f"[{i.decode()}] {dec(msg['Date'])} | {dec(msg['From'])} -> {dec(msg['To'])} | {dec(msg['Subject'])}")
+ m.logout()
+
+
+def cmd_read(a):
+ m = imap()
+ m.select(_mb(a.folder), readonly=True)
+ t, data = m.fetch(a.uid, "(RFC822)")
+ msg = email.message_from_bytes(data[0][1])
+ print("From:", dec(msg["From"]))
+ print("To:", dec(msg["To"]))
+ print("Date:", dec(msg["Date"]))
+ print("Subject:", dec(msg["Subject"]))
+ print("-" * 60)
+ print(body_text(msg))
+ m.logout()
+
+
+def cmd_send(a):
+ body = a.body
+ if a.body_file:
+ body = open(a.body_file, encoding="utf-8").read()
+ msg = EmailMessage()
+ msg["From"] = addr()
+ msg["To"] = ", ".join(a.to)
+ msg["Subject"] = a.subject
+ msg["Date"] = formatdate(localtime=True)
+ msg.set_content(body)
+ for f in a.attach or []:
+ import mimetypes
+ ctype, _ = mimetypes.guess_type(f)
+ maintype, subtype = (ctype or "application/octet-stream").split("/", 1)
+ msg.add_attachment(open(f, "rb").read(), maintype=maintype, subtype=subtype, filename=os.path.basename(f))
+ raw = msg.as_bytes()
+ s = smtplib.SMTP_SSL(SMTP_HOST, SMTP_PORT, context=_ctx(), timeout=60)
+ s.login(addr(), code())
+ s.send_message(msg)
+ s.quit()
+ print("SMTP 已投递:", ", ".join(a.to))
+ # 自己留一份到「已发送」,否则在邮箱里看不到发送记录
+ m = imap()
+ m.append(_mb(SENT), "(\\Seen)", imaplib.Time2Internaldate(time.time()), raw)
+ m.logout()
+ print("已存入「已发送」")
+
+
+def main():
+ p = argparse.ArgumentParser(description="Coremail 邮箱 IMAP/SMTP 工具")
+ p.add_argument("--addr", default="", help="邮箱地址(默认取环境变量 CSU_MAIL_ADDR)")
+ sub = p.add_subparsers(dest="cmd", required=True)
+ sub.add_parser("check").set_defaults(fn=cmd_check)
+ q = sub.add_parser("list"); q.add_argument("folder", nargs="?", default="INBOX"); q.add_argument("limit", nargs="?", type=int, default=10); q.set_defaults(fn=cmd_list)
+ q = sub.add_parser("search"); q.add_argument("keyword"); q.add_argument("folder", nargs="?", default="INBOX"); q.add_argument("limit", nargs="?", type=int, default=10); q.set_defaults(fn=cmd_search)
+ q = sub.add_parser("read"); q.add_argument("uid"); q.add_argument("folder", nargs="?", default="INBOX"); q.set_defaults(fn=cmd_read)
+ q = sub.add_parser("send"); q.add_argument("--to", action="append", required=True); q.add_argument("--subject", required=True); q.add_argument("--body", default=""); q.add_argument("--body-file"); q.add_argument("--attach", action="append"); q.set_defaults(fn=cmd_send)
+ a = p.parse_args()
+ global _ADDR
+ _ADDR = a.addr
+ a.fn(a)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/plugins/wechat-miniprogram/LICENSE b/plugins/wechat-miniprogram/LICENSE
new file mode 100644
index 00000000..261eeb9e
--- /dev/null
+++ b/plugins/wechat-miniprogram/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/plugins/wechat-miniprogram/icon.svg b/plugins/wechat-miniprogram/icon.svg
new file mode 100644
index 00000000..d6829d22
--- /dev/null
+++ b/plugins/wechat-miniprogram/icon.svg
@@ -0,0 +1,7 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
+ <rect x="4" y="2.5" width="16" height="19" rx="3" />
+ <path d="M8 6.5h8" />
+ <circle cx="9" cy="11" r="1.3" />
+ <circle cx="15" cy="11" r="1.3" />
+ <path d="M8.5 15c1 1 2.2 1.5 3.5 1.5s2.5-.5 3.5-1.5" />
+</svg>
diff --git a/plugins/wechat-miniprogram/package.json b/plugins/wechat-miniprogram/package.json
new file mode 100644
index 00000000..95d1714c
--- /dev/null
+++ b/plugins/wechat-miniprogram/package.json
@@ -0,0 +1,20 @@
+{
+ "name": "@lmliheng/wechat-miniprogram",
+ "version": "0.2.13",
+ "description": "Publish a WeChat mini-program end to end from a headless Linux server: QR login to mp.weixin.qq.com, switching from a public account to the mini-program backend, the AppID and upload key, IP whitelisting, miniprogram-ci upload, the privacy policy, review and release.",
+ "license": "Apache-2.0",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/lmliheng/Adelie.git",
+ "directory": "plugins/wechat-miniprogram"
+ },
+ "files": [
+ "plugin.json",
+ "icon.svg",
+ "skills",
+ "LICENSE"
+ ],
+ "publishConfig": {
+ "access": "public"
+ }
+}
diff --git a/plugins/wechat-miniprogram/plugin.json b/plugins/wechat-miniprogram/plugin.json
new file mode 100644
index 00000000..356f9d1c
--- /dev/null
+++ b/plugins/wechat-miniprogram/plugin.json
@@ -0,0 +1,9 @@
+{
+ "description": "Publish a WeChat mini-program end to end from a headless Linux server: log in to mp.weixin.qq.com by QR, switch from a public account to the mini-program backend, read the AppID, reset the code-upload private key, whitelist the server IP, upload with miniprogram-ci, hand the user a verified preview QR, fill the mandatory user-privacy policy, submit for review and publish.",
+ "description_zh": "在无桌面的 Linux 服务器上把微信小程序从代码做到发布:扫码登录 mp.weixin.qq.com、从公众号后台切到小程序后台、取 AppID 与上传密钥、加 IP 白名单、用 miniprogram-ci 上传、交付校验过的预览码、填写必填的用户隐私保护指引、提交审核与发布。",
+ "short_description": "WeChat mini-program: login, upload, privacy policy, review, publish.",
+ "short_description_zh": "微信小程序全流程:扫码登录与切号、上传、隐私指引、提交审核与发布。",
+ "version": "2026.10.01.1",
+ "category": "software-development",
+ "preinstall": false
+}
diff --git a/plugins/wechat-miniprogram/skills/wechat-miniprogram/SKILL.md b/plugins/wechat-miniprogram/skills/wechat-miniprogram/SKILL.md
new file mode 100644
index 00000000..29e2e9f9
--- /dev/null
+++ b/plugins/wechat-miniprogram/skills/wechat-miniprogram/SKILL.md
@@ -0,0 +1,148 @@
+---
+name: wechat-miniprogram
+description: Take a WeChat mini-program from code to published, driving the real mp.weixin.qq.com admin from a headless Linux server — log in by QR, switch from a public account to the mini-program backend, read the AppID, reset the code-upload private key, whitelist the server IP, upload with miniprogram-ci, hand the user a preview QR, fill the mandatory user-privacy policy, submit for review, withdraw a stale review version, and publish.
+---
+
+# 微信小程序:登录 → 开发 → 上传 → 审核 → 发布
+
+## Before you start
+
+如果消息只是点名这个技能(比如「用 wechat-miniprogram」)而没有具体的小程序或具体环节,先问清楚是
+发布新版本、查后台信息,还是准备发布材料。扫码登录与重置密钥都**要用户本人在场**(二维码 5–10 分钟
+过期、重置要管理员扫码),人不在就别开等待进程。
+
+用真人路径(浏览器打开 mp.weixin.qq.com 后台,点真实按钮)完成小程序的上架链路。适用于:写并发布一个小程序、更新已有小程序版本、查小程序后台信息、准备发布材料。
+
+微信的后台**大量关键步骤不报错、只是静默失败**(提审按钮点了没反应、上传返回一句 `invalid ip`),所以本技能的核心价值是:**知道每一步真正的前置条件,以及怎么独立复核结果**。
+
+## 一、先搞清楚:登录态与账号归属
+
+**公众号≠小程序。** 公众号后台的「小程序管理」页只暴露**原始 ID**(`gh_xxxx`),拿不到 AppID;AppID 只在小程序自己的后台里。两者用同一套 mp.weixin.qq.com 登录,靠「切换账号」在同一个浏览器 profile 里来回切。
+
+| 事实 | 说明 |
+| --- | --- |
+| 登录只需一次扫码 | 登录态由 Chromium profile 持久化,cookie 有效期约几天;过期后让用户重扫一次 |
+| 切到小程序后台**不用再扫码** | 公众号后台左下角点账号块 `.mp_account_box`(要点一下,hover 无效)→ `li.account_box-panel-item` 里的「切换账号」→ 弹窗 `.switch-account-dialog` → 点小程序那一行 |
+| 切换弹窗里可能出现「小程序测试号 / 小游戏测试号」 | **测试号不能提交审核发布**,只能开发调试,别在它上面浪费时间 |
+| 扫码登录的坑 | 登录二维码是 472×472 的 jpg 被 CSS 缩到 122×122 显示,**元素截图拿到的是降采样图,微信扫不出来**。必须在页面里用 canvas 取原图、放大 2 倍导出 PNG,**并用 jsQR 解码验证**后再交给用户 |
+| 每次换号/换码都要让用户本人在场 | 二维码约 5–10 分钟过期。**人不在就别开等待进程**,白耗资源 |
+
+## 二、把代码推上去(这一步不需要扫码,但要白名单)
+
+1. **拿上传密钥**:开发管理 → 开发设置 → 小程序代码上传密钥 → **重置**(旧密钥不可查看,只能重置)。重置要**管理员微信扫码**(弹窗「重置代码上传密钥 / 身份确认」),确认后弹窗第二步给「下载密钥」,用 Playwright 的 `download` 事件把 `private.<appid>.key` 存到服务器。
+2. **加 IP 白名单**:同一页「IP白名单 → 编辑」,**同样要管理员扫码**。不加就上传,服务端会返回
+ `{"errCode":-10008,"errMsg":"invalid ip: <你的出口IP>, reference: ..."}`。
+ 先 `curl -s https://api.ipify.org` 拿出口 IP 再填。
+3. **上传**:`miniprogram-ci`
+ ```bash
+ cd <项目> && MP_APPID=wx... MP_KEY_PATH=<key> MP_VERSION=1.0.0 MP_DESC="..." node upload.js
+ ```
+ 成功后该版本出现在后台「管理 → 版本管理 → 开发版本」。
+4. **预览码**(给用户试用,**不需要扫码授权**,但会用掉一次上传配额):
+ ```bash
+ MP_APPID=wx... MP_KEY_PATH=<key> MP_QR_OUT=<输出路径> node preview.js
+ ```
+ 微信返回的可能是 **470×470 的 JPEG**(哪怕文件名写成 .png)。用 `jpeg-js` 解码 → `jsQR` 验证能解出 `https://mp.weixin.qq.com/a/~~...~~` → 最近邻放大 2 倍存成真 PNG 再交给用户。预览码约 25 分钟有效。
+
+## 三、提审与发布(真正的坑都在这)
+
+**发布链路:上传开发版 → 提交审核 → 微信审核(1–7 天)→ 发布(替换线上版本)。** 提交审核与发布都是后台的人工动作,个人主体小程序必须过审才能发布。
+
+### 前置条件清单(缺一个就静默失败)
+
+- [ ] **用户隐私保护指引**必须已配置(见下)——否则点「提交审核 → 须知 → 下一步 → 继续提交」后**什么都不发生**,页面只悄悄发一次 `CheckPrivacyApiAuth`。
+- [ ] **不能已有版本在审核中**——旧审核版本要先撤回。
+- [ ] 服务类目已设置(基本设置里可见)。
+
+### 用户隐私保护指引(最容易卡住的一步)
+
+入口:**基本设置 → 服务内容声明 → 用户隐私保护指引「去完善」**(点它会**新开一个标签页**)。
+地址必须带参数,少了就显示「页面连接异常,请关闭重试」:
+
+```
+https://mp.weixin.qq.com/wxamp/wadevelopcode/privacy?ver=1&id=0&wait=0&token=<token>&lang=zh_CN
+```
+
+编辑器里这些**全是必填**,漏一个「确定并提交协议」就无反应:
+
+| 位置 | 怎么填 |
+| --- | --- |
+| 每条信息类型的「用途」 | `input[placeholder="请填写用途"]`,微信按代码识别出 2–5 条(手机号 / 相册 / 位置 / 剪切板…),**给用户的用途文案必须先让用户拍板**,这是对外公示的法律声明 |
+| 联系方式 | 点「请选择」→ 选类型(电话/邮箱/微信号/qq)→ 填**同行**的输入框(用 `input[placeholder="邮箱"]` 之类的 placeholder 精确定位,别用"最后一个输入框",会填错到别的栏) |
+| 5.2「再次以 ___ 方式告知」 | 预览时会显示「**待填写**」,必须补,例如「弹窗提示」 |
+| 底部声明勾选框 | 「本小程序已对用户的信息处理进行了逐一、如实的说明…」必须勾上 |
+
+然后点「预览后提交协议」→ 确认预览里**没有「待填写/待完善」**→ 勾声明 →「确定并提交协议」。**提交成功的判据是回到基本设置看到「用户隐私保护指引 → 审核中」**(不是看编辑器页面有没有跳转)。
+
+⚠️ **隐私指引处于「审核中」时,代码提审照样被拦**,要等它先过。
+
+### 提交代码审核
+
+点开发版本右侧的「**提交审核**」→ 弹窗「确认提交审核?」勾两个确认项 → **下一步** → 弹窗「代码审核进行安全测试提醒」→ **继续提交**。之后应进入审核信息表单;若页面毫无反应,回去查上面的前置条件清单。
+
+### 撤回旧审核版本
+
+版本管理页「审核版本」块里点「**删除**」→ **要管理员扫码**(「删除当前版本 / 请使用微信扫描二维码进行验证」)→ 扫码确认后自动完成。撤回只删"待审记录",**同名开发版本仍在**,随时可重提。
+
+## 四、复核(不要凭页面文字下结论)
+
+| 要确认什么 | 怎么看 |
+| --- | --- |
+| 登录态 | 打开 `https://mp.weixin.qq.com/`,URL 里有 `token=<数字>` 即为已登录 |
+| 当前是在哪个账号后台 | URL 含 `/wxamp/` = 小程序后台;含 `/cgi-bin/` = 公众号后台 |
+| AppID | 基本设置页 `/wxamp/basicprofile/index` 正文里的 `wx[0-9a-f]{16}` |
+| 上传是否真成功 | 版本管理页 `/wxamp/wacodepage/getcodepage` 的「开发版本」里出现该版本号 + `ci机器人1` |
+| 隐私指引是否提交成功 | 基本设置里那一行变成「**审核中**」 |
+| 代码是否真进了审核 | 版本管理页「审核版本」块里出现版本号(**注意:「你暂无提交审核的版本或者版本已发布上线」只是审核版本为空的占位文案,不是报错**) |
+
+## 五、命令行手艺(Linux 无桌面环境)
+
+- 有头模式跑:`xvfb-run -a --server-args="-screen 0 1440x900x24" node xxx.mjs`
+- **页面一律用 `waitUntil: 'commit'` + 固定等待**;机器负载高时 `domcontentloaded` 会 60s 超时。
+- **弹窗里的按钮先 `scrollIntoView({block:'center'})` 再按坐标点**,否则坐标可能落在视口外(y=920 > 视口 900)而点击无效。
+- 二维码交付三条铁律:**先解码验证** → **按二维码内容 hash 命名**(同一张码反复截图不会换名删旧文件,别用 PNG 字节做 hash)→ **只保留当前一张**。
+- `pkill -f "xxx.mjs"` 会匹配到**自己这条 shell 命令行**(里面含脚本名)导致自杀。用 `P=$(printf 'add-%s2.mjs' ip); pkill -f "$P"`,或把 kill 和"启动脚本"分成两条命令。
+- 长时间等待扫码的进程:用 `setsid ... &` 起独立会话,否则这次 shell 一结束就被连带清理;等待进程要**先把用户叫到跟前**。
+- 管理员扫码那类等待脚本的"第二步已就绪"判据:**不能看「身份确认」字样**(步骤条里一直有),要看"请使用管理员微信扫描"是否消失。
+
+## 六、资产
+
+工具(**不要重造**):`<app_data_dir>/agents/<agent_id>/shared_env/wechat-mp/`
+本技能 `scripts/` 是同一批脚本的**便携快照**,新环境直接把 `scripts/` 拷到 shared_env 再用:
+
+```bash
+cp -r <skills>/wechat-miniprogram/scripts <shared_env>/wechat-mp
+cd <shared_env>/wechat-mp && npm install # 依赖见 scripts/package.json
+npx playwright install chromium # 没装过浏览器才需要
+```
+
+脚本之间用 `./stealth.mjs` 相对引用、浏览器 profile 默认落在脚本同目录的 `profile/`,
+所以**拷过去即可跑,只差一次扫码登录**(`node login2.mjs` 出码 → 用户扫 → 登录态存进 profile)。
+
+| 脚本 | 作用 |
+| --- | --- |
+| `stealth.mjs` | `launchStealth(profileDir,{headless})`:反检测 + 持久化 profile 的浏览器 |
+| `login2.mjs` | 扫码登录:出码(canvas 放大 + jsQR 校验 + 内容 hash 命名)、等扫码、检测登录成功 |
+| `check-session.mjs` | 复用 profile 验证登录态并回报账号名 |
+| `to-miniapp.mjs` | 公众号后台 →「切换账号」→ 切到指定小程序后台,并 dump 落地页 |
+| `miniapp-info.mjs` | 一次采完:小程序后台首页 / 基本设置(AppID)/ 开发设置(上传密钥与白名单) |
+| `miniapp-nav.mjs` | 打开后台任意页面并 dump 文本/按钮(`node miniapp-nav.mjs /wxamp/xxx label outDir`) |
+| `reset-key2.mjs` | 重置上传密钥:出码 → 等扫码 → 捕获密钥下载落盘 |
+| `add-ip2.mjs` | 加 IP 白名单:出码 → 等扫码 → 填 IP → 保存 → 复核 |
+| `privacy-fill2.mjs` | 填写并提交用户隐私保护指引(用途 + 联系方式 + 5.2 + 声明勾选) |
+| `submit-review4.mjs` | 提审全流程:须知 → 下一步 → 安全测试提醒 → 继续提交,并抓即时提示 |
+| `withdraw2.mjs` | 撤回(删除)审核版本 |
+| `auto-submit.mjs` | 状态巡检 + 条件提审:隐私未过就只报告,过了就自动提审;结果写 status.json(适合挂定时任务) |
+| `probe-*.mjs` | 排查用:`probe-switch*.mjs` 切号入口、`probe-key-qr.mjs` 二维码元素与分辨率、`probe-privacy.mjs` 隐私页、`probe-privcheck.mjs` 提审请求体 |
+
+模板:`templates/miniprogram-todo/` —— 一个零后端、纯本地的待办清单小程序(含 `tools/validate.js` 静态校验与 `tools/test-page.js` 无头逻辑单测,打桩 `wx`/`Page`)。复制出去 `npm install` 即可用。
+
+账号相关的**具体信息**(AppID、密钥路径、profile 目录、当前进度)写进记忆,不要写死在本技能里。
+
+## 七、铁律
+
+1. **密钥、cookie、`.vault.toml` 绝不打印、绝不让用户贴进对话**;密钥文件只落服务器。
+2. 需要扫码的步骤**先把用户叫到跟前**,再开码;人不在就停,不要空挂浏览器。
+3. 提交审核、发布、删除/撤回都是**改变账号状态的动作**:先确认用户意图,再动手。
+4. 「发布」会**替换线上版本**——发布前明确告诉用户旧版本会被覆盖。
+5. 任何"已完成"的结论都要**回到后台页面独立复核**(见第四节),不要凭弹窗关闭或页面跳转下结论。
diff --git a/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/add-ip2.mjs b/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/add-ip2.mjs
new file mode 100644
index 00000000..679fea4a
--- /dev/null
+++ b/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/add-ip2.mjs
@@ -0,0 +1,358 @@
+// 编辑 IP 白名单:出管理员验证二维码 → 等扫码 → 在第二步填入 IP → 保存 → 复核
+// 用法: node add-ip2.mjs <qrPrefix> <statusPath> <ip列表逗号分隔> [超时分钟]
+import { launchStealth } from "./stealth.mjs";
+import fs from "node:fs";
+import path from "node:path";
+import crypto from "node:crypto";
+import { fileURLToPath } from "node:url";
+import { PNG } from "pngjs";
+import jsQR from "jsqr";
+
+const here = path.dirname(fileURLToPath(import.meta.url));
+const qrPrefix = process.argv[2];
+const statusPath = process.argv[3];
+const ips = (process.argv[4] || "")
+ .split(",")
+ .map((s) => s.trim())
+ .filter(Boolean);
+const timeoutMin = Number(process.argv[5] || 20);
+const outDir = path.dirname(qrPrefix);
+const base = path.basename(qrPrefix).replace(/\.png$/, "");
+const write = (o) =>
+ fs.writeFileSync(statusPath, JSON.stringify({ at: new Date().toISOString(), ...o }, null, 2));
+const log = (...a) => console.log(new Date().toISOString(), ...a);
+
+function upscale3x(png) {
+ const s = 3,
+ b = new PNG({ width: png.width * s, height: png.height * s });
+ for (let y = 0; y < b.height; y++)
+ for (let x = 0; x < b.width; x++) {
+ const si = (((y / s) | 0) * png.width + ((x / s) | 0)) << 2,
+ di = (y * b.width + x) << 2;
+ b.data[di] = png.data[si];
+ b.data[di + 1] = png.data[si + 1];
+ b.data[di + 2] = png.data[si + 2];
+ b.data[di + 3] = 255;
+ }
+ return b;
+}
+function deliverQr(pngBuf) {
+ const png = PNG.sync.read(pngBuf);
+ const big = upscale3x(png);
+ const dec = jsQR(new Uint8Array(big.data), big.width, big.height);
+ const hash = crypto
+ .createHash("sha1")
+ .update(dec ? dec.data : PNG.sync.write(big))
+ .digest("hex")
+ .slice(0, 8);
+ const file = path.join(outDir, `${base}-${hash}.png`);
+ if (!fs.existsSync(file)) {
+ fs.writeFileSync(file, PNG.sync.write(big));
+ const re = new RegExp(`^${base}-[0-9a-f]{8}\\.png$`);
+ for (const f of fs.readdirSync(outDir))
+ if (re.test(f) && path.join(outDir, f) !== file) {
+ try {
+ fs.unlinkSync(path.join(outDir, f));
+ } catch {}
+ }
+ }
+ return {
+ file,
+ hash,
+ size: `${big.width}x${big.height}`,
+ decoded: dec ? dec.data.slice(0, 100) : null,
+ };
+}
+
+const ctx = await launchStealth(path.join(here, "profile"), { headless: false });
+const page = ctx.pages()[0] || (await ctx.newPage());
+await page.goto("https://mp.weixin.qq.com/", { waitUntil: "domcontentloaded", timeout: 60000 });
+await page.waitForTimeout(10000);
+const token = (page.url().match(/token=(\d+)/) || [])[1];
+if (!token) {
+ write({ state: "NOT_LOGGED_IN" });
+ log("NOT LOGGED IN");
+ await ctx.close().catch(() => {});
+ process.exit(2);
+}
+await page
+ .goto(`https://mp.weixin.qq.com/wxamp/devprofile/get_profile?token=${token}&lang=zh_CN`, {
+ waitUntil: "commit",
+ timeout: 60000,
+ })
+ .catch(() => {});
+await page.waitForTimeout(12000);
+
+const dlgText = () =>
+ page.evaluate(() => {
+ const ds = Array.from(document.querySelectorAll('[class*="dialog"],[class*="modal"]')).filter(
+ (e) => e.offsetWidth > 200 && e.offsetHeight > 150,
+ );
+ return ds
+ .map((e) => (e.innerText || "").replace(/\s+/g, " ").trim())
+ .filter(Boolean)
+ .join(" || ")
+ .slice(0, 500);
+ });
+
+const openDialog = async () => {
+ const btn = await page.evaluate(() => {
+ const label = Array.from(document.querySelectorAll("*")).find(
+ (e) => e.children.length === 0 && (e.innerText || "").trim() === "IP白名单",
+ );
+ let n = label;
+ for (let i = 0; i < 8 && n; i++) {
+ n = n.parentElement;
+ if (!n) break;
+ const c = Array.from(n.querySelectorAll("a,button,span,div")).filter(
+ (e) => e.children.length === 0 && (e.innerText || "").trim() === "编辑",
+ );
+ if (c[0]) {
+ const r = c[0].getBoundingClientRect();
+ return { x: r.x + r.width / 2, y: r.y + r.height / 2 };
+ }
+ }
+ return null;
+ });
+ if (!btn) return false;
+ await page.mouse.click(btn.x, btn.y);
+ await page.waitForTimeout(4000);
+ return true;
+};
+
+const grabQr = async () => {
+ const el = await page.evaluateHandle(() => {
+ const ds = Array.from(document.querySelectorAll('[class*="dialog"],[class*="modal"]')).filter(
+ (e) => e.offsetWidth > 200 && e.offsetHeight > 150,
+ );
+ for (const d of ds)
+ for (const img of d.querySelectorAll("img")) {
+ const r = img.getBoundingClientRect();
+ if (r.width > 120) return img;
+ }
+ for (const d of ds)
+ for (const cv of d.querySelectorAll("canvas")) {
+ const r = cv.getBoundingClientRect();
+ if (r.width > 120) return cv;
+ }
+ return null;
+ });
+ const node = el.asElement();
+ if (!node) return null;
+ const buf = await node.screenshot().catch(() => null);
+ return buf ? deliverQr(buf) : null;
+};
+
+if (!(await openDialog())) {
+ write({ state: "NO_EDIT_BTN" });
+ log("no edit btn");
+ await ctx.close().catch(() => {});
+ process.exit(3);
+}
+
+let t = await dlgText();
+log("dialog:", t);
+let qrInfo = null,
+ lastQrAt = 0;
+const deadline = Date.now() + timeoutMin * 60 * 1000;
+let scanned = false;
+
+let tick = 0;
+while (Date.now() < deadline && !scanned) {
+ t = await dlgText();
+ tick++;
+ if (tick % 8 === 0) {
+ log("tick dialog:", t.slice(0, 220));
+ await page.screenshot({ path: path.join(outDir, `${base}-live.png`) }).catch(() => {});
+ }
+ // 注意:进到第二步后步骤条里仍然有「身份确认」字样,不能拿它判断;只看"请扫码/请在手机上确认"是否消失
+ if (!/请使用管理员微信扫描|请在手机上进行确认/.test(t)) {
+ scanned = true;
+ log("STEP_READY:", t.slice(0, 160));
+ break;
+ }
+ if (/失效|过期|刷新|重新获取/.test(t)) {
+ const r = await page
+ .evaluate(() => {
+ const ds = Array.from(
+ document.querySelectorAll('[class*="dialog"],[class*="modal"]'),
+ ).filter((e) => e.offsetWidth > 200);
+ for (const d of ds)
+ for (const e of d.querySelectorAll("a,button,span,div")) {
+ if (e.children.length === 0 && /刷新|重新获取/.test((e.innerText || "").trim())) {
+ const r = e.getBoundingClientRect();
+ return { x: r.x + r.width / 2, y: r.y + r.height / 2 };
+ }
+ }
+ return null;
+ })
+ .catch(() => null);
+ if (r) {
+ await page.mouse.click(r.x, r.y);
+ await page.waitForTimeout(3000);
+ }
+ qrInfo = null;
+ lastQrAt = 0;
+ }
+ if (!qrInfo || Date.now() - lastQrAt > 15000) {
+ const info = await grabQr();
+ if (info) {
+ const changed = !qrInfo || info.decoded !== qrInfo.decoded;
+ qrInfo = info;
+ lastQrAt = Date.now();
+ if (changed) {
+ log(
+ "QR_READY",
+ path.basename(info.file),
+ info.size,
+ info.decoded ? "decoded-ok" : "UNREADABLE",
+ );
+ write({ state: "WAIT_SCAN", ...info, dialog: t });
+ }
+ }
+ }
+ await page.waitForTimeout(2000);
+}
+
+if (!scanned) {
+ write({ state: "TIMEOUT" });
+ log("TIMEOUT");
+ await ctx.close().catch(() => {});
+ process.exit(4);
+}
+
+await page.waitForTimeout(4000);
+t = await dlgText();
+log("step2 dialog:", t);
+write({ state: "STEP2", dialog: t });
+await page.screenshot({ path: path.join(outDir, `${base}-step2.png`) }).catch(() => {});
+
+const step2 = await page.evaluate(() => {
+ const ds = Array.from(document.querySelectorAll('[class*="dialog"],[class*="modal"]')).filter(
+ (e) => e.offsetWidth > 200 && e.offsetHeight > 150,
+ );
+ const out = { inputs: [], btns: [] };
+ for (const d of ds) {
+ for (const i of d.querySelectorAll("input,textarea")) {
+ const r = i.getBoundingClientRect();
+ if (r.width)
+ out.inputs.push({
+ tag: i.tagName,
+ ph: i.placeholder || "",
+ val: i.value || "",
+ rect: `${Math.round(r.x)},${Math.round(r.y)}`,
+ });
+ }
+ for (const b of d.querySelectorAll("button,a,span,div")) {
+ if (b.children.length === 0) {
+ const tx = (b.innerText || "").trim();
+ if (tx && tx.length <= 10) {
+ const r = b.getBoundingClientRect();
+ if (r.width) out.btns.push({ t: tx, rect: `${Math.round(r.x)},${Math.round(r.y)}` });
+ }
+ }
+ }
+ }
+ return out;
+});
+log("step2 struct", JSON.stringify(step2));
+
+// 若没有输入框,先点「添加」
+if (step2.inputs.length === 0) {
+ const add = await page.evaluate(() => {
+ const ds = Array.from(document.querySelectorAll('[class*="dialog"],[class*="modal"]')).filter(
+ (e) => e.offsetWidth > 200,
+ );
+ for (const d of ds)
+ for (const e of d.querySelectorAll("a,button,span,div")) {
+ if (
+ e.children.length === 0 &&
+ /^(添加|新增|添加IP|新建)$/.test((e.innerText || "").trim())
+ ) {
+ const r = e.getBoundingClientRect();
+ return { x: r.x + r.width / 2, y: r.y + r.height / 2 };
+ }
+ }
+ return null;
+ });
+ if (add) {
+ await page.mouse.click(add.x, add.y);
+ await page.waitForTimeout(2500);
+ log("clicked 添加");
+ }
+}
+
+// 填入 IP(多行/多框都支持)
+const setVals = await page.evaluate((list) => {
+ const ds = Array.from(document.querySelectorAll('[class*="dialog"],[class*="modal"]')).filter(
+ (e) => e.offsetWidth > 200,
+ );
+ const boxes = [];
+ for (const d of ds)
+ for (const i of d.querySelectorAll("input,textarea"))
+ if (i.getBoundingClientRect().width) boxes.push(i);
+ if (!boxes.length) return 0;
+ if (boxes.length === 1) {
+ const i = boxes[0];
+ i.focus();
+ i.value = list.join("\n");
+ i.dispatchEvent(new Event("input", { bubbles: true }));
+ i.dispatchEvent(new Event("change", { bubbles: true }));
+ return 1;
+ }
+ list.forEach((v, k) => {
+ const i = boxes[k];
+ if (!i) return;
+ i.focus();
+ i.value = v;
+ i.dispatchEvent(new Event("input", { bubbles: true }));
+ i.dispatchEvent(new Event("change", { bubbles: true }));
+ });
+ return boxes.length;
+}, ips);
+log("setVals boxes", setVals, JSON.stringify(ips));
+await page.waitForTimeout(1500);
+await page.screenshot({ path: path.join(outDir, `${base}-filled.png`) }).catch(() => {});
+
+const save = await page.evaluate(() => {
+ const ds = Array.from(document.querySelectorAll('[class*="dialog"],[class*="modal"]')).filter(
+ (e) => e.offsetWidth > 200,
+ );
+ for (const d of ds)
+ for (const e of d.querySelectorAll("button,a,span,div")) {
+ if (
+ e.children.length === 0 &&
+ /^(保存|确定|确认|提交|完成)$/.test((e.innerText || "").trim())
+ ) {
+ const r = e.getBoundingClientRect();
+ if (r.width)
+ return { x: r.x + r.width / 2, y: r.y + r.height / 2, t: (e.innerText || "").trim() };
+ }
+ }
+ return null;
+});
+log("save btn", JSON.stringify(save));
+if (save) {
+ await page.mouse.click(save.x, save.y);
+ await page.waitForTimeout(5000);
+}
+await page.screenshot({ path: path.join(outDir, `${base}-saved.png`) }).catch(() => {});
+log("after save dialog:", await dlgText());
+
+// 复核:重新打开开发设置页
+await page
+ .goto(`https://mp.weixin.qq.com/wxamp/devprofile/get_profile?token=${token}&lang=zh_CN`, {
+ waitUntil: "commit",
+ timeout: 60000,
+ })
+ .catch(() => {});
+await page.waitForTimeout(12000);
+const verify = await page.evaluate(() => {
+ const t = (document.body.innerText || "").replace(/\s+/g, " ");
+ const i = t.indexOf("IP白名单");
+ return t.slice(i, i + 120);
+});
+log("VERIFY:", verify);
+write({ state: "DONE", saved: !!save, ips, verify });
+await ctx.close().catch(() => {});
+process.exit(0);
diff --git a/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/auto-submit.mjs b/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/auto-submit.mjs
new file mode 100644
index 00000000..a20a7ff8
--- /dev/null
+++ b/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/auto-submit.mjs
@@ -0,0 +1,170 @@
+// 自动检查:隐私指引审核状态 + 代码是否已提交审核;隐私指引通过后自动重试提交代码审核
+// 用法: node auto-submit.mjs [关键词] [状态文件]
+import { launchStealth } from "./stealth.mjs";
+import fs from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+const here = path.dirname(fileURLToPath(import.meta.url));
+const keyword = process.argv[2] || "待办清单";
+const statusPath = process.argv[3] || path.join(here, "auto-submit-status.json");
+const log = (...a) => console.log(new Date().toISOString(), ...a);
+const out = { at: new Date().toISOString() };
+
+const ctx = await launchStealth(path.join(here, "profile"), { headless: false });
+const page = ctx.pages()[0] || (await ctx.newPage());
+await page
+ .goto("https://mp.weixin.qq.com/", { waitUntil: "commit", timeout: 60000 })
+ .catch(() => {});
+await page.waitForTimeout(15000);
+const token = (page.url().match(/token=(\d+)/) || [])[1];
+if (!token) {
+ out.state = "NOT_LOGGED_IN";
+ fs.writeFileSync(statusPath, JSON.stringify(out, null, 2));
+ log("NOT LOGGED IN");
+ await ctx.close().catch(() => {});
+ process.exit(2);
+}
+const txt = () => page.evaluate(() => (document.body.innerText || "").replace(/\s+/g, " "));
+
+// 1) 隐私指引状态
+await page
+ .goto(`https://mp.weixin.qq.com/wxamp/basicprofile/index?token=${token}&lang=zh_CN`, {
+ waitUntil: "commit",
+ timeout: 60000,
+ })
+ .catch(() => {});
+await page.waitForTimeout(16000);
+const basic = await txt();
+const pi = basic.indexOf("用户隐私保护指引");
+out.privacyLine = basic.slice(pi, pi + 60);
+out.privacyOk =
+ /审核通过|已更新|已通过/.test(basic.slice(pi, pi + 30)) ||
+ !/未更新|审核中|未通过|审核不通过/.test(basic.slice(pi, pi + 30));
+log("隐私指引:", out.privacyLine);
+
+// 2) 版本管理状态
+await page
+ .goto(`https://mp.weixin.qq.com/wxamp/wacodepage/getcodepage?token=${token}&lang=zh_CN`, {
+ waitUntil: "commit",
+ timeout: 60000,
+ })
+ .catch(() => {});
+await page.waitForTimeout(16000);
+const ver = await txt();
+const hasReview = /审核版本\s*版本号/.test(ver);
+out.hasReviewVersion = hasReview;
+out.versionsLine = ver.slice(ver.indexOf("线上版本"), ver.indexOf("线上版本") + 420);
+log("版本:", out.versionsLine);
+log("已有审核版本:", hasReview);
+
+function summarize(reason) {
+ out.state = reason;
+ fs.writeFileSync(statusPath, JSON.stringify(out, null, 2));
+ log("STATE", reason);
+}
+
+if (hasReview) {
+ summarize("ALREADY_IN_REVIEW");
+ await ctx.close().catch(() => {});
+ process.exit(0);
+}
+if (!out.privacyOk) {
+ summarize("WAITING_PRIVACY");
+ await ctx.close().catch(() => {});
+ process.exit(0);
+}
+
+// 3) 隐私通过且无审核版本 → 提交代码审核
+const findBtn = () =>
+ page.evaluate((kw) => {
+ const marker = Array.from(document.querySelectorAll("*")).find(
+ (e) => e.children.length === 0 && (e.innerText || "").includes(kw),
+ );
+ const btns = Array.from(document.querySelectorAll("button,a")).filter(
+ (e) => e.offsetWidth && (e.innerText || "").trim() === "提交审核",
+ );
+ if (!btns.length) return null;
+ const my = marker ? marker.getBoundingClientRect().y : 0;
+ const chosen = btns
+ .map((b) => ({ b, y: b.getBoundingClientRect().y }))
+ .filter((o) => o.y > my - 40)
+ .sort((a, b) => a.y - b.y)[0];
+ const b = chosen ? chosen.b : btns[0];
+ b.scrollIntoView({ block: "center" });
+ const r = b.getBoundingClientRect();
+ return { x: r.x + r.width / 2, y: r.y + r.height / 2 };
+ }, keyword);
+
+let opened = false;
+for (let i = 0; i < 3 && !opened; i++) {
+ const p = await findBtn();
+ if (!p) break;
+ await page.mouse.click(p.x, p.y);
+ for (let w = 0; w < 12; w++) {
+ await page.waitForTimeout(1000);
+ if (/确认提交审核/.test(await txt())) {
+ opened = true;
+ break;
+ }
+ }
+}
+if (!opened) {
+ summarize("SUBMIT_BTN_FAILED");
+ await ctx.close().catch(() => {});
+ process.exit(4);
+}
+
+for (const t of ["已仔细阅读", "已阅读并了解平台审核规则"]) {
+ const c = await page.evaluate((t) => {
+ const el = Array.from(document.querySelectorAll("label,span,div,p"))
+ .filter(
+ (e) => e.offsetWidth && (e.innerText || "").includes(t) && (e.innerText || "").length < 120,
+ )
+ .pop();
+ if (!el) return null;
+ const r = el.getBoundingClientRect();
+ return { x: r.x + 12, y: r.y + r.height / 2 };
+ }, t);
+ if (c) {
+ await page.mouse.click(c.x, c.y);
+ await page.waitForTimeout(700);
+ }
+}
+const clickText = async (label) => {
+ const p = await page.evaluate((label) => {
+ const els = Array.from(document.querySelectorAll("button,a,span,div")).filter(
+ (e) => e.offsetWidth && e.children.length === 0 && (e.innerText || "").trim() === label,
+ );
+ if (!els.length) return null;
+ els[els.length - 1].scrollIntoView({ block: "center" });
+ const r = els[els.length - 1].getBoundingClientRect();
+ return { x: r.x + r.width / 2, y: r.y + r.height / 2 };
+ }, label);
+ if (!p) return false;
+ await page.mouse.click(p.x, p.y);
+ await page.waitForTimeout(4500);
+ log("clicked", label);
+ return true;
+};
+await clickText("下一步");
+await clickText("继续提交");
+await page.waitForTimeout(12000);
+await page
+ .screenshot({ path: path.join(here, "auto-submit-final.png"), fullPage: true })
+ .catch(() => {});
+
+// 复核是否进了审核
+await page
+ .goto(`https://mp.weixin.qq.com/wxamp/wacodepage/getcodepage?token=${token}&lang=zh_CN`, {
+ waitUntil: "commit",
+ timeout: 60000,
+ })
+ .catch(() => {});
+await page.waitForTimeout(15000);
+const ver2 = await txt();
+out.versionsAfter = ver2.slice(ver2.indexOf("线上版本"), ver2.indexOf("线上版本") + 420);
+out.submitted = /审核版本\s*版本号/.test(ver2);
+summarize(out.submitted ? "SUBMITTED" : "SUBMIT_NO_EFFECT");
+await ctx.close().catch(() => {});
+process.exit(0);
diff --git a/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/check-session.mjs b/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/check-session.mjs
new file mode 100644
index 00000000..c09cdaf5
--- /dev/null
+++ b/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/check-session.mjs
@@ -0,0 +1,40 @@
+// 复用已持久化的 profile 验证登录态是否还在,并回报账号信息
+import { launchStealth } from "./stealth.mjs";
+import fs from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+const here = path.dirname(fileURLToPath(import.meta.url));
+const shot = process.argv[2] || path.join(here, "home.png");
+const infoOut = process.argv[3] || path.join(here, "session-check.json");
+
+const ctx = await launchStealth(path.join(here, "profile"), { headless: false });
+const page = ctx.pages()[0] || (await ctx.newPage());
+await page.goto("https://mp.weixin.qq.com/", { waitUntil: "domcontentloaded", timeout: 60000 });
+await page.waitForTimeout(7000);
+
+const info = await page.evaluate(() => {
+ const t = (s) => {
+ const e = document.querySelector(s);
+ return e ? (e.innerText || "").trim().slice(0, 60) : null;
+ };
+ return {
+ title: document.title,
+ nickname:
+ t(".weui-desktop-account__nickname") || t(".account__nickname") || t('[class*="nickname"]'),
+ menus: Array.from(document.querySelectorAll(".weui-desktop-menu__link, .weui-desktop-menu a"))
+ .map((e) => (e.innerText || "").trim())
+ .filter(Boolean)
+ .slice(0, 30),
+ };
+});
+await page.screenshot({ path: shot }).catch(() => {});
+const out = {
+ url: page.url(),
+ loggedIn: page.url().includes("/cgi-bin/home") || page.url().includes("token="),
+ ...info,
+ shot,
+};
+fs.writeFileSync(infoOut, JSON.stringify(out, null, 2));
+console.log(JSON.stringify(out, null, 2));
+await ctx.close();
diff --git a/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/login2.mjs b/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/login2.mjs
new file mode 100644
index 00000000..a92f427b
--- /dev/null
+++ b/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/login2.mjs
@@ -0,0 +1,226 @@
+// 微信公众号扫码登录 v2:直接抓取二维码原图(而非元素截图),放大并校验可解码性
+import { launchStealth } from "./stealth.mjs";
+import fs from "node:fs";
+import crypto from "node:crypto";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { PNG } from "pngjs";
+import jsQR from "jsqr";
+
+const here = path.dirname(fileURLToPath(import.meta.url));
+const qrOut = process.argv[2] || path.join(here, "qr.png");
+const statusPath = process.argv[3] || path.join(here, "login-status.json");
+const timeoutMin = Number(process.argv[4] || 12);
+const write = (o) =>
+ fs.writeFileSync(statusPath, JSON.stringify({ at: new Date().toISOString(), ...o }, null, 2));
+
+// 二维码原图是 jpg(472x472),页面里被缩到 122x122 显示;这里取原图并在浏览器里放大成 PNG
+function savePng(pngBuf, out) {
+ fs.writeFileSync(out, pngBuf);
+ const png = PNG.sync.read(pngBuf);
+ const dec = jsQR(new Uint8Array(png.data), png.width, png.height);
+ return { size: `${png.width}x${png.height}`, decoded: dec ? dec.data : null };
+}
+
+const ctx = await launchStealth(path.join(here, "profile"), { headless: false });
+const page = ctx.pages()[0] || (await ctx.newPage());
+write({ state: "STARTING" });
+
+const cookiesHave = async () => {
+ const cs = await ctx.cookies("https://mp.weixin.qq.com").catch(() => []);
+ return cs.map((c) => c.name).filter((n) => ["slave_sid", "slave_user", "bizuin"].includes(n));
+};
+
+async function grabQr() {
+ const res = await page
+ .evaluate(async (scale) => {
+ const img = document.querySelector('img[class*="qrcode"], img[src*="scanloginqrcode"]');
+ if (!img) return null;
+ const src = img.src;
+ if (!img.complete || !img.naturalWidth) return { src, png: null, natural: null };
+ const c = document.createElement("canvas");
+ c.width = img.naturalWidth * scale;
+ c.height = img.naturalHeight * scale;
+ const g = c.getContext("2d");
+ g.imageSmoothingEnabled = false;
+ g.fillStyle = "#fff";
+ g.fillRect(0, 0, c.width, c.height);
+ g.drawImage(img, 0, 0, c.width, c.height);
+ return {
+ src,
+ png: c.toDataURL("image/png").split(",")[1],
+ natural: `${img.naturalWidth}x${img.naturalHeight}`,
+ };
+ }, 2)
+ .catch(() => null);
+ return res;
+}
+
+let lastSrc = "";
+let dumped = false;
+const deadline = Date.now() + timeoutMin * 60 * 1000;
+let state = "WAITING_SCAN";
+
+try {
+ await page.goto("https://mp.weixin.qq.com/", { waitUntil: "domcontentloaded", timeout: 60000 });
+} catch (e) {
+ write({ state: "GOTO_ERROR", error: e.message });
+}
+
+while (Date.now() < deadline) {
+ const url = page.url();
+ if (url.includes("/cgi-bin/home") || url.includes("token=")) {
+ await page.waitForTimeout(2500);
+ const home = qrOut.replace(/\.png$/, "") + "-home.png";
+ await page.screenshot({ path: home }).catch(() => {});
+ try {
+ await ctx.storageState({ path: path.join(here, "session.json") });
+ } catch {}
+ write({
+ state: "LOGGED_IN",
+ url,
+ title: await page.title().catch(() => ""),
+ homeShot: home,
+ cookies: await cookiesHave(),
+ });
+ console.log("LOGGED_IN", url);
+ await ctx.close();
+ process.exit(0);
+ }
+
+ if (!dumped) {
+ dumped = true;
+ const html = await page
+ .evaluate(() => {
+ const box =
+ document.querySelector(".login__type__container__scan") ||
+ document.querySelector('[class*="login__type__container"]');
+ return box ? box.outerHTML.slice(0, 4000) : "(no login container)";
+ })
+ .catch(() => "");
+ const refreshish = await page
+ .evaluate(() =>
+ Array.from(document.querySelectorAll(".login__type__container__scan *"))
+ .filter((e) => /失效|刷新|重新获取/.test(e.innerText || ""))
+ .map(
+ (e) =>
+ (e.className || "").toString() + " :: " + (e.innerText || "").trim().slice(0, 30),
+ )
+ .slice(0, 10),
+ )
+ .catch(() => []);
+ console.log(
+ "--- login container html ---\n" +
+ html +
+ "\n--- refresh candidates ---\n" +
+ JSON.stringify(refreshish),
+ );
+ }
+
+ const qr = await grabQr();
+ if (qr && qr.src !== lastSrc && qr.png) {
+ // 按内容 hash 命名,避免同样的文件名被看图工具缓存成旧图
+ const buf = Buffer.from(qr.png, "base64");
+ const hash = crypto.createHash("sha1").update(buf).digest("hex").slice(0, 8);
+ const file = qrOut.replace(/\.png$/, `-${hash}.png`);
+ if (!fs.existsSync(file)) {
+ fs.writeFileSync(file, buf);
+ for (const f of fs.readdirSync(path.dirname(file))) {
+ if (
+ /^wechat-mp-login-qr-[0-9a-f]{8}\.png$/.test(f) &&
+ path.join(path.dirname(file), f) !== file
+ ) {
+ try {
+ fs.unlinkSync(path.join(path.dirname(file), f));
+ } catch {}
+ }
+ }
+ }
+ const info = savePng(buf, file);
+ lastSrc = qr.src;
+ state = "WAITING_SCAN";
+ write({ state, url, qrSrc: qr.src, qrFile: file, native: qr.natural, ...info });
+ console.log(
+ "QR_READY",
+ new Date().toISOString(),
+ path.basename(file),
+ JSON.stringify({ native: qr.natural, ...info }),
+ );
+ }
+
+ // 轮询扫码状态
+ const ask = await page
+ .evaluate(async () => {
+ const img = document.querySelector('img[class*="qrcode"], img[src*="scanloginqrcode"]');
+ const m = img && (img.getAttribute("src") || "").match(/random=(\d+)/);
+ if (!m) return null;
+ try {
+ const r = await fetch(
+ `/cgi-bin/scanloginqrcode?action=ask&random=${m[1]}&lang=zh_CN&token=`,
+ { credentials: "include" },
+ );
+ return { text: (await r.text()).slice(0, 300) };
+ } catch (e) {
+ return { error: e.message };
+ }
+ })
+ .catch(() => null);
+ if (ask) {
+ let st = null;
+ try {
+ st = JSON.parse(ask.text);
+ } catch {}
+ write({ state, url, qrFile: qrOut, ask: ask.text });
+ if (st && st.status !== undefined && st.status !== 0)
+ console.log("ASK status=" + st.status, ask.text.slice(0, 200));
+ if (st && ["1", "2", "4", "5"].includes(String(st.status)))
+ state = "SCANNED(status=" + st.status + ")";
+ if (st && ["3", "6", "7", "8"].includes(String(st.status))) {
+ state = "QR_EXPIRED(status=" + st.status + ")";
+ const clicked = await page
+ .evaluate(() => {
+ const cand = Array.from(
+ document.querySelectorAll(".login__type__container__scan *"),
+ ).filter((e) => /失效|刷新|重新获取/.test(e.innerText || ""));
+ if (cand[0]) {
+ cand[0].click();
+ return (cand[0].innerText || "").trim().slice(0, 30);
+ }
+ return null;
+ })
+ .catch(() => null);
+ console.log("EXPIRED -> refresh click:", clicked);
+ lastSrc = "";
+ if (!clicked) {
+ await page.reload({ waitUntil: "domcontentloaded", timeout: 60000 }).catch(() => {});
+ console.log("EXPIRED -> reloaded page for a fresh QR");
+ }
+ await page.waitForTimeout(2500);
+ }
+ }
+
+ const bodyText = await page
+ .evaluate(() => (document.body.innerText || "").slice(0, 800))
+ .catch(() => "");
+ if (/选择(公众平台)?账号|选择公众号/.test(bodyText) && !/微信扫一扫/.test(bodyText)) {
+ const shotPath = qrOut.replace(/\.png$/, "") + "-chooser.png";
+ await page.screenshot({ path: shotPath }).catch(() => {});
+ write({ state: "ACCOUNT_CHOOSER", url, shot: shotPath, text: bodyText.slice(0, 400) });
+ console.log("CHOOSER:", bodyText.slice(0, 300).replace(/\n+/g, " | "));
+ const first = page
+ .locator('a[class*="account"], li[class*="account"], [class*="account__item"]')
+ .first();
+ if ((await first.count().catch(() => 0)) > 0) {
+ await first.click({ timeout: 5000 }).catch((e) => console.log("click failed", e.message));
+ await page.waitForTimeout(4000);
+ continue;
+ }
+ }
+
+ await page.waitForTimeout(2000);
+}
+
+write({ state: "TIMEOUT", url: page.url() });
+console.log("TIMEOUT");
+await ctx.close();
+process.exit(1);
diff --git a/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/miniapp-info.mjs b/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/miniapp-info.mjs
new file mode 100644
index 00000000..8d2ebf07
--- /dev/null
+++ b/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/miniapp-info.mjs
@@ -0,0 +1,67 @@
+// 小程序后台信息采集:首页 / 基本设置(AppID) / 开发设置(上传密钥入口)
+// 用法: node miniapp-info.mjs <outDir> <shotPrefix>
+import { launchStealth } from "./stealth.mjs";
+import fs from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+const here = path.dirname(fileURLToPath(import.meta.url));
+const outDir = process.argv[2] || here;
+const shotPrefix = process.argv[3] || path.join(outDir, "miniapp");
+
+const ctx = await launchStealth(path.join(here, "profile"), { headless: false });
+const page = ctx.pages()[0] || (await ctx.newPage());
+await page.goto("https://mp.weixin.qq.com/", { waitUntil: "domcontentloaded", timeout: 60000 });
+await page.waitForTimeout(7000);
+console.log("home", page.url());
+const token = (page.url().match(/token=(\d+)/) || [])[1];
+console.log("token", token);
+
+const grab = async (label, url) => {
+ await page
+ .goto(url, { waitUntil: "domcontentloaded", timeout: 60000 })
+ .catch((e) => console.log(label, "goto err", e.message));
+ await page.waitForTimeout(7000);
+ const info = await page.evaluate(() => {
+ const vis = (e) => !!(e.offsetWidth || e.offsetHeight);
+ const all = document.body.innerText || "";
+ const appids = [...new Set(all.match(/wx[0-9a-f]{16}/g) || [])];
+ const links = Array.from(document.querySelectorAll("a[href]"))
+ .filter(vis)
+ .map((a) => ({ t: (a.innerText || "").trim().slice(0, 20), href: a.getAttribute("href") }))
+ .filter((l) => l.href && l.href !== "javascript:;")
+ .slice(0, 100);
+ const menu = Array.from(
+ document.querySelectorAll('[class*="menu__item"], [class*="menu-item"], [class*="nav"] a'),
+ )
+ .filter(vis)
+ .map((e) => (e.innerText || "").replace(/\s+/g, " ").trim())
+ .filter(Boolean)
+ .slice(0, 60);
+ return {
+ url: location.href,
+ title: document.title,
+ appids,
+ links,
+ menu,
+ text: all.replace(/\s+/g, " ").slice(0, 2000),
+ };
+ });
+ await page.screenshot({ path: `${shotPrefix}-${label}.png` }).catch(() => {});
+ fs.writeFileSync(path.join(outDir, `miniapp-${label}.json`), JSON.stringify(info, null, 2));
+ console.log(`--- ${label} ${info.url}`);
+ console.log(" title", info.title, "appids", JSON.stringify(info.appids));
+ console.log(" menu", JSON.stringify(info.menu.slice(0, 30)));
+ console.log(" text", info.text.slice(0, 700));
+ return info;
+};
+
+await grab("home", "https://mp.weixin.qq.com/wxamp/index/index?lang=zh_CN&token=" + token);
+await grab("basic", `https://mp.weixin.qq.com/wxamp/basicprofile/index?lang=zh_CN&token=${token}`);
+await grab(
+ "dev",
+ `https://mp.weixin.qq.com/wxamp/devprofile/get_profile?lang=zh_CN&token=${token}`,
+);
+
+await ctx.close().catch(() => {});
+process.exit(0);
diff --git a/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/miniapp-nav.mjs b/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/miniapp-nav.mjs
new file mode 100644
index 00000000..7203efd9
--- /dev/null
+++ b/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/miniapp-nav.mjs
@@ -0,0 +1,56 @@
+// 在小程序后台打开指定页面并 dump 文本/按钮;用法: node miniapp-nav.mjs <path> [label] [outDir]
+import { launchStealth } from "./stealth.mjs";
+import fs from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+const here = path.dirname(fileURLToPath(import.meta.url));
+const p = process.argv[2] || "/wxamp/index/index";
+const label = process.argv[3] || "page";
+const outDir = process.argv[4] || here;
+
+const ctx = await launchStealth(path.join(here, "profile"), { headless: false });
+const page = ctx.pages()[0] || (await ctx.newPage());
+await page
+ .goto("https://mp.weixin.qq.com/", { waitUntil: "commit", timeout: 60000 })
+ .catch((e) => console.log("home goto warn", e.message.split("\n")[0]));
+await page.waitForTimeout(14000);
+const token = (page.url().match(/token=(\d+)/) || [])[1];
+console.log("home", page.url(), "token", token);
+if (!token) {
+ console.log("NOT LOGGED IN");
+ await ctx.close().catch(() => {});
+ process.exit(2);
+}
+
+await page
+ .goto(`https://mp.weixin.qq.com${p}?token=${token}&lang=zh_CN`, {
+ waitUntil: "commit",
+ timeout: 60000,
+ })
+ .catch((e) => console.log("goto warn", e.message.split("\n")[0]));
+await page.waitForTimeout(15000);
+const info = await page.evaluate(() => {
+ const vis = (e) => !!(e.offsetWidth || e.offsetHeight);
+ const btns = Array.from(document.querySelectorAll('button,a,[role="button"]'))
+ .filter(vis)
+ .map((e) => ({
+ t: (e.innerText || "").replace(/\s+/g, " ").trim().slice(0, 24),
+ cls: (e.className || "").toString().slice(0, 70),
+ href: e.getAttribute && e.getAttribute("href"),
+ }))
+ .filter((b) => b.t && b.t.length < 24);
+ return {
+ url: location.href,
+ title: document.title,
+ text: (document.body.innerText || "").replace(/\s+/g, " ").slice(0, 2500),
+ btns: btns.slice(0, 60),
+ };
+});
+await page.screenshot({ path: path.join(outDir, `miniapp-${label}.png`) }).catch(() => {});
+fs.writeFileSync(path.join(outDir, `miniapp-${label}.json`), JSON.stringify(info, null, 2));
+console.log("URL", info.url);
+console.log("TEXT", info.text);
+console.log("BTNS", JSON.stringify(info.btns));
+await ctx.close().catch(() => {});
+process.exit(0);
diff --git a/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/package.json b/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/package.json
new file mode 100644
index 00000000..5f127947
--- /dev/null
+++ b/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/package.json
@@ -0,0 +1,12 @@
+{
+ "name": "wechat-mp-scripts",
+ "version": "1.0.0",
+ "private": true,
+ "description": "微信小程序后台自动化脚本(登录/切号/密钥/IP 白名单/隐私指引/提审/撤回)的依赖清单",
+ "dependencies": {
+ "jpeg-js": "^0.4.4",
+ "jsqr": "^1.4.0",
+ "playwright": "^1.63.0",
+ "pngjs": "^7.0.0"
+ }
+}
diff --git a/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/privacy-fill2.mjs b/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/privacy-fill2.mjs
new file mode 100644
index 00000000..21989ef1
--- /dev/null
+++ b/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/privacy-fill2.mjs
@@ -0,0 +1,302 @@
+// 填写隐私指引 → 预览 → 确定并提交协议;如需扫码则出码等待
+import { launchStealth } from "./stealth.mjs";
+import fs from "node:fs";
+import path from "node:path";
+import crypto from "node:crypto";
+import { fileURLToPath } from "node:url";
+import { PNG } from "pngjs";
+import jsQR from "jsqr";
+
+const here = path.dirname(fileURLToPath(import.meta.url));
+const outDir = process.argv[2] || here;
+const contact = process.argv[3] || "[email protected]";
+const log = (...a) => console.log(new Date().toISOString(), ...a);
+const PURPOSES = [
+ "用于账号注册、登录与身份校验",
+ "用于保存你生成或导出的图片到相册",
+ "用于按你所在位置提供本地化内容",
+ "用于识别你复制的文本并快速创建内容",
+];
+
+function upscale3x(png) {
+ const s = 3,
+ b = new PNG({ width: png.width * s, height: png.height * s });
+ for (let y = 0; y < b.height; y++)
+ for (let x = 0; x < b.width; x++) {
+ const si = (((y / s) | 0) * png.width + ((x / s) | 0)) << 2,
+ di = (y * b.width + x) << 2;
+ b.data[di] = png.data[si];
+ b.data[di + 1] = png.data[si + 1];
+ b.data[di + 2] = png.data[si + 2];
+ b.data[di + 3] = 255;
+ }
+ return b;
+}
+function deliverQr(pngBuf) {
+ const png = PNG.sync.read(pngBuf);
+ const big = upscale3x(png);
+ const dec = jsQR(new Uint8Array(big.data), big.width, big.height);
+ const hash = crypto
+ .createHash("sha1")
+ .update(dec ? dec.data : PNG.sync.write(big))
+ .digest("hex")
+ .slice(0, 8);
+ const file = path.join(outDir, `wechat-mp-priv-qr-${hash}.png`);
+ if (!fs.existsSync(file)) {
+ fs.writeFileSync(file, PNG.sync.write(big));
+ for (const f of fs.readdirSync(outDir))
+ if (/^wechat-mp-priv-qr-[0-9a-f]{8}\.png$/.test(f) && path.join(outDir, f) !== file) {
+ try {
+ fs.unlinkSync(path.join(outDir, f));
+ } catch {}
+ }
+ }
+ return {
+ file,
+ hash,
+ size: `${big.width}x${big.height}`,
+ decoded: dec ? dec.data.slice(0, 90) : null,
+ };
+}
+
+const ctx = await launchStealth(path.join(here, "profile"), { headless: false });
+const page = ctx.pages()[0] || (await ctx.newPage());
+await page
+ .goto("https://mp.weixin.qq.com/", { waitUntil: "commit", timeout: 60000 })
+ .catch(() => {});
+await page.waitForTimeout(15000);
+const token = (page.url().match(/token=(\d+)/) || [])[1];
+if (!token) {
+ log("NOT LOGGED IN");
+ await ctx.close().catch(() => {});
+ process.exit(2);
+}
+await page
+ .goto(
+ `https://mp.weixin.qq.com/wxamp/wadevelopcode/privacy?ver=1&id=0&wait=0&token=${token}&lang=zh_CN`,
+ { waitUntil: "commit", timeout: 60000 },
+ )
+ .catch(() => {});
+await page.waitForTimeout(22000);
+
+const txt = () => page.evaluate(() => (document.body.innerText || "").replace(/\s+/g, " "));
+const clickText = async (label, { last = true } = {}) => {
+ const p = await page.evaluate(
+ ({ label, last }) => {
+ const els = Array.from(document.querySelectorAll("button,a,span,div,li")).filter(
+ (e) => e.offsetWidth && e.children.length === 0 && (e.innerText || "").trim() === label,
+ );
+ if (!els.length) return null;
+ const e = last ? els[els.length - 1] : els[0];
+ e.scrollIntoView({ block: "center" });
+ const r = e.getBoundingClientRect();
+ return { x: r.x + r.width / 2, y: r.y + r.height / 2 };
+ },
+ { label, last },
+ );
+ if (!p) {
+ log("no elem", label);
+ return false;
+ }
+ await page.mouse.click(p.x, p.y);
+ await page.waitForTimeout(3000);
+ log("clicked", label);
+ return true;
+};
+
+// 1) 用途
+const boxes = page.locator('input[placeholder="请填写用途"]');
+for (let i = 0; i < (await boxes.count()); i++)
+ await boxes
+ .nth(i)
+ .fill(PURPOSES[i] || PURPOSES[0])
+ .catch(() => {});
+
+// 2) 联系方式:定位「请选择」所在行,选中类型后填同行输入框
+const anchorY = await page.evaluate(() => {
+ const e = Array.from(document.querySelectorAll("*")).find(
+ (x) => x.offsetWidth && x.children.length === 0 && (x.innerText || "").trim() === "请选择",
+ );
+ if (!e) return null;
+ e.scrollIntoView({ block: "center" });
+ return e.getBoundingClientRect().y;
+});
+log("anchor y", anchorY);
+await page.waitForTimeout(800);
+if (anchorY !== null) {
+ const p = await page.evaluate(() => {
+ const e = Array.from(document.querySelectorAll("*")).find(
+ (x) => x.offsetWidth && x.children.length === 0 && (x.innerText || "").trim() === "请选择",
+ );
+ if (!e) return null;
+ const r = e.getBoundingClientRect();
+ return { x: r.x + r.width / 2, y: r.y + r.height / 2 };
+ });
+ if (p) {
+ await page.mouse.click(p.x, p.y);
+ await page.waitForTimeout(2000);
+ }
+ const opt = await page.evaluate(() => {
+ const els = Array.from(document.querySelectorAll('li,[role="option"],span,div')).filter(
+ (x) => x.offsetWidth && x.children.length === 0 && (x.innerText || "").trim() === "邮箱",
+ );
+ if (!els.length) return null;
+ const r = els[els.length - 1].getBoundingClientRect();
+ return { x: r.x + r.width / 2, y: r.y + r.height / 2 };
+ });
+ if (opt) {
+ await page.mouse.click(opt.x, opt.y);
+ await page.waitForTimeout(2500);
+ log("picked 邮箱");
+ }
+
+ // 填到与「请选择」同一行的输入框
+ // 用 placeholder=邮箱 精确定位联系方式输入框
+ const byPh = page.locator('input[placeholder="邮箱"]');
+ if (await byPh.count().catch(() => 0)) {
+ await byPh
+ .first()
+ .fill(contact)
+ .catch((e) => log("contact fill err", e.message.split("\n")[0]));
+ log("contact filled via placeholder");
+ }
+ const res = await page.evaluate(
+ ({ y, v }) => {
+ const inputs = Array.from(
+ document.querySelectorAll("input[type=text],input:not([type])"),
+ ).filter((e) => e.offsetWidth && !/请填写用途/.test(e.placeholder || ""));
+ const near = inputs.filter((i) => Math.abs(i.getBoundingClientRect().y - y) < 90);
+ if (!near.length)
+ return {
+ ok: false,
+ cands: inputs.map((i) => ({
+ y: Math.round(i.getBoundingClientRect().y),
+ ph: i.placeholder,
+ val: i.value,
+ })),
+ };
+ const t = near[0];
+ const setter = Object.getOwnPropertyDescriptor(
+ window.HTMLInputElement.prototype,
+ "value",
+ ).set;
+ setter.call(t, v);
+ t.dispatchEvent(new Event("input", { bubbles: true }));
+ t.dispatchEvent(new Event("change", { bubbles: true }));
+ return { ok: true, val: t.value, ph: t.placeholder };
+ },
+ { y: anchorY, v: contact },
+ );
+ log("contact fill", JSON.stringify(res));
+}
+// 2.5) 补 5.2「再次以 ___ 方式告知」那一栏(预览时会显示「待填写」)
+const fifth = await page.evaluate(() => {
+ const inputs = Array.from(document.querySelectorAll("input[type=text],input:not([type])")).filter(
+ (e) =>
+ e.offsetWidth &&
+ !/请填写用途/.test(e.placeholder || "") &&
+ !/邮箱|电话|微信号|qq/.test(e.placeholder || ""),
+ );
+ const t = inputs[inputs.length - 1];
+ if (!t) return null;
+ const setter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set;
+ setter.call(t, "弹窗提示");
+ t.dispatchEvent(new Event("input", { bubbles: true }));
+ t.dispatchEvent(new Event("change", { bubbles: true }));
+ return { ph: t.placeholder || "", val: t.value, y: Math.round(t.getBoundingClientRect().y) };
+});
+log("5.2 填写", JSON.stringify(fifth));
+await page.waitForTimeout(1200);
+await page
+ .screenshot({ path: path.join(outDir, "pf2-before-preview.png"), fullPage: true })
+ .catch(() => {});
+
+// 3) 预览 → 提交
+await clickText("预览后提交协议");
+await page.waitForTimeout(7000);
+let t = await txt();
+log("preview tail:", t.slice(-400));
+const stillWarn = /联系方式待完善|部分进行完善/.test(t);
+log("still warn", stillWarn);
+await page
+ .screenshot({ path: path.join(outDir, "pf2-preview.png"), fullPage: true })
+ .catch(() => {});
+
+if (!stillWarn) {
+ // 勾选「本小程序已对用户的信息处理进行了逐一、如实的说明…」
+ const cb = await page.evaluate(() => {
+ const el = Array.from(document.querySelectorAll("label,span,div,p"))
+ .filter(
+ (e) =>
+ e.offsetWidth &&
+ /本小程序已对用户的信息处理/.test(e.innerText || "") &&
+ (e.innerText || "").length < 120,
+ )
+ .pop();
+ if (!el) return null;
+ el.scrollIntoView({ block: "center" });
+ const r = el.getBoundingClientRect();
+ return { x: r.x + 10, y: r.y + r.height / 2 };
+ });
+ log("agree checkbox", JSON.stringify(cb));
+ if (cb) {
+ await page.mouse.click(cb.x, cb.y);
+ await page.waitForTimeout(1500);
+ }
+ const st = await page.evaluate(() =>
+ Array.from(document.querySelectorAll("input[type=checkbox]")).map((c) => ({
+ checked: c.checked,
+ vis: !!c.offsetParent,
+ })),
+ );
+ log("checkbox state", JSON.stringify(st));
+ await page
+ .screenshot({ path: path.join(outDir, "pf2-agreed.png"), fullPage: true })
+ .catch(() => {});
+ await clickText("确定并提交协议");
+ await page.waitForTimeout(8000);
+ t = await txt();
+ log("after submit url", page.url());
+ log("after submit tail", t.slice(-400));
+ await page
+ .screenshot({ path: path.join(outDir, "pf2-submitted.png"), fullPage: true })
+ .catch(() => {});
+
+ // 可能弹扫码
+ const el = await page.evaluateHandle(() => {
+ const ds = Array.from(document.querySelectorAll('[class*="dialog"],[class*="modal"]')).filter(
+ (e) => e.offsetWidth > 200 && e.offsetHeight > 120,
+ );
+ for (const d of ds)
+ for (const img of d.querySelectorAll("img")) {
+ if (img.getBoundingClientRect().width > 120) return img;
+ }
+ for (const d of ds)
+ for (const cv of d.querySelectorAll("canvas")) {
+ if (cv.getBoundingClientRect().width > 120) return cv;
+ }
+ return null;
+ });
+ const node = el.asElement();
+ if (node) {
+ const buf = await node.screenshot().catch(() => null);
+ if (buf) {
+ const info = deliverQr(buf);
+ log(
+ "QR_READY",
+ path.basename(info.file),
+ info.size,
+ info.decoded ? "decoded-ok" : "UNREADABLE",
+ );
+ }
+ }
+ const dlg = await page.evaluate(() => {
+ const ds = Array.from(document.querySelectorAll('[class*="dialog"],[class*="modal"]')).filter(
+ (e) => e.offsetWidth > 200 && e.offsetHeight > 120,
+ );
+ return ds.map((d) => (d.innerText || "").replace(/\s+/g, " ").trim().slice(0, 200));
+ });
+ log("dialogs after submit", JSON.stringify(dlg));
+}
+await ctx.close().catch(() => {});
+process.exit(0);
diff --git a/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/probe-key-qr.mjs b/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/probe-key-qr.mjs
new file mode 100644
index 00000000..ea615047
--- /dev/null
+++ b/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/probe-key-qr.mjs
@@ -0,0 +1,147 @@
+// 探明「重置代码上传密钥」弹窗里二维码的元素类型与原始分辨率
+import { launchStealth } from "./stealth.mjs";
+import fs from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { PNG } from "pngjs";
+import jsQR from "jsqr";
+
+const here = path.dirname(fileURLToPath(import.meta.url));
+const outDir = process.argv[2] || here;
+const ctx = await launchStealth(path.join(here, "profile"), { headless: false });
+const page = ctx.pages()[0] || (await ctx.newPage());
+await page.goto("https://mp.weixin.qq.com/", { waitUntil: "domcontentloaded", timeout: 60000 });
+await page.waitForTimeout(10000);
+const token = (page.url().match(/token=(\d+)/) || [])[1];
+await page.goto(`https://mp.weixin.qq.com/wxamp/devprofile/get_profile?token=${token}&lang=zh_CN`, {
+ waitUntil: "domcontentloaded",
+ timeout: 60000,
+});
+await page.waitForTimeout(9000);
+
+const btn = await page.evaluate(() => {
+ const label = Array.from(document.querySelectorAll("*")).find(
+ (e) => e.children.length === 0 && (e.innerText || "").trim() === "小程序代码上传密钥",
+ );
+ let n = label;
+ for (let i = 0; i < 8 && n; i++) {
+ n = n.parentElement;
+ if (!n) break;
+ const c = Array.from(n.querySelectorAll("a,button,span,div")).filter(
+ (e) => e.children.length === 0 && (e.innerText || "").trim() === "重置",
+ );
+ if (c[0]) {
+ const r = c[0].getBoundingClientRect();
+ return { x: r.x + r.width / 2, y: r.y + r.height / 2 };
+ }
+ }
+ return null;
+});
+await page.mouse.click(btn.x, btn.y);
+await page.waitForTimeout(4000);
+
+const info = await page.evaluate(() => {
+ const dlg = document.querySelector(".weui-desktop-dialog") || document.body;
+ const out = { imgs: [], canvases: [], divs: [] };
+ for (const img of dlg.querySelectorAll("img")) {
+ const r = img.getBoundingClientRect();
+ out.imgs.push({
+ srcKind: (img.src || "").slice(0, 40),
+ dataUrl: (img.src || "").startsWith("data:"),
+ nat: `${img.naturalWidth}x${img.naturalHeight}`,
+ rect: `${Math.round(r.width)}x${Math.round(r.height)}`,
+ cls: (img.className || "").toString(),
+ });
+ }
+ for (const cv of dlg.querySelectorAll("canvas")) {
+ const r = cv.getBoundingClientRect();
+ out.canvases.push({
+ size: `${cv.width}x${cv.height}`,
+ rect: `${Math.round(r.width)}x${Math.round(r.height)}`,
+ cls: (cv.className || "").toString(),
+ });
+ }
+ for (const d of dlg.querySelectorAll("div,span")) {
+ const r = d.getBoundingClientRect();
+ const bg = getComputedStyle(d).backgroundImage;
+ if (bg && bg !== "none" && r.width > 80)
+ out.divs.push({
+ bg: bg.slice(0, 80),
+ rect: `${Math.round(r.width)}x${Math.round(r.height)}`,
+ cls: (d.className || "").toString().slice(0, 60),
+ });
+ }
+ return out;
+});
+console.log(JSON.stringify(info, null, 2));
+
+// 尝试从 img(data URL)或 canvas 取原始位图
+const raw = await page.evaluate(() => {
+ const dlg = document.querySelector(".weui-desktop-dialog") || document.body;
+ const toPng = (src, w, h) => {
+ const c = document.createElement("canvas");
+ c.width = w;
+ c.height = h;
+ const g = c.getContext("2d");
+ g.fillStyle = "#fff";
+ g.fillRect(0, 0, w, h);
+ g.drawImage(src, 0, 0, w, h);
+ return c.toDataURL("image/png").split(",")[1];
+ };
+ for (const img of dlg.querySelectorAll("img"))
+ if (img.naturalWidth >= 100)
+ return {
+ kind: "img",
+ w: img.naturalWidth,
+ h: img.naturalHeight,
+ png: toPng(img, img.naturalWidth, img.naturalHeight),
+ };
+ for (const cv of dlg.querySelectorAll("canvas"))
+ if (cv.width >= 100)
+ return {
+ kind: "canvas",
+ w: cv.width,
+ h: cv.height,
+ png: cv.toDataURL("image/png").split(",")[1],
+ };
+ return null;
+});
+if (raw) {
+ const buf = Buffer.from(raw.png, "base64");
+ fs.writeFileSync(path.join(outDir, "probe-key-qr-native.png"), buf);
+ const png = PNG.sync.read(buf);
+ const dec = jsQR(new Uint8Array(png.data), png.width, png.height);
+ console.log(
+ "RAW kind",
+ raw.kind,
+ png.width + "x" + png.height,
+ "jsQR:",
+ dec ? dec.data.slice(0, 90) : "FAIL",
+ );
+ // 3 倍最近邻放大再试
+ const s = 3;
+ const big = new PNG({ width: png.width * s, height: png.height * s });
+ for (let y = 0; y < big.height; y++)
+ for (let x = 0; x < big.width; x++) {
+ const si = (((y / s) | 0) * png.width + ((x / s) | 0)) << 2,
+ di = (y * big.width + x) << 2;
+ big.data[di] = png.data[si];
+ big.data[di + 1] = png.data[si + 1];
+ big.data[di + 2] = png.data[si + 2];
+ big.data[di + 3] = 255;
+ }
+ const bigBuf = PNG.sync.write(big);
+ fs.writeFileSync(path.join(outDir, "probe-key-qr-3x.png"), bigBuf);
+ const dec2 = jsQR(new Uint8Array(big.data), big.width, big.height);
+ console.log("3x", big.width + "x" + big.height, "jsQR:", dec2 ? dec2.data.slice(0, 90) : "FAIL");
+}
+
+// 元素截图对比
+const el = page.locator(".weui-desktop-dialog canvas, .weui-desktop-dialog img").first();
+if (await el.count().catch(() => 0)) {
+ await el.screenshot({ path: path.join(outDir, "probe-key-qr-el.png") }).catch(() => {});
+ console.log("element shot saved");
+}
+await page.screenshot({ path: path.join(outDir, "probe-key-qr-page.png") }).catch(() => {});
+await ctx.close().catch(() => {});
+process.exit(0);
diff --git a/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/probe-privacy.mjs b/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/probe-privacy.mjs
new file mode 100644
index 00000000..6866403b
--- /dev/null
+++ b/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/probe-privacy.mjs
@@ -0,0 +1,73 @@
+// 探查隐私保护指引页:iframe / 网络失败原因
+import { launchStealth } from "./stealth.mjs";
+import fs from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+const here = path.dirname(fileURLToPath(import.meta.url));
+const outDir = process.argv[2] || here;
+const log = (...a) => console.log(new Date().toISOString(), ...a);
+
+const ctx = await launchStealth(path.join(here, "profile"), { headless: false });
+const page = ctx.pages()[0] || (await ctx.newPage());
+const errs = [];
+page.on("requestfailed", (r) =>
+ errs.push(`FAIL ${r.failure()?.errorText || ""} ${r.url().slice(0, 160)}`),
+);
+page.on("response", (r) => {
+ const u = r.url();
+ if (r.status() >= 400) errs.push(`HTTP ${r.status()} ${u.slice(0, 160)}`);
+});
+page.on("pageerror", (e) => errs.push(`PAGEERR ${String(e.message).slice(0, 200)}`));
+page.on("framenavigated", (f) => log("frame nav", f.url().slice(0, 160)));
+
+await page
+ .goto("https://mp.weixin.qq.com/", { waitUntil: "commit", timeout: 60000 })
+ .catch(() => {});
+await page.waitForTimeout(15000);
+const token = (page.url().match(/token=(\d+)/) || [])[1];
+await page
+ .goto(`https://mp.weixin.qq.com/wxamp/wadevelopcode/privacy?token=${token}&lang=zh_CN`, {
+ waitUntil: "commit",
+ timeout: 60000,
+ })
+ .catch(() => {});
+await page.waitForTimeout(25000);
+
+const info = await page.evaluate(() => {
+ const vis = (e) => !!(e.offsetWidth || e.offsetHeight);
+ const frames = Array.from(document.querySelectorAll("iframe")).map((f) => ({
+ src: (f.src || "").slice(0, 160),
+ w: f.offsetWidth,
+ h: f.offsetHeight,
+ }));
+ const btns = [
+ ...new Set(
+ Array.from(document.querySelectorAll('button,a,[role="button"],div,span'))
+ .filter((e) => vis(e) && e.children.length === 0)
+ .map((e) => (e.innerText || "").replace(/\s+/g, " ").trim())
+ .filter((t) => t && t.length <= 12),
+ ),
+ ];
+ const inputs = Array.from(document.querySelectorAll("input,textarea,select"))
+ .filter(vis)
+ .map((e) => ({ tag: e.tagName, ph: e.placeholder || "", val: (e.value || "").slice(0, 30) }));
+ return {
+ url: location.href,
+ frames,
+ btns,
+ inputs,
+ text: (document.body.innerText || "").replace(/\s+/g, " ").slice(0, 1500),
+ };
+});
+log("frames", JSON.stringify(info.frames));
+log("btns", JSON.stringify(info.btns));
+log("inputs", JSON.stringify(info.inputs));
+log("text", info.text.slice(0, 900));
+log("--- errors ---");
+for (const e of [...new Set(errs)].slice(0, 40)) log(e);
+await page
+ .screenshot({ path: path.join(outDir, "probe-privacy.png"), fullPage: true })
+ .catch(() => {});
+await ctx.close().catch(() => {});
+process.exit(0);
diff --git a/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/probe-privcheck.mjs b/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/probe-privcheck.mjs
new file mode 100644
index 00000000..9b1a1a6d
--- /dev/null
+++ b/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/probe-privcheck.mjs
@@ -0,0 +1,129 @@
+// 提交审核流程中抓 CheckPrivacyApiAuth 的响应体,确认卡点
+import { launchStealth } from "./stealth.mjs";
+import fs from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+const here = path.dirname(fileURLToPath(import.meta.url));
+const outDir = process.argv[2] || here;
+const keyword = process.argv[3] || "待办清单";
+const log = (...a) => console.log(new Date().toISOString(), ...a);
+
+const ctx = await launchStealth(path.join(here, "profile"), { headless: false });
+const page = ctx.pages()[0] || (await ctx.newPage());
+const bodies = [];
+page.on("response", async (r) => {
+ const u = r.url();
+ if (/privacy|Privacy|submit|audit/i.test(u) && !/aegis|res\.wx\.qq\.com/.test(u)) {
+ let body = "";
+ try {
+ body = (await r.text()).slice(0, 600);
+ } catch {}
+ bodies.push(`[${r.status()}] ${u.slice(0, 140)}\n ${body}`);
+ }
+});
+page.on("pageerror", (e) => bodies.push("PAGEERR " + String(e.message).slice(0, 200)));
+
+await page
+ .goto("https://mp.weixin.qq.com/", { waitUntil: "commit", timeout: 60000 })
+ .catch(() => {});
+await page.waitForTimeout(15000);
+const token = (page.url().match(/token=(\d+)/) || [])[1];
+if (!token) {
+ log("NOT LOGGED IN");
+ await ctx.close().catch(() => {});
+ process.exit(2);
+}
+await page
+ .goto(`https://mp.weixin.qq.com/wxamp/wacodepage/getcodepage?token=${token}&lang=zh_CN`, {
+ waitUntil: "commit",
+ timeout: 60000,
+ })
+ .catch(() => {});
+await page.waitForTimeout(15000);
+
+const bodyText = () => page.evaluate(() => (document.body.innerText || "").replace(/\s+/g, " "));
+const findBtn = () =>
+ page.evaluate((kw) => {
+ const marker = Array.from(document.querySelectorAll("*")).find(
+ (e) => e.children.length === 0 && (e.innerText || "").includes(kw),
+ );
+ const btns = Array.from(document.querySelectorAll("button,a")).filter(
+ (e) => e.offsetWidth && (e.innerText || "").trim() === "提交审核",
+ );
+ if (!btns.length) return null;
+ const my = marker ? marker.getBoundingClientRect().y : 0;
+ const chosen = btns
+ .map((b) => ({ b, y: b.getBoundingClientRect().y }))
+ .filter((o) => o.y > my - 40)
+ .sort((a, b) => a.y - b.y)[0];
+ const b = chosen ? chosen.b : btns[0];
+ b.scrollIntoView({ block: "center" });
+ const r = b.getBoundingClientRect();
+ return { x: r.x + r.width / 2, y: r.y + r.height / 2 };
+ }, keyword);
+
+let opened = false;
+for (let i = 0; i < 3 && !opened; i++) {
+ const p = await findBtn();
+ if (!p) break;
+ await page.mouse.click(p.x, p.y);
+ for (let w = 0; w < 12; w++) {
+ await page.waitForTimeout(1000);
+ if (/确认提交审核/.test(await bodyText())) {
+ opened = true;
+ break;
+ }
+ }
+}
+log("notice opened", opened);
+if (!opened) {
+ await ctx.close().catch(() => {});
+ process.exit(4);
+}
+
+for (const t of ["已仔细阅读", "已阅读并了解平台审核规则"]) {
+ const c = await page.evaluate((t) => {
+ const el = Array.from(document.querySelectorAll("label,span,div,p"))
+ .filter(
+ (e) => e.offsetWidth && (e.innerText || "").includes(t) && (e.innerText || "").length < 120,
+ )
+ .pop();
+ if (!el) return null;
+ const r = el.getBoundingClientRect();
+ return { x: r.x + 12, y: r.y + r.height / 2 };
+ }, t);
+ if (c) {
+ await page.mouse.click(c.x, c.y);
+ await page.waitForTimeout(700);
+ }
+}
+const clickText = async (txt) => {
+ const p = await page.evaluate((txt) => {
+ const e = Array.from(document.querySelectorAll("button,a,span,div,label"))
+ .filter((x) => x.offsetWidth && x.children.length === 0 && (x.innerText || "").trim() === txt)
+ .pop();
+ if (!e) return null;
+ e.scrollIntoView({ block: "center" });
+ const r = e.getBoundingClientRect();
+ return { x: r.x + r.width / 2, y: r.y + r.height / 2 };
+ }, txt);
+ if (!p) {
+ log("no btn", txt);
+ return false;
+ }
+ await page.mouse.click(p.x, p.y);
+ await page.waitForTimeout(4000);
+ return true;
+};
+await clickText("下一步");
+await clickText("继续提交");
+await page.waitForTimeout(12000);
+
+log("final url", page.url());
+log("--- privacy/submit responses ---");
+for (const b of bodies.slice(-20)) log(b);
+fs.writeFileSync(path.join(outDir, "privcheck.log"), bodies.join("\n\n"));
+await page.screenshot({ path: path.join(outDir, "privcheck.png"), fullPage: true }).catch(() => {});
+await ctx.close().catch(() => {});
+process.exit(0);
diff --git a/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/probe-switch3.mjs b/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/probe-switch3.mjs
new file mode 100644
index 00000000..14155ecb
--- /dev/null
+++ b/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/probe-switch3.mjs
@@ -0,0 +1,104 @@
+// 正确姿势点「切换账号」:先点开左下角账号面板,再点菜单项,观察结果
+import { launchStealth } from "./stealth.mjs";
+import fs from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+const here = path.dirname(fileURLToPath(import.meta.url));
+const out = process.argv[2] || "/tmp/probe-switch3.json";
+const shotPrefix = process.argv[3] || "/tmp/probe-switch3";
+const ctx = await launchStealth(path.join(here, "profile"), { headless: false });
+const page = ctx.pages()[0] || (await ctx.newPage());
+page.on("dialog", (d) => {
+ console.log("DIALOG", d.type(), d.message());
+ d.dismiss().catch(() => {});
+});
+page.on("framenavigated", (f) => {
+ if (f === page.mainFrame()) console.log("NAV", f.url());
+});
+await page.goto("https://mp.weixin.qq.com/", { waitUntil: "domcontentloaded", timeout: 60000 });
+await page.waitForTimeout(8000);
+
+const items = page.locator("li.account_box-panel-item");
+console.log(
+ "panel items",
+ await items.count(),
+ "visible0",
+ await items
+ .first()
+ .isVisible()
+ .catch(() => null),
+);
+await page
+ .click(".mp_account_box", { timeout: 5000 })
+ .catch((e) => console.log("open err", e.message.split("\n")[0]));
+await page.waitForTimeout(1500);
+console.log(
+ "visible after open",
+ await items
+ .first()
+ .isVisible()
+ .catch(() => null),
+);
+await page.screenshot({ path: `${shotPrefix}-a.png` }).catch(() => {});
+
+const target = page.locator("li.account_box-panel-item", { hasText: "切换账号" }).first();
+const box = await target.boundingBox().catch(() => null);
+console.log("box", JSON.stringify(box));
+if (box) await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);
+else
+ await target
+ .click({ timeout: 5000, force: true })
+ .catch((e) => console.log("click err", e.message.split("\n")[0]));
+await page.waitForTimeout(7000);
+console.log("url after", page.url());
+
+// 收集可能的 toast / 弹窗文字
+const info = await page.evaluate(() => {
+ const vis = (e) => !!(e.offsetWidth || e.offsetHeight);
+ const dialogs = [];
+ for (const e of document.querySelectorAll(
+ '[class*="dialog"],[class*="toast"],[class*="modal"],[class*="message_box"],[class*="weui-desktop-dialog"]',
+ )) {
+ if (!vis(e)) continue;
+ const t = (e.innerText || "").replace(/\s+/g, " ").trim();
+ if (t)
+ dialogs.push({
+ cls: (e.className || "").toString().slice(0, 100),
+ t: t.slice(0, 300),
+ html: e.outerHTML.slice(0, 500),
+ });
+ }
+ const qrs = Array.from(document.querySelectorAll("img"))
+ .filter(vis)
+ .map((i) => ({
+ src: (i.src || "").slice(0, 60),
+ w: i.naturalWidth,
+ h: i.naturalHeight,
+ cls: (i.className || "").toString().slice(0, 60),
+ }))
+ .filter((i) => i.w > 100 && i.h > 100);
+ const clickableTexts = [];
+ for (const e of document.querySelectorAll("a,li,div,section,button")) {
+ if (!vis(e)) continue;
+ const t = (e.innerText || "").replace(/\s+/g, " ").trim();
+ if (!t || t.length > 30) continue;
+ const cls = (e.className || "").toString();
+ if (/account|item|card|select|choose|login__type|dialog/i.test(cls))
+ clickableTexts.push({ tag: e.tagName, cls: cls.slice(0, 90), t });
+ }
+ return {
+ url: location.href,
+ text: (document.body.innerText || "").replace(/\n{2,}/g, "\n").slice(0, 900),
+ dialogs: dialogs.slice(0, 8),
+ qrs,
+ clickableTexts: clickableTexts.slice(0, 30),
+ };
+});
+await page.screenshot({ path: `${shotPrefix}-b.png` }).catch(() => {});
+fs.writeFileSync(out, JSON.stringify(info, null, 2));
+console.log("dialogs", JSON.stringify(info.dialogs.slice(0, 3)));
+console.log("qrs", JSON.stringify(info.qrs));
+console.log("clickable", JSON.stringify(info.clickableTexts.slice(0, 20)));
+console.log("text:", info.text.replace(/\n/g, " | ").slice(0, 600));
+await ctx.close();
diff --git a/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/reset-key2.mjs b/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/reset-key2.mjs
new file mode 100644
index 00000000..e92cdf17
--- /dev/null
+++ b/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/reset-key2.mjs
@@ -0,0 +1,259 @@
+// 重置「小程序代码上传密钥」:出管理员验证二维码 → 等用户扫码 → 等密钥下载落盘
+// 用法: node reset-key2.mjs <qrOutPrefix> <statusPath> <keyOutPath> [超时分钟]
+import { launchStealth } from "./stealth.mjs";
+import fs from "node:fs";
+import path from "node:path";
+import crypto from "node:crypto";
+import { fileURLToPath } from "node:url";
+import { PNG } from "pngjs";
+import jsQR from "jsqr";
+
+const here = path.dirname(fileURLToPath(import.meta.url));
+const qrPrefix = process.argv[2] || path.join(here, "key-qr.png");
+const statusPath = process.argv[3] || path.join(here, "reset-key-status.json");
+const keyOut = process.argv[4] || path.join(here, "mp-upload-key.key");
+const timeoutMin = Number(process.argv[5] || 12);
+const outDir = path.dirname(qrPrefix);
+const base = path.basename(qrPrefix).replace(/\.png$/, "");
+const write = (o) =>
+ fs.writeFileSync(statusPath, JSON.stringify({ at: new Date().toISOString(), ...o }, null, 2));
+const log = (...a) => console.log(new Date().toISOString(), ...a);
+
+function upscale3x(png) {
+ const s = 3;
+ const b = new PNG({ width: png.width * s, height: png.height * s });
+ for (let y = 0; y < b.height; y++)
+ for (let x = 0; x < b.width; x++) {
+ const si = (((y / s) | 0) * png.width + ((x / s) | 0)) << 2,
+ di = (y * b.width + x) << 2;
+ b.data[di] = png.data[si];
+ b.data[di + 1] = png.data[si + 1];
+ b.data[di + 2] = png.data[si + 2];
+ b.data[di + 3] = 255;
+ }
+ return b;
+}
+
+function deliverQr(pngBuf) {
+ const png = PNG.sync.read(pngBuf);
+ const big = upscale3x(png);
+ const buf = PNG.sync.write(big);
+ const dec = jsQR(new Uint8Array(big.data), big.width, big.height);
+ // 用「解码内容」做 hash:同一张码反复截图得到同一个文件名,不会把用户手上的文件删掉
+ const hash = crypto
+ .createHash("sha1")
+ .update(dec ? dec.data : buf)
+ .digest("hex")
+ .slice(0, 8);
+ const file = path.join(outDir, `${base}-${hash}.png`);
+ if (!fs.existsSync(file)) {
+ fs.writeFileSync(file, buf);
+ const re = new RegExp(`^${base}-[0-9a-f]{8}\\.png$`);
+ for (const f of fs.readdirSync(outDir))
+ if (re.test(f) && path.join(outDir, f) !== file) {
+ try {
+ fs.unlinkSync(path.join(outDir, f));
+ } catch {}
+ }
+ }
+ return {
+ file,
+ hash,
+ size: `${big.width}x${big.height}`,
+ decoded: dec ? dec.data.slice(0, 100) : null,
+ };
+}
+
+const ctx = await launchStealth(path.join(here, "profile"), { headless: false });
+const page = ctx.pages()[0] || (await ctx.newPage());
+let downloaded = null;
+page.on("download", async (d) => {
+ try {
+ await d.saveAs(keyOut);
+ downloaded = keyOut;
+ log("DOWNLOAD saved", keyOut, fs.statSync(keyOut).size);
+ write({ state: "KEY_DOWNLOADED", keyOut });
+ } catch (e) {
+ log("download err", e.message);
+ }
+});
+
+await page.goto("https://mp.weixin.qq.com/", { waitUntil: "domcontentloaded", timeout: 60000 });
+await page.waitForTimeout(10000);
+const token = (page.url().match(/token=(\d+)/) || [])[1];
+if (!token) {
+ write({ state: "NOT_LOGGED_IN" });
+ log("NOT LOGGED IN");
+ await ctx.close().catch(() => {});
+ process.exit(2);
+}
+await page.goto(`https://mp.weixin.qq.com/wxamp/devprofile/get_profile?token=${token}&lang=zh_CN`, {
+ waitUntil: "domcontentloaded",
+ timeout: 60000,
+});
+await page.waitForTimeout(9000);
+
+const clickReset = async () => {
+ const btn = await page.evaluate(() => {
+ const label = Array.from(document.querySelectorAll("*")).find(
+ (e) => e.children.length === 0 && (e.innerText || "").trim() === "小程序代码上传密钥",
+ );
+ let n = label;
+ for (let i = 0; i < 8 && n; i++) {
+ n = n.parentElement;
+ if (!n) break;
+ const c = Array.from(n.querySelectorAll("a,button,span,div")).filter(
+ (e) => e.children.length === 0 && (e.innerText || "").trim() === "重置",
+ );
+ if (c[0]) {
+ const r = c[0].getBoundingClientRect();
+ return { x: r.x + r.width / 2, y: r.y + r.height / 2 };
+ }
+ }
+ return null;
+ });
+ if (!btn) return false;
+ await page.mouse.click(btn.x, btn.y);
+ await page.waitForTimeout(4000);
+ return true;
+};
+
+const dlgText = () =>
+ page.evaluate(() => {
+ const ds = Array.from(document.querySelectorAll('[class*="dialog"],[class*="modal"]')).filter(
+ (e) => e.offsetWidth > 200 && e.offsetHeight > 150,
+ );
+ return ds
+ .map((e) => (e.innerText || "").replace(/\s+/g, " ").trim())
+ .filter(Boolean)
+ .join(" || ")
+ .slice(0, 400);
+ });
+
+if (!(await clickReset())) {
+ write({ state: "NO_RESET_BTN" });
+ log("no reset btn");
+ await ctx.close().catch(() => {});
+ process.exit(3);
+}
+
+const grabQr = async () => {
+ // 1) 可见 dialog 内的 img
+ const el = await page.evaluateHandle(() => {
+ const ds = Array.from(document.querySelectorAll('[class*="dialog"],[class*="modal"]')).filter(
+ (e) => e.offsetWidth > 200 && e.offsetHeight > 150,
+ );
+ for (const d of ds)
+ for (const img of d.querySelectorAll("img")) {
+ const r = img.getBoundingClientRect();
+ if (r.width > 120 && r.height > 120) return img;
+ }
+ for (const d of ds)
+ for (const cv of d.querySelectorAll("canvas")) {
+ const r = cv.getBoundingClientRect();
+ if (r.width > 120 && r.height > 120) return cv;
+ }
+ return null;
+ });
+ const node = el.asElement();
+ if (!node) return null;
+ const buf = await node.screenshot().catch(() => null);
+ if (!buf) return null;
+ return deliverQr(buf);
+};
+
+let lastText = "";
+let qrInfo = null;
+const deadline = Date.now() + timeoutMin * 60 * 1000;
+let lastQrAt = 0;
+
+while (Date.now() < deadline) {
+ if (downloaded) break;
+ const t = await dlgText();
+
+ if (t !== lastText) {
+ lastText = t;
+ log("dialog:", t);
+ if (/失效|过期|刷新|重新获取/.test(t)) {
+ log("QR expired -> refresh");
+ const r = await page
+ .evaluate(() => {
+ const ds = Array.from(
+ document.querySelectorAll('[class*="dialog"],[class*="modal"]'),
+ ).filter((e) => e.offsetWidth > 200);
+ for (const d of ds)
+ for (const e of d.querySelectorAll("a,button,span,div")) {
+ const tx = (e.innerText || "").trim();
+ if (e.children.length === 0 && /刷新|重新获取|点击刷新/.test(tx)) {
+ const r = e.getBoundingClientRect();
+ window.__qrRefresh = { x: r.x + r.width / 2, y: r.y + r.height / 2 };
+ return window.__qrRefresh;
+ }
+ }
+ return null;
+ })
+ .catch(() => null);
+ if (r) {
+ await page.mouse.click(r.x, r.y);
+ await page.waitForTimeout(3000);
+ }
+ qrInfo = null;
+ lastQrAt = 0;
+ }
+ }
+
+ if (!qrInfo || Date.now() - lastQrAt > 15000) {
+ const info = await grabQr();
+ if (info) {
+ const changed = !qrInfo || info.decoded !== qrInfo.decoded;
+ qrInfo = info;
+ lastQrAt = Date.now();
+ // 只有码真的换了才落盘并打印
+ if (changed) {
+ log(
+ "QR_READY",
+ path.basename(info.file),
+ info.size,
+ info.decoded ? "decoded-ok" : "UNREADABLE",
+ );
+ write({ state: "WAIT_SCAN", ...info, dialog: t });
+ }
+ }
+ }
+
+ // 扫码后:找下载按钮
+ const dl = await page
+ .evaluate(() => {
+ const ds = Array.from(document.querySelectorAll('[class*="dialog"],[class*="modal"]')).filter(
+ (e) => e.offsetWidth > 200 && e.offsetHeight > 150,
+ );
+ for (const d of ds)
+ for (const e of d.querySelectorAll("a,button,span,div")) {
+ const tx = (e.innerText || "").trim();
+ if (e.children.length === 0 && /^(下载|下载密钥|重新下载)$/.test(tx)) {
+ const r = e.getBoundingClientRect();
+ if (r.width > 0) return { x: r.x + r.width / 2, y: r.y + r.height / 2, t: tx };
+ }
+ }
+ return null;
+ })
+ .catch(() => null);
+ if (dl) {
+ log("click 下载", dl.t);
+ await page.mouse.click(dl.x, dl.y);
+ await page.waitForTimeout(5000);
+ }
+
+ await page.waitForTimeout(2500);
+}
+
+await page.screenshot({ path: path.join(outDir, `${base}-final.png`) }).catch(() => {});
+if (downloaded) {
+ log("DONE", keyOut);
+ write({ state: "DONE", keyOut });
+} else {
+ log("TIMEOUT");
+ write({ state: "TIMEOUT", url: page.url() });
+}
+await ctx.close().catch(() => {});
+process.exit(0);
diff --git a/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/stealth.mjs b/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/stealth.mjs
new file mode 100644
index 00000000..53229a58
--- /dev/null
+++ b/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/stealth.mjs
@@ -0,0 +1,92 @@
+// 反检测上下文:无头 Chromium 最常见的暴露点是 UA 里的 HeadlessChrome 与若干 navigator 特征
+import { chromium } from "playwright";
+import path from "node:path";
+
+const UA =
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36";
+
+export async function launchStealth(profileDir, { headless = true } = {}) {
+ const ctx = await chromium.launchPersistentContext(profileDir, {
+ headless,
+ userAgent: UA,
+ locale: "zh-CN",
+ timezoneId: "Asia/Shanghai",
+ viewport: { width: 1440, height: 900 },
+ deviceScaleFactor: 1,
+ args: ["--disable-blink-features=AutomationControlled", "--lang=zh-CN"],
+ });
+ await ctx.addInitScript(() => {
+ Object.defineProperty(navigator, "webdriver", { get: () => undefined });
+ Object.defineProperty(navigator, "languages", { get: () => ["zh-CN", "zh", "en"] });
+ Object.defineProperty(navigator, "plugins", {
+ get: () => [1, 2, 3].map((i) => ({ name: `Plugin ${i}` })),
+ });
+ window.chrome = window.chrome || { runtime: {} };
+ const patch = (proto) => {
+ if (!proto) return;
+ const orig = proto.getParameter;
+ proto.getParameter = function (p) {
+ if (p === 37445) return "Google Inc. (Intel)";
+ if (p === 37446)
+ return "ANGLE (Intel, Intel(R) UHD Graphics 630 Direct3D11 vs_5_0 ps_5_0, D3D11)";
+ return orig.call(this, p);
+ };
+ };
+ try {
+ patch(window.WebGLRenderingContext && window.WebGLRenderingContext.prototype);
+ } catch {}
+ try {
+ patch(window.WebGL2RenderingContext && window.WebGL2RenderingContext.prototype);
+ } catch {}
+ });
+ return ctx;
+}
+
+// 人类化拖动:加速—匀速—减速,带纵向抖动,末端微调后停顿再松手
+export async function dragSlider(
+ page,
+ {
+ handleSel = ".aliyunCaptcha-sliding-slider",
+ trackSel = ".aliyunCaptcha-sliding-text-box",
+ } = {},
+) {
+ const handle = page.locator(handleSel).first();
+ const track = page.locator(trackSel).first();
+ const hb = await handle.boundingBox();
+ const tb = await track.boundingBox();
+ if (!hb || !tb) return false;
+ const y = hb.y + hb.height / 2;
+ const sx = hb.x + hb.width / 2;
+ const ex = tb.x + tb.width - hb.width / 2;
+
+ await page.mouse.move(sx - 25 + Math.random() * 20, y + (Math.random() - 0.5) * 12);
+ await page.waitForTimeout(120 + Math.random() * 180);
+ await page.mouse.move(sx, y, { steps: 3 });
+ await page.waitForTimeout(90 + Math.random() * 120);
+ await page.mouse.down();
+ await page.waitForTimeout(150 + Math.random() * 200);
+
+ const dist = ex - sx;
+ const steps = 30 + Math.floor(Math.random() * 12);
+ let done = 0;
+ for (let i = 1; i <= steps; i++) {
+ const t = i / steps;
+ // 慢起—快中—慢收
+ const eased =
+ t < 0.2 ? (t / 0.2) ** 2 * 0.06 + t * 0.14 : t > 0.85 ? 1 - ((1 - t) / 0.15) * 0.05 : t;
+ const target = Math.min(1, eased) * dist;
+ const jitter = (Math.random() - 0.5) * 1.4;
+ done = target;
+ await page.mouse.move(sx + target, y + jitter);
+ await page.waitForTimeout(9 + Math.random() * 17);
+ if (Math.random() < 0.12) await page.waitForTimeout(40 + Math.random() * 90);
+ }
+ // 末端微调
+ await page.mouse.move(sx + dist + 3, y, { steps: 2 });
+ await page.waitForTimeout(90);
+ await page.mouse.move(sx + dist, y);
+ await page.waitForTimeout(180 + Math.random() * 150);
+ await page.mouse.up();
+ void done;
+ return true;
+}
diff --git a/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/submit-review4.mjs b/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/submit-review4.mjs
new file mode 100644
index 00000000..2ea2c36e
--- /dev/null
+++ b/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/submit-review4.mjs
@@ -0,0 +1,186 @@
+// 提交审核:须知 → 下一步 → 安全测试提醒「继续提交」→ dump 审核信息表单/结果
+import { launchStealth } from "./stealth.mjs";
+import fs from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+const here = path.dirname(fileURLToPath(import.meta.url));
+const outDir = process.argv[2] || here;
+const label = process.argv[3] || "submit4";
+const keyword = process.argv[4] || "待办清单";
+const stopAfter = process.argv[5] || ""; // 例如 'continue' 表示到「继续提交」为止不点
+const log = (...a) => console.log(new Date().toISOString(), ...a);
+
+const ctx = await launchStealth(path.join(here, "profile"), { headless: false });
+const page = ctx.pages()[0] || (await ctx.newPage());
+await page.goto("https://mp.weixin.qq.com/", { waitUntil: "domcontentloaded", timeout: 60000 });
+await page.waitForTimeout(10000);
+const token = (page.url().match(/token=(\d+)/) || [])[1];
+if (!token) {
+ log("NOT LOGGED IN");
+ await ctx.close().catch(() => {});
+ process.exit(2);
+}
+await page
+ .goto(`https://mp.weixin.qq.com/wxamp/wacodepage/getcodepage?token=${token}&lang=zh_CN`, {
+ waitUntil: "commit",
+ timeout: 60000,
+ })
+ .catch(() => {});
+await page.waitForTimeout(12000);
+
+const bodyText = () => page.evaluate(() => (document.body.innerText || "").replace(/\s+/g, " "));
+
+// 打开须知
+const findBtn = () =>
+ page.evaluate((kw) => {
+ const marker = Array.from(document.querySelectorAll("*")).find(
+ (e) => e.children.length === 0 && (e.innerText || "").includes(kw),
+ );
+ const btns = Array.from(document.querySelectorAll("button,a")).filter(
+ (e) => e.offsetWidth && (e.innerText || "").trim() === "提交审核",
+ );
+ if (!btns.length) return null;
+ const my = marker ? marker.getBoundingClientRect().y : 0;
+ const chosen = btns
+ .map((b) => ({ b, y: b.getBoundingClientRect().y }))
+ .filter((o) => o.y > my - 40)
+ .sort((a, b) => a.y - b.y)[0];
+ const b = chosen ? chosen.b : btns[0];
+ b.scrollIntoView({ block: "center" });
+ const r = b.getBoundingClientRect();
+ return { x: r.x + r.width / 2, y: r.y + r.height / 2 };
+ }, keyword);
+
+let opened = false;
+for (let i = 0; i < 3 && !opened; i++) {
+ const p = await findBtn();
+ if (!p) break;
+ await page.mouse.click(p.x, p.y);
+ for (let w = 0; w < 12; w++) {
+ await page.waitForTimeout(1000);
+ if (/确认提交审核/.test(await bodyText())) {
+ opened = true;
+ break;
+ }
+ }
+}
+if (!opened) {
+ log("FAILED TO OPEN");
+ await ctx.close().catch(() => {});
+ process.exit(4);
+}
+log("notice opened");
+
+// 勾选两个确认项
+for (const t of ["已仔细阅读", "已阅读并了解平台审核规则"]) {
+ const c = await page.evaluate((t) => {
+ const el = Array.from(document.querySelectorAll("label,span,div,p"))
+ .filter(
+ (e) => e.offsetWidth && (e.innerText || "").includes(t) && (e.innerText || "").length < 120,
+ )
+ .pop();
+ if (!el) return null;
+ const r = el.getBoundingClientRect();
+ return { x: r.x + 12, y: r.y + r.height / 2 };
+ }, t);
+ if (c) {
+ await page.mouse.click(c.x, c.y);
+ await page.waitForTimeout(700);
+ }
+}
+log(
+ "checked",
+ JSON.stringify(
+ await page.evaluate(() =>
+ Array.from(document.querySelectorAll("input[type=checkbox]"))
+ .filter((c) => c.offsetParent)
+ .map((c) => c.checked),
+ ),
+ ),
+);
+
+const clickText = async (txt) => {
+ const p = await page.evaluate((txt) => {
+ const e = Array.from(document.querySelectorAll("button,a,span,div,label"))
+ .filter((x) => x.offsetWidth && x.children.length === 0 && (x.innerText || "").trim() === txt)
+ .pop();
+ if (!e) return null;
+ e.scrollIntoView({ block: "center" });
+ const r = e.getBoundingClientRect();
+ return { x: r.x + r.width / 2, y: r.y + r.height / 2 };
+ }, txt);
+ if (!p) {
+ log("no btn", txt);
+ return false;
+ }
+ await page.mouse.click(p.x, p.y);
+ await page.waitForTimeout(4000);
+ log("clicked", txt);
+ return true;
+};
+
+await clickText("下一步");
+log("after 下一步:", (await bodyText()).slice(-260));
+await page.screenshot({ path: path.join(outDir, `miniapp-${label}-safety.png`) }).catch(() => {});
+
+if (stopAfter !== "continue") {
+ await clickText("继续提交");
+ // 抓一下提交后的即时提示(toast 很快就消失)
+ for (let i = 0; i < 16; i++) {
+ const tip = await page
+ .evaluate(() => {
+ const out = [];
+ for (const e of document.querySelectorAll(
+ '[class*="toast"],[class*="tip"],[class*="message"],[class*="dialog"],[class*="warn"],[class*="error"]',
+ )) {
+ if (!e.offsetWidth) continue;
+ const t = (e.innerText || "").replace(/\s+/g, " ").trim();
+ if (t) out.push(t.slice(0, 200));
+ }
+ return [...new Set(out)];
+ })
+ .catch(() => []);
+ if (tip.length) log("tip@" + i, JSON.stringify(tip));
+ await page.waitForTimeout(500);
+ }
+ await page.waitForTimeout(4000);
+ log("after 继续提交 url:", page.url());
+ log("after 继续提交 text:", (await bodyText()).slice(0, 1800));
+ await page
+ .screenshot({ path: path.join(outDir, `miniapp-${label}-after.png`), fullPage: true })
+ .catch(() => {});
+}
+
+const info = await page.evaluate(() => {
+ const vis = (e) => !!(e.offsetWidth || e.offsetHeight);
+ const btns = [
+ ...new Set(
+ Array.from(document.querySelectorAll('button,a,[role="button"],label'))
+ .filter(vis)
+ .map((e) => (e.innerText || "").replace(/\s+/g, " ").trim().slice(0, 30))
+ .filter((t) => t && t.length <= 30),
+ ),
+ ];
+ const inputs = Array.from(document.querySelectorAll("input,textarea"))
+ .filter(vis)
+ .map((e) => ({
+ tag: e.tagName,
+ type: e.type || "",
+ ph: e.placeholder || "",
+ val: (e.value || "").slice(0, 30),
+ }));
+ return {
+ url: location.href,
+ text: (document.body.innerText || "").replace(/\s+/g, " ").slice(0, 3000),
+ btns,
+ inputs,
+ };
+});
+fs.writeFileSync(path.join(outDir, `miniapp-${label}-state.json`), JSON.stringify(info, null, 2));
+log("STATE URL", info.url);
+log("STATE TEXT:", info.text.slice(0, 1500));
+log("STATE BTNS:", JSON.stringify(info.btns.slice(0, 50)));
+log("STATE INPUTS:", JSON.stringify(info.inputs.slice(0, 25)));
+await ctx.close().catch(() => {});
+process.exit(0);
diff --git a/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/to-miniapp.mjs b/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/to-miniapp.mjs
new file mode 100644
index 00000000..bb85360e
--- /dev/null
+++ b/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/to-miniapp.mjs
@@ -0,0 +1,136 @@
+// 从公众号后台切到指定小程序后台,并 dump 落地页(URL/标题/AppID/侧边菜单/链接)
+// 用法: node to-miniapp.mjs "lmliheng" <out.json> <shot.png>
+import { launchStealth } from "./stealth.mjs";
+import fs from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+const here = path.dirname(fileURLToPath(import.meta.url));
+const keyword = process.argv[2] || "lmliheng";
+const out = process.argv[3] || "/tmp/to-miniapp.json";
+const shot = process.argv[4] || "/tmp/to-miniapp.png";
+
+const ctx = await launchStealth(path.join(here, "profile"), { headless: false });
+let page = ctx.pages()[0] || (await ctx.newPage());
+page.on("framenavigated", (f) => {
+ if (f === page.mainFrame()) console.log("NAV", f.url());
+});
+ctx.on("page", (p) => {
+ console.log("NEW PAGE", p.url());
+});
+
+await page.goto("https://mp.weixin.qq.com/", { waitUntil: "domcontentloaded", timeout: 60000 });
+await page.waitForTimeout(8000);
+console.log("start url", page.url());
+
+// 如果已经是小程序后台,直接 dump
+const isMini = /\/wxamp\//.test(page.url());
+if (!isMini) {
+ await page
+ .click(".mp_account_box", { timeout: 8000 })
+ .catch((e) => console.log("open err", e.message.split("\n")[0]));
+ await page.waitForTimeout(1500);
+ const target = page.locator("li.account_box-panel-item", { hasText: "切换账号" }).first();
+ const box = await target.boundingBox().catch(() => null);
+ if (box) await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);
+ else
+ await target
+ .click({ timeout: 5000, force: true })
+ .catch((e) => console.log("click1 err", e.message.split("\n")[0]));
+ await page.waitForTimeout(4000);
+
+ // 弹窗结构 dump(便于排错)
+ const dlg = await page.evaluate(() => {
+ const d = document.querySelector(".switch-account-dialog");
+ if (!d) return null;
+ return Array.from(d.querySelectorAll("*"))
+ .filter((e) => e.children.length === 0 && (e.innerText || "").trim())
+ .map((e) => ({
+ cls: (e.className || "").toString().slice(0, 80),
+ t: (e.innerText || "").trim().slice(0, 30),
+ parentCls: (e.parentElement.className || "").toString().slice(0, 80),
+ }));
+ });
+ console.log("dialog leaves", JSON.stringify(dlg));
+
+ // 弹窗内的小程序行:找精确文本的最小节点,点它的矩形中心
+ const row = page.getByText(keyword, { exact: true }).first();
+ let rb = await row.boundingBox().catch(() => null);
+ if (!rb) {
+ // 退一步:点该文本所在的可点击祖先
+ rb = await page
+ .evaluate((kw) => {
+ const els = Array.from(document.querySelectorAll(".switch-account-dialog *")).filter(
+ (e) => (e.innerText || "").trim() === kw,
+ );
+ if (!els[0]) return null;
+ let n = els[0];
+ for (
+ let i = 0;
+ i < 4 && n.parentElement && n.parentElement.closest(".switch-account-dialog");
+ i++
+ )
+ n = n.parentElement;
+ const r = n.getBoundingClientRect();
+ return { x: r.x, y: r.y, width: r.width, height: r.height };
+ }, keyword)
+ .catch(() => null);
+ }
+ console.log("row box", JSON.stringify(rb));
+ if (rb) await page.mouse.click(rb.x + Math.min(60, rb.width / 2), rb.y + rb.height / 2);
+ else
+ await row
+ .click({ timeout: 5000, force: true })
+ .catch((e) => console.log("click2 err", e.message.split("\n")[0]));
+ await page.waitForTimeout(10000);
+ // 可能开了新标签页
+ const pages = ctx.pages();
+ console.log("pages now", JSON.stringify(pages.map((p) => p.url())));
+ const mini = pages.find((p) => /\/wxamp\//.test(p.url()));
+ if (mini) {
+ await mini.bringToFront().catch(() => {});
+ page = mini;
+ }
+ console.log("after switch url", page.url());
+ const afterText = await page
+ .evaluate(() => (document.body.innerText || "").replace(/\s+/g, " ").slice(0, 600))
+ .catch(() => "");
+ console.log("after switch text:", afterText);
+ await page.screenshot({ path: shot.replace(/\.png$/, "-after-switch.png") }).catch(() => {});
+}
+
+const info = await page.evaluate(() => {
+ const vis = (e) => !!(e.offsetWidth || e.offsetHeight);
+ const all = document.body.innerText || "";
+ const appids = [...new Set(all.match(/wx[0-9a-f]{16}/g) || [])];
+ const links = Array.from(document.querySelectorAll("a[href]"))
+ .filter(vis)
+ .map((a) => ({ t: (a.innerText || "").trim().slice(0, 16), href: a.getAttribute("href") }))
+ .filter((l) => l.href && l.href !== "javascript:;");
+ const menu = Array.from(
+ document.querySelectorAll(
+ '.weui-desktop-menu__item, .weui-desktop-sub-menu__item, [class*="menu__item"]',
+ ),
+ )
+ .filter(vis)
+ .map((e) => (e.innerText || "").replace(/\s+/g, " ").trim())
+ .filter(Boolean);
+ return {
+ url: location.href,
+ title: document.title,
+ appids,
+ links: links.slice(0, 80),
+ menu,
+ text: all.replace(/\s+/g, " ").slice(0, 1500),
+ };
+});
+await page.screenshot({ path: shot, fullPage: false }).catch(() => {});
+fs.writeFileSync(out, JSON.stringify(info, null, 2));
+console.log("URL", info.url);
+console.log("TITLE", info.title);
+console.log("APPIDS", JSON.stringify(info.appids));
+console.log("MENU", JSON.stringify(info.menu.slice(0, 40)));
+console.log("LINKS", JSON.stringify(info.links.slice(0, 40)));
+console.log("TEXT", info.text.slice(0, 800));
+await ctx.close().catch(() => {});
+process.exit(0);
diff --git a/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/withdraw2.mjs b/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/withdraw2.mjs
new file mode 100644
index 00000000..3125e3fe
--- /dev/null
+++ b/plugins/wechat-miniprogram/skills/wechat-miniprogram/scripts/withdraw2.mjs
@@ -0,0 +1,229 @@
+// 删除(撤回)审核版本:出管理员验证二维码 → 等扫码 → 完成删除 → 复核
+// 用法: node withdraw2.mjs <qrPrefix> <statusPath> [超时分钟]
+import { launchStealth } from "./stealth.mjs";
+import fs from "node:fs";
+import path from "node:path";
+import crypto from "node:crypto";
+import { fileURLToPath } from "node:url";
+import { PNG } from "pngjs";
+import jsQR from "jsqr";
+
+const here = path.dirname(fileURLToPath(import.meta.url));
+const qrPrefix = process.argv[2] || path.join(here, "del-qr.png");
+const statusPath = process.argv[3] || path.join(here, "withdraw-status.json");
+const timeoutMin = Number(process.argv[4] || 20);
+const outDir = path.dirname(qrPrefix);
+const base = path.basename(qrPrefix).replace(/\.png$/, "");
+const write = (o) =>
+ fs.writeFileSync(statusPath, JSON.stringify({ at: new Date().toISOString(), ...o }, null, 2));
+const log = (...a) => console.log(new Date().toISOString(), ...a);
+
+function upscale3x(png) {
+ const s = 3,
+ b = new PNG({ width: png.width * s, height: png.height * s });
+ for (let y = 0; y < b.height; y++)
+ for (let x = 0; x < b.width; x++) {
+ const si = (((y / s) | 0) * png.width + ((x / s) | 0)) << 2,
+ di = (y * b.width + x) << 2;
+ b.data[di] = png.data[si];
+ b.data[di + 1] = png.data[si + 1];
+ b.data[di + 2] = png.data[si + 2];
+ b.data[di + 3] = 255;
+ }
+ return b;
+}
+function deliverQr(pngBuf) {
+ const png = PNG.sync.read(pngBuf);
+ const big = upscale3x(png);
+ const dec = jsQR(new Uint8Array(big.data), big.width, big.height);
+ const hash = crypto
+ .createHash("sha1")
+ .update(dec ? dec.data : PNG.sync.write(big))
+ .digest("hex")
+ .slice(0, 8);
+ const file = path.join(outDir, `${base}-${hash}.png`);
+ if (!fs.existsSync(file)) {
+ fs.writeFileSync(file, PNG.sync.write(big));
+ const re = new RegExp(`^${base}-[0-9a-f]{8}\\.png$`);
+ for (const f of fs.readdirSync(outDir))
+ if (re.test(f) && path.join(outDir, f) !== file) {
+ try {
+ fs.unlinkSync(path.join(outDir, f));
+ } catch {}
+ }
+ }
+ return {
+ file,
+ hash,
+ size: `${big.width}x${big.height}`,
+ decoded: dec ? dec.data.slice(0, 100) : null,
+ };
+}
+
+const ctx = await launchStealth(path.join(here, "profile"), { headless: false });
+const page = ctx.pages()[0] || (await ctx.newPage());
+await page.goto("https://mp.weixin.qq.com/", { waitUntil: "domcontentloaded", timeout: 60000 });
+await page.waitForTimeout(10000);
+const token = (page.url().match(/token=(\d+)/) || [])[1];
+if (!token) {
+ write({ state: "NOT_LOGGED_IN" });
+ log("NOT LOGGED IN");
+ await ctx.close().catch(() => {});
+ process.exit(2);
+}
+await page
+ .goto(`https://mp.weixin.qq.com/wxamp/wacodepage/getcodepage?token=${token}&lang=zh_CN`, {
+ waitUntil: "commit",
+ timeout: 60000,
+ })
+ .catch(() => {});
+await page.waitForTimeout(12000);
+
+const dlgText = () =>
+ page.evaluate(() => {
+ const ds = Array.from(document.querySelectorAll('[class*="dialog"],[class*="modal"]')).filter(
+ (e) => e.offsetWidth > 200 && e.offsetHeight > 120,
+ );
+ return ds
+ .map((e) => (e.innerText || "").replace(/\s+/g, " ").trim())
+ .filter(Boolean)
+ .join(" || ")
+ .slice(0, 400);
+ });
+const pageText = () => page.evaluate(() => (document.body.innerText || "").replace(/\s+/g, " "));
+
+const p = await page.evaluate(() => {
+ const btn = Array.from(document.querySelectorAll("button,a")).filter(
+ (e) => e.offsetWidth && (e.innerText || "").trim() === "删除",
+ )[0];
+ if (!btn) return null;
+ btn.scrollIntoView({ block: "center" });
+ const r = btn.getBoundingClientRect();
+ return { x: r.x + r.width / 2, y: r.y + r.height / 2 };
+});
+if (!p) {
+ write({ state: "NO_DELETE_BTN" });
+ log("NO_DELETE_BTN");
+ await ctx.close().catch(() => {});
+ process.exit(3);
+}
+await page.mouse.click(p.x, p.y);
+await page.waitForTimeout(4000);
+
+const grabQr = async () => {
+ const el = await page.evaluateHandle(() => {
+ const ds = Array.from(document.querySelectorAll('[class*="dialog"],[class*="modal"]')).filter(
+ (e) => e.offsetWidth > 200 && e.offsetHeight > 120,
+ );
+ for (const d of ds)
+ for (const img of d.querySelectorAll("img")) {
+ const r = img.getBoundingClientRect();
+ if (r.width > 120) return img;
+ }
+ for (const d of ds)
+ for (const cv of d.querySelectorAll("canvas")) {
+ const r = cv.getBoundingClientRect();
+ if (r.width > 120) return cv;
+ }
+ return null;
+ });
+ const node = el.asElement();
+ if (!node) return null;
+ const buf = await node.screenshot().catch(() => null);
+ return buf ? deliverQr(buf) : null;
+};
+
+let t = await dlgText();
+log("dialog:", t);
+write({ state: "DIALOG", dialog: t });
+let qrInfo = null,
+ lastQrAt = 0,
+ done = false;
+const deadline = Date.now() + timeoutMin * 60 * 1000;
+
+while (Date.now() < deadline) {
+ t = await dlgText();
+ if (!/请使用微信扫描二维码进行验证|请在手机上进行确认/.test(t)) {
+ done = true;
+ break;
+ }
+ if (/失效|过期|刷新|重新获取/.test(t)) {
+ const r = await page
+ .evaluate(() => {
+ const ds = Array.from(
+ document.querySelectorAll('[class*="dialog"],[class*="modal"]'),
+ ).filter((e) => e.offsetWidth > 200);
+ for (const d of ds)
+ for (const e of d.querySelectorAll("a,button,span,div")) {
+ if (e.children.length === 0 && /刷新|重新获取/.test((e.innerText || "").trim())) {
+ const r = e.getBoundingClientRect();
+ return { x: r.x + r.width / 2, y: r.y + r.height / 2 };
+ }
+ }
+ return null;
+ })
+ .catch(() => null);
+ if (r) {
+ await page.mouse.click(r.x, r.y);
+ await page.waitForTimeout(3000);
+ }
+ qrInfo = null;
+ lastQrAt = 0;
+ }
+ if (!qrInfo || Date.now() - lastQrAt > 15000) {
+ const info = await grabQr();
+ if (info) {
+ const changed = !qrInfo || info.decoded !== qrInfo.decoded;
+ qrInfo = info;
+ lastQrAt = Date.now();
+ if (changed) {
+ log(
+ "QR_READY",
+ path.basename(info.file),
+ info.size,
+ info.decoded ? "decoded-ok" : "UNREADABLE",
+ );
+ write({ state: "WAIT_SCAN", ...info, dialog: t });
+ }
+ }
+ }
+ await page.waitForTimeout(2000);
+}
+
+if (!done) {
+ write({ state: "TIMEOUT" });
+ log("TIMEOUT");
+ await ctx.close().catch(() => {});
+ process.exit(4);
+}
+log("verified, dialog now:", t);
+await page.waitForTimeout(4000);
+
+const c = await page.evaluate(() => {
+ const e = Array.from(document.querySelectorAll("button,a,span,div"))
+ .filter(
+ (x) =>
+ x.offsetWidth &&
+ x.children.length === 0 &&
+ /^(确定|确认|删除)$/.test((x.innerText || "").trim()),
+ )
+ .pop();
+ if (!e) return null;
+ const r = e.getBoundingClientRect();
+ return { x: r.x + r.width / 2, y: r.y + r.height / 2, t: (e.innerText || "").trim() };
+});
+log("confirm:", JSON.stringify(c));
+if (c) {
+ await page.mouse.click(c.x, c.y);
+ await page.waitForTimeout(7000);
+}
+await page.screenshot({ path: path.join(outDir, `${base}-done.png`) }).catch(() => {});
+const after = await pageText();
+log("after:", after.slice(0, 700));
+write({
+ state: "DONE",
+ hasReviewVersion: /审核版本\s*版本号/.test(after),
+ after: after.slice(0, 600),
+});
+await ctx.close().catch(() => {});
+process.exit(0);
diff --git a/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/README.md b/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/README.md
new file mode 100644
index 00000000..991391e2
--- /dev/null
+++ b/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/README.md
@@ -0,0 +1,46 @@
+# 待办清单小程序(todo-miniprogram)
+
+一个纯离线、零后端、零第三方依赖的微信小程序:记待办、勾选完成、删除、按「全部 / 未完成 / 已完成」筛选,数据存在本机 `wx.setStorageSync`。
+
+- AppID:先在 `project.config.json` 里填自己的 AppID(本模板留作占位符 `wxTEMPLATE_PLACEHOLDER`)
+
+## 目录
+
+| 路径 | 作用 |
+| --- | --- |
+| `app.json` / `app.js` / `app.wxss` | 全局配置、启动逻辑、全局样式 |
+| `pages/index/` | 首页:新增、勾选、删除、筛选、清空已完成 |
+| `pages/about/` | 关于页 |
+| `project.config.json` | 项目配置(AppID、编译设置、打包忽略) |
+| `sitemap.json` | 搜索索引配置 |
+| `upload.js` | 用 miniprogram-ci 上传代码,生成开发版 |
+| `preview.js` | 用 miniprogram-ci 生成体验版二维码 |
+| `tools/validate.js` | 本地静态校验(结构 / JSON / JS 语法 / WXML 插值) |
+| `tools/test-page.js` | 无头逻辑测试(打桩 `wx` / `Page`,跑页面的增删改查) |
+
+## 本地校验
+
+```bash
+npm install
+npm run validate # 结构与语法校验
+node tools/test-page.js # 页面逻辑单测
+```
+
+## 上传(Linux 命令行,无需微信开发者工具)
+
+1. 在 mp.weixin.qq.com → 管理 → 开发管理 → 开发设置 → 小程序代码上传,生成上传密钥,下载 `private.<appid>.key`。
+2. 运行:
+
+```bash
+MP_APPID=wx你的AppID MP_KEY_PATH=/path/to/private.<appid>.key MP_VERSION=1.0.0 node upload.js
+```
+
+上传成功后,到小程序后台「管理 → 版本管理」把该开发版设为体验版或提交审核。
+
+体验版二维码:
+
+```bash
+MP_APPID=wx你的AppID MP_KEY_PATH=/path/to/private.<appid>.key node preview.js
+```
+
+> 密钥文件只放服务器或本机,不要提交进仓库、不要贴到聊天里。
diff --git a/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/app.js b/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/app.js
new file mode 100644
index 00000000..2532ba54
--- /dev/null
+++ b/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/app.js
@@ -0,0 +1,14 @@
+App({
+ globalData: {
+ version: "1.0.0",
+ },
+
+ onLaunch() {
+ // 记录一次启动时间,用于「关于」页展示
+ try {
+ wx.setStorageSync("app:lastLaunch", Date.now());
+ } catch (e) {
+ // 存储不可用时忽略
+ }
+ },
+});
diff --git a/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/app.json b/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/app.json
new file mode 100644
index 00000000..86d4bb14
--- /dev/null
+++ b/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/app.json
@@ -0,0 +1,12 @@
+{
+ "pages": ["pages/index/index", "pages/about/about"],
+ "window": {
+ "backgroundTextStyle": "light",
+ "navigationBarBackgroundColor": "#ffffff",
+ "navigationBarTitleText": "待办清单",
+ "navigationBarTextStyle": "black",
+ "backgroundColor": "#f6f7f8"
+ },
+ "style": "v2",
+ "sitemapLocation": "sitemap.json"
+}
diff --git a/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/app.wxss b/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/app.wxss
new file mode 100644
index 00000000..51c01357
--- /dev/null
+++ b/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/app.wxss
@@ -0,0 +1,13 @@
+page {
+ background: #f6f7f8;
+ color: #1a1b1c;
+ font-size: 30rpx;
+ line-height: 1.5;
+ font-family: -apple-system, "PingFang SC", "Helvetica Neue", sans-serif;
+}
+
+.page {
+ min-height: 100vh;
+ padding: 24rpx 24rpx 48rpx;
+ box-sizing: border-box;
+}
diff --git a/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/package.json b/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/package.json
new file mode 100644
index 00000000..047d35a8
--- /dev/null
+++ b/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/package.json
@@ -0,0 +1,14 @@
+{
+ "name": "todo-miniprogram",
+ "version": "1.0.0",
+ "private": true,
+ "description": "简单待办清单小程序(微信)",
+ "scripts": {
+ "validate": "node tools/validate.js",
+ "upload": "node upload.js",
+ "preview": "node preview.js"
+ },
+ "devDependencies": {
+ "miniprogram-ci": "^2.1.31"
+ }
+}
diff --git a/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/pages/about/about.js b/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/pages/about/about.js
new file mode 100644
index 00000000..974a9a8f
--- /dev/null
+++ b/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/pages/about/about.js
@@ -0,0 +1,33 @@
+const app = getApp();
+
+Page({
+ data: {
+ version: "1.0.0",
+ lastLaunch: "",
+ },
+
+ onLoad() {
+ let last = "";
+ try {
+ const ts = wx.getStorageSync("app:lastLaunch");
+ if (ts) {
+ const d = new Date(ts);
+ const pad = (n) => (n < 10 ? `0${n}` : `${n}`);
+ last = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
+ }
+ } catch (e) {
+ last = "";
+ }
+ this.setData({
+ version: (app && app.globalData && app.globalData.version) || "1.0.0",
+ lastLaunch: last,
+ });
+ },
+
+ copyLink() {
+ wx.setClipboardData({
+ data: "https://github.com/",
+ success: () => wx.showToast({ title: "已复制", icon: "none" }),
+ });
+ },
+});
diff --git a/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/pages/about/about.json b/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/pages/about/about.json
new file mode 100644
index 00000000..24dac3ee
--- /dev/null
+++ b/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/pages/about/about.json
@@ -0,0 +1,4 @@
+{
+ "navigationBarTitleText": "关于",
+ "usingComponents": {}
+}
diff --git a/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/pages/about/about.wxml b/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/pages/about/about.wxml
new file mode 100644
index 00000000..a1ce8d3c
--- /dev/null
+++ b/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/pages/about/about.wxml
@@ -0,0 +1,24 @@
+<view class="page">
+ <view class="card">
+ <view class="card__title">待办清单</view>
+ <view class="card__desc">一个离线可用的极简待办小程序,数据只存在你的手机里(wx.setStorage),不联网、不上传。</view>
+ </view>
+
+ <view class="card">
+ <view class="row">
+ <text class="row__k">版本</text>
+ <text class="row__v">{{version}}</text>
+ </view>
+ <view class="row">
+ <text class="row__k">上次启动</text>
+ <text class="row__v">{{lastLaunch || '—'}}</text>
+ </view>
+ </view>
+
+ <view class="tips">
+ <view class="tips__title">怎么用</view>
+ <view class="tips__item">· 顶部输入框写内容,回车或点「添加」</view>
+ <view class="tips__item">· 点条目或左侧圆圈切换完成状态</view>
+ <view class="tips__item">· 右侧「删除」删单条,「清空已完成」批量清理</view>
+ </view>
+</view>
diff --git a/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/pages/about/about.wxss b/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/pages/about/about.wxss
new file mode 100644
index 00000000..7c8e393c
--- /dev/null
+++ b/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/pages/about/about.wxss
@@ -0,0 +1,49 @@
+.card {
+ background: #ffffff;
+ border-radius: 20rpx;
+ padding: 32rpx 28rpx;
+ margin-bottom: 24rpx;
+ box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
+}
+
+.card__title {
+ font-size: 36rpx;
+ font-weight: 600;
+}
+
+.card__desc {
+ margin-top: 14rpx;
+ font-size: 27rpx;
+ color: #7e8081;
+}
+
+.row {
+ display: flex;
+ justify-content: space-between;
+ padding: 14rpx 0;
+}
+
+.row__k {
+ color: #7e8081;
+ font-size: 28rpx;
+}
+
+.row__v {
+ font-size: 28rpx;
+}
+
+.tips {
+ padding: 0 8rpx;
+}
+
+.tips__title {
+ font-size: 28rpx;
+ font-weight: 600;
+ margin-bottom: 12rpx;
+}
+
+.tips__item {
+ font-size: 27rpx;
+ color: #7e8081;
+ line-height: 1.9;
+}
diff --git a/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/pages/index/index.js b/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/pages/index/index.js
new file mode 100644
index 00000000..f67fb8db
--- /dev/null
+++ b/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/pages/index/index.js
@@ -0,0 +1,145 @@
+const STORAGE_KEY = "todos:v1";
+
+// 同一毫秒内可能连续添加多条,单用时间戳会撞 id,这里加随机后缀保证唯一
+function makeId() {
+ return `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
+}
+
+function formatTime(ts) {
+ const d = new Date(ts);
+ const pad = (n) => (n < 10 ? `0${n}` : `${n}`);
+ const now = new Date();
+ const sameDay = d.toDateString() === now.toDateString();
+ if (sameDay) return `今天 ${pad(d.getHours())}:${pad(d.getMinutes())}`;
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
+}
+
+Page({
+ data: {
+ todos: [],
+ visible: [],
+ input: "",
+ filter: "all", // all | active | done
+ counts: { total: 0, active: 0, done: 0 },
+ },
+
+ onLoad() {
+ this.load();
+ },
+
+ // ---------- 数据 ----------
+ load() {
+ let todos = [];
+ try {
+ todos = wx.getStorageSync(STORAGE_KEY) || [];
+ } catch (e) {
+ todos = [];
+ }
+ if (!Array.isArray(todos)) todos = [];
+ todos = todos.map((t) => ({ ...t, timeText: formatTime(t.createdAt || Date.now()) }));
+ this.commit(todos);
+ },
+
+ persist(todos) {
+ try {
+ wx.setStorageSync(
+ STORAGE_KEY,
+ todos.map(({ timeText, ...rest }) => rest),
+ );
+ } catch (e) {
+ wx.showToast({ title: "保存失败", icon: "none" });
+ }
+ },
+
+ // 统一出口:落盘 + 计数 + 按筛选条件生成可见列表
+ commit(todos) {
+ const done = todos.filter((t) => t.done).length;
+ const total = todos.length;
+ const { filter } = this.data;
+ const visible = todos.filter((t) => {
+ if (filter === "active") return !t.done;
+ if (filter === "done") return t.done;
+ return true;
+ });
+ this.setData({
+ todos,
+ visible,
+ counts: { total, done, active: total - done },
+ });
+ this.persist(todos);
+ },
+
+ // ---------- 交互 ----------
+ onInput(e) {
+ this.setData({ input: e.detail.value });
+ },
+
+ addTodo() {
+ const text = (this.data.input || "").trim();
+ if (!text) {
+ wx.showToast({ title: "先写点内容", icon: "none" });
+ return;
+ }
+ const now = Date.now();
+ const todos = [
+ { id: makeId(), text, done: false, createdAt: now, timeText: formatTime(now) },
+ ...this.data.todos,
+ ];
+ this.setData({ input: "" });
+ this.commit(todos);
+ wx.vibrateShort({ type: "light" });
+ },
+
+ toggleTodo(e) {
+ const id = e.currentTarget.dataset.id;
+ const todos = this.data.todos.map((t) => (t.id === id ? { ...t, done: !t.done } : t));
+ if (this.data.filter !== "all") {
+ // 在筛选视图里切换状态时,让列表立刻反映当前筛选
+ this.commit(todos);
+ return;
+ }
+ this.commit(todos);
+ },
+
+ removeTodo(e) {
+ const id = e.currentTarget.dataset.id;
+ const target = this.data.todos.find((t) => t.id === id);
+ wx.showModal({
+ title: "删除这条待办?",
+ content: target ? target.text.slice(0, 40) : "",
+ confirmText: "删除",
+ confirmColor: "#fa5151",
+ success: (res) => {
+ if (!res.confirm) return;
+ this.commit(this.data.todos.filter((t) => t.id !== id));
+ },
+ });
+ },
+
+ clearDone() {
+ const done = this.data.counts.done;
+ if (!done) {
+ wx.showToast({ title: "没有已完成的", icon: "none" });
+ return;
+ }
+ wx.showModal({
+ title: `清空 ${done} 条已完成?`,
+ content: "清空后无法恢复",
+ confirmText: "清空",
+ confirmColor: "#fa5151",
+ success: (res) => {
+ if (!res.confirm) return;
+ this.commit(this.data.todos.filter((t) => !t.done));
+ },
+ });
+ },
+
+ setFilter(e) {
+ const filter = e.currentTarget.dataset.filter;
+ this.setData({ filter }, () => this.commit(this.data.todos));
+ },
+
+ goAbout() {
+ wx.navigateTo({ url: "/pages/about/about" });
+ },
+});
diff --git a/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/pages/index/index.json b/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/pages/index/index.json
new file mode 100644
index 00000000..98a8e682
--- /dev/null
+++ b/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/pages/index/index.json
@@ -0,0 +1,4 @@
+{
+ "navigationBarTitleText": "待办清单",
+ "usingComponents": {}
+}
diff --git a/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/pages/index/index.wxml b/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/pages/index/index.wxml
new file mode 100644
index 00000000..20383d5d
--- /dev/null
+++ b/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/pages/index/index.wxml
@@ -0,0 +1,55 @@
+<view class="page">
+ <view class="header">
+ <view class="header__title">待办清单</view>
+ <view class="header__stat">
+ <text class="stat__num">{{counts.active}}</text>
+ <text class="stat__label">进行中</text>
+ <text class="stat__sep">·</text>
+ <text class="stat__num">{{counts.done}}</text>
+ <text class="stat__label">已完成</text>
+ </view>
+ </view>
+
+ <view class="composer">
+ <input
+ class="composer__input"
+ value="{{input}}"
+ placeholder="添加一条待办…"
+ placeholder-class="composer__placeholder"
+ confirm-type="done"
+ maxlength="80"
+ bindinput="onInput"
+ bindconfirm="addTodo"
+ />
+ <button class="composer__btn" size="mini" bindtap="addTodo">添加</button>
+ </view>
+
+ <view class="tabs">
+ <view class="tab {{filter === 'all' ? 'tab_active' : ''}}" data-filter="all" bindtap="setFilter">全部</view>
+ <view class="tab {{filter === 'active' ? 'tab_active' : ''}}" data-filter="active" bindtap="setFilter">进行中</view>
+ <view class="tab {{filter === 'done' ? 'tab_active' : ''}}" data-filter="done" bindtap="setFilter">已完成</view>
+ </view>
+
+ <view class="list">
+ <view class="item {{item.done ? 'item_done' : ''}}" wx:for="{{visible}}" wx:key="id">
+ <view class="item__check" data-id="{{item.id}}" bindtap="toggleTodo">
+ <view class="item__box">{{item.done ? '✓' : ''}}</view>
+ </view>
+ <view class="item__body" data-id="{{item.id}}" bindtap="toggleTodo">
+ <text class="item__text">{{item.text}}</text>
+ <text class="item__time">{{item.timeText}}</text>
+ </view>
+ <view class="item__del" data-id="{{item.id}}" catchtap="removeTodo">删除</view>
+ </view>
+
+ <view class="empty" wx:if="{{visible.length === 0}}">
+ <view class="empty__title">{{counts.total === 0 ? '还没有待办' : '这个筛选下是空的'}}</view>
+ <view class="empty__desc">在上面的输入框里写一条,回车或点「添加」</view>
+ </view>
+ </view>
+
+ <view class="footer">
+ <view class="footer__btn" bindtap="clearDone">清空已完成</view>
+ <view class="footer__btn" bindtap="goAbout">关于</view>
+ </view>
+</view>
diff --git a/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/pages/index/index.wxss b/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/pages/index/index.wxss
new file mode 100644
index 00000000..60b7bcc0
--- /dev/null
+++ b/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/pages/index/index.wxss
@@ -0,0 +1,173 @@
+.header {
+ padding: 8rpx 8rpx 24rpx;
+}
+
+.header__title {
+ font-size: 44rpx;
+ font-weight: 600;
+ letter-spacing: 1rpx;
+}
+
+.header__stat {
+ margin-top: 8rpx;
+ color: #7e8081;
+ font-size: 26rpx;
+}
+
+.stat__num {
+ color: #07c160;
+ font-weight: 600;
+ margin-right: 6rpx;
+}
+
+.stat__label {
+ margin-right: 16rpx;
+}
+
+.stat__sep {
+ margin-right: 16rpx;
+}
+
+.composer {
+ display: flex;
+ align-items: center;
+ background: #ffffff;
+ border-radius: 20rpx;
+ padding: 16rpx 16rpx 16rpx 24rpx;
+ box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
+}
+
+.composer__input {
+ flex: 1;
+ font-size: 30rpx;
+ min-height: 60rpx;
+}
+
+.composer__placeholder {
+ color: #b1b2b3;
+}
+
+.composer__btn {
+ margin-left: 16rpx;
+ background: #07c160;
+ color: #ffffff;
+ border-radius: 12rpx;
+ font-size: 28rpx;
+ line-height: 2.2;
+}
+
+.tabs {
+ display: flex;
+ margin: 28rpx 4rpx 12rpx;
+}
+
+.tab {
+ padding: 8rpx 24rpx;
+ margin-right: 16rpx;
+ font-size: 28rpx;
+ color: #7e8081;
+ border-radius: 999rpx;
+ background: #ececee;
+}
+
+.tab_active {
+ background: #07c160;
+ color: #ffffff;
+}
+
+.list {
+ margin-top: 8rpx;
+}
+
+.item {
+ display: flex;
+ align-items: center;
+ background: #ffffff;
+ border-radius: 20rpx;
+ padding: 26rpx 24rpx;
+ margin-bottom: 16rpx;
+ box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
+}
+
+.item_done {
+ opacity: 0.55;
+}
+
+.item__check {
+ padding-right: 20rpx;
+}
+
+.item__box {
+ width: 44rpx;
+ height: 44rpx;
+ border-radius: 50%;
+ border: 2rpx solid #d4d5d6;
+ color: #ffffff;
+ font-size: 26rpx;
+ text-align: center;
+ line-height: 44rpx;
+}
+
+.item_done .item__box {
+ background: #07c160;
+ border-color: #07c160;
+}
+
+.item__body {
+ flex: 1;
+ min-width: 0;
+}
+
+.item__text {
+ display: block;
+ font-size: 31rpx;
+ word-break: break-all;
+}
+
+.item_done .item__text {
+ text-decoration: line-through;
+ color: #8a8b8c;
+}
+
+.item__time {
+ display: block;
+ margin-top: 6rpx;
+ font-size: 22rpx;
+ color: #b1b2b3;
+}
+
+.item__del {
+ margin-left: 16rpx;
+ padding: 8rpx 12rpx;
+ font-size: 26rpx;
+ color: #fa5151;
+}
+
+.empty {
+ padding: 96rpx 24rpx;
+ text-align: center;
+}
+
+.empty__title {
+ font-size: 30rpx;
+ color: #7e8081;
+}
+
+.empty__desc {
+ margin-top: 12rpx;
+ font-size: 25rpx;
+ color: #b1b2b3;
+}
+
+.footer {
+ display: flex;
+ justify-content: space-between;
+ margin-top: 32rpx;
+ padding: 0 8rpx;
+}
+
+.footer__btn {
+ font-size: 27rpx;
+ color: #576b95;
+ padding: 12rpx 8rpx;
+}
diff --git a/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/preview.js b/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/preview.js
new file mode 100644
index 00000000..e9a87c63
--- /dev/null
+++ b/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/preview.js
@@ -0,0 +1,53 @@
+/**
+ * 用官方 CI 工具生成「体验版」预览二维码(图片落盘,可直接给用户扫)。
+ *
+ * 环境变量同 upload.js:MP_APPID / MP_KEY_PATH
+ * 可选:MP_QR_OUT 二维码输出路径,默认 ./preview-qrcode.png
+ *
+ * 用法:MP_APPID=wx... MP_KEY_PATH=/path/private.key node preview.js
+ */
+const fs = require("fs");
+const path = require("path");
+const ci = require("miniprogram-ci");
+
+const appid = process.env.MP_APPID;
+const keyPath = process.env.MP_KEY_PATH;
+
+if (!appid || !keyPath) {
+ console.error("缺少环境变量:需要 MP_APPID 和 MP_KEY_PATH");
+ process.exit(2);
+}
+
+const project = new ci.Project({
+ appid,
+ type: "miniProgram",
+ projectPath: __dirname,
+ privateKeyPath: path.resolve(keyPath),
+ ignores: ["node_modules/**/*", "tools/**/*"],
+});
+
+(async () => {
+ const result = await ci.preview({
+ project,
+ desc: `预览 ${new Date().toISOString()}`,
+ setting: { es6: true, minify: true },
+ qrcodeFormat: "image",
+ qrcodeOutputDest: process.env.MP_QR_OUT || path.join(__dirname, "preview-qrcode.png"),
+ onProgressUpdate: (info) =>
+ console.log(
+ "[progress]",
+ typeof info === "string" ? info : JSON.stringify(info).slice(0, 200),
+ ),
+ });
+ const out = process.env.MP_QR_OUT || path.join(__dirname, "preview-qrcode.png");
+ console.log(
+ "预览二维码:",
+ out,
+ fs.existsSync(out) ? `(${fs.statSync(out).size} 字节)` : "(未生成)",
+ );
+ if (result && result.subPackageInfo)
+ console.log("分包信息:", JSON.stringify(result.subPackageInfo).slice(0, 300));
+})().catch((err) => {
+ console.error("生成预览失败:", err && err.message ? err.message : err);
+ process.exit(1);
+});
diff --git a/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/project.config.json b/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/project.config.json
new file mode 100644
index 00000000..27a646d7
--- /dev/null
+++ b/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/project.config.json
@@ -0,0 +1,25 @@
+{
+ "description": "简单待办清单小程序",
+ "appid": "wxTEMPLATE_PLACEHOLDER",
+ "projectname": "todo-miniprogram",
+ "compileType": "miniprogram",
+ "miniprogramRoot": "./",
+ "libVersion": "latest",
+ "setting": {
+ "es6": true,
+ "enhance": true,
+ "postcss": true,
+ "minified": true,
+ "urlCheck": false,
+ "coverView": true,
+ "ignoreDevUnusedFiles": false,
+ "ignoreUploadUnusedFiles": true
+ },
+ "packOptions": {
+ "ignore": [
+ { "type": "folder", "value": "node_modules" },
+ { "type": "folder", "value": "tools" },
+ { "type": "file", "value": "README.md" }
+ ]
+ }
+}
diff --git a/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/sitemap.json b/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/sitemap.json
new file mode 100644
index 00000000..967c992d
--- /dev/null
+++ b/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/sitemap.json
@@ -0,0 +1,9 @@
+{
+ "desc": "小程序索引配置,默认允许全部页面被微信索引",
+ "rules": [
+ {
+ "action": "allow",
+ "page": "*"
+ }
+ ]
+}
diff --git a/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/tools/test-page.js b/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/tools/test-page.js
new file mode 100644
index 00000000..263cec13
--- /dev/null
+++ b/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/tools/test-page.js
@@ -0,0 +1,123 @@
+/**
+ * 页面逻辑的无头测试:把 wx / Page / getApp 打桩后直接跑 pages/index 的业务方法。
+ * 微信开发者工具跑不了(服务器是 Linux 无图形界面),所以用这个保证核心逻辑正确。
+ * 用法:node tools/test-page.js
+ */
+const assert = require("assert");
+
+let store = {};
+const toasts = [];
+let modalConfirm = true;
+
+global.wx = {
+ getStorageSync: (k) => (k in store ? store[k] : ""),
+ setStorageSync: (k, v) => {
+ store[k] = v;
+ },
+ showToast: (o) => toasts.push(o && o.title),
+ showModal: (o) => {
+ if (o && o.success) o.success({ confirm: modalConfirm });
+ },
+ vibrateShort: () => {},
+ navigateTo: () => {},
+};
+global.getApp = () => ({ globalData: { version: "test" } });
+
+let pageDef = null;
+global.Page = (def) => {
+ pageDef = def;
+};
+
+require("../pages/index/index.js");
+assert.ok(pageDef, "Page() 没有被调用");
+
+function newInstance() {
+ const inst = { data: JSON.parse(JSON.stringify(pageDef.data)) };
+ inst.setData = function (patch, cb) {
+ Object.assign(this.data, patch);
+ if (cb) cb();
+ };
+ for (const key of Object.keys(pageDef)) {
+ if (typeof pageDef[key] === "function") inst[key] = pageDef[key].bind(inst);
+ }
+ return inst;
+}
+
+const tap = (id) => ({ currentTarget: { dataset: { id } } });
+
+// 1. 空存储时初始化
+store = {};
+let p = newInstance();
+p.load();
+assert.deepStrictEqual(p.data.counts, { total: 0, active: 0, done: 0 });
+assert.strictEqual(p.data.visible.length, 0);
+
+// 2. 空白输入不添加
+p.setData({ input: " " });
+p.addTodo();
+assert.strictEqual(p.data.todos.length, 0, "空白输入不应新增");
+assert.ok(toasts.includes("先写点内容"), "应提示先写内容");
+
+// 3. 正常添加:去空格、置顶、清空输入、落盘
+p.setData({ input: " 写周报 " });
+p.addTodo();
+assert.strictEqual(p.data.todos.length, 1);
+assert.strictEqual(p.data.todos[0].text, "写周报");
+assert.strictEqual(p.data.input, "");
+assert.strictEqual(store["todos:v1"].length, 1, "应写入本地存储");
+assert.ok(p.data.todos[0].timeText, "应有时间文案");
+assert.strictEqual(p.data.counts.active, 1);
+
+// 4. 再添加一条,新的排在最前
+p.setData({ input: "买牛奶" });
+p.addTodo();
+assert.strictEqual(p.data.todos[0].text, "买牛奶");
+assert.strictEqual(p.data.counts.total, 2);
+
+// 5. 切换完成状态
+const firstId = p.data.todos[0].id;
+p.toggleTodo(tap(firstId));
+assert.strictEqual(p.data.todos[0].done, true);
+assert.deepStrictEqual(p.data.counts, { total: 2, active: 1, done: 1 });
+
+// 6. 筛选
+p.setData({ filter: "done" });
+p.commit(p.data.todos);
+assert.strictEqual(p.data.visible.length, 1);
+assert.strictEqual(p.data.visible[0].id, firstId);
+p.setFilter({ currentTarget: { dataset: { filter: "active" } } });
+assert.strictEqual(p.data.visible.length, 1);
+assert.strictEqual(p.data.visible[0].text, "写周报");
+p.setFilter({ currentTarget: { dataset: { filter: "all" } } });
+assert.strictEqual(p.data.visible.length, 2);
+
+// 7. 取消删除时数据不动
+modalConfirm = false;
+p.removeTodo(tap(firstId));
+assert.strictEqual(p.data.todos.length, 2, "取消后不应删除");
+
+// 8. 确认删除
+modalConfirm = true;
+p.removeTodo(tap(firstId));
+assert.strictEqual(p.data.todos.length, 1);
+assert.strictEqual(p.data.counts.done, 0);
+assert.strictEqual(store["todos:v1"].length, 1, "删除后存储同步");
+
+// 9. 持久化 round-trip:新实例能读回
+const p2 = newInstance();
+p2.load();
+assert.strictEqual(p2.data.todos.length, 1);
+assert.strictEqual(p2.data.todos[0].text, "写周报");
+
+// 10. 清空已完成
+p2.toggleTodo(tap(p2.data.todos[0].id));
+p2.clearDone();
+assert.strictEqual(p2.data.todos.length, 0);
+assert.strictEqual(store["todos:v1"].length, 0);
+
+// 11. 落盘时不应把展示用的 timeText 也存进去
+p2.setData({ input: "检查存储字段" });
+p2.addTodo();
+assert.ok(!("timeText" in store["todos:v1"][0]), "存储里不应包含 timeText");
+
+console.log("✅ 页面逻辑测试全部通过(11 项)");
diff --git a/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/tools/validate.js b/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/tools/validate.js
new file mode 100644
index 00000000..8471f2f6
--- /dev/null
+++ b/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/tools/validate.js
@@ -0,0 +1,103 @@
+/**
+ * 校验小程序工程结构(不依赖微信开发者工具,纯 Node)
+ * 检查:app.json 声明的页面四件套是否齐全、所有 JSON 能否解析、所有 JS 语法是否合法、
+ * WXML 的插值括号是否配对、project.config.json 的 appid 是否还是占位值。
+ */
+const fs = require("fs");
+const path = require("path");
+const { execFileSync } = require("child_process");
+
+const root = path.resolve(__dirname, "..");
+const errors = [];
+const warnings = [];
+const rel = (p) => path.relative(root, p);
+
+function readJson(file) {
+ const text = fs.readFileSync(file, "utf8");
+ try {
+ return JSON.parse(text);
+ } catch (e) {
+ errors.push(`${rel(file)} JSON 解析失败: ${e.message}`);
+ return null;
+ }
+}
+
+// 1. 遍历全部 json / wxml,做语法层面检查
+function walk(dir) {
+ for (const name of fs.readdirSync(dir)) {
+ if (name === "node_modules" || name.startsWith(".")) continue;
+ const full = path.join(dir, name);
+ const stat = fs.statSync(full);
+ if (stat.isDirectory()) {
+ walk(full);
+ continue;
+ }
+ if (name.endsWith(".json")) readJson(full);
+ if (name.endsWith(".wxml")) {
+ const t = fs.readFileSync(full, "utf8");
+ const open = (t.match(/\{\{/g) || []).length;
+ const close = (t.match(/\}\}/g) || []).length;
+ if (open !== close) errors.push(`${rel(full)} 插值括号不配对:{{ ×${open} vs }} ×${close}`);
+ }
+ if (name.endsWith(".js")) {
+ if (/^\s*(import|export)\s/m.test(fs.readFileSync(full, "utf8"))) {
+ errors.push(`${rel(full)} 使用了 ESM 语法,小程序页面应使用 CommonJS`);
+ }
+ try {
+ execFileSync(process.execPath, ["--check", full], { stdio: "pipe" });
+ } catch (e) {
+ errors.push(`${rel(full)} 语法错误: ${String(e.stderr || e.message).split("\n")[0]}`);
+ }
+ }
+ }
+}
+
+// 2. app.json 页面四件套
+const appJsonPath = path.join(root, "app.json");
+const appJson = fs.existsSync(appJsonPath)
+ ? readJson(appJsonPath)
+ : (errors.push("缺少 app.json"), null);
+if (appJson) {
+ if (!Array.isArray(appJson.pages) || appJson.pages.length === 0)
+ errors.push("app.json 没有声明 pages");
+ for (const page of appJson.pages || []) {
+ for (const ext of ["js", "wxml", "json"]) {
+ const f = path.join(root, `${page}.${ext}`);
+ if (!fs.existsSync(f)) errors.push(`页面文件缺失: ${page}.${ext}`);
+ }
+ if (!fs.existsSync(path.join(root, `${page}.wxss`)))
+ warnings.push(`${page}.wxss 不存在(不是必须)`);
+ }
+ if (appJson.sitemapLocation && !fs.existsSync(path.join(root, appJson.sitemapLocation))) {
+ errors.push(`sitemapLocation 指向的文件不存在: ${appJson.sitemapLocation}`);
+ }
+}
+
+// 3. 入口文件
+for (const f of ["app.js", "app.wxss", "project.config.json"]) {
+ if (!fs.existsSync(path.join(root, f))) errors.push(`缺少 ${f}`);
+}
+
+// 4. appid 占位提醒
+const pcPath = path.join(root, "project.config.json");
+if (fs.existsSync(pcPath)) {
+ const pc = readJson(pcPath);
+ if (pc && ["touristappid", "", undefined].includes(pc.appid)) {
+ warnings.push(
+ `project.config.json 的 appid 仍是占位值「${pc.appid}」,正式上传前需替换为真实 AppID`,
+ );
+ }
+}
+
+walk(root);
+
+if (warnings.length) {
+ console.log("提醒:");
+ warnings.forEach((w) => console.log(" ⚠ " + w));
+}
+if (errors.length) {
+ console.log("发现 " + errors.length + " 个问题:");
+ errors.forEach((e) => console.log(" ✗ " + e));
+ process.exit(1);
+}
+console.log("✅ 校验通过:页面结构、JSON、JS 语法、WXML 插值均正常");
diff --git a/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/upload.js b/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/upload.js
new file mode 100644
index 00000000..48f709dc
--- /dev/null
+++ b/plugins/wechat-miniprogram/skills/wechat-miniprogram/templates/miniprogram-todo/upload.js
@@ -0,0 +1,49 @@
+/**
+ * 用官方 CI 工具上传代码,生成开发版/体验版(不需要微信开发者工具,Linux 可跑)。
+ *
+ * 需要两个环境变量:
+ * MP_APPID 小程序 AppID(wx 开头)
+ * MP_KEY_PATH 后台「开发管理 → 开发设置 → 小程序代码上传」生成的密钥文件路径
+ * 可选:
+ * MP_VERSION 版本号,默认 1.0.0
+ * MP_DESC 版本描述,默认时间戳
+ *
+ * 用法:MP_APPID=wx... MP_KEY_PATH=/path/private.key node upload.js
+ */
+const path = require("path");
+const ci = require("miniprogram-ci");
+
+const appid = process.env.MP_APPID;
+const keyPath = process.env.MP_KEY_PATH;
+
+if (!appid || !keyPath) {
+ console.error("缺少环境变量:需要 MP_APPID 和 MP_KEY_PATH");
+ process.exit(2);
+}
+
+const project = new ci.Project({
+ appid,
+ type: "miniProgram",
+ projectPath: __dirname,
+ privateKeyPath: path.resolve(keyPath),
+ ignores: ["node_modules/**/*", "tools/**/*"],
+});
+
+(async () => {
+ const result = await ci.upload({
+ project,
+ version: process.env.MP_VERSION || "1.0.0",
+ desc: process.env.MP_DESC || `CI 上传 ${new Date().toISOString()}`,
+ setting: { es6: true, minify: true, autoPrefixWXSS: true },
+ onProgressUpdate: (info) =>
+ console.log(
+ "[progress]",
+ typeof info === "string" ? info : JSON.stringify(info).slice(0, 200),
+ ),
+ });
+ console.log("上传完成:", result && result.subPackageInfo ? "已上传分包信息" : "已上传");
+ console.log("接着去 mp.weixin.qq.com → 管理 → 版本管理,把这次上传设为体验版 / 提交审核");
+})().catch((err) => {
+ console.error("上传失败:", err && err.message ? err.message : err);
+ process.exit(1);
+});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 7736ba8f..7f7134ae 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -63,6 +63,9 @@ importers:
'@lmliheng/continual-learning':
specifier: workspace:*
version: link:../../plugins/continual-learning
+ '@lmliheng/csu-mail':
+ specifier: workspace:*
+ version: link:../../plugins/csu-mail
'@lmliheng/data-analysis':
specifier: workspace:*
version: link:../../plugins/data-analysis
@@ -96,6 +99,9 @@ importers:
'@lmliheng/use-firecrawl':
specifier: workspace:*
version: link:../../plugins/use-firecrawl
+ '@lmliheng/wechat-miniprogram':
+ specifier: workspace:*
+ version: link:../../plugins/wechat-miniprogram
'@modelcontextprotocol/client':
specifier: ^2.0.0
version: 2.0.0
@@ -148,6 +154,9 @@ importers:
'@lmliheng/continual-learning':
specifier: workspace:*
version: link:../../plugins/continual-learning
+ '@lmliheng/csu-mail':
+ specifier: workspace:*
+ version: link:../../plugins/csu-mail
'@lmliheng/data-analysis':
specifier: workspace:*
version: link:../../plugins/data-analysis
@@ -175,6 +184,9 @@ importers:
'@lmliheng/use-firecrawl':
specifier: workspace:*
version: link:../../plugins/use-firecrawl
+ '@lmliheng/wechat-miniprogram':
+ specifier: workspace:*
+ version: link:../../plugins/wechat-miniprogram
'@modelcontextprotocol/client':
specifier: ^2.0.0
version: 2.0.0
@@ -233,6 +245,9 @@ importers:
'@lmliheng/continual-learning':
specifier: workspace:*
version: link:../../plugins/continual-learning
+ '@lmliheng/csu-mail':
+ specifier: workspace:*
+ version: link:../../plugins/csu-mail
'@lmliheng/data-analysis':
specifier: workspace:*
version: link:../../plugins/data-analysis
@@ -260,6 +275,9 @@ importers:
'@lmliheng/use-firecrawl':
specifier: workspace:*
version: link:../../plugins/use-firecrawl
+ '@lmliheng/wechat-miniprogram':
+ specifier: workspace:*
+ version: link:../../plugins/wechat-miniprogram
devDependencies:
'@lmliheng/penguin-cli':
specifier: workspace:*
@@ -638,6 +656,8 @@ importers:
plugins/continual-learning: {}
+ plugins/csu-mail: {}
+
plugins/data-analysis: {}
plugins/goal: {}
@@ -720,6 +740,8 @@ importers:
plugins/use-firecrawl: {}
+ plugins/wechat-miniprogram: {}
+
packages:
'@ampproject/[email protected]':
@@ -1426,6 +1448,9 @@ packages:
'@lmliheng/continual-learning@file:plugins/continual-learning':
resolution: {directory: plugins/continual-learning, type: directory}
+ '@lmliheng/csu-mail@file:plugins/csu-mail':
+ resolution: {directory: plugins/csu-mail, type: directory}
+
'@lmliheng/data-analysis@file:plugins/data-analysis':
resolution: {directory: plugins/data-analysis, type: directory}
@@ -1469,6 +1494,9 @@ packages:
'@lmliheng/use-firecrawl@file:plugins/use-firecrawl':
resolution: {directory: plugins/use-firecrawl, type: directory}
+ '@lmliheng/wechat-miniprogram@file:plugins/wechat-miniprogram':
+ resolution: {directory: plugins/wechat-miniprogram, type: directory}
+
'@malept/[email protected]':
resolution: {integrity: sha512-1DpKU0Z5ThltBwjNySMC14g0CkbyhCaz9FkhxqNsZI6uAPJXFS8cMXlBKo26FJ8ZuW6S9GCMcR9IO5k2X5/9Fg==}
engines: {node: '>= 12.13.0'}
@@ -5501,6 +5529,8 @@ snapshots:
'@lmliheng/continual-learning@file:plugins/continual-learning': {}
+ '@lmliheng/csu-mail@file:plugins/csu-mail': {}
+
'@lmliheng/data-analysis@file:plugins/data-analysis': {}
'@lmliheng/goal@file:plugins/goal': {}
@@ -5516,6 +5546,7 @@ snapshots:
'@lmliheng/agent-tuning': file:plugins/agent-tuning
'@lmliheng/browser-automation': file:plugins/browser-automation
'@lmliheng/continual-learning': file:plugins/continual-learning
+ '@lmliheng/csu-mail': file:plugins/csu-mail
'@lmliheng/data-analysis': file:plugins/data-analysis
'@lmliheng/goal': file:plugins/goal
'@lmliheng/humanizer': file:plugins/humanizer
@@ -5527,6 +5558,7 @@ snapshots:
'@lmliheng/use-bento-slides': file:plugins/use-bento-slides
'@lmliheng/use-claude-code': file:plugins/use-claude-code
'@lmliheng/use-firecrawl': file:plugins/use-firecrawl
+ '@lmliheng/wechat-miniprogram': file:plugins/wechat-miniprogram
'@modelcontextprotocol/client': 2.0.0
'@prismshadow/agenthub': 0.4.15([email protected])([email protected])
commander: 13.1.0
@@ -5549,6 +5581,7 @@ snapshots:
'@lmliheng/agent-tuning': file:plugins/agent-tuning
'@lmliheng/browser-automation': file:plugins/browser-automation
'@lmliheng/continual-learning': file:plugins/continual-learning
+ '@lmliheng/csu-mail': file:plugins/csu-mail
'@lmliheng/data-analysis': file:plugins/data-analysis
'@lmliheng/goal': file:plugins/goal
'@lmliheng/humanizer': file:plugins/humanizer
@@ -5558,6 +5591,7 @@ snapshots:
'@lmliheng/use-bento-slides': file:plugins/use-bento-slides
'@lmliheng/use-claude-code': file:plugins/use-claude-code
'@lmliheng/use-firecrawl': file:plugins/use-firecrawl
+ '@lmliheng/wechat-miniprogram': file:plugins/wechat-miniprogram
'@modelcontextprotocol/client': 2.0.0
'@prismshadow/agenthub': 0.4.15([email protected])([email protected])
arktype: 2.2.3
@@ -5578,6 +5612,7 @@ snapshots:
'@lmliheng/agent-tuning': file:plugins/agent-tuning
'@lmliheng/browser-automation': file:plugins/browser-automation
'@lmliheng/continual-learning': file:plugins/continual-learning
+ '@lmliheng/csu-mail': file:plugins/csu-mail
'@lmliheng/data-analysis': file:plugins/data-analysis
'@lmliheng/goal': file:plugins/goal
'@lmliheng/humanizer': file:plugins/humanizer
@@ -5587,6 +5622,7 @@ snapshots:
'@lmliheng/use-bento-slides': file:plugins/use-bento-slides
'@lmliheng/use-claude-code': file:plugins/use-claude-code
'@lmliheng/use-firecrawl': file:plugins/use-firecrawl
+ '@lmliheng/wechat-miniprogram': file:plugins/wechat-miniprogram
'@modelcontextprotocol/client': 2.0.0
'@prismshadow/agenthub': 0.4.15([email protected])([email protected])([email protected])
arktype: 2.2.3
@@ -5675,6 +5711,8 @@ snapshots:
'@lmliheng/use-firecrawl@file:plugins/use-firecrawl': {}
+ '@lmliheng/wechat-miniprogram@file:plugins/wechat-miniprogram': {}
+
'@malept/[email protected]':
dependencies:
cross-spawn: 7.0.6