#!/usr/bin/python3 -I
"""Quest's fixed, user-initiated package-manager handoff. No privilege grant."""
import hashlib
import json
import os
from pathlib import Path
import pwd
import re
import selectors
import stat
import subprocess
import sys
import time
import tempfile
import urllib.request
import datetime

ORIGIN = 'https://packages.quest.app/linux'
FINGERPRINT = '608169BD011970FB902E2DEC0593D4AF3D1AC96E'
RECEIPT = Path('/var/lib/quest/installation.json')
HELPER = Path('/opt/Quest/resources/linux-updater/quest-package-update')
EXECUTABLE = Path('/opt/Quest/quest')
SYSTEM_PATH = '/usr/sbin:/usr/bin:/sbin:/bin'
CONFIGS = {
    'apt': {'/etc/apt/keyrings/quest.asc', '/etc/apt/sources.list.d/quest.sources', '/etc/apt/preferences.d/quest'},
    'dnf': {'/etc/pki/rpm-gpg/RPM-GPG-KEY-quest', '/etc/yum.repos.d/quest.repo'},
    'pacman': {'/etc/pacman.d/quest.conf', '/etc/pacman.conf', '/etc/pacman.d/quest.asc'},
}

class Refused(Exception):
    pass


def require(value, code):
    if not value:
        raise Refused(code)


def root_file(path, limit=262144):
    path = Path(path)
    require(path.is_absolute() and path.resolve() == path, 'unsafe-path')
    for directory in path.parents:
        info = directory.stat()
        require(stat.S_ISDIR(info.st_mode) and info.st_uid == 0 and not info.st_mode & 0o022,
                'unsafe-directory')
    fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
    try:
        info = os.fstat(fd)
        require(stat.S_ISREG(info.st_mode) and info.st_uid == 0 and info.st_nlink == 1
                and not info.st_mode & 0o022 and 0 < info.st_size <= limit, 'unsafe-file')
        raw = os.read(fd, limit + 1)
        require(len(raw) == info.st_size, 'file-changed')
        return raw
    finally:
        os.close(fd)


def digest(raw):
    return hashlib.sha256(raw).hexdigest()


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, *args, **kwargs):
        raise Refused('repository-redirect')


def metadata(path):
    require(re.fullmatch(r'/[A-Za-z0-9._/-]+', path) and '..' not in path, 'metadata-path')
    with urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect).open(
            urllib.request.Request(ORIGIN + path, headers={'Accept-Encoding': 'identity'}), timeout=30) as response:
        require(response.status == 200 and not response.headers.get('Content-Encoding'), 'metadata-response')
        chunks, size, deadline = [], 0, time.monotonic() + 30
        while True:
            require(time.monotonic() < deadline, 'metadata-timeout')
            chunk = response.read1(65536)
            if not chunk:
                break
            size += len(chunk)
            require(size <= 2 * 1024 * 1024, 'metadata-size')
            chunks.append(chunk)
        raw = b''.join(chunks)
        require(0 < len(raw) <= 2 * 1024 * 1024, 'metadata-size')
        return raw


def valid_signature(status):
    require(not re.search(r'^\[GNUPG:\] (BADSIG|ERRSIG|EXPSIG|EXPKEYSIG|REVKEYSIG|NO_PUBKEY)\b', status, re.M), 'signature-invalid')
    rows = re.findall(r'^\[GNUPG:\] VALIDSIG (.+)$', status, re.M)
    require(len(rows) == 1, 'signature-count')
    fields = rows[0].split()
    require(len(fields) in (9, 10) and (fields[9] if len(fields) == 10 else fields[0]) == FINGERPRINT
            and re.fullmatch(r'[A-F0-9]{40}', fields[0]) and fields[7] in ('8', '9', '10')
            and fields[8] == '00' and fields[2].isdigit() and fields[3].isdigit()
            and int(fields[2]) <= time.time() + 300 and (fields[3] == '0' or int(fields[3]) > time.time()),
            'signature-identity')


# Repair metadata has authority only after repository/candidate signature verification.
# These checks preserve the original set/app identity and authenticate the closed
# packaging input without accepting caller-supplied paths or changing old routes.
def repair_object(value, keys):
    require(isinstance(value, dict) and set(value) == set(keys), 'repair-fields')
    return value


def repair_hash(value, length=64):
    return isinstance(value, str) and re.fullmatch(r'[a-f0-9]{' + str(length) + '}', value) is not None


def repair_file_identity(value, keys=('bytes', 'sha256'), maximum=2*1024*1024):
    row = repair_object(value, keys)
    require(type(row['bytes']) is int and 0 < row['bytes'] <= maximum
            and repair_hash(row['sha256']), 'repair-file-identity')
    return row


def repair_digest(value):
    def json_value(item):
        if item is None or type(item) in (str, bool):
            return
        if type(item) is int:
            require(abs(item) <= 9007199254740991, 'repair-json-number')
        elif isinstance(item, list):
            for child in item: json_value(child)
        elif isinstance(item, dict):
            require(all(isinstance(key, str) and key.isascii() for key in item), 'repair-json-key')
            for child in item.values(): json_value(child)
        else:
            require(False, 'repair-json-value')
    json_value(value)
    return digest(json.dumps(value, sort_keys=True, separators=(',', ':'), ensure_ascii=False,
                             allow_nan=False).encode('utf-8'))


