jackson 1 week geleden
bovenliggende
commit
10f6b36a3d

+ 1 - 0
.gitignore

@@ -0,0 +1 @@
+

File diff suppressed because it is too large
+ 2 - 2
SKILL.md


+ 4 - 0
credentials.json

@@ -0,0 +1,4 @@
+{
+    "app_id":  "cli_aa55b32acb79dd28",
+    "app_secret":  "tiOJkOJmKetDwLSOCw2zNgTvqYegaIh8"
+}

BIN
scripts/__pycache__/audit.cpython-313.pyc


BIN
scripts/__pycache__/feishu_credentials.cpython-313.pyc


BIN
scripts/__pycache__/fetch_table.cpython-313.pyc


BIN
scripts/__pycache__/rule_check.cpython-313.pyc


BIN
scripts/__pycache__/sync_package.cpython-313.pyc


+ 10 - 10
scripts/audit.py

@@ -27,7 +27,8 @@ audit.py — SKU 审核执行器(固定脚本,结果可复现)
     --skip-images     不下载图片,FZ-06 记 NEED_HUMAN(离线/提速用)
     --coverage        只打印判定表全部项(当前 63 项)的覆盖情况后退出
 
-凭证:环境变量 FEISHU_APP_ID / FEISHU_APP_SECRET,或 ~/.sku_audit/credentials.json
+凭证:环境变量 FEISHU_APP_ID / FEISHU_APP_SECRET,或 ~/.sku_audit/credentials.json,
+      或技能包根目录 credentials.json(见 feishu_credentials.py)
 """
 import argparse
 import glob
@@ -60,8 +61,11 @@ try:
 except ImportError:
     requests = None
 
+if _HERE not in sys.path:
+    sys.path.insert(0, _HERE)
+import feishu_credentials  # noqa: E402
+
 BASE = "https://open.feishu.cn/open-apis"
-HOME_DIR = os.path.expanduser("~/.sku_audit")
 
 # ---------------------------------------------------------------- 结论档位
 PASS = "✅ 通过"
@@ -378,14 +382,10 @@ def norm_usage(s):
 def feishu_token():
     if requests is None:
         raise SystemExit("缺少依赖:pip3 install requests")
-    aid, sec = os.environ.get("FEISHU_APP_ID"), os.environ.get("FEISHU_APP_SECRET")
-    if not (aid and sec):
-        p = os.path.join(HOME_DIR, "credentials.json")
-        if os.path.exists(p):
-            d = json.load(open(p, encoding="utf-8"))
-            aid, sec = d.get("app_id"), d.get("app_secret")
-    if not (aid and sec):
-        raise SystemExit("未找到凭证:设置 FEISHU_APP_ID / FEISHU_APP_SECRET,或写入 ~/.sku_audit/credentials.json")
+    found = feishu_credentials.load()
+    if not found:
+        raise SystemExit(feishu_credentials.missing_message())
+    aid, sec = found
     r = requests.post(f"{BASE}/auth/v3/tenant_access_token/internal",
                       json={"app_id": aid, "app_secret": sec}, timeout=20).json()
     if r.get("code") != 0:

+ 51 - 0
scripts/feishu_credentials.py

@@ -0,0 +1,51 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+"""
+飞书凭证读取(四个脚本共用)。
+
+按顺序取第一个可用来源:
+    1) 环境变量 FEISHU_APP_ID / FEISHU_APP_SECRET
+    2) ~/.sku_audit/credentials.json
+    3) 技能包根目录的 credentials.json(托管沙箱无法配置环境变量或用户目录时随包提供)
+
+文件格式:{"app_id": "...", "app_secret": "..."}
+凭证值不写入任何输出;提示信息只包含路径。
+"""
+import json
+import os
+
+FILE_NAME = "credentials.json"
+HOME_FILE = os.path.join(os.path.expanduser("~/.sku_audit"), FILE_NAME)
+PACKAGE_FILE = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), FILE_NAME)
+
+
+def read_file(path):
+    """读取一个凭证文件;不存在、无法解析或缺项时返回 None。"""
+    try:
+        with open(path, encoding="utf-8-sig") as f:
+            data = json.load(f)
+    except (OSError, ValueError):
+        return None
+    if not isinstance(data, dict):
+        return None
+    app_id, secret = data.get("app_id"), data.get("app_secret")
+    if isinstance(app_id, str) and isinstance(secret, str) and app_id.strip() and secret.strip():
+        return app_id.strip(), secret.strip()
+    return None
+
+
+def load():
+    """返回 (app_id, app_secret);没有可用来源时返回 None。"""
+    app_id, secret = os.environ.get("FEISHU_APP_ID"), os.environ.get("FEISHU_APP_SECRET")
+    if app_id and secret:
+        return app_id, secret
+    for path in (HOME_FILE, PACKAGE_FILE):
+        found = read_file(path)
+        if found:
+            return found
+    return None
+
+
+def missing_message():
+    return ("未找到可用凭证。请设置环境变量 FEISHU_APP_ID / FEISHU_APP_SECRET,"
+            f"或写入 {HOME_FILE},或在技能包根目录放置 {FILE_NAME}")

+ 8 - 13
scripts/fetch_table.py

@@ -22,7 +22,8 @@
     GET https://open.feishu.cn/open-apis/drive/v1/medias/{file_token}/download
     带 Header  Authorization: Bearer <tenant_access_token>
 
-凭证:环境变量 FEISHU_APP_ID / FEISHU_APP_SECRET,或 ~/.sku_audit/credentials.json
+凭证:环境变量 FEISHU_APP_ID / FEISHU_APP_SECRET,或 ~/.sku_audit/credentials.json,
+      或技能包根目录 credentials.json(见 feishu_credentials.py)
 """
 import argparse
 import csv
