AI 用法手册English

本地与私密 AI

上传云端前先脱敏:占位符替换、本地映射表、人工过目

验证情况

实测日期
2026-11-23
实测范围
redact.py / restore.py / leakcheck.py on made-up sample text only; no real documents, PDFs, images or cloud models
证据级别
在本机用模拟输入跑过,未用真实服务
状态
已发布
版本
0.1.0
更新时间
2026-12-05
来源提交
e16314b8c3
适用工具
python3 (standard library only) — the scripts below、any cloud chat/API model (the destination), or a local model (no redaction needed)
模型
未填
适合人群
creators、knowledge-workers、developers
国内可用性
可用
国内替代
keep the whole job local (see local-model-jetson-consumer-gpu, offline-lm-studio)、a data-masking tool or DLP feature your company already approves、manual redaction for short texts

范围说明: 这是「降低风险」的做法,不是匿名化保证。正则只认格式,认不出所有敏感信息;真正机密的内容请走本地模型。示例数据全部是虚构的。

口径:一位独立开发者的工作流。 目的地可以是任何云端模型(Kimi、GLM、Qwen、DeepSeek,或 Claude、GPT 等示例);脚本与厂商无关。提到 Claude:Anthropic 自 2026-11-12 起不支持中国大陆、香港、澳门(2026-11-23 核对),国内读者用国内模型即可。

场景

你会得到什么

步骤

  1. 先判断要不要上云: 用本篇下方的分级表。内容属于「机密」就别上传,改用本地。
  2. 列出人名清单 names.txt: 客户名、公司名、项目代号、内部系统名,每行一个。正则找不到名字,这一步只能靠你。
  3. 运行脱敏: python3 redact.py in.txt out.txt map.json names.txt。映射文件 map.json 以 600 权限写出(脚本会对已存在的文件也强制改成 600),只留在本机,别上传、别提交进仓库。
  4. 人工过目 out.txt: 通读一遍,找漏网的(地址、公司缩写、业务细节、截图里的文字)。必要时补进 names.txt 重跑。
  5. 上传 out.txt 给云端模型,提示里说明「方括号占位符是脱敏替换,请原样保留」。
  6. 还原: 把模型回复存成 ans.txt,python3 restore.py ans.txt map.json back.txt,在本机得到带原值的结果。
  7. 用完删除 map.json 和中间文件(或放在加密磁盘上)。

模板

分级表 / Classification table

| 级别 | 例子 | 处理 |
|---|---|---|
| 公开 | 已发布的文章、官方文档 | 可直接上云 |
| 内部 | 一般工作文档、不含个人信息的日志 | 脱敏后上云,或本地 |
| 敏感 | 含个人信息的客户数据、财务明细 | 只在本地;确需上云先问合规 |
| 机密 | 密钥、未公开的合同条款、受保密协议约束的内容 | 不上云,不贴给任何云端或第三方 AI;只允许在你自己控制的本机上用本地模型处理 |

redact.py

#!/usr/bin/env python3
"""Replace sensitive-looking strings with placeholders BEFORE text leaves your machine (single pass over the ORIGINAL text).
usage: redact.py in.txt out.txt map.json [names.txt]
- map.json stays local (mode 600) and is used by restore.py to put the originals back into the model's answer.
- names.txt: one name / company / project per line (regex can't find names by itself)."""
import json, os, re, sys

PATTERNS = [                       # alternation order = priority at the same position
    ("KEY",    r"\b(?:sk|pk|ghp|gho|xox[bp])[-_][A-Za-z0-9_-]{16,}\b"),
    ("EMAIL",  r"\b[\w.+-]+@[\w-]+(?:\.[\w-]+)+\b"),
    ("IDCARD", r"(?<!\d)\d{17}[\dXx](?!\d)"),                 # mainland-China 18-char resident ID shape
    ("PHONE",  r"(?<!\d)1[3-9]\d{9}(?!\d)"),                   # mainland-China mobile number shape
    ("CARD",   r"(?<!\d)\d{4}[ -]?\d{4}[ -]?\d{4}[ -]?\d{3,4}(?!\d)"),
    ("IP",     r"(?<!\d)(?:\d{1,3}\.){3}\d{1,3}(?!\d)"),
]
src, dst, mp = sys.argv[1:4]
names = sorted({l.strip() for l in open(sys.argv[4], encoding="utf-8") if l.strip()}, key=len, reverse=True) if len(sys.argv) > 4 else []
text = open(src, encoding="utf-8").read()
parts = [f"(?P<{k}>{p})" for k, p in PATTERNS]
if names: parts.append("(?P<NAME>" + "|".join(re.escape(n) for n in names) + ")")
rx = re.compile("|".join(parts), re.I if names else 0)
mapping, seen, counters = {}, {}, {}