def repair_projection(stage):
    if 'packagingRepair' not in stage:
        return None
    projection = repair_object(stage['packagingRepair'],
                               ('schema', 'repairId', 'inputSha256', 'buildReceiptSha256', 'parent', 'tooling'))
    require(type(projection['schema']) is int and projection['schema'] == 1, 'repair-schema')
    version, build, revision = stage.get('version'), stage.get('build'), stage.get('revision')
    require(isinstance(version, str) and re.fullmatch(r'(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)', version)
            and isinstance(build, str) and re.fullmatch(r'[1-9][0-9]{0,3}', build)
            and type(revision) is int and 1 <= revision <= 999999 and repair_hash(stage.get('commit'), 40)
            and projection['repairId'] == version + '-linux-build' + build
            and repair_hash(projection['inputSha256']) and repair_hash(projection['buildReceiptSha256']),
            'repair-stage-identity')
    parent = repair_object(projection['parent'], ('build', 'candidateSha256', 'bundleSha256',
        'publicationIntentSha256', 'publicationEvidenceSha256', 'generationSha256', 'reviewSha256', 'recordSha256'))
    require(isinstance(parent['build'], str) and re.fullmatch(r'[1-9][0-9]{0,3}', parent['build'])
            and int(build) > int(parent['build']) and all(repair_hash(v) for k, v in parent.items() if k != 'build'),
            'repair-parent')
    tooling = repair_object(projection['tooling'], ('sourceCommit', 'inputManifestSha256'))
    require(repair_hash(tooling['sourceCommit'], 40) and repair_hash(tooling['inputManifestSha256']), 'repair-tooling')
    return projection


def repair_candidate_prefix(stage):
    require(repair_projection(stage) is not None, 'repair-missing')
    return '/candidates/' + stage['version'] + '/repairs/build-' + stage['build'] + '/' + stage['commit']