@@ -36,7 +37,11 @@ except ImportError:
     print("缺少依赖:pip3 install requests", file=sys.stderr)
     sys.exit(2)
 
-HOME_DIR = os.path.expanduser("~/.sku_audit")
+_HERE = os.path.dirname(os.path.abspath(__file__))
+if _HERE not in sys.path:
+    sys.path.insert(0, _HERE)
+import feishu_credentials  # noqa: E402
+
 BASE = "https://open.feishu.cn/open-apis"
 
 
@@ -46,17 +51,7 @@ def die(msg, code=2):
 
 
 def load_credentials():
-    app_id = os.environ.get("FEISHU_APP_ID")
-    secret = os.environ.get("FEISHU_APP_SECRET")
-    if app_id and secret:
-        return app_id, secret
-    p = os.path.join(HOME_DIR, "credentials.json")
-    if os.path.exists(p):
-        d = json.load(open(p, encoding="utf-8"))
-        if d.get("app_id") and d.get("app_secret"):
-            return d["app_id"], d["app_secret"]
-    die("未找到凭证。请设置 FEISHU_APP_ID / FEISHU_APP_SECRET,"
-        f"或写入 {p}")
+    return feishu_credentials.load() or die(feishu_credentials.missing_message())
 
 
 def get_token(app_id, secret):

+ 6 - 15
scripts/rule_check.py

@@ -13,9 +13,10 @@ SKU 审核规则一致性核验工具
     python3 rule_check.py all        # 上面两步一起跑(默认)
     python3 rule_check.py verify --workbook 路径 --report 输出.xlsx
 
-凭证(二选一,不会写入任何输出):
+凭证(按顺序取第一个可用来源,不会写入任何输出):
     1) 环境变量:FEISHU_APP_ID / FEISHU_APP_SECRET
     2) 文件:~/.sku_audit/credentials.json  {"app_id": "...", "app_secret": "..."}
+    3) 文件:技能包根目录 credentials.json(托管沙箱随包提供,格式同上)
 
 退出码:
     0 = 全部通过
@@ -39,6 +40,9 @@ except ImportError:
 
 DEFAULT_DOC = "SFQjdsMoRoxPjsx4wGhc95uxnEc"
 _HERE = os.path.dirname(os.path.abspath(__file__))
+if _HERE not in sys.path:
+    sys.path.insert(0, _HERE)
+import feishu_credentials  # noqa: E402
 # 默认工作簿:优先用技能包内的 assets/,否则用当前目录同名文件
 def _pick_workbook():
     """优先取 assets 下版本号最高的工具包,避免升级后仍指向旧文件名"""
@@ -128,20 +132,7 @@ def die(msg, code=2):
 
 
 def load_credentials():
-    app_id = os.environ.get("FEISHU_APP_ID")
-    secret = os.environ.get("FEISHU_APP_SECRET")
-    if app_id and secret:
-        return app_id, secret
-    p = os.path.join(HOME_DIR, "credentials.json")
-    if os.path.exists(p):
-        try:
-            d = json.load(open(p, encoding="utf-8"))
-            if d.get("app_id") and d.get("app_secret"):
-                return d["app_id"], d["app_secret"]
-        except Exception:
-            pass
-    die("未找到凭证。请设置环境变量 FEISHU_APP_ID / FEISHU_APP_SECRET,"
-        f"或写入 {p}")
+    return feishu_credentials.load() or die(feishu_credentials.missing_message())
 
 
 def get_token(app_id, app_secret):