def placeholder(kind):
    while True:                                      # never reuse a placeholder-shaped string that already occurs in the input
        counters[kind] = counters.get(kind, 0) + 1
        ph = f"[{kind}_{counters[kind]}]"
        if ph not in text and ph not in mapping: return ph

def rep(m):
    kind, v = m.lastgroup, m.group(0)
    key = (kind, v.lower() if kind == "NAME" else v)
    if key not in seen:
        ph = placeholder(kind); seen[key] = ph; mapping[ph] = v
    return seen[key]

out = rx.sub(rep, text)                              # one pass: placeholders are never re-scanned
open(dst, "w", encoding="utf-8").write(out)
fd = os.open(mp, os.O_WRONLY | os.O_CREAT, 0o600)
os.fchmod(fd, 0o600)                                 # open() keeps the mode of an EXISTING file, so force 600 before writing
os.ftruncate(fd, 0)
with os.fdopen(fd, "w", encoding="utf-8") as f: json.dump(mapping, f, ensure_ascii=False, indent=1)
kinds = {}
for ph in mapping: kinds[ph[1:ph.index("_")]] = kinds.get(ph[1:ph.index("_")], 0) + 1
print(f"{len(mapping)} distinct values replaced: " + ", ".join(f"{k}={v}" for k, v in kinds.items()))

restore.py

#!/usr/bin/env python3
"""usage: restore.py answer.txt map.json out.txt  — put originals back into the model's reply (local only; single pass)."""
import json, re, sys
t = open(sys.argv[1], encoding="utf-8").read(); m = json.load(open(sys.argv[2], encoding="utf-8"))
open(sys.argv[3], "w", encoding="utf-8").write(re.sub(r"\[[A-Z]+_\d+\]", lambda x: m.get(x.group(0), x.group(0)), t))

leakcheck.py(确认原值不在待上传文件里;失败时只打印占位符名称,不打印原值)

#!/usr/bin/env python3
"""usage: leakcheck.py redacted.txt map.json — exit 1 if any original value still appears in the redacted text (prints placeholder names only)."""
import json, sys
t = open(sys.argv[1], encoding="utf-8").read()
leaks = [ph for ph, v in json.load(open(sys.argv[2], encoding="utf-8")).items() if v in t]   # report placeholders, never the secret values
print(f"LEAK: {len(leaks)} original value(s) still present, for placeholders: {', '.join(leaks)}" if leaks else "no known originals left"); sys.exit(1 if leaks else 0)

失败案例

国内替代

安全提示

实测记录

验证

来源 / Sources

  • OWASP MCP Security Cheat Sheet (data exfiltration risks in tool use): https://cheatsheetseries.owasp.org/cheatsheets/MCP_Security_Cheat_Sheet.html
  • Anthropic Supported Regions Policy (checked 2026-11-23): https://www.anthropic.com/legal/supported-regions

来源链接

导出到你的 Agent

路径: redact-before-upload/SKILL.md

预览
---
name: redact-before-upload
description: "上传云端前先脱敏:占位符替换、本地映射表、人工过目(Redact before you upload: placeholders, a local mapping file, a human look)。当用户要做这件事时使用本手册。"
metadata:
  version: "0.1.0"
  status: "published"
  source-commit: "5f7272be13826bec473d6f2e073c82a5a620f1d2"
---

# 上传云端前先脱敏:占位符替换、本地映射表、人工过目

- 版本: 0.1.0
- 状态: published
- 实测日期: 2026-11-23
- 实测范围: redact.py / restore.py / leakcheck.py on made-up sample text only; no real documents, PDFs, images or cloud models
- 证据级别: local-simulated-test
- 来源提交: 5f7272be13826bec473d6f2e073c82a5a620f1d2

> 这是参考手册,仅在用户要求做这件事时参照;执行命令或不可逆操作前先问人。

## 中文

> **范围说明:** 这是「降低风险」的做法,**不是匿名化保证**。正则只认格式,认不出所有敏感信息;真正机密的内容请走本地模型。示例数据全部是虚构的。

> **口径:一位独立开发者的工作流。** 目的地可以是任何云端模型(Kimi、GLM、Qwen、DeepSeek,或 Claude、GPT 等示例);脚本与厂商无关。提到 Claude:Anthropic 自 2026-11-12 起不支持中国大陆、香港、澳门(2026-11-23 核对),国内读者用国内模型即可。

### 场景
- **适合谁:** 想用云端模型处理合同、客服记录、日志、客户表格,但里面夹带邮箱、手机号、证件号、密钥、内部 IP、客户名的人。
- **什么时候用:** 任务需要云端模型的能力,但原文里的**具体个人/客户信息对任务不重要**(例如「把这段客服对话归类」)。
- **不要用在:** 敏感信息本身就是任务对象(例如「核对这个人的身份证号」)——此时改用本地模型;受法律法规或合同禁止出境/外传的数据,先问合规,不要靠脱敏碰运气。