def validate_packaging_repair(stage, candidate):
    projection = repair_projection(stage)
    if projection is None:
        require('packagingRepair' not in candidate, 'repair-stage-missing')
        return None
    repair = repair_object(candidate.get('packagingRepair'), ('schema', 'input', 'buildReceipt', 'buildReceiptSha256'))
    require(type(repair['schema']) is int and repair['schema'] == 1, 'repair-schema')
    value = repair_object(repair['input'], ('schema', 'kind', 'repairId', 'version', 'build', 'appSourceCommit',
        'releaseSetSha256', 'revision', 'parent', 'tooling'))
    require(type(value['schema']) is int and value['schema'] == 1 and value['kind'] == 'quest-linux-packaging-repair-build'
            and candidate.get('platform') == 'linux' and candidate.get('arch') == 'x64' and candidate.get('buildMode') == 'release'
            and value['version'] == stage['version'] == candidate.get('version')
            and value['build'] == stage['build'] == candidate.get('build')
            and value['appSourceCommit'] == stage['commit'] == candidate.get('commit')
            and type(value['revision']) is int and value['revision'] == stage['revision']
            and value['repairId'] == projection['repairId'] and value['parent'] == projection['parent']
            and repair_hash(value['releaseSetSha256']), 'repair-input-identity')
    tooling = repair_object(value['tooling'], ('sourceCommit', 'inputManifestSha256', 'inputs', 'appAdapters'))
    require({key: tooling[key] for key in ('sourceCommit', 'inputManifestSha256')} == projection['tooling'], 'repair-tooling')
    paths = ('ops/linux-installer/quest-package-auto-update.service', 'ops/linux-installer/quest-package-auto-update.timer',
             'scripts/linux-package-tooling.mjs', 'scripts/prepare-linux-package-tooling.mjs',
             'scripts/quest-package-auto-update.py', 'scripts/quest-package-tooling.py', 'scripts/quest-package-update.py')
    require(isinstance(tooling['inputs'], list) and len(tooling['inputs']) == len(paths), 'repair-tooling-inventory')
    for path, row in zip(paths, tooling['inputs']):
        repair_object(row, ('path', 'bytes', 'sha256'))
        require(row['path'] == path and type(row['bytes']) is int and 0 < row['bytes'] <= 256 * 1024
                and repair_hash(row['sha256']), 'repair-tooling-inventory')
    adapters = ('apps/app/src/main/linux-appimage-update.ts', 'apps/app/src/main/linux-update-feed.ts', 'apps/app/src/main/linux-updater.ts', 'apps/app/src/main/update-runtime.ts')
    require(isinstance(tooling['appAdapters'], list) and len(tooling['appAdapters']) == len(adapters),
            'repair-app-adapters')
    for path, row in zip(adapters, tooling['appAdapters']):
        repair_object(row, ('path', 'original', 'replacement'))
        require(row['path'] == path, 'repair-app-adapters')
        for identity in ('original', 'replacement'):
            file = repair_object(row[identity], ('bytes', 'sha256'))
            require(type(file['bytes']) is int and 0 < file['bytes'] <= 256 * 1024
                    and repair_hash(file['sha256']), 'repair-app-adapters')
        require(row['original']['sha256'] != row['replacement']['sha256'], 'repair-app-adapters')
    require(repair_digest({key: tooling[key] for key in ('inputs', 'appAdapters')}) == tooling['inputManifestSha256']
            and repair_digest(value) == projection['inputSha256'], 'repair-input-digest')
    binding = repair_object(candidate.get('releaseSet'),
        ('schema', 'setSha256', 'sourceCommit', 'version', 'platform', 'candidateId', 'revision'))
    require(type(binding['schema']) is int and binding['schema'] == 2 and type(binding['revision']) is int
            and binding['revision'] == value['revision'] and binding['setSha256'] == value['releaseSetSha256']
            and binding['sourceCommit'] == value['appSourceCommit'] and binding['version'] == value['version']
            and binding['platform'] == 'linux' and binding['candidateId'] == 'quest-linux@' + value['version'] + '+' + value['releaseSetSha256']
            and candidate.get('releaseId') == 'quest-desktop-linux@' + value['version'] + '-r' + str(value['revision'])
                + '-b' + value['build'] + '+' + value['appSourceCommit'], 'repair-release-set')
    receipt = repair_object(repair['buildReceipt'], ('schema', 'kind', 'inputSha256', 'workflow',
        'configurationSha256', 'electronVersion', 'overlay', 'overlaySha256', 'payload', 'assets'))
    require(type(receipt['schema']) is int and receipt['schema'] == 1
            and receipt['kind'] == 'quest-linux-packaging-repair-build-receipt'
            and receipt['inputSha256'] == projection['inputSha256']
            and repair_digest(receipt) == repair['buildReceiptSha256'] == projection['buildReceiptSha256'], 'repair-receipt-digest')
    require(repair_hash(receipt['configurationSha256']) and isinstance(receipt['electronVersion'], str)
            and re.fullmatch(r'[0-9]+\.[0-9]+\.[0-9]+', receipt['electronVersion']), 'repair-receipt-identity')
    workflow = repair_object(receipt['workflow'], ('path', 'commit', 'repository', 'repositoryId', 'runId', 'runAttempt'))
    require(workflow['path'] == candidate.get('workflow') == '.github/workflows/native-linux-repair.yml'
            and workflow['commit'] == candidate.get('workflowCommit') == tooling['sourceCommit']
            and workflow['repository'] == candidate.get('sourceRepository') == 'NiklasSteenfatt/quest'
            and type(workflow['repositoryId']) is int and workflow['repositoryId'] == candidate.get('sourceRepositoryId') == 1259577003
            and isinstance(workflow['runId'], str) and re.fullmatch(r'[1-9][0-9]{0,15}', workflow['runId'])
            and int(workflow['runId']) <= 9007199254740991 and workflow['runId'] == candidate.get('runId')
            and type(workflow['runAttempt']) is int and type(candidate.get('runAttempt')) is int
            and workflow['runAttempt'] == candidate.get('runAttempt') == 1,
            'repair-workflow')
    overlay = receipt['overlay']
    require(isinstance(overlay, dict) and overlay.get('inputSha256') == projection['inputSha256']
            and overlay.get('appSourceCommit') == value['appSourceCommit']
            and overlay.get('toolingSourceCommit') == tooling['sourceCommit']
            and overlay.get('appAdapters') == tooling['appAdapters']
            and repair_digest(overlay) == receipt['overlaySha256'], 'repair-overlay-digest')
    repair_object(overlay, ('schema', 'kind', 'inputSha256', 'appSourceCommit', 'appTree',
        'toolingSourceCommit', 'toolingTree', 'dependencies', 'outputDirectory', 'files',
        'toolingManifestSha256', 'appAdapters'))
    require(type(overlay['schema']) is int and overlay['schema'] == 1
            and overlay['kind'] == 'quest-linux-packaging-repair-overlay'
            and repair_hash(overlay['appTree'], 40) and repair_hash(overlay['toolingTree'], 40)
            and overlay['outputDirectory'] == 'apps/app/.cache/linux-package-tooling', 'repair-overlay-identity')
    dependencies = repair_object(overlay['dependencies'],
        ('lock', 'appPackage', 'builderConfig', 'builder', 'builderLibrary', 'template'))
    for key, path in (('lock', 'pnpm-lock.yaml'), ('appPackage', 'apps/app/package.json'),
                      ('builderConfig', 'apps/app/electron-builder.config.mjs')):
        row = repair_file_identity(dependencies[key], ('path', 'bytes', 'sha256'))
        require(row['path'] == path, 'repair-dependency-path')
    for key, name in (('builder', 'electron-builder'), ('builderLibrary', 'app-builder-lib')):
        row = repair_file_identity(dependencies[key], ('name', 'version', 'bytes', 'sha256'))
        require(row['name'] == name and isinstance(row['version'], str)
                and re.fullmatch(r'[0-9]+\.[0-9]+\.[0-9]+(?:-[A-Za-z0-9.-]+)?', row['version']),
                'repair-dependency-identity')
    repair_file_identity(dependencies['template'], maximum=256*1024)
    outputs = (
        ('after-install-deb.tpl', 0o644), ('after-install-rpm.tpl', 0o644),
        ('after-transaction-rpm.sh', 0o644), ('before-remove-deb.sh', 0o644),
        ('before-remove-rpm.sh', 0o644), ('resources/manifest.json', 0o644),
        ('resources/quest-package-auto-update', 0o755),
        ('resources/quest-package-auto-update.service', 0o644),
        ('resources/quest-package-auto-update.timer', 0o644),
        ('resources/quest-package-tooling.py', 0o755), ('resources/quest-package-update', 0o755))
    require(isinstance(overlay['files'], list) and len(overlay['files']) == len(outputs), 'repair-output-inventory')
    for (path, mode), value_file in zip(outputs, overlay['files']):
        row = repair_file_identity(value_file, ('path', 'bytes', 'sha256', 'mode'))
        require(row['path'] == path and type(row['mode']) is int and row['mode'] == mode, 'repair-output-inventory')
        if path == 'resources/manifest.json':
            require(overlay['toolingManifestSha256'] == row['sha256'], 'repair-tooling-manifest')
    payload = repair_object(receipt['payload'], ('artifactId', 'artifactSha256', 'inventorySha256'))
    require(isinstance(payload['artifactId'], str) and re.fullmatch(r'[1-9][0-9]{0,15}', payload['artifactId'])
            and int(payload['artifactId']) <= 9007199254740991
            and repair_hash(payload['artifactSha256']) and repair_hash(payload['inventorySha256']), 'repair-payload')
    assets = receipt['assets']
    require(isinstance(assets, list) and len(assets) == 3 and isinstance(candidate.get('assets'), list)
            and len(candidate['assets']) == 3, 'repair-assets')
    for suffix, asset in zip(('x86_64.AppImage', 'amd64.deb', 'x86_64.rpm'), assets):
        repair_object(asset, ('name', 'size', 'sha256'))
        name = 'Quest-' + value['version'] + '-linux-' + suffix
        require(asset['name'] == name and type(asset['size']) is int and 0 < asset['size'] <= 2 * 1024**3
                and repair_hash(asset['sha256']), 'repair-assets')
        actual = [row for row in candidate['assets'] if isinstance(row, dict) and row.get('name') == name]
        require(len(actual) == 1, 'repair-assets')
        repair_object(actual[0], ('name', 'size', 'sha256'))
        require(type(actual[0]['size']) is int and 0 < actual[0]['size'] <= 2 * 1024**3
                and repair_hash(actual[0]['sha256']) and (suffix == 'x86_64.rpm' or actual[0] == asset), 'repair-assets')
    return projection


