#!/usr/bin/env python3 """Build/test the pinned WhatsApp bridge with Xessenger's session-isolation patch, with photos and videos sent together going as one WhatsApp album, and with its account keys and the history sync's waiting messages stored sealed with the bridge's key when XESSENGER_SEAL_KEY_FILE is set (mautrix-seal.patch, whatsmeow-seal.patch, history-seal.patch), and with each contact's phone number named from what the bridge stored of it, for the handle of the encrypted profiles of contacts known before the bridge kept it (ghost-identifiers.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_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-whatsapp-') 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 and whatsmeow taken from copies as below, so only what the patches touch compiles again. if warm: patch_dependency(source_dir, 'maunium.net/go/mautrix', []) patch_dependency(source_dir, 'go.mau.fi/whatsmeow', []) run(['go', 'build', '-trimpath', '-tags', 'goolm', '-o', os.devnull, './cmd/mautrix-whatsapp'], cwd=source_dir, env=env) return for patch in ['single-owner.patch', 'peer-profile.patch', 'own-profile.patch', 'album.patch', 'album-receive.patch', 'recent-chats.patch', 'ghost-identifiers.patch']: run(['patch', '--batch', '--fuzz=0', '-p1', '-i', str(ROOT / patch)], cwd=source_dir) # The account keys are sealed in mautrix-go (login metadata) and whatsmeow (device keys), and the history sync's # messages that wait for a room in the bridge itself, with the seal package in seal/, the same in every bridge. 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) run(['patch', '--batch', '--fuzz=0', '-p1', '-i', str(ROOT / 'history-seal.patch')], cwd=source_dir) patch_dependency(source_dir, 'maunium.net/go/mautrix', ['mautrix-seal.patch', 'mautrix-device-keys.patch']) patch_dependency(source_dir, 'go.mau.fi/whatsmeow', ['whatsmeow-seal.patch']) shutil.copy(ROOT / 'seal_test.go', source_dir / 'pkg/waid/xessenger_seal_test.go') use_bridgekit(source_dir, 'cmd/mautrix-whatsapp') if test: run(['go', 'test', '-trimpath', '-tags', 'goolm', './pkg/connector', './pkg/msgconv', './pkg/waid'], cwd=source_dir, env=env) # One package at a time: with XESSENGER_SEAL_TEST_POSTGRES each empties the same database. run(['go', 'test', '-p', '1', '-trimpath', '-tags', 'goolm', '-run', 'Xessenger', 'maunium.net/go/mautrix/bridgev2/database', 'maunium.net/go/mautrix/crypto/xessengertest', 'go.mau.fi/whatsmeow/store/sqlstore', './pkg/connector/wadb'], cwd=source_dir, env=env) run(['go', 'build', '-trimpath', '-tags', 'goolm', '-o', os.devnull, './cmd/mautrix-whatsapp'], 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.2609.0-xessenger-shared-sessions', '-o', str(output), './cmd/mautrix-whatsapp'], 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)