#!/usr/bin/env python3 """Build/test the pinned Telegram bridge with Xessenger's single-owner patch, with broadcast channels left out (Xessenger bridges conversations, not feeds), with a private chat the user deleted removed along with its last message, with photos and videos sent together going as one Telegram album, with its account keys stored sealed with the bridge's key when XESSENGER_SEAL_KEY_FILE is set (mautrix-seal.patch), and with the empty state key kept in the plaintext of its encrypted state (mautrix-state-key.patch).""" import argparse import json import os from pathlib import Path import shutil import subprocess import tempfile ROOT = Path(__file__).resolve().parent def run(args, **kwargs): return subprocess.run(args, check=True, text=True, **kwargs) def writable(directory): for path in [directory, *directory.rglob('*')]: path.chmod(path.stat().st_mode | 0o200) def patch_dependency(source_dir, path, patches): """Build with a copy of the dependency version the bridge pins (go.sum checks the download), patched. The copy lives in the source tree and the replace is relative, so the binary records no temporary directory.""" module = json.loads(run(['go', 'mod', 'download', '-json', path], cwd=source_dir, capture_output=True).stdout) target = source_dir / '.xessenger' / path.rsplit('/', 1)[-1] shutil.copytree(module['Dir'], target) writable(target) for patch in patches: run(['patch', '--batch', '--fuzz=0', '-p1', '-i', str(ROOT / patch)], cwd=target) run(['go', 'mod', 'edit', '-replace='+path+'=./'+target.relative_to(source_dir).as_posix()], cwd=source_dir) def use_seal(source_dir): """The seal package in seal/, the same in every bridge, which the patched mautrix-go imports.""" shutil.copytree(ROOT / 'seal', source_dir / '.xessenger' / 'seal') run(['go', 'mod', 'edit', '-require=xessenger.local/seal@v0.0.0', '-replace=xessenger.local/seal=./.xessenger/seal'], cwd=source_dir) def use_bridgekit(source_dir, command): """services/bridgekit, Xessenger's extension every bridge runs with (QA-289), installed in main.go (bridgekit.patch): taken from the repository, or in Docker from the bridgekit build context the Dockerfile copies to XESSENGER_BRIDGEKIT. Looked up only here: the --warm layer has neither.""" bridgekit = Path(os.environ.get('XESSENGER_BRIDGEKIT') or ROOT.parents[2] / 'services' / 'bridgekit') shutil.copytree(bridgekit, source_dir / '.xessenger' / 'bridgekit', ignore=shutil.ignore_patterns('*_test.go', 'testdata')) run(['go', 'mod', 'edit', '-require=xessenger/bridgekit@v0.0.0', '-replace=xessenger/bridgekit=./.xessenger/bridgekit'], cwd=source_dir) run(['patch', '--batch', '--fuzz=0', '-p1', '-i', str(ROOT / 'bridgekit.patch')], cwd=source_dir) # The patch must change the command this script builds, or the bridge would run without the extension. if 'bridgekit.Install(' not in (source_dir / command / 'main.go').read_text(): raise RuntimeError(f'bridgekit.patch does not install bridgekit in {command}') def build(output=None, test=False, warm=False): lock = json.loads((ROOT / 'upstream.json').read_text()) source = json.loads(run(['go', 'mod', 'download', '-json', lock['Path']+'@'+lock['Version']], capture_output=True).stdout) if any(source.get(k) != v for k, v in lock.items()): raise RuntimeError('Upstream module does not match the pinned checksums') with tempfile.TemporaryDirectory(prefix='xessenger-telegram-') as temp: source_dir = Path(temp) / 'source' shutil.copytree(source['Dir'], source_dir) writable(source_dir) env = dict(os.environ, CGO_ENABLED='1') # Every build runs with -trimpath: Go keys its build cache on the package directory otherwise, and this one # is new each time. --warm compiles the unpatched upstream into that cache for the image's next layer, with # mautrix-go taken from a copy as below, so only what the patches touch compiles again. if warm: patch_dependency(source_dir, 'maunium.net/go/mautrix', []) run(['go', 'build', '-trimpath', '-tags', 'goolm', '-o', os.devnull, './cmd/mautrix-telegram'], cwd=source_dir, env=env) return for patch in ['single-owner.patch', 'conversations-only.patch', 'chat-delete.patch', 'album.patch', 'album-receive.patch', 'recent-chats.patch']: run(['patch', '--batch', '--fuzz=0', '-p1', '-i', str(ROOT / patch)], cwd=source_dir) # The login's secrets, its MTProto session among them, are sealed in mautrix-go. use_seal(source_dir) # Its encrypted state keeps the empty state key in the plaintext under Go 1.27's encoding/json/v2. patch_dependency(source_dir, 'maunium.net/go/mautrix', ['mautrix-seal.patch', 'mautrix-device-keys.patch', 'mautrix-state-key.patch']) shutil.copy(ROOT / 'seal_test.go', source_dir / 'pkg/connector/xessenger_seal_test.go') use_bridgekit(source_dir, 'cmd/mautrix-telegram') if test: run(['go', 'test', '-trimpath', '-tags', 'goolm', './pkg/connector'], cwd=source_dir, env=env) run(['go', 'test', '-p', '1', '-trimpath', '-tags', 'goolm', '-run', 'Xessenger', 'maunium.net/go/mautrix/bridgev2/database', 'maunium.net/go/mautrix/crypto/xessengertest'], cwd=source_dir, env=env) run(['go', 'build', '-trimpath', '-tags', 'goolm', '-o', os.devnull, './cmd/mautrix-telegram'], cwd=source_dir, env=env) if output: output = Path(output).resolve() output.parent.mkdir(parents=True, exist_ok=True) run(['go', 'build', '-trimpath', '-tags', 'goolm', '-ldflags', '-X main.Tag=v0.2610.0-xessenger-conversations', '-o', str(output), './cmd/mautrix-telegram'], cwd=source_dir, env=env) if __name__ == '__main__': parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--output') parser.add_argument('--test', action='store_true') parser.add_argument('--warm', action='store_true', help='only compile the unpatched upstream into the Go build cache') args = parser.parse_args() if args.warm and (args.output or args.test): parser.error('--warm runs alone') if not args.output and not args.test and not args.warm: parser.error('Choose --test and/or --output, or --warm') build(args.output, args.test, args.warm)