#!/usr/bin/env python3 """Build/test the pinned LINE bridge (beeper/line) with Xessenger's single-owner patch, signing in with the QR code only (the password flow would keep the LINE password to reconnect with it), and deleting a chat the user left or removed in LINE (chat-delete.patch), as the other bridges do, marking the photos of a group LINE shows as one grid (image-group.patch), and on connecting making rooms only for chats active within initial_sync_days and reading again only the chats whose last message isn't bridged (recent-chats.patch), and with its account keys stored sealed with the bridge's key when XESSENGER_SEAL_KEY_FILE is set, its E2EE keys then kept in the sealed login only, not in a file under data/ (mautrix-seal.patch, 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 and seal.patch import.""" 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-line-') 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/matrix-line'], cwd=source_dir, env=env) return for patch in ['single-owner.patch', 'qr-only.patch', 'chat-delete.patch', 'image-group.patch', 'recent-chats.patch', 'seal.patch']: run(['patch', '--batch', '--fuzz=0', '-p1', '-i', str(ROOT / patch)], cwd=source_dir) # The login's secrets are sealed in mautrix-go, with the seal package in seal/, the same in every bridge. 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/matrix-line') 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/matrix-line'], 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='+lock['Version']+'-xessenger-qr', '-o', str(output), './cmd/matrix-line'], 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)