### 你会得到什么
- 一个本地脱敏脚本:把邮箱、手机号、身份证号形状的数字、银行卡号形状的数字、IP、常见密钥前缀、以及你列出的人名/公司名/项目名换成 `[EMAIL_1]` 这样的占位符;
- 一个只留在本机的映射文件,把模型回复里的占位符还原;
- 一份「上传前过目清单」。

### 步骤
1. **先判断要不要上云:** 用本篇下方的分级表。内容属于「机密」就别上传,改用本地。
2. **列出人名清单 `names.txt`:** 客户名、公司名、项目代号、内部系统名,每行一个。正则找不到名字,这一步只能靠你。
3. **运行脱敏:** `python3 redact.py in.txt out.txt map.json names.txt`。映射文件 `map.json` 以 600 权限写出(脚本会对已存在的文件也强制改成 600),**只留在本机,别上传、别提交进仓库**。
4. **人工过目 `out.txt`:** 通读一遍,找漏网的(地址、公司缩写、业务细节、截图里的文字)。必要时补进 `names.txt` 重跑。
5. **上传 `out.txt` 给云端模型**,提示里说明「方括号占位符是脱敏替换,请原样保留」。
6. **还原:** 把模型回复存成 `ans.txt`,`python3 restore.py ans.txt map.json back.txt`,在本机得到带原值的结果。
7. **用完删除 `map.json` 和中间文件**(或放在加密磁盘上)。

### 模板
**分级表 / Classification table**
```markdown
| 级别 | 例子 | 处理 |
|---|---|---|
| 公开 | 已发布的文章、官方文档 | 可直接上云 |
| 内部 | 一般工作文档、不含个人信息的日志 | 脱敏后上云,或本地 |
| 敏感 | 含个人信息的客户数据、财务明细 | 只在本地;确需上云先问合规 |
| 机密 | 密钥、未公开的合同条款、受保密协议约束的内容 | 不上云,不贴给任何云端或第三方 AI;只允许在你自己控制的本机上用本地模型处理 |
```

**`redact.py`**
```python
#!/usr/bin/env python3
"""Replace sensitive-looking strings with placeholders BEFORE text leaves your machine (single pass over the ORIGINAL text).
usage: redact.py in.txt out.txt map.json [names.txt]
- map.json stays local (mode 600) and is used by restore.py to put the originals back into the model's answer.
- names.txt: one name / company / project per line (regex can't find names by itself)."""
import json, os, re, sys

PATTERNS = [                       # alternation order = priority at the same position
    ("KEY",    r"\b(?:sk|pk|ghp|gho|xox[bp])[-_][A-Za-z0-9_-]{16,}\b"),
    ("EMAIL",  r"\b[\w.+-]+@[\w-]+(?:\.[\w-]+)+\b"),
    ("IDCARD", r"(?<!\d)\d{17}[\dXx](?!\d)"),                 # mainland-China 18-char resident ID shape
    ("PHONE",  r"(?<!\d)1[3-9]\d{9}(?!\d)"),                   # mainland-China mobile number shape
    ("CARD",   r"(?<!\d)\d{4}[ -]?\d{4}[ -]?\d{4}[ -]?\d{3,4}(?!\d)"),
    ("IP",     r"(?<!\d)(?:\d{1,3}\.){3}\d{1,3}(?!\d)"),
]
src, dst, mp = sys.argv[1:4]
names = sorted({l.strip() for l in open(sys.argv[4], encoding="utf-8") if l.strip()}, key=len, reverse=True) if len(sys.argv) > 4 else []
text = open(src, encoding="utf-8").read()
parts = [f"(?P<{k}>{p})" for k, p in PATTERNS]
if names: parts.append("(?P<NAME>" + "|".join(re.escape(n) for n in names) + ")")
rx = re.compile("|".join(parts), re.I if names else 0)
mapping, seen, counters = {}, {}, {}

def placeholder(kind):
    while True:                                      # never reuse a placeholder-shaped string that already occurs in the input
        counters[kind] = counters.get(kind, 0) + 1
        ph = f"[{kind}_{counters[kind]}]"
        if ph not in text and ph not in mapping: return ph

def rep(m):
    kind, v = m.lastgroup, m.group(0)
    key = (kind, v.lower() if kind == "NAME" else v)
    if key not in seen:
        ph = placeholder(kind); seen[key] = ph; mapping[ph] = v
    return seen[key]

out = rx.sub(rep, text)                              # one pass: placeholders are never re-scanned
open(dst, "w", encoding="utf-8").write(out)
fd = os.open(mp, os.O_WRONLY | os.O_CREAT, 0o600)
os.fchmod(fd, 0o600)                                 # open() keeps the mode of an EXISTING file, so force 600 before writing
os.ftruncate(fd, 0)
with os.fdopen(fd, "w", encoding="utf-8") as f: json.dump(mapping, f, ensure_ascii=False, indent=1)
kinds = {}
for ph in mapping: kinds[ph[1:ph.index("_")]] = kinds.get(ph[1:ph.index("_")], 0) + 1
print(f"{len(mapping)} distinct values replaced: " + ", ".join(f"{k}={v}" for k, v in kinds.items()))
```
**`restore.py`**
```python
#!/usr/bin/env python3
"""usage: restore.py answer.txt map.json out.txt  — put originals back into the model's reply (local only; single pass)."""
import json, re, sys
t = open(sys.argv[1], encoding="utf-8").read(); m = json.load(open(sys.argv[2], encoding="utf-8"))
open(sys.argv[3], "w", encoding="utf-8").write(re.sub(r"\[[A-Z]+_\d+\]", lambda x: m.get(x.group(0), x.group(0)), t))
```
**`leakcheck.py`**(确认原值不在待上传文件里;失败时只打印占位符名称,不打印原值)
```python
#!/usr/bin/env python3
"""usage: leakcheck.py redacted.txt map.json — exit 1 if any original value still appears in the redacted text (prints placeholder names only)."""
import json, sys
t = open(sys.argv[1], encoding="utf-8").read()
leaks = [ph for ph, v in json.load(open(sys.argv[2], encoding="utf-8")).items() if v in t]   # report placeholders, never the secret values
print(f"LEAK: {len(leaks)} original value(s) still present, for placeholders: {', '.join(leaks)}" if leaks else "no known originals left"); sys.exit(1 if leaks else 0)
```

