open-pushscan 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,160 @@
1
+ """`open-pushscan publish-check`: everything to look at before a private repository is made public."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import shutil
6
+ import subprocess
7
+
8
+ from . import config, gitscan, report, visibility
9
+ from .i18n import command, t
10
+ from .scanner import Scanner, gitleaks
11
+
12
+ TEXT = {
13
+ 'title': ('改公開前的檢查', 'Before making this repository public'),
14
+ 'step_history': ('1. 整段歷史({n} 個 commit)', '1. The whole history ({n} commits)'),
15
+ 'history_clean': (' 沒有發現問題', ' Nothing found'),
16
+ 'history_found': (' 找到 {n} 項,列在下面', ' {n} item(s) found, listed below'),
17
+ 'step_clean': ('2. 怎麼把歷史清乾淨', '2. How to clean the history'),
18
+ 'clean_none': (' 不用清', ' Nothing to clean'),
19
+ 'clean_how': (' 歷史裡已經有的,改掉最新的檔案還不夠,舊的 commit 一樣看得到。照下面做:\n'
20
+ ' (1) 安裝 git-filter-repo:pip install git-filter-repo\n'
21
+ ' (2) 在這個 repo 的一份新 clone 裡跑:\n{cmds}\n'
22
+ ' (3) 重要:改寫過歷史的 repo 不要直接改成公開。GitHub 會留著舊的 commit,知道編號就讀得到。\n'
23
+ ' 請另外開一個全新的公開 repo,把清好的歷史推上去;原本的私人 repo 改名留著或刪掉。',
24
+ ' Fixing the latest files is not enough: old commits still show it. Do this:\n'
25
+ ' (1) Install git-filter-repo: pip install git-filter-repo\n'
26
+ ' (2) In a fresh clone of this repository run:\n{cmds}\n'
27
+ ' (3) Important: do not just switch a rewritten repository to public. GitHub keeps the old commits,\n'
28
+ ' readable by anyone who knows their id. Create a brand-new public repository and push the\n'
29
+ ' cleaned history there; rename or delete the private one.'),
30
+ 'replace_file': (' 要替換的文字已經寫在:{path}(每一行一項,可以自己改)', ' The text to replace is listed in: {path} (one per line; edit as needed)'),
31
+ 'step_github': ('3. GitHub 上的其他地方', '3. Other places on GitHub'),
32
+ 'gh_missing': (' 沒有登入 gh(GitHub 的指令工具),請自己到網頁看:Release 附檔、issue 和 PR 的內文、wiki、有沒有人 fork',
33
+ ' gh (GitHub CLI) is not signed in; check these on the website: release files, issue and PR text, wiki, forks'),
34
+ 'gh_forks': (' fork:{n} 個(私人 repo 的 fork 在改公開時不會跟著公開,但先確認是誰的)', ' Forks: {n} (forks of a private repo stay private, but check whose they are)'),
35
+ 'gh_releases': (' Release:{n} 個,附檔 {files} 個,公開後都看得到,請確認內容', ' Releases: {n}, with {files} file(s); all become public, so check them'),
36
+ 'gh_text': (' issue 和 PR:看了 {n} 則', ' Issues and pull requests: {n} checked'),
37
+ 'gh_wiki': (' wiki 有內容,公開後也看得到,請自己看一次', ' The wiki has pages; they become public too, so read them once'),
38
+ 'step_files': ('4. 公開專案該有的檔案', '4. Files a public project should have'),
39
+ 'has': (' 有', ' yes'),
40
+ 'missing': (' 沒有', ' missing'),
41
+ 'license': ('授權(LICENSE):別人才知道能不能用你的程式', 'LICENSE: tells people whether they may use your code'),
42
+ 'readme': ('說明(README):別人第一眼看到的頁面', 'README: the first page people see'),
43
+ 'gitignore_env': ('.gitignore 有排除 .env', '.gitignore keeps .env out'),
44
+ 'done_ok': ('可以公開了。', 'Ready to go public.'),
45
+ 'done_fix': ('照上面處理完,再跑一次 {cmd} publish-check。', 'After handling the items above, run {cmd} publish-check again.'),
46
+ }
47
+
48
+
49
+ def tx(key, l, **kw):
50
+ zh, en = TEXT[key]
51
+ kw.setdefault('cmd', command())
52
+ return (zh if l == 'zh' else en).format(**kw)
53
+
54
+
55
+ def _gh(*args):
56
+ if not shutil.which('gh'):
57
+ return None
58
+ p = subprocess.run(['gh', *args], capture_output=True, timeout=60)
59
+ return p.stdout.decode('utf-8', 'replace') if p.returncode == 0 else None
60
+
61
+
62
+ def run(l: str) -> int:
63
+ top = gitscan.toplevel()
64
+ url = gitscan.remote_url()
65
+ key = config.repo_key(top, url)
66
+ scanner = Scanner(repo=key)
67
+ print(tx('title', l) + f':{top}' if l == 'zh' else tx('title', l) + f': {top}')
68
+ print()
69
+
70
+ changes = gitscan.commits(['--all']) if gitscan.has_head() else []
71
+ findings = []
72
+ for c in changes:
73
+ findings += scanner.scan_change(c, gitscan.blob, gitscan.size)
74
+ findings += gitleaks(['--all'])
75
+ findings, notes = report.split(findings)
76
+ items = report.group(findings)
77
+ report.save(key, items)
78
+ print(tx('step_history', l, n=len(changes)))
79
+ print(tx('history_found', l, n=len(items)) if items else tx('history_clean', l))
80
+ if notes:
81
+ print(report.render_notes(notes, l), end='')
82
+ print()
83
+
84
+ print(tx('step_clean', l))
85
+ text_items = [i for i in items if i['where'] in ('content', 'metadata', 'message', 'filename') and i['rule'] not in ('large-file',)]
86
+ file_items = sorted({i['path'] for i in items if i['rule'] in ('sensitive-file', 'ai-config', 'large-file') and i['path']})
87
+ if not items:
88
+ print(tx('clean_none', l))
89
+ else:
90
+ cmds = []
91
+ if text_items:
92
+ rp = config.path('state', f'replace-{key}.txt')
93
+ config.ensure()
94
+ with open(rp, 'w', encoding='utf-8') as f:
95
+ for i in text_items:
96
+ # notes written for an AI are simply removed; everything else becomes REDACTED
97
+ f.write(f"{i['text']}==>{'' if i['rule'] == 'ai-note' else 'REDACTED'}\n")
98
+ cmds.append(f' git filter-repo --replace-text "{rp}" --force')
99
+ if file_items:
100
+ cmds.append(' git filter-repo --invert-paths ' + ' '.join(f'--path "{p}"' for p in file_items) + ' --force')
101
+ if any(i['where'] in ('author', 'committer') for i in items):
102
+ cmds.append(' ' + ('(作者資訊)用 git filter-repo --mailmap 換成要公開的名字和 email' if l == 'zh'
103
+ else '(author details) use git filter-repo --mailmap to set the public name and email'))
104
+ print(tx('clean_how', l, cmds='\n'.join(cmds)))
105
+ if text_items:
106
+ print(tx('replace_file', l, path=config.path('state', f'replace-{key}.txt')))
107
+ print()
108
+
109
+ print(tx('step_github', l))
110
+ gh = visibility.github_repo(url) if url else None
111
+ github_findings = []
112
+ if gh and _gh('auth', 'status') is not None:
113
+ full = f'{gh[0]}/{gh[1]}'
114
+ info = _gh('api', f'repos/{full}')
115
+ if info:
116
+ data = json.loads(info)
117
+ print(tx('gh_forks', l, n=data.get('forks_count', 0)))
118
+ if data.get('has_wiki'):
119
+ wiki = subprocess.run(['git', 'ls-remote', f'https://github.com/{full}.wiki.git'], capture_output=True)
120
+ if wiki.returncode == 0 and wiki.stdout.strip():
121
+ print(tx('gh_wiki', l))
122
+ rel = _gh('api', f'repos/{full}/releases', '--paginate')
123
+ if rel:
124
+ releases = json.loads(rel) if rel.strip().startswith('[') else []
125
+ print(tx('gh_releases', l, n=len(releases), files=sum(len(r.get('assets', [])) for r in releases)))
126
+ for r in releases:
127
+ github_findings += scanner.scan_text(r.get('body') or '', 'content', f"Release {r.get('tag_name')}", 0)
128
+ n = 0
129
+ for kind in ('issue', 'pr'):
130
+ out = _gh(kind, 'list', '-R', full, '--state', 'all', '--limit', '200', '--json', 'number,title,body')
131
+ for it in json.loads(out) if out else []:
132
+ n += 1
133
+ where = f"{'Issue' if kind == 'issue' else 'PR'} #{it.get('number')}"
134
+ for part in (it.get('title') or '', it.get('body') or ''):
135
+ for ln, line in enumerate(part.splitlines(), 1):
136
+ github_findings += scanner.scan_text(line, 'content', where, ln)
137
+ print(tx('gh_text', l, n=n))
138
+ else:
139
+ print(tx('gh_missing', l))
140
+ print()
141
+
142
+ print(tx('step_files', l))
143
+ tree = gitscan.git('ls-tree', '--name-only', 'HEAD', check=False) if gitscan.has_head() else ''
144
+ lower = {n.lower() for n in tree.split('\n') if n}
145
+ checks = [
146
+ ('license', any(n.startswith(('license', 'licence', 'copying')) for n in lower)),
147
+ ('readme', any(n.startswith('readme') for n in lower)),
148
+ ]
149
+ ignore = gitscan.git('show', 'HEAD:.gitignore', check=False) if '.gitignore' in lower else ''
150
+ checks.append(('gitignore_env', '.env' in ignore))
151
+ for k, ok in checks:
152
+ print(f" {'✓' if ok else '✗'} {tx(k, l)}")
153
+ print()
154
+
155
+ all_items = report.group(findings + report.split(github_findings)[0])
156
+ if all_items:
157
+ report.save(key, all_items)
158
+ print(report.render(all_items, t('check_found', l, n=len(all_items)), [t('foot_allow_any', l)], l, limit=200))
159
+ print(tx('done_fix', l) if all_items or not all(ok for _, ok in checks[:2]) else tx('done_ok', l))
160
+ return 1 if all_items else 0
@@ -0,0 +1,130 @@
1
+ """Turn findings into a short report people can act on, and remember it for `open-pushscan allow N`."""
2
+ from __future__ import annotations
3
+
4
+ from . import config
5
+ from .fingerprints import label_text
6
+ from .i18n import t
7
+ from .rules import CATEGORIES, RULES
8
+ from .scanner import SECRET_RULES
9
+
10
+ SHOW_MAX = 20
11
+
12
+
13
+ def group(findings: list) -> list:
14
+ """One item per (rule, text); later places are counted, not repeated. File contents come first."""
15
+ from .scanner import ORDER
16
+ items, index = [], {}
17
+ for f in sorted(findings, key=lambda f: ORDER.get(f.where, 9)):
18
+ key = (f.rule, f.text)
19
+ if key in index:
20
+ items[index[key]]['others'] += 1
21
+ continue
22
+ index[key] = len(items)
23
+ d = f.to_dict()
24
+ d['others'] = 0
25
+ items.append(d)
26
+ for n, d in enumerate(items, 1):
27
+ d['n'] = n
28
+ return items
29
+
30
+
31
+ def split(findings: list) -> tuple:
32
+ """(findings, reminders): lines skipped with "open-pushscan: allow" are only reminders, never stop anything."""
33
+ return [f for f in findings if f.rule != 'inline-allow'], [f for f in findings if f.rule == 'inline-allow']
34
+
35
+
36
+ def render_notes(notes: list, l: str) -> str:
37
+ rows = []
38
+ for f in notes:
39
+ row = f" {_where(f.to_dict(), l)}{':' if l == 'zh' else ': '}{f.text if len(f.text) <= 100 else f.text[:97] + '…'}"
40
+ if row not in rows:
41
+ rows.append(row)
42
+ if not rows:
43
+ return ''
44
+ more = [t('more', l, n=len(rows) - SHOW_MAX)] if len(rows) > SHOW_MAX else []
45
+ return '\n'.join([t('notes', l, n=len(rows))] + rows[:SHOW_MAX] + more) + '\n'
46
+
47
+
48
+ def _shown(item: dict) -> str:
49
+ text = item['text']
50
+ if item['rule'] in SECRET_RULES and len(text) > 10:
51
+ return text[:4] + '…' + text[-2:]
52
+ return text if len(text) <= 160 else text[:157] + '…'
53
+
54
+
55
+ def _detail(item: dict, l: str) -> str:
56
+ rule, detail = item['rule'], item.get('detail') or ''
57
+ if rule == 'fingerprint':
58
+ return label_text(detail, l)
59
+ if rule == 'commit-identity':
60
+ if detail in ('fingerprint',) or detail in ('host', 'domain', 'account', 'home', 'ip', 'tailscale', 'ssh', 'email', 'added'):
61
+ what = label_text(detail, l) if detail != 'email' else ('個人 email' if l == 'zh' else 'a personal email')
62
+ elif detail in RULES:
63
+ what = RULES[detail].title[l]
64
+ else:
65
+ what = detail
66
+ return t('contains', l, what=what)
67
+ if rule in ('team', 'personal') and detail and detail.lower() != item['text'].lower():
68
+ return detail
69
+ if rule == 'gitleaks':
70
+ return detail
71
+ return ''
72
+
73
+
74
+ def _where(item: dict, l: str) -> str:
75
+ w = item['where']
76
+ if w == 'content':
77
+ s = t('line', l, path=item['path'], line=item['line'])
78
+ elif w in ('filename', 'file', 'metadata'):
79
+ s = t(w, l, path=item['path'])
80
+ else:
81
+ s = t(w, l)
82
+ if item.get('commit'):
83
+ s += t('in_commit', l, sha=item['commit'])
84
+ return s
85
+
86
+
87
+ def brief(item: dict, l: str) -> list:
88
+ """The first two lines of an item: number, place and what it is; then the text found."""
89
+ rule = RULES.get(item['rule'])
90
+ title = rule.title[l] if rule else item['rule']
91
+ extra = _detail(item, l)
92
+ if extra:
93
+ title += f'({extra})' if l == 'zh' else f' ({extra})'
94
+ head = f"{item['n']}. {_where(item, l)}|{title}" if l == 'zh' else f"{item['n']}. {_where(item, l)} | {title}"
95
+ return [head, f' {_shown(item)}']
96
+
97
+
98
+ def render(items: list, header: str, footer: list, l: str, limit: int = SHOW_MAX) -> str:
99
+ out = [header, '']
100
+ explained = {}
101
+ for item in items[:limit]:
102
+ rule = RULES.get(item['rule'])
103
+ out += brief(item, l)
104
+ if rule and rule.id in explained:
105
+ out.append(' ' + t('same_as', l, n=explained[rule.id]))
106
+ elif rule:
107
+ explained[rule.id] = item['n']
108
+ out.append(f" {t('why', l)}:{rule.why[l]}" if l == 'zh' else f" {t('why', l)}: {rule.why[l]}")
109
+ out.append(f" {t('fix', l)}:{rule.fix[l]}" if l == 'zh' else f" {t('fix', l)}: {rule.fix[l]}")
110
+ if item.get('others'):
111
+ out.append(' ' + t('also', l, n=item['others']))
112
+ out.append('')
113
+ if len(items) > limit:
114
+ out.append(t('more', l, n=len(items) - limit))
115
+ out.append('')
116
+ out += footer
117
+ return '\n'.join(out).rstrip() + '\n'
118
+
119
+
120
+ def save(repo: str, items: list) -> None:
121
+ config.save_report(repo, items)
122
+
123
+
124
+ def category_counts(items: list, l: str) -> dict:
125
+ counts = {}
126
+ for item in items:
127
+ rule = RULES.get(item['rule'])
128
+ cat = CATEGORIES[rule.category][l] if rule else item['rule']
129
+ counts[cat] = counts.get(cat, 0) + 1
130
+ return counts
open_pushscan/rules.py ADDED
@@ -0,0 +1,277 @@
1
+ """All checks: what each rule looks for, and the words shown to people (why it matters, how to fix it).
2
+
3
+ A rule's text is written for someone new to programming: short, plain, and always with a next step.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ import math
8
+ import re
9
+ from dataclasses import dataclass
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class Rule:
14
+ id: str
15
+ category: str # see CATEGORIES
16
+ title: dict # {'zh': ..., 'en': ...}
17
+ why: dict
18
+ fix: dict
19
+
20
+
21
+ CATEGORIES = {
22
+ 'fingerprint': {'zh': '你的電腦指紋', 'en': 'Your computer'},
23
+ 'team': {'zh': '團隊規則', 'en': 'Team rules'},
24
+ 'personal': {'zh': '你的自訂規則', 'en': 'Your own rules'},
25
+ 'network': {'zh': '內部網路', 'en': 'Private network'},
26
+ 'path': {'zh': '本機路徑', 'en': 'Local path'},
27
+ 'pii': {'zh': '個人資料', 'en': 'Personal data'},
28
+ 'secret': {'zh': '密碼與金鑰', 'en': 'Passwords and keys'},
29
+ 'file': {'zh': '敏感檔案', 'en': 'Sensitive file'},
30
+ 'commit': {'zh': 'commit 資訊', 'en': 'Commit details'},
31
+ 'media': {'zh': '檔案裡藏的資訊', 'en': 'Hidden file details'},
32
+ 'ai': {'zh': 'AI 工具痕跡', 'en': 'AI tool traces'},
33
+ }
34
+
35
+
36
+ def _r(id, category, title_zh, title_en, why_zh, why_en, fix_zh, fix_en):
37
+ return Rule(id, category, {'zh': title_zh, 'en': title_en}, {'zh': why_zh, 'en': why_en}, {'zh': fix_zh, 'en': fix_en})
38
+
39
+
40
+ RULES = {r.id: r for r in [
41
+ # ---- fingerprints, team, personal (patterns come from the computer or from files) ----
42
+ _r('fingerprint', 'fingerprint', '你的電腦指紋', 'Something that identifies your computer',
43
+ '這是從你電腦上找到的名稱或位址(主機名稱、帳號、內網位址等),公開出去別人就知道你用哪台電腦、在哪個網路',
44
+ 'This name or address was found on your computer (host name, account, private address…). Made public, it tells people which computer and network you use',
45
+ '換成一般的寫法,例如「my-server」「localhost」,或直接拿掉',
46
+ 'Replace it with something generic such as "my-server" or "localhost", or remove it'),
47
+ _r('team', 'team', '團隊規則裡的名稱', 'A name from your team rules',
48
+ '你的團隊把這個名稱列為不能公開(單位、專案、客戶或內部網域)',
49
+ 'Your team listed this name as not public (organisation, project, client or internal domain)',
50
+ '拿掉或換成一般的說法', 'Remove it or use a generic word instead'),
51
+ _r('personal', 'personal', '你的自訂規則', 'Matches one of your own rules',
52
+ '你自己把這個寫法列為不能公開', 'You listed this as not public',
53
+ '拿掉或換成一般的說法', 'Remove it or use a generic word instead'),
54
+ # ---- network ----
55
+ _r('private-ip', 'network', '內部網路位址', 'Private network address',
56
+ '這是家裡或公司內部的網路位址(包括 Tailscale 的 100.x),公開後別人知道你的網路怎麼配置',
57
+ 'This is an address inside a home or company network (including Tailscale 100.x). It shows how your network is laid out',
58
+ '換成 127.0.0.1、localhost,或文件用的範例位址 192.0.2.10',
59
+ 'Use 127.0.0.1, localhost, or the documentation example address 192.0.2.10'),
60
+ _r('private-ipv6', 'network', '內部網路位址(IPv6)', 'Private network address (IPv6)',
61
+ '這是內部網路用的 IPv6 位址', 'This IPv6 address is only used inside a private network',
62
+ '換成 ::1 或文件用的範例位址 2001:db8::1', 'Use ::1 or the documentation example address 2001:db8::1'),
63
+ _r('internal-host', 'network', '內部主機名稱', 'Internal host name',
64
+ '這個網址只在你的內部網路或 Tailscale 裡用得到,公開後別人知道你的機器叫什麼',
65
+ 'This address only works inside your own network or Tailscale; it names your machines',
66
+ '換成 example.com 或 localhost', 'Use example.com or localhost'),
67
+ _r('mac-address', 'network', '網卡硬體位址(MAC)', 'Hardware (MAC) address',
68
+ 'MAC 位址可以認出是哪一台裝置', 'A MAC address identifies one particular device',
69
+ '換成 00:00:00:00:00:00 這種範例值', 'Use an example value such as 00:00:00:00:00:00'),
70
+ # ---- path ----
71
+ _r('local-path', 'path', '你的電腦帳號資料夾', 'Your account folder on this computer',
72
+ '路徑裡有你的帳號名稱和資料夾結構,別人看得到', 'The path shows your account name and how your folders are laid out',
73
+ '改成相對路徑,或用 ~ 代替家目錄', 'Use a relative path, or ~ for the home folder'),
74
+ # ---- personal data ----
75
+ _r('email', 'pii', '個人 email', 'Personal email address',
76
+ '公開後會被收集去寄垃圾信,也可能被認出是你', 'Once public it gets collected for spam and can be traced back to you',
77
+ '換成 you@example.com;commit 用的 email 可以改成 GitHub 給的隱藏 email(設定 > Emails)',
78
+ 'Use you@example.com; for commits, use the private email GitHub gives you (Settings > Emails)'),
79
+ _r('tw-id', 'pii', '身分證或居留證號碼', 'Taiwan ID or residence permit number',
80
+ '這是可以認出一個人的證件號碼', 'This ID number identifies a person',
81
+ '馬上拿掉;測試資料請用假的號碼', 'Remove it now; use made-up numbers in test data'),
82
+ _r('tw-mobile', 'pii', '手機號碼', 'Mobile phone number',
83
+ '公開後可能被拿去騷擾或詐騙', 'Once public it can be used for spam calls or scams',
84
+ '換成 0900-000-000 這種假號碼', 'Use a fake number such as 0900-000-000'),
85
+ # ---- secrets ----
86
+ _r('private-key', 'secret', '私鑰', 'Private key',
87
+ '有了私鑰就能冒用你登入伺服器或簽章', 'With this key anyone can log in or sign as you',
88
+ '從檔案拿掉,並立刻換一把新的金鑰(舊的要當作已經外洩)', 'Remove it and create a new key right away; treat the old one as leaked'),
89
+ _r('api-key', 'secret', 'API 金鑰或 token', 'API key or token',
90
+ '別人拿到就能用你的帳號、花你的錢', 'Anyone holding it can use your account and spend your money',
91
+ '改用環境變數或 .env 檔(記得把 .env 加進 .gitignore),並到服務網站撤銷這把金鑰、換新的',
92
+ 'Read it from an environment variable or a .env file (add .env to .gitignore), then revoke the key on the service and make a new one'),
93
+ _r('password', 'secret', '寫死的密碼', 'Password written in the code',
94
+ '密碼公開後,任何人都能登入', 'Once public, anyone can log in with it',
95
+ '改用環境變數或 .env 檔,並把密碼換掉', 'Read it from an environment variable or a .env file, and change the password'),
96
+ _r('url-credentials', 'secret', '網址裡帶著帳號密碼', 'User name and password inside a URL',
97
+ '網址裡的帳號密碼公開後,任何人都能登入', 'Anyone can log in with the user name and password in this URL',
98
+ '把帳號密碼拿出網址,改用環境變數', 'Take the user name and password out of the URL and read them from environment variables'),
99
+ _r('webhook', 'secret', 'Webhook 網址', 'Webhook URL',
100
+ '有了這個網址,任何人都能往你的頻道發訊息', 'Anyone with this URL can post to your channel',
101
+ '改用環境變數,並到 Discord/Slack 重新產生一個網址', 'Read it from an environment variable and create a new URL in Discord/Slack'),
102
+ _r('high-entropy', 'secret', '看起來像金鑰的字串', 'Something that looks like a key',
103
+ '這個值很長又像亂碼,又放在 key、token、secret 這類名稱後面,很可能是真的金鑰',
104
+ 'This long random-looking value is assigned to a name like key, token or secret, so it is probably a real key',
105
+ '如果是真的金鑰,改用環境變數並換一把新的;如果只是範例,改成 your-key-here',
106
+ 'If it is a real key, read it from an environment variable and replace it; if it is an example, write your-key-here'),
107
+ _r('gitleaks', 'secret', 'gitleaks 找到的金鑰', 'Secret found by gitleaks',
108
+ 'gitleaks 判斷這裡有金鑰或密碼', 'gitleaks thinks this is a key or password',
109
+ '改用環境變數,並到服務網站撤銷、換新', 'Read it from an environment variable, then revoke it and make a new one'),
110
+ # ---- files ----
111
+ _r('sensitive-file', 'file', '不該公開的檔案', 'A file that should not be public',
112
+ '這種檔案通常裝著密碼、金鑰或登入資訊', 'Files like this usually hold passwords, keys or login details',
113
+ '把它移出 repo,檔名加進 .gitignore;已經 commit 的用 git rm --cached 檔名',
114
+ 'Move it out of the repo and add its name to .gitignore; if already committed, run git rm --cached <file>'),
115
+ _r('large-file', 'file', '很大的檔案', 'Very large file',
116
+ '大檔案會讓 repo 變慢、難以下載,GitHub 超過 100 MB 會直接拒收;也常常是不小心放進來的資料或模型',
117
+ 'Large files slow the repo down and GitHub refuses anything over 100 MB; they are often data or models added by accident',
118
+ '改放到 GitHub Release、雲端硬碟,或用 Git LFS', 'Put it in a GitHub Release or cloud storage, or use Git LFS'),
119
+ # ---- commit details ----
120
+ _r('commit-identity', 'commit', 'commit 的作者資訊', 'Commit author details',
121
+ 'commit 的作者名字和 email 會跟著公開,每個人都看得到', 'The author name and email of every commit are public',
122
+ '用 git config --global user.name 和 user.email 改成要公開的名字和 GitHub 的隱藏 email,再重做這個 commit(git commit --amend --reset-author)',
123
+ 'Set the name and the private GitHub email you want public with git config --global user.name / user.email, then redo the commit (git commit --amend --reset-author)'),
124
+ _r('commit-message', 'commit', 'commit 訊息', 'Commit message',
125
+ 'commit 訊息會跟著公開', 'Commit messages are public',
126
+ '用 git commit --amend 改訊息(已經推出去的要改寫歷史)', 'Edit it with git commit --amend (already pushed messages need a history rewrite)'),
127
+ # ---- hidden file details ----
128
+ _r('media-gps', 'media', '照片裡的 GPS 位置', 'GPS location inside a photo',
129
+ '照片裡記著拍攝地點,可能是你家或公司', 'The photo records where it was taken, which may be your home or office',
130
+ '用相簿的「移除位置資訊」或修圖軟體另存一份不含位置的照片', 'Save a copy without location (most photo apps have "remove location")'),
131
+ _r('media-owner', 'media', '照片裡的擁有者或序號', 'Owner name or serial number inside a photo',
132
+ '照片記著相機擁有者、作者或機身序號', 'The photo records the camera owner, author or serial number',
133
+ '用修圖軟體另存一份,不要保留中繼資料(metadata)', 'Save a copy without metadata'),
134
+ _r('media-device', 'media', '照片裡的相機或手機型號', 'Camera or phone model inside a photo',
135
+ '照片記著是用哪支手機或相機拍的', 'The photo records which phone or camera took it',
136
+ '不在意可以放行;要拿掉就另存一份不含中繼資料的照片', 'Fine to allow if you do not mind; otherwise save a copy without metadata'),
137
+ _r('media-text', 'media', '圖片裡夾帶的文字', 'Text hidden inside an image',
138
+ 'PNG 圖片可以夾帶文字(作者、說明、AI 繪圖的提示詞等),看圖片時看不到', 'PNG files can carry hidden text (author, comments, AI image prompts) that you do not see in the picture',
139
+ '用修圖軟體另存一份,不要保留中繼資料', 'Save a copy without metadata'),
140
+ _r('document-author', 'media', '文件裡的作者資訊', 'Author details inside a document',
141
+ 'Word、Excel、PowerPoint、PDF 會記著作者、最後修改的人和公司名稱', 'Word, Excel, PowerPoint and PDF files record the author, last editor and company',
142
+ '在 Office 用「檢查文件」移除個人資訊,PDF 另存時不保留文件資訊', 'In Office use "Inspect Document" to remove personal info; for PDF, save without document properties'),
143
+ # ---- AI traces ----
144
+ _r('ai-config', 'ai', 'AI 工具的設定檔', 'AI tool settings file',
145
+ '這類檔案是給 AI 工具看的筆記,常寫著機器名稱、內部流程和私人習慣', 'These notes are for AI tools and often mention machine names, internal steps and private habits',
146
+ '留在你的電腦上就好:git rm --cached 檔名,再把檔名寫進 .git/info/exclude(這個檔不會被推上去)',
147
+ 'Keep it on your computer only: git rm --cached <file>, then list it in .git/info/exclude (that file is never pushed)'),
148
+ _r('ai-signature', 'ai', 'AI 工具的署名', 'AI tool signature',
149
+ 'commit 訊息裡註明了 AI 工具或共同作者是 AI', 'The commit message credits an AI tool',
150
+ '用 git commit --amend 拿掉那一行;也可以在 AI 工具的設定裡關掉自動署名', 'Remove the line with git commit --amend; most AI tools can stop adding it in their settings'),
151
+ _r('ai-note', 'ai', '寫給 AI 看的決策註記', 'A note written for an AI assistant',
152
+ '把作者寫成「使用者」(例如「使用者決定」「the user picked」),一看就知道是 AI 工具幫忙寫的紀錄', # open-pushscan: allow
153
+ 'The author is called "the user" ("the user picked…"), which reads like an AI assistant\'s log', # open-pushscan: allow
154
+ '直接寫內容,不寫是誰決定的', 'Just state the content, not who decided it'),
155
+ ]}
156
+
157
+
158
+ # ---------------------------------------------------------------- text rules
159
+
160
+ def _tw_id_ok(s: str) -> bool:
161
+ """Checksum of a Taiwan ID / residence permit number (A123456789, A800000014).""" # open-pushscan: allow
162
+ letters = 'ABCDEFGHJKLMNPQRSTUVXYWZIO'
163
+ s = s.upper()
164
+ if len(s) != 10 or s[0] not in letters or not s[1:].isdigit():
165
+ return False
166
+ code = letters.index(s[0]) + 10
167
+ digits = [code // 10, code % 10] + [int(c) for c in s[1:]]
168
+ weights = [1, 9, 8, 7, 6, 5, 4, 3, 2, 1, 1]
169
+ return sum(d * w for d, w in zip(digits, weights)) % 10 == 0
170
+
171
+
172
+ def _not_example_mac(s: str) -> bool:
173
+ v = re.sub(r'[:-]', '', s.lower())
174
+ return v not in ('000000000000', 'ffffffffffff', '001122334455', 'aabbccddeeff', '0123456789ab', '112233445566')
175
+
176
+
177
+ def _host_ip(s: str) -> bool:
178
+ """A network (x.x.x.0) or broadcast (x.x.x.255) address names no machine."""
179
+ return not s.endswith(('.0', '.255'))
180
+
181
+
182
+ def _entropy(s: str) -> float:
183
+ counts = {}
184
+ for ch in s:
185
+ counts[ch] = counts.get(ch, 0) + 1
186
+ return -sum(c / len(s) * math.log2(c / len(s)) for c in counts.values())
187
+
188
+
189
+ def _looks_random(value: str) -> bool:
190
+ if len(value) < 20 or ' ' in value:
191
+ return False
192
+ kinds = sum(bool(re.search(p, value)) for p in (r'[a-z]', r'[A-Z]', r'\d'))
193
+ return kinds >= 2 and _entropy(value) >= 3.8
194
+
195
+
196
+ # (rule id, regex, group to report or 0, validator or None). Text rules run on file contents and commit messages.
197
+ TEXT_RULES = [
198
+ ('private-ip', re.compile(r'(?<![\d.])(?:10\.\d{1,3}\.\d{1,3}\.\d{1,3}|172\.(?:1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3}'
199
+ r'|192\.168\.\d{1,3}\.\d{1,3}|100\.(?:6[4-9]|[7-9]\d|1[01]\d|12[0-7])\.\d{1,3}\.\d{1,3}'
200
+ r')(?![\d.]*\d)'), 0, _host_ip),
201
+ ('private-ipv6', re.compile(r'(?i)(?<![0-9a-f:])f[cd][0-9a-f]{2}(?::[0-9a-f]{0,4}){2,7}(?![0-9a-f:])'), 0, None),
202
+ ('internal-host', re.compile(r'(?i)\b[a-z0-9-]+\.(?:tail[0-9a-f]{6}|[a-z]+-[a-z]+)\.ts\.net\b'), 0, None),
203
+ ('internal-host', re.compile(r'(?i)(?:(?<=://)|(?<=@))[a-z0-9.-]+\.(?:local|internal|lan|corp|intranet|home\.arpa)\b'), 0, None),
204
+ ('mac-address', re.compile(r'(?i)(?<![0-9a-f:-])(?:[0-9a-f]{2}[:-]){5}[0-9a-f]{2}(?![0-9a-f:-])'), 0, _not_example_mac),
205
+ ('local-path', re.compile(r'/home/[A-Za-z_][\w.-]*/|/Users/[A-Za-z][\w.-]*/|[A-Za-z]:(?:\\{1,2}|/)Users(?:\\{1,2}|/)[^\\/\s"\'<>|*?]+'), 0, None),
206
+ ('email', re.compile(r'[\w.+-]+@[\w-]+(?:\.[\w-]+)*\.[A-Za-z]{2,}\b'), 0, None),
207
+ ('tw-id', re.compile(r'(?<![A-Za-z0-9])[A-Za-z][1289]\d{8}(?![A-Za-z0-9])'), 0, _tw_id_ok),
208
+ ('tw-mobile', re.compile(r'(?<![\d+])(?:\+886[- ]?|0)9\d{2}[- ]?\d{3}[- ]?\d{3}(?!\d)'), 0, None),
209
+ ('private-key', re.compile(r'-----BEGIN [A-Z ]*PRIVATE KEY-----'), 0, None),
210
+ ('api-key', re.compile(r'\b(?:AKIA[0-9A-Z]{16}|gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{40,}|AIza[0-9A-Za-z_-]{35}'
211
+ r'|sk-(?:ant-|proj-)?[A-Za-z0-9_-]{20,}|xox[abprs]-[A-Za-z0-9-]{10,}|[sr]k_live_[0-9A-Za-z]{20,}'
212
+ r'|hf_[A-Za-z0-9]{30,}|npm_[A-Za-z0-9]{36}|pypi-AgEIcHlwaS5vcmc[A-Za-z0-9_-]{50,}|glpat-[A-Za-z0-9_-]{20,})\b'), 0, None),
213
+ ('api-key', re.compile(r'\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}'), 0, None),
214
+ ('api-key', re.compile(r'(?<![\d:])\d{8,10}:AA[A-Za-z0-9_-]{33}\b'), 0, None),
215
+ ('webhook', re.compile(r'https://(?:discord(?:app)?\.com/api/webhooks/\d+/[\w-]+|hooks\.slack\.com/services/[\w/]+)'), 0, None),
216
+ ('url-credentials', re.compile(r'(?i)\b[a-z][a-z0-9+.-]*://[^\s/:@"\'<>]+:([^\s/@"\'<>]{3,})@[\w.-]+'), 0, None),
217
+ ('password', re.compile(r'(?i)\b(?:password|passwd|pwd|secret|api_?key|access_?key|auth_?token|token)\b\s*[:=]\s*["\']([^"\'\s]{6,})["\']'), 0, None),
218
+ ('high-entropy', re.compile(r'(?i)\b[\w.-]*(?:key|secret|token|passw(?:or)?d|credential|auth)[\w.-]*\b\s*[:=]\s*["\']([A-Za-z0-9+/=_.-]{20,})["\']'), 1, _looks_random),
219
+ ('high-entropy', re.compile(r'^\s*(?:export\s+)?[A-Z0-9_]*(?:KEY|SECRET|TOKEN|PASSWORD|PASSWD|CREDENTIAL|AUTH)[A-Z0-9_]*\s*=\s*([A-Za-z0-9+/=_.-]{20,})\s*$'), 1, _looks_random),
220
+ ]
221
+
222
+ # Things that are clearly examples or public, so a match on them is not reported.
223
+ BUILTIN_ALLOW = [re.compile(p) for p in [
224
+ r'[\w.+-]+@users\.noreply\.github\.com', r'noreply@[\w.-]+', r'[\w.+-]+@(?:example|test|localhost)\.(?:com|org|net|local)?',
225
+ r'[\w.+-]+@example\.(?:com|org|net)', r'(?i)git@[\w.-]+', r'[\w.+-]+@localhost',
226
+ r'/home/(?:user|you|me|runner|username|yourname|name|example|ubuntu|vscode|codespace)/',
227
+ r'/Users/(?:user|you|me|runner|username|yourname|name|example|Shared)/',
228
+ r'(?i)[A-Za-z]:(?:\\{1,2}|/)Users(?:\\{1,2}|/)(?:user|you|me|username|yourname|name|example|runneradmin|Public|Default|你|<[^>]*>)',
229
+ r'(?i).*\b(?:change-?me|your[_-]?\w*|example|placeholder|xxx+|dummy|sample|fake|redacted|test[_-]\w+|\*{3,})\b.*',
230
+ r'0900[- ]?000[- ]?000', r'(?i)[a-z][12]23456789',
231
+ ]]
232
+
233
+ # A file whose path matches is not looked at (lock files hold other people's package data).
234
+ SKIP_PATHS = re.compile(r'(?:^|/)(?:package-lock\.json|yarn\.lock|pnpm-lock\.yaml|go\.sum|Cargo\.lock|poetry\.lock|uv\.lock|Pipfile\.lock'
235
+ r'|composer\.lock|Gemfile\.lock|tokenizer\.json|vocab\.(?:json|txt)|merges\.txt|[\w.-]+\.vocab)$')
236
+
237
+ # Rules that are relaxed in some files: version numbers in dependency lists look like addresses; licences and
238
+ # third-party notices carry public contact addresses; example config files hold made-up addresses.
239
+ DEPENDENCY_FILES = re.compile(r'(?i)(?:^|/)(?:requirements[\w.-]*\.txt|environment[\w.-]*\.ya?ml|constraints[\w.-]*\.txt|Pipfile|setup\.cfg)$')
240
+ LEGAL_FILES = re.compile(r'(?i)(?:^|/)(?:LICEN[CS]E|COPYING|NOTICE|AUTHORS|CONTRIBUTORS|THIRD[_-]PARTY|USE[_-]POLICY|CODE[_-]OF[_-]CONDUCT)[\w.-]*$')
241
+ EXAMPLE_FILES = re.compile(r'(?i)(?:\.(?:example|sample|template|dist|tmpl)$|(?:^|/)examples?/)')
242
+ ROLE_EMAIL = re.compile(r'(?i)^(?:support|info|contact|help|hello|admin|webmaster|security|privacy|legal|abuse|press|sales|team|'
243
+ r'feedback|opensource|licensing|noreply|no-reply|donotreply|do-not-reply|notifications|github|bugs)[\w.+-]*@'
244
+ r'|@[\w.-]*(?:meta|google|microsoft|apple|github|gitlab|openai|anthropic|nvidia|huggingface)\.(?:com|co|org)$')
245
+
246
+ # ---------------------------------------------------------------- file name rules
247
+
248
+ SENSITIVE_FILES = re.compile(
249
+ r'(?i)(?:^|/)(?:\.env(?!\.(?:example|sample|template|dist|defaults?)$)(?:\.[\w.-]+)?'
250
+ r'|id_(?:rsa|dsa|ecdsa|ed25519)|[\w.-]+\.(?:pem|p12|pfx|keystore|jks|ppk|kdbx|ovpn)'
251
+ r'|(?:credentials|client_secrets?[\w-]*|service[-_]account[\w-]*)\.json|kubeconfig|\.kube/config'
252
+ r'|\.netrc|\.git-credentials|\.pgpass|\.htpasswd|claude_desktop_config\.json)$')
253
+
254
+ AI_FILES = re.compile(r'(?:^|/)(?:CLAUDE\.md|CLAUDE\.local\.md|AGENTS\.md|GEMINI\.md|\.cursorrules|\.windsurfrules|\.clinerules'
255
+ r'|copilot-instructions\.md|\.aider[^/]*)$'
256
+ r'|(?:^|/)\.(?:claude|codex|cursor|windsurf|gemini|aider)/')
257
+
258
+ # ---------------------------------------------------------------- AI wording
259
+
260
+ AI_MESSAGE = [
261
+ re.compile(r'(?i)co-authored-by:.*(?:claude|anthropic|codex|openai|chatgpt|copilot|cursor|gemini|aider)'),
262
+ re.compile(r'(?i)generated (?:with|by) \[?(?:claude|codex|chatgpt|copilot|cursor|gemini|aider|ai)\b'),
263
+ re.compile('\N{ROBOT FACE}'),
264
+ re.compile(r'(?i)\bclaude code\b|\banthropic\b'),
265
+ re.compile(r'(?i)\b(?:CLAUDE|AGENTS|GEMINI)\.md\b|\.claude/'),
266
+ ]
267
+ # "the user" meaning the app's user is fine; only notes that call the author "the user" are flagged.
268
+ AI_CONTENT = [
269
+ re.compile(r'[((][^))\n]*使用者(?:決定|挑|選(?!擇|項|單|取))[^))\n]*[))]'),
270
+ re.compile(r'使用者決定(?:不做|要做|先做|改成)'), # open-pushscan: allow
271
+ re.compile(r'使用者(?:選|挑)了?\s*[A-Za-z0-9](?![\w])'),
272
+ re.compile(r'(?i)\b(?:decided|chosen|picked|approved) by the user\b'),
273
+ re.compile(r'(?i)\bthe user (?:picked|chose|decided|approved)\b(?! not\b| to\b)'),
274
+ re.compile(r"(?i)\buser'?s (?:decision|call)\b"),
275
+ ]
276
+
277
+ MEDIA_EXT = re.compile(r'(?i)\.(?:jpe?g|png|webp|tiff?|heic|heif|avif|pdf|docx|docm|xlsx|xlsm|pptx|pptm|odt|ods|odp)$')