def verified_candidate(route):
    key_path = {'apt': '/etc/apt/keyrings/quest.asc', 'dnf': '/etc/pki/rpm-gpg/RPM-GPG-KEY-quest',
                'pacman': '/etc/pacman.d/quest.asc'}[route]
    key = root_file(Path(key_path), 65536)
    require(b'PRIVATE KEY' not in key and key.startswith(b'-----BEGIN PGP PUBLIC KEY BLOCK-----'), 'key-invalid')
    with tempfile.TemporaryDirectory(prefix='quest-update-key-') as directory:
        home = Path(directory); os.chmod(home, 0o700)
        args = ['/usr/bin/gpg', '--no-options', '--homedir', str(home), '--batch', '--no-tty',
                '--no-auto-key-retrieve', '--no-auto-key-import', '--no-autostart']
        public = home / 'key.asc'; public.write_bytes(key)
        listing = command([*args, '--with-colons', '--show-keys', str(public)])
        primaries = [line.split(':') for line in listing.splitlines() if line.startswith('pub:')]
        fingerprints = [line.split(':')[9] for line in listing.splitlines() if line.startswith('fpr:')]
        require(len(primaries) == 1 and fingerprints and fingerprints[0] == FINGERPRINT
                and primaries[0][1] not in ('r', 'e', 'd')
                and (not primaries[0][6] or primaries[0][6] == '0' or int(primaries[0][6]) > time.time()), 'key-expired-or-different')
        command([*args, '--import', str(public)])
        def verify(path):
            raw, signed = metadata(path), metadata(path + '.asc')
            data, signature = home / 'data', home / 'signature'
            data.write_bytes(raw); signature.write_bytes(signed)
            valid_signature(command([*args, '--status-fd', '1', '--verify', str(signature), str(data)]))
            return raw
        stage = json.loads(verify('/repository-stage.json'))
        revision = stage.get('revision')
        require(revision is None or type(revision) is int and 1 <= revision <= 999999, 'stage-revision')
        require(re.fullmatch(r'\d+\.\d+\.\d+', stage.get('version', ''))
                and re.fullmatch(r'[a-f0-9]{40}', stage.get('commit', '')), 'stage-identity')
        prefix = (repair_candidate_prefix(stage) if 'packagingRepair' in stage else
                  '/candidates/' + stage['version'] + '/' + ('r' + str(revision) + '/' if revision else '') + stage['commit'])
        return validate_candidate(stage, verify(prefix + '/linux-candidate.json'))


