Files
wp-plugin-contactform/scripts/update_altcha.py
T

82 lines
4.1 KiB
Python
Raw Normal View History

#!/usr/bin/env python3
"""Vendor pinned official ALTCHA releases; --check only reports available versions."""
import argparse
import base64
import hashlib
import io
import json
from pathlib import Path
import tarfile
from urllib.request import Request, urlopen
ROOT = Path(__file__).resolve().parents[1]
MANIFEST = ROOT / 'includes/vendor/altcha/versions.json'
def fetch(url):
with urlopen(Request(url, headers={'User-Agent': 'HG-Contactform-dependency-update'}), timeout=30) as response:
return response.read()
def members(blob):
with tarfile.open(fileobj=io.BytesIO(blob), mode='r:gz') as archive:
return {member.name: archive.extractfile(member).read() for member in archive if member.isfile()}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--check', action='store_true')
parser.add_argument('--widget-version')
parser.add_argument('--php-version')
args = parser.parse_args()
if args.check:
current = json.loads(MANIFEST.read_text())
widget = json.loads(fetch('https://registry.npmjs.org/altcha/latest'))['version']
php = json.loads(fetch('https://api.github.com/repos/altcha-org/altcha-lib-php/releases/latest'))['tag_name'].removeprefix('v')
print(f"Widget: installed {current['widget']['version']}, latest {widget}")
print(f"PHP: installed {current['php']['version']}, latest {php}")
return
if not args.widget_version or not args.php_version:
parser.error('Supply both explicit versions; no automatic upgrades.')
import re
if any(not re.fullmatch(r'\d+\.\d+\.\d+', value) for value in (args.widget_version, args.php_version)):
parser.error('Use stable x.y.z versions.')
metadata = json.loads(fetch(f'https://registry.npmjs.org/altcha/{args.widget_version}'))
widget_url = metadata['dist']['tarball']
widget_blob = fetch(widget_url)
integrity = 'sha512-' + base64.b64encode(hashlib.sha512(widget_blob).digest()).decode()
if integrity != metadata['dist']['integrity']:
raise RuntimeError('NPM integrity mismatch')
php_url = f'https://api.github.com/repos/altcha-org/altcha-lib-php/tarball/v{args.php_version}'
php_blob = fetch(php_url)
widget_files, php_files = members(widget_blob), members(php_blob)
outputs = {
'assets/vendor/altcha/widget.js': widget_files['package/dist/main/altcha.i18n.min.js'],
'assets/vendor/altcha/LICENSE.txt': widget_files['package/LICENSE.txt'],
}
for name, data in php_files.items():
relative = name.split('/', 1)[1]
if relative.startswith('src/') and relative.endswith('.php'):
# Private namespace avoids conflicts with other WordPress plugins.
outputs['includes/vendor/altcha/' + relative] = data.replace(b'AltchaOrg\\Altcha', b'HGCFVendor\\AltchaOrg\\Altcha')
elif relative in ('LICENSE.txt', 'composer.json'):
outputs['includes/vendor/altcha/' + relative] = data
if 'includes/vendor/altcha/src/Altcha.php' not in outputs:
raise RuntimeError('Missing PHP library entry point')
# Parse and validate both archives completely before replacing vendored files.
php_source = ROOT / 'includes/vendor/altcha/src'
if php_source.exists():
for old in php_source.rglob('*.php'):
if str(old.relative_to(ROOT)) not in outputs:
old.unlink()
for relative, data in outputs.items():
path = ROOT / relative
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(data)
manifest = {
'widget': {'version': args.widget_version, 'source': widget_url, 'integrity': integrity},
'php': {'version': args.php_version, 'source': php_url, 'archive_sha256': hashlib.sha256(php_blob).hexdigest(), 'namespace': 'HGCFVendor\\AltchaOrg\\Altcha'},
'files_sha256': {name: hashlib.sha256(data).hexdigest() for name, data in sorted(outputs.items())},
}
MANIFEST.write_text(json.dumps(manifest, indent=2) + '\n')
print('ALTCHA bundled. Review diff, run security/browser tests, then build the plugin ZIP.')
if __name__ == '__main__':
main()