+ 20 - 13
scripts/sync_package.py

@@ -11,6 +11,10 @@
     python3 scripts/sync_package.py --out ~/dist    # 指定输出目录
     python3 scripts/sync_package.py --check-only    # 只检查,不打包(核验通过后仍会更新随包基线并重建参考表,只是不升版本、不打 zip)
     python3 scripts/sync_package.py --no-bump       # 打包但不升版本号
+    python3 scripts/sync_package.py --no-bump --with-credentials
+                                                    # 另打一个带根目录 credentials.json 的包,只用于上传托管沙箱
+
+技能包根目录的 credentials.json 默认不进包,避免凭证随分发包外流。
 
 规则是否变更以随包基线 references/doc-snapshot.txt 为准(不是本地快照);基线只在核验与自检都通过后才更新,
 核验失败后再次运行仍会报告规则有变更。手工维护的 rules.md / known-gaps.md / mcp-mode.md 不在机器核验范围,
@@ -55,6 +59,7 @@ DEFAULT_DOC = "SFQjdsMoRoxPjsx4wGhc95uxnEc"
 
 sys.path.insert(0, HERE)
 import rule_check  # noqa: E402  比对口径与 rule_check 共用一份实现
+import feishu_credentials  # noqa: E402
 
 
 def die(msg, code=2):
@@ -63,16 +68,7 @@ def die(msg, code=2):
 
 
 def load_credentials():
-    a = os.environ.get("FEISHU_APP_ID")
-    s = os.environ.get("FEISHU_APP_SECRET")
-    if a and s:
-        return a, s
-    p = os.path.join(HOME_DIR, "credentials.json")
-    if os.path.exists(p):
-        d = json.load(open(p, encoding="utf-8"))
-        if d.get("app_id") and d.get("app_secret"):
-            return d["app_id"], d["app_secret"]
-    die(f"未找到凭证:设置 FEISHU_APP_ID / FEISHU_APP_SECRET,或写入 {p}")
+    return feishu_credentials.load() or die(feishu_credentials.missing_message())
 
 
 def get_token(a, s):
@@ -291,9 +287,14 @@ def audit_selfcheck():
     }
 
 
-def make_zip(skill_dir, out_dir, ver):
+def make_zip(skill_dir, out_dir, ver, with_credentials=False):
+    """打 zip。根目录 credentials.json 默认不进包;with_credentials 仅用于上传托管沙箱的包。"""
+    secret_file = os.path.join(skill_dir, feishu_credentials.FILE_NAME)
+    if with_credentials and not feishu_credentials.read_file(secret_file):
+        die(f"--with-credentials 需要技能包根目录有可用的 {feishu_credentials.FILE_NAME}"
+            "(含 app_id 与 app_secret)")
     os.makedirs(out_dir, exist_ok=True)
-    name = f"SKU审核专员-技能包_v{ver}.zip"
+    name = f"SKU审核专员-技能包_v{ver}{'-含凭证' if with_credentials else ''}.zip"
     path = os.path.join(out_dir, name)
     if os.path.exists(path):
         os.remove(path)
@@ -305,6 +306,8 @@ def make_zip(skill_dir, out_dir, ver):
                 if f.endswith((".pyc", ".DS_Store")) or f.startswith("~$"):
                     continue
                 full = os.path.join(root, f)
+                if not with_credentials and os.path.abspath(full) == os.path.abspath(secret_file):
+                    continue
                 rel = os.path.relpath(full, base)
                 z.write(full, rel)
     # 确认审核脚本真的进包了(分发包没有 audit.py 就跑不了审核)
@@ -322,6 +325,8 @@ def main():
     ap.add_argument("--out", default=os.path.join(os.path.dirname(SKILL_DIR), "dist"))
     ap.add_argument("--check-only", action="store_true")
     ap.add_argument("--no-bump", action="store_true")
+    ap.add_argument("--with-credentials", action="store_true",
+                    help="把技能包根目录的 credentials.json 一并打包(仅用于上传托管沙箱,不得外发)")
     args = ap.parse_args()
 
     doc_id = args.doc
@@ -385,10 +390,12 @@ def main():
     print(f"\n[5/7] 版本:v{ver}")
 
     # 6. 打包