def validate_candidate(stage, raw, now=None):
    now = time.time() if now is None else now
    require(stage.get('schema') == 1 and stage.get('kind') == 'local-linux-repository-stage'
            and stage.get('baseUrl') == ORIGIN and stage.get('signingFingerprint') == FINGERPRINT
            and re.fullmatch(r'\d+\.\d+\.\d+', stage.get('version', ''))
            and re.fullmatch(r'[a-f0-9]{40}', stage.get('commit', '')), 'stage-identity')
    created, expiry = [datetime.datetime.fromisoformat(stage[name].replace('Z', '+00:00')).timestamp()
                       for name in ('createdAt', 'aptValidUntil')]
    require(created <= now + 300 < expiry and 0 < expiry - created <= 31 * 86400, 'stage-expired')
    revision = stage.get('revision')
    require(revision is None or type(revision) is int and 1 <= revision <= 999999, 'stage-revision')
    require(digest(raw) == stage.get('candidateSha256'), 'candidate-digest')
    value = json.loads(raw)
    require(value.get('schema') == 1 and value.get('platform') == 'linux' and value.get('arch') == 'x64'
            and value.get('buildMode') == 'release' and value.get('sourceRepository') == 'NiklasSteenfatt/quest'
            and value.get('sourceRepositoryId') == 1259577003 and value.get('version') == stage['version']
            and value.get('commit') == stage['commit'] and value.get('signingFingerprint') == FINGERPRINT
            and re.fullmatch(r'[1-9]\d{0,14}', value.get('build', '')), 'candidate-identity')
    binding = value.get('releaseSet')
    if binding is not None or revision is not None:
        require(isinstance(binding, dict) and set(binding) == {'schema', 'setSha256', 'sourceCommit', 'version', 'platform', 'candidateId'} | ({'revision'} if revision is not None else set())
                and binding['schema'] == (2 if revision is not None else 1) and binding.get('revision') == revision
                and re.fullmatch(r'[a-f0-9]{64}', binding['setSha256']) and binding['sourceCommit'] == value['commit']
                and binding['version'] == value['version'] and binding['platform'] == 'linux'
                and binding['candidateId'] == 'quest-linux@' + value['version'] + '+' + binding['setSha256'], 'candidate-binding')
    repair = validate_packaging_repair(stage, value)
    expected_id = 'quest-desktop-linux@' + value['version'] + ('-r' + str(revision) if revision else '') + '+' + value['commit']
    # Historical uncoordinated candidates used the short source ID; revised candidates cannot.
    require(repair is not None or value.get('releaseId') == expected_id or (binding is None and revision is None
            and value.get('releaseId') == 'quest-desktop@' + value['version'] + '+' + value['commit'][:7]), 'candidate-release-id')
    assets = value.get('assets')
    names = {'Quest-' + value['version'] + '-linux-' + suffix for suffix in ('x86_64.AppImage', 'amd64.deb', 'x86_64.rpm')}
    require(isinstance(assets, list) and len(assets) == 3 and all(isinstance(a, dict) for a in assets)
            and {a.get('name') for a in assets} == names and all(type(a.get('size')) is int and 0 < a['size'] <= 1024**3
            and re.fullmatch(r'[a-f0-9]{64}', a.get('sha256', '')) for a in assets), 'candidate-assets')
    value['_repositoryValidUntil'] = expiry
    return value


def load_tooling(route, read=root_file, run=None):
    # Authenticate the module before executing it; then verify the complete closed inventory.
    import types
    run = command if run is None else run
    directory = Path('/opt/Quest/resources/linux-updater')
    manifest_path, module_path = directory / 'manifest.json', directory / 'quest-package-tooling.py'
    for path in (manifest_path, module_path):
        require(path.resolve() == path, 'unsafe-tooling-path')
        for parent in path.parents:
            info = parent.stat()
            require(stat.S_ISDIR(info.st_mode) and info.st_uid == 0 and not info.st_mode & 0o022, 'unsafe-tooling-directory')
    manifest = json.loads(read(manifest_path))
    require(isinstance(manifest, dict) and set(manifest) == {'schema', 'kind', 'files'}
            and type(manifest['schema']) is int and manifest['schema'] == 1 and manifest['kind'] == 'quest-linux-package-tooling'
            and isinstance(manifest['files'], dict) and set(manifest['files']) == {
                'quest-package-update', 'quest-package-auto-update', 'quest-package-tooling.py',
                'quest-package-auto-update.service', 'quest-package-auto-update.timer'}, 'tooling-manifest')
    row = manifest['files']['quest-package-tooling.py']
    raw = read(module_path)
    require(isinstance(row, dict) and set(row) == {'sha256', 'bytes', 'mode'}
            and row['bytes'] == len(raw) and row['sha256'] == hashlib.sha256(raw).hexdigest()
            and row['mode'] == 0o755 and stat.S_IMODE(module_path.stat().st_mode) == 0o755,
            'tooling-module-changed')
    for path in (manifest_path, module_path):
        if route == 'apt':
            result, expected = run(['/usr/bin/dpkg-query', '-S', str(path)]), 'quest: ' + str(path)
        elif route == 'dnf':
            result, expected = run(['/usr/bin/rpm', '-qf', '--qf', '%{NAME}', str(path)]), 'quest'
        else:
            require(route == 'pacman', 'installation-route')
            result, expected = run(['/usr/bin/pacman', '-Qoq', str(path)]), 'quest'
        require(result == expected, 'tooling-package-owner')
    module = types.ModuleType('quest_package_tooling')
    exec(compile(raw, str(module_path), 'exec'), module.__dict__)
    module.verify_tooling(route, read, run)
    return module