### 失败案例
- **正则漏网(本机演示已发现的边界):** 只认格式。人名、地址、公司缩写、「那个大客户」这类描述都不会被替换,必须靠 `names.txt` 和人工过目。
- **误伤:** 16 位订单号、日期串可能被当成银行卡号;18 位数字可能是别的编号。所以要过目,并能用 `map.json` 看到换了什么。
- **映射文件泄露等于没脱敏:** `map.json` 里是全部原值。别上传、别进仓库、别发到聊天里。
- **模型改写了占位符:** 提示里要求「原样保留」,还原前检查占位符数量是否对得上。
- **其他格式:** 脚本只处理纯文本。PDF / 图片 / 表格要先转成文本,图片里的文字(截图)更要小心;本篇没有处理这些格式。

### 国内替代
- `china_availability: yes`:脚本只用本机标准库,无需任何境外服务。目的地模型用 Kimi / GLM / Qwen / DeepSeek 等国内服务即可;是否可以把某类数据交给某个服务,**以你的合同、公司规定和适用的法律法规为准**,本篇不构成合规意见。
- 本篇的身份证、手机号格式按中国大陆常见形状写,其他国家/地区的证件格式需要自己加规则。

### 安全提示
- **不要对「机密」级内容使用云端模型,脱敏也不行**(在你自己控制的本机上用本地模型处理是允许的)。
- 脱敏后的文本仍可能通过上下文被重新识别(组合推断);风险高时请用本地模型。
- 脚本和映射文件只在本机运行,**不要把真实映射文件提交进任何仓库**;仓库里只放示例。
- 不要把真实的密钥、证件号当作测试数据;用虚构数据(如本篇的示例)。

### 实测记录
- 2026-11-23,本机(WSL2 Linux、Python 3.8,仅标准库),用**虚构**样本文本验证:邮箱、手机号形状、18 位证件号形状、银行卡号形状、IPv4、`sk-` 前缀的假密钥、两个人名/项目名,共 8 个值被替换,重复出现的同一邮箱得到同一个占位符;`map.json` 权限为 600(预先存在的 644 文件也被改成 600);`leakcheck.py` 通过,对未脱敏文本会失败并只打印占位符名称、不打印原值;单次扫描替换:名单里含 `NAME` 且输入里已有 `[NAME_1]`、`[EMAIL_1]` 字样时,新生成的占位符会避开已有的,回填后与原文一致(姓名大小写以首次出现为准);`restore.py` 能把回复里的占位符还原。
- **未实测:** 真实文档;PDF/图片;中文地址与人名;任何云端模型对占位符的处理方式。

### 验证
- 在样本文本上跑一遍,核对 `out.txt` 里没有任何原值(`leakcheck.py` 通过 + 人工看)。
- 用真实任务前,先拿一份已经去掉真实信息的「像样的假文档」走完整流程。

## 来源 / Sources

- OWASP MCP Security Cheat Sheet (data exfiltration risks in tool use): https://cheatsheetseries.owasp.org/cheatsheets/MCP_Security_Cheat_Sheet.html
- Anthropic Supported Regions Policy (checked 2026-11-23): https://www.anthropic.com/legal/supported-regions