-    path = make_zip(SKILL_DIR, args.out, ver)
+    path = make_zip(SKILL_DIR, args.out, ver, with_credentials=args.with_credentials)
     size = os.path.getsize(path) / 1024
     print(f"\n[6/7] 打包完成:{path}")
     print(f"      {size:.0f} KB | {nfiles} 个文件")
+    if args.with_credentials:
+        print("      ⚠️ 本包含飞书凭证:只上传到托管沙箱的技能配置,不要外发、不要提交到代码仓")
 
     print(f"\n[7/7] 结论")
     if changed:

BIN
tests/__pycache__/test_credentials.cpython-313.pyc


+ 139 - 0
tests/test_credentials.py

@@ -0,0 +1,139 @@
+import contextlib
+import io
+import json
+import os
+import sys
+import tempfile
+import types
+import unittest
+import zipfile
+from pathlib import Path
+from unittest.mock import patch
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT / "scripts"))
+import audit
+import feishu_credentials as cred
+with patch.dict(sys.modules, {"requests": types.ModuleType("requests")}):
+    import fetch_table
+    import rule_check
+    import sync_package
+
+NO_ENV = {"FEISHU_APP_ID": "", "FEISHU_APP_SECRET": ""}
+
+
+class CredentialSourceTests(unittest.TestCase):
+    def setUp(self):
+        self.tmp = tempfile.TemporaryDirectory()
+        self.addCleanup(self.tmp.cleanup)
+        self.home = os.path.join(self.tmp.name, "home.json")
+        self.package = os.path.join(self.tmp.name, "package.json")
+        for target, value in ((cred, "HOME_FILE"), (cred, "PACKAGE_FILE")):
+            patcher = patch.object(target, value, self.home if value == "HOME_FILE" else self.package)
+            patcher.start()
+            self.addCleanup(patcher.stop)
+        patcher = patch.dict(os.environ, NO_ENV)
+        patcher.start()
+        self.addCleanup(patcher.stop)
+
+    def write(self, path, data, encoding="utf-8"):
+        with open(path, "w", encoding=encoding) as f:
+            f.write(data if isinstance(data, str) else json.dumps(data))
+
+    def test_environment_wins_over_files(self):
+        self.write(self.home, {"app_id": "home", "app_secret": "home-secret"})
+        self.write(self.package, {"app_id": "pkg", "app_secret": "pkg-secret"})
+        with patch.dict(os.environ, {"FEISHU_APP_ID": "env", "FEISHU_APP_SECRET": "env-secret"}):
+            self.assertEqual(cred.load(), ("env", "env-secret"))
+
+    def test_home_file_wins_over_package_file(self):
+        self.write(self.home, {"app_id": "home", "app_secret": "home-secret"})
+        self.write(self.package, {"app_id": "pkg", "app_secret": "pkg-secret"})
+        self.assertEqual(cred.load(), ("home", "home-secret"))
+
+    def test_package_file_is_used_when_nothing_else_is_configured(self):
+        self.write(self.package, {"app_id": "pkg", "app_secret": "pkg-secret"})
+        self.assertEqual(cred.load(), ("pkg", "pkg-secret"))
+
+    def test_package_file_with_bom_is_accepted(self):
+        self.write(self.package, {"app_id": "pkg", "app_secret": "pkg-secret"}, encoding="utf-8-sig")
+        self.assertEqual(cred.load(), ("pkg", "pkg-secret"))
+
+    def test_broken_or_incomplete_file_falls_through(self):
+        self.write(self.home, "{not json")
+        self.assertIsNone(cred.load())
+        self.write(self.home, {"app_id": "home"})
+        self.write(self.package, {"app_id": "pkg", "app_secret": "pkg-secret"})
+        self.assertEqual(cred.load(), ("pkg", "pkg-secret"))
+
+    def test_every_script_reads_the_package_file(self):
+        self.write(self.package, {"app_id": "pkg", "app_secret": "pkg-secret"})
+        for module in (rule_check, fetch_table, sync_package):
+            with self.subTest(module=module.__name__):
+                self.assertEqual(module.load_credentials(), ("pkg", "pkg-secret"))
+        sent = {}
+
+        def post(url, json=None, timeout=None):
+            sent.update(json)
+            return types.SimpleNamespace(json=lambda: {"code": 0, "tenant_access_token": "t"})
+
+        with patch.object(audit, "requests", types.SimpleNamespace(post=post)):
+            self.assertEqual(audit.feishu_token(), "t")
+        self.assertEqual(sent, {"app_id": "pkg", "app_secret": "pkg-secret"})
+
+    def test_missing_credentials_stop_every_script_without_echoing_values(self):
+        self.write(self.home, {"app_id": "leak-me", "app_secret": ""})
+        for call in (rule_check.load_credentials, fetch_table.load_credentials,
+                     sync_package.load_credentials):
+            err = io.StringIO()
+            with self.subTest(call=call.__module__), contextlib.redirect_stderr(err), \
+                    self.assertRaises(SystemExit):
+                call()
+            self.assertNotIn("leak-me", err.getvalue())
+        with patch.object(audit, "requests", types.SimpleNamespace()), \
+                self.assertRaises(SystemExit) as raised:
+            audit.feishu_token()
+        self.assertNotIn("leak-me", str(raised.exception))
+
+
+class PackageZipTests(unittest.TestCase):
+    def setUp(self):
+        self.tmp = tempfile.TemporaryDirectory()
+        self.addCleanup(self.tmp.cleanup)
+        self.skill = os.path.join(self.tmp.name, "sku-audit")
+        os.makedirs(os.path.join(self.skill, "scripts"))
+        os.makedirs(os.path.join(self.skill, "references"))
+        for rel, text in (("scripts/audit.py", "# audit"),
+                          ("references/credentials.json", "{}"),
+                          ("credentials.json", '{"app_id": "pkg", "app_secret": "pkg-secret"}')):
+            with open(os.path.join(self.skill, rel), "w", encoding="utf-8") as f:
+                f.write(text)
+        self.out = os.path.join(self.tmp.name, "dist")
+
+    def names(self, path):
+        with zipfile.ZipFile(path) as z:
+            return set(z.namelist())
+
+    def test_default_package_leaves_credentials_out(self):
+        path = sync_package.make_zip(self.skill, self.out, "9.9")
+        names = self.names(path)
+        self.assertNotIn("sku-audit/credentials.json", names)
+        self.assertIn("sku-audit/scripts/audit.py", names)
+        self.assertIn("sku-audit/references/credentials.json", names)
+        self.assertNotIn("含凭证", os.path.basename(path))
+
+    def test_hosted_package_carries_credentials_and_is_named_apart(self):
+        path = sync_package.make_zip(self.skill, self.out, "9.9", with_credentials=True)
+        self.assertIn("sku-audit/credentials.json", self.names(path))
+        self.assertIn("含凭证", os.path.basename(path))
+
+    def test_hosted_package_requires_a_usable_credentials_file(self):
+        with open(os.path.join(self.skill, "credentials.json"), "w", encoding="utf-8") as f:
+            f.write('{"app_id": "pkg"}')
+        with contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit):
+            sync_package.make_zip(self.skill, self.out, "9.9", with_credentials=True)
+        self.assertFalse(os.path.isdir(self.out) and os.listdir(self.out))
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 17 - 2
安装说明.md