def validate_receipt(value, read=root_file):
    require(isinstance(value, dict) and value.get('schema') == 2, 'installation-migration-required')
    tooling = load_tooling(value.get('route'), read)
    route = tooling.receipt_identity(value, read)
    return route, value['distro']


def command(args, *, timeout=30):
    child = subprocess.Popen(args, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                             env={'PATH': SYSTEM_PATH, 'LC_ALL': 'C', 'HOME': '/nonexistent'})
    out, total, deadline = [], 0, time.monotonic() + timeout
    try:
        with selectors.DefaultSelector() as poll:
            poll.register(child.stdout, selectors.EVENT_READ, True)
            poll.register(child.stderr, selectors.EVENT_READ, False)
            while poll.get_map():
                require(time.monotonic() < deadline, 'package-query-timeout')
                for key, _ in poll.select(min(0.1, max(0, deadline - time.monotonic()))):
                    chunk = os.read(key.fileobj.fileno(), 8192)
                    if not chunk:
                        poll.unregister(key.fileobj)
                        continue
                    total += len(chunk)
                    require(total <= 262144, 'package-query-size')
                    if key.data:
                        out.append(chunk)
        require(child.wait(timeout=max(0.01, deadline - time.monotonic())) == 0, 'package-query-failed')
        return b''.join(out).decode('utf-8', errors='strict').strip()
    finally:
        if child.poll() is None:
            child.kill()
            child.wait()
        child.stdout.close()
        child.stderr.close()


def installed_version(route, run=command):
    require(EXECUTABLE.resolve() == EXECUTABLE, 'package-executable-path')
    info = EXECUTABLE.stat()
    require(stat.S_ISREG(info.st_mode) and info.st_uid == 0 and not info.st_mode & 0o022,
            'package-executable-owner')
    if route == 'apt':
        require(run(['/usr/bin/dpkg-query', '-S', str(EXECUTABLE)]) == 'quest: /opt/Quest/quest',
                'package-ownership')
        value = run(['/usr/bin/dpkg-query', '-W', '-f=${db:Status-Status} ${Version}', 'quest'])
        require(value.startswith('installed '), 'package-not-installed')
        value = value.removeprefix('installed ')
    elif route == 'dnf':
        require(run(['/usr/bin/rpm', '-qf', '--qf', '%{NAME}', str(EXECUTABLE)]) == 'quest', 'package-ownership')
        value = run(['/usr/bin/rpm', '-q', '--qf', '%{VERSION}-%{RELEASE}', 'quest'])
    else:
        require(run(['/usr/bin/pacman', '-Qoq', str(EXECUTABLE)]) == 'quest', 'package-ownership')
        value = run(['/usr/bin/pacman', '-Q', 'quest'])
        require(value.startswith('quest '), 'package-not-installed')
        value = value.removeprefix('quest ')
    match = re.fullmatch(r'(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(?:-([1-9][0-9]*))?(?:\.x86_64)?', value)
    require(match and len(value) <= 80, 'package-version')
    return { 'version': '.'.join(match.groups()[:3]), 'build': match.group(4), 'nativeVersion': value }


def omarchy_command(home):
    # Current Omarchy is an Arch package. A stale version marker is not authority.
    path = Path('/usr/bin/omarchy')
    root_file(path)
    require(os.access(path, os.X_OK)
            and command(['/usr/bin/pacman', '-Qoq', str(path)]) == 'omarchy', 'omarchy-command-owner')
    return str(path)


def omarchy_root():
    # Validate a specific Omarchy-owned file: the directory itself is shared with
    # other packages. root_file also checks its canonical, root-owned parent chain.
    version = Path('/usr/share/omarchy/version')
    root_file(version)
    require(command(['/usr/bin/pacman', '-Qoq', str(version)]) == 'omarchy', 'omarchy-source-owner')
    return str(version.parent)


def detect_omarchy(home):
    # A partially removed installation must not silently fall back to raw pacman -Syu.
    return any(path.exists() or path.is_symlink() for path in
               (Path('/usr/bin/omarchy'), Path('/usr/share/omarchy'),
                Path(home) / '.local/share/omarchy', Path('/etc/omarchy')))


def apply_commands(route, distro, home):
    require(os.getuid() != 0 and os.geteuid() == os.getuid(), 'user-session-required')
    if route == 'apt':
        safe = ['-o', 'Acquire::AllowInsecureRepositories=false', '-o', 'Acquire::AllowDowngradeToInsecureRepositories=false',
                '-o', 'APT::Get::AllowUnauthenticated=false']
        # Refresh only Quest metadata; existing system sources and their trust are untouched.
        return [['/usr/bin/sudo', '--', '/usr/bin/apt-get', *safe,
                 '-o', 'Dir::Etc::sourcelist=/etc/apt/sources.list.d/quest.sources',
                 '-o', 'Dir::Etc::sourceparts=-', 'update'],
                ['/usr/bin/sudo', '--', '/usr/bin/apt-get', *safe, 'install', '--only-upgrade', 'quest']]
    if route == 'dnf':
        return [['/usr/bin/sudo', '--', '/usr/bin/dnf', '--refresh', '--disablerepo=*', '--enablerepo=quest',
                 '--setopt=gpgcheck=1', '--setopt=repo_gpgcheck=1', '--setopt=localpkg_gpgcheck=1', 'upgrade', 'quest']]
    if distro == 'omarchy' or detect_omarchy(home):
        return [[omarchy_command(home), 'update']]
    return [['/usr/bin/sudo', '--', '/usr/bin/pacman', '-Syu', 'quest/quest']]


def apt_candidate(policy):
    candidates = re.findall(r'^  Candidate: (\S+)$', policy, re.M)
    require(len(candidates) == 1 and re.fullmatch(r'\d+\.\d+\.\d+(?:-[1-9]\d*)?', candidates[0]),
            'package-candidate-invalid')
    candidate, selected, priorities, origins = candidates[0], False, [], []
    for line in policy.splitlines():
        # Other available versions can use Debian suffixes outside Quest's grammar.
        # Every version block resets selection, even at zero/negative priority.
        version = re.fullmatch(
            r'\s*(?:\*\*\*\s+)?(\S+)\s+(-?(?:0|[1-9]\d*))'
            r'(?:\s+\(phased (?:100|[1-9]?\d)%\))?', line)
        if version:
            selected = version.group(1) == candidate
            if selected:
                priorities.append(int(version.group(2)))
        elif re.match(r'\s*(?:\*\*\*\s+)?\d\S*\s+[-+]?\d', line):
            # Unknown version annotations must not lend origins to the prior block.
            require(False, 'package-candidate-invalid')
        elif selected and ' Packages' in line:
            origins.append(line.strip())
    # Specific package pins determine the version priority. Quest's installer
    # permits quest at 700 while denying other packages from its index at -1.
    require(len(priorities) == 1 and priorities[0] > 0, 'package-candidate-priority')
    # Pins do not choose between sources of the same version. Keep exactly one
    # origin, independently of its signed index priority.
    require(len(origins) == 1 and re.fullmatch(
        r'-?(?:0|[1-9]\d*) https://packages\.quest\.app/linux/apt stable/main amd64 Packages', origins[0]),
        'package-candidate-origin')
    return candidate


def selected_native_version(route, selected):
    revised = selected.get('releaseSet', {}).get('revision') is not None
    if route == 'apt' and not revised:
        return selected['version']
    return selected['version'] + '-' + (selected['build'] if revised or route == 'pacman' else '1')


def native_version_order(version):
    match = re.fullmatch(r'(\d+)\.(\d+)\.(\d+)(?:-([1-9]\d*))?', version)
    require(match, 'package-version')
    return tuple(int(part or 0) for part in match.groups())


def quest_running():
    # Never terminate a process; refuse unreadable processes owned by this update user.
    for directory in Path('/proc').iterdir():
        if directory.name.isdecimal():
            try:
                target = os.readlink(directory / 'exe')
            except PermissionError:
                try:
                    require(os.getuid() != 0 and directory.stat().st_uid != os.getuid(),
                            'process-identity-unavailable')
                except (FileNotFoundError, ProcessLookupError):
                    pass
                continue
            except (FileNotFoundError, ProcessLookupError):
                continue
            if target in (str(EXECUTABLE), str(EXECUTABLE) + ' (deleted)'):
                return True
    return False


def wait_closed(*, allow_privileged_check=False):
    try:
        deadline = time.monotonic() + 60
        while quest_running() and time.monotonic() < deadline:
            time.sleep(0.25)
        require(not quest_running(), 'quest-still-running')
    except Refused as error:
        if str(error) != 'process-identity-unavailable' or not allow_privileged_check:
            raise
        # PAM/SSH processes can retain this UID while denying /proc/PID/exe reads.
        # Their mutable names are not proof that they are unrelated to Quest.
        # After the user's update consent, ask the same package-owned helper to
        # inspect actual executable identities with ordinary sudo authentication.
        require(os.getuid() == os.geteuid() != 0, 'user-session-required')
        require(sys.stdin.isatty() and sys.stdout.isatty(), 'interactive-terminal-required')
        print('Administrator authentication is needed to verify that Quest has closed.', flush=True)
        result = subprocess.run(['/usr/bin/sudo', '--', str(HELPER), 'wait-closed'],
                                env={'PATH': SYSTEM_PATH, 'LC_ALL': 'C.UTF-8'}, check=False)
        require(result.returncode == 0, 'process-check-failed')


def main(args):
    require(args in (['check'], ['apply'], ['wait-closed'], ['automatic'], ['automatic-enable'], ['automatic-disable']), 'command-invalid')
    if args == ['wait-closed']:
        require(os.getuid() == os.geteuid() == 0, 'root-required')
    receipt = json.loads(root_file(RECEIPT))
    route, distro = validate_receipt(receipt)
    identity = installed_version(route)
    home = pwd.getpwuid(os.getuid()).pw_dir
    if route == 'pacman' and detect_omarchy(home):
        distro = 'omarchy'
    if args == ['check']:
        automatic = None
        if route in ('apt', 'dnf'):
            try:
                automatic = load_tooling(route).automatic_status(route)
            except Exception:
                automatic = 'unavailable'
        print(json.dumps({'schema': 1, 'installation': distro if distro == 'omarchy' else route,
                          **identity, **({'automaticUpdates': automatic} if automatic else {})}))
        return
    require(sys.stdin.isatty() and sys.stdout.isatty(), 'interactive-terminal-required')
    if args == ['wait-closed']:
        # Receipt, native ownership and the full installed tooling manifest have
        # already been validated above. This fixed mode only observes processes.
        wait_closed()
        print('Quest is closed.')
        return
    if args[0].startswith('automatic'):
        require(route in ('apt', 'dnf') and distro == 'other', 'automatic-route-refused')
        if args == ['automatic']:
            print('Quest-only automatic updates run daily while Quest is closed. The next launch uses the installed version.')
            print('They do not upgrade the rest of your system. Dependency conflicts require a manual update.')
            choice = input('Enable, disable, or cancel? [e/d/N] ').strip().lower()
            require(choice in ('e', 'd'), 'cancelled')
            mode = 'automatic-enable' if choice == 'e' else 'automatic-disable'
            # Ordinary sudo prompts in this terminal. No password or privileged operation
            # crosses renderer IPC, and the root invocation repeats every trust check above.
            result = subprocess.run(['/usr/bin/sudo', '--', str(HELPER), mode],
                env={'PATH': SYSTEM_PATH, 'HOME': home, 'LC_ALL': 'C.UTF-8'}, check=False)
            require(result.returncode == 0, 'automatic-settings-failed')
        else:
            require(os.getuid() == 0 and os.geteuid() == 0, 'root-required')
            enabled = args == ['automatic-enable']
            require(input(('Enable' if enabled else 'Disable') + ' Quest-only automatic updates? [y/N] ').strip().lower() == 'y', 'cancelled')
            require(installed_version(route) == identity, 'package-changed')
            tooling = load_tooling(route)
            tooling.configure_automatic(route, enabled)
            print('Quest automatic updates enabled.' if enabled else
                  'Quest automatic updates disabled. A package transaction already started may finish.')
        return
    commands = apply_commands(route, distro, home)
    full = route == 'pacman'
    print('Quest will close before continuing. ' + ('This is a full system update using your distribution workflow.' if full
          else 'Only the Quest package will be requested. Dependencies may be updated by your package manager.'))
    require(input('Continue? [y/N] ').strip().lower() == 'y', 'cancelled')
    wait_closed(allow_privileged_check=True)
    # Recheck all trust and ownership after user interaction and before any package action.
    require(validate_receipt(json.loads(root_file(RECEIPT))) == (route, receipt['distro']), 'installation-changed')
    require(installed_version(route) == identity, "package-changed")
    selected = verified_candidate(route)
    expected = selected_native_version(route, selected)
    if expected == identity['nativeVersion']:
        print('Quest is already up to date.')
        return
    require(native_version_order(expected) > native_version_order(identity['nativeVersion']),
            'package-downgrade-refused')
    env = {key: value for key, value in os.environ.items() if key in
           ('DISPLAY', 'WAYLAND_DISPLAY', 'XDG_RUNTIME_DIR', 'DBUS_SESSION_BUS_ADDRESS', 'TERM', 'COLORTERM')}
    env.update({'PATH': SYSTEM_PATH, 'HOME': home, 'USER': pwd.getpwuid(os.getuid()).pw_name, 'LC_ALL': 'C.UTF-8'})
    if route == 'pacman' and (distro == 'omarchy' or detect_omarchy(home)):
        omarchy_command(home)
        env['OMARCHY_PATH'] = omarchy_root()
    for args in commands:
        require(selected['_repositoryValidUntil'] > time.time(), 'stage-expired')
        if route == 'apt' and '--only-upgrade' in args:
            candidate = apt_candidate(command(['/usr/bin/apt-cache', 'policy', 'quest']))
            require(candidate == expected, 'package-selection-changed')
            command(['/usr/bin/dpkg', '--compare-versions', candidate, 'gt', identity['nativeVersion']])
            # Pin the verified candidate; another configured repository must not win selection.
            args = [*args[:-1], 'quest=' + candidate]
        elif route == 'dnf':
            args = [*args[:-1], 'quest-' + expected + '.x86_64']
        require(subprocess.run(args, env=env, check=False).returncode == 0, 'package-update-failed')
    # In particular, Omarchy may return zero when its confirmation was cancelled. Native
    # ownership and the exact signed selection, not a command exit, establish Quest's outcome.
    require(installed_version(route)['nativeVersion'] == expected, 'package-update-unconfirmed')
    require(validate_receipt(json.loads(root_file(RECEIPT))) == (route, receipt['distro']), 'post-update-tooling-unconfirmed')
    print('Package update finished. You can reopen Quest.')

if __name__ == '__main__':
    exit_code = 0
    try:
        main(sys.argv[1:])
    except Exception as error:
        code = str(error) if isinstance(error, Refused) else 'update-unavailable'
        print(json.dumps({'schema': 1, 'error': code}), file=sys.stderr)
        exit_code = 1
    finally:
        if sys.argv[1:] in (['apply'], ['automatic']) and sys.stdin.isatty() and sys.stdout.isatty():
            try:
                input('Press Enter to close this terminal. ')
            except (EOFError, KeyboardInterrupt):
                pass
    sys.exit(exit_code)
