telegram-mcp/scripts/export_source.py
2026-11-05 14:26:28 +03:00

89 lines
3.7 KiB
Python

#!/usr/bin/env python3
"""Export reviewed source only; fail closed for runtime or unexpected files."""
from pathlib import Path
import hashlib
import io
import json
import re
import sys
import tarfile
ROOT = Path(__file__).resolve().parents[1]
FILES = ['README.md', 'LICENSE', 'UPSTREAM.md', 'SECURITY.md', 'CONTRIBUTING.md',
'.gitignore', 'requirements.in', 'requirements.lock',
'cli/package.json', 'cli/package-lock.json', 'cli/LICENSE',
'cli/tsconfig.json', 'cli/tsup.config.ts', 'cli/vitest.config.ts']
DIRECTORIES = ['cli/src', 'cli/tests', 'mcp_server', 'scripts', 'tests', 'docs', 'examples']
SUFFIXES = {'.py', '.mjs', '.ts', '.json', '.md'}
PATTERNS = [
('private-key', re.compile(r'-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----')),
('bot-token', re.compile(r'\b\d{8,12}:[A-Za-z0-9_-]{30,}\b')),
('access-token', re.compile(r'\b(?:ghp_|github_pat_|sk-proj-)[A-Za-z0-9_-]{20,}\b')),
('credential-url', re.compile(r'https?://[^\s/@:]+:[^\s/@]+@')),
('personal-path', re.compile(r'/(?:Users|home)/(?!(?:user|example|test|runner)(?:/|\b))[^\s/]+/')),
]
def source_files():
paths = [ROOT / p for p in FILES]
for path in paths + [ROOT / d for d in DIRECTORIES]:
if path.is_symlink():
raise ValueError(f"Symlink is not permitted: {path.relative_to(ROOT)}")
for directory in DIRECTORIES:
for p in (ROOT / directory).rglob('*'):
if '__pycache__' in p.parts:
continue
if p.is_symlink():
raise ValueError(f'Symlink is not permitted: {p.relative_to(ROOT)}')
if not p.is_file():
continue
if p.suffix not in SUFFIXES:
raise ValueError(f'Unexpected source file: {p.relative_to(ROOT)}')
paths.append(p)
return sorted(paths)
def validate(paths):
findings = []
for path in paths:
text = path.read_text()
for kind, pattern in PATTERNS:
for match in pattern.finditer(text):
findings.append(f'{path.relative_to(ROOT)}:{text.count(chr(10), 0, match.start()) + 1}: {kind}')
if path.suffix == '.md':
for target in re.findall(r'\]\(([^)]+)\)', text):
if '://' not in target and not target.startswith('#'):
if not (path.parent / target.split('#')[0]).exists():
findings.append(f'{path.relative_to(ROOT)}: broken local link')
if findings:
raise ValueError('\n'.join(findings))
def main():
if len(sys.argv) != 2:
raise SystemExit('Usage: python3 scripts/export_source.py /outside/checkout/source.tar.gz')
output = Path(sys.argv[1]).resolve()
if output == ROOT or ROOT in output.parents:
raise SystemExit('Export outside the source checkout')
if output.exists():
raise SystemExit('Destination exists; choose a new filename')
paths = source_files()
validate(paths)
manifest = {str(p.relative_to(ROOT)): hashlib.sha256(p.read_bytes()).hexdigest() for p in paths}
with tarfile.open(output, 'w:gz') as archive:
for p in paths:
data = p.read_bytes()
info = tarfile.TarInfo('telegram-mcp/' + str(p.relative_to(ROOT)))
info.size = len(data)
info.mode = 0o644
archive.addfile(info, io.BytesIO(data))
data = (json.dumps(manifest, indent=2) + '\n').encode()
info = tarfile.TarInfo('telegram-mcp/SOURCE-MANIFEST.json')
info.size = len(data)
info.mode = 0o644
archive.addfile(info, io.BytesIO(data))
print(f'Exported {len(paths)} source files; SHA-256 {hashlib.sha256(output.read_bytes()).hexdigest()}')
if __name__ == '__main__':
main()