@@ -45,7 +45,7 @@ xcopy /E /I sku-audit %USERPROFILE%\.codebuddy\skills\sku-audit
 
 ## 配置凭证(必需)
 
-规则文档和多维表格都要读,需要一个有权限的飞书自建应用。二选一:
+规则文档和多维表格都要读,需要一个有权限的飞书自建应用。脚本按 A → B → C 的顺序取第一个可用来源:
 
 **方式 A:环境变量**
 
@@ -64,7 +64,22 @@ EOF
 chmod 600 ~/.sku_audit/credentials.json
 ```
 
-应用需要开通:云文档读取、多维表格读取、云空间附件下载。
+**方式 C:随技能包提供(托管沙箱,如 WorkBuddy Managed Agent)**
+
+控制台不能配置环境变量、沙箱用户目录也不由你管理时,把凭证文件放在技能包根目录(与 `SKILL.md` 同级),随包上传:
+
+```bash
+cat > credentials.json <<'EOF'
+{"app_id": "cli_xxxxx", "app_secret": "xxxxx"}
+EOF
+python3 scripts/sync_package.py --no-bump --with-credentials   # 生成「…-含凭证.zip」
+```
+
+- 这个文件已在 `.gitignore` 中,默认打包也不会带上;只有 `--with-credentials` 生成的包含凭证,只用于上传到托管沙箱,不外发。
+- 沙箱里的代理能读到这个文件。给托管沙箱单独建一个飞书应用,只开云文档只读权限,并只把规则文档共享给它;MCP 页面预审的图片和认证文件来自 MCP 返回的链接,不需要多维表格和附件权限。
+- 代理不得打开、打印或复制该文件,只通过脚本使用。
+
+应用需要开通:云文档读取、多维表格读取、云空间附件下载(方式 C 的专用应用只需云文档读取)。
 
 ## 依赖