#!/usr/bin/python3
# summary: Add or remove an optional PIN-protected FIDO2 sign-in key.
"""Usage: starchaser security key status | enroll | remove

Enrollment exchanges JSON lines with Settings for PIN, touch and explicit saving.
The register command offers a terminal conversation. Your password stays available.
"""
import json
import ctypes
import fcntl
import os
import pwd
import re
import selectors
import shutil
import signal
import subprocess
import sys
import termios
import time
from pathlib import Path

USER = pwd.getpwuid(os.getuid()).pw_name
MAPPING = Path('/etc/starchaser/security-keys') / USER
UNCONFIRMED_SAVE = "Couldn't confirm whether the security key was saved. Choose Check again before trying again. Your password still works."


def verify_saved(credential):
    """Resolve a lost helper reply using the account's public, root-owned mapping."""
    try:
        saved = MAPPING.read_text()
    except FileNotFoundError:
        saved = ''
    except (OSError, UnicodeError):
        return False, UNCONFIRMED_SAVE
    if saved.strip() == credential.strip():
        return True, 'Security key saved. Your password still works.'
    return False, "The new security key wasn't saved. Your password still works."


class EnrollmentStopped(Exception):
    pass


class EnrollmentFailure(Exception):
    pass


def enroll_dialog(timeout=120):
    """Private TTY for the tool; public credential stdout never enters the UI stream."""
    for lib in (Path(__file__).resolve().parents[1] / 'system/usr/local/lib/starchaser', Path('/usr/local/lib/starchaser')):
        if (lib / 'local_auth.py').is_file():
            sys.path.insert(0, str(lib))
            break
    from local_auth import validate_mapping
    child = None
    master = slave = None
    deadline = time.monotonic() + timeout
    incoming = bytearray()
    public = bytearray()
    tty_text = ''
    phase = 'waiting'
    pin_sent = False
    tool_problem = "Couldn't add the security key. Plug in a key with a PIN set, check its PIN and try again. Your sign-in methods weren't changed."
    parent = os.getppid()

    def emit(state, message, ok=True):
        nonlocal phase
        phase = state
        print(json.dumps(dict(phase=state, ok=ok, message=message)), flush=True)

    def stop(*_):
        raise EnrollmentStopped()

    old_handler = signal.signal(signal.SIGTERM, stop)
    # Quickshell closes a destroyed page's process. Also handle a parent that dies abruptly.
    ctypes.CDLL(None).prctl(1, signal.SIGTERM, 0, 0, 0)
    try:
        if os.getppid() != parent:
            raise EnrollmentStopped()
        emit('waiting', 'Plug in your security key. Its PIN must already be set. Your password still works.')
        master, slave = os.openpty()
        attrs = termios.tcgetattr(slave)
        attrs[3] &= ~termios.ECHO
        termios.tcsetattr(slave, termios.TCSANOW, attrs)
        owner = os.getpid()

        def private_terminal():
            os.setsid()
            fcntl.ioctl(slave, termios.TIOCSCTTY, 0)
            ctypes.CDLL(None).prctl(1, signal.SIGTERM, 0, 0, 0)
            if os.getppid() != owner:
                os._exit(1)

        child = subprocess.Popen(['pamu2fcfg', '-u', USER, '-o', 'pam://starchaser', '-i', 'pam://starchaser', '-N'],
            stdin=slave, stdout=subprocess.PIPE, stderr=slave, preexec_fn=private_terminal,
            env=dict(os.environ, LC_ALL='C'))
        os.close(slave); slave = None
        with selectors.DefaultSelector() as selector:
            selector.register(master, selectors.EVENT_READ, 'tty')
            selector.register(child.stdout, selectors.EVENT_READ, 'public')
            selector.register(sys.stdin, selectors.EVENT_READ, 'input')
            streams = 2
            ready = False
            while True:
                if time.monotonic() >= deadline:
                    raise EnrollmentFailure('Adding the security key took too long. Try again. Your password still works.')
                for key, _ in selector.select(min(.1, max(0, deadline-time.monotonic()))):
                    try:
                        data = os.read(key.fd, 4096)
                    except OSError:
                        if key.data != 'tty': raise
                        data = b''  # PTY end of file is EIO on Linux.
                    if not data:
                        selector.unregister(key.fileobj)
                        if key.data == 'input': raise EnrollmentStopped()
                        streams -= 1
                        continue
                    if key.data == 'public':
                        public.extend(data)
                        if len(public) > 18000: raise EnrollmentFailure('The key returned an unsupported credential. Your password still works.')
                    elif key.data == 'tty':
                        # Raw tool diagnostics may contain device paths or echo; never publish them.
                        tty_text += data.decode('utf-8', 'replace')
                        if 'No FIDO authenticator available' in tty_text:
                            tool_problem = "No security key was found. Plug it in, then try again. Your sign-in methods weren't changed."
                        elif 'FIDO_ERR_PIN_INVALID' in tty_text:
                            tool_problem = "That PIN wasn't accepted. Check it and try again. A key locks itself after several wrong PINs. Your sign-in methods weren't changed."
                        elif 'has no PIN' in tty_text or 'does not support PIN' in tty_text:
                            tool_problem = "This key needs a PIN set before it can be added. Use a PIN-protected FIDO2 key. Your sign-in methods weren't changed."
                        if re.search(r'Enter PIN for [^\r\n]{1,256}: ', tty_text):
                            if pin_sent or phase == 'pin':
                                raise EnrollmentFailure('The key asked for its PIN again. Check the PIN before trying again. Your password still works.')
                            emit('pin', 'Enter the PIN for your security key.')
                            tty_text = ''
                        tty_text = tty_text[-1024:]
                    else:
                        incoming.extend(data)
                        if len(incoming) > 4096: raise EnrollmentStopped()
                        while b'\n' in incoming:
                            line, _, rest = incoming.partition(b'\n'); incoming = bytearray(rest)
                            frame = json.loads(line)
                            if not isinstance(frame, dict): raise EnrollmentStopped()
                            if frame.get('action') == 'cancel': raise EnrollmentStopped()
                            if frame.get('action') == 'save' and ready:
                                emit('saving', 'Approve saving the security key in the password prompt. Your password still works.')
                                result = subprocess.run(['pkexec', '/usr/local/lib/starchaser/starchaser-local-auth', 'add'],
                                    input=public.decode(), text=True, capture_output=True, timeout=120)
                                try: saved = json.loads(result.stdout)
                                except ValueError: saved = {}
                                if not isinstance(saved, dict): saved = {}
                                ok = result.returncode == 0 and saved.get('ok') is True
                                error = saved.get('errors')
                                confirmed_failure = (result.returncode > 0 and saved.get('ok') is False
                                                     and isinstance(error, str) and bool(error.strip()))
                                if ok:
                                    message = 'Security key saved. Your password still works.'
                                elif result.returncode in (126, 127) and not result.stdout.strip():
                                    # pkexec never dispatched our helper for these authorization outcomes.
                                    message = 'Nothing changed. Saving the security key was not approved. Your password still works.'
                                elif confirmed_failure:
                                    message = error
                                else:
                                    ok, message = verify_saved(public.decode())
                                emit('done', message, ok)
                                return 0 if ok else 1
                            pin = frame.pop('pin', None)
                            if phase != 'pin' or not isinstance(pin, str) or not 4 <= len(pin.encode('utf-8')) <= 63 or any(ord(c)<32 or ord(c)==127 for c in pin):
                                raise EnrollmentStopped()
                            os.write(master, pin.encode('utf-8')+b'\n')
                            pin = None; line = b''; frame.clear()
                            pin_sent = True
                            emit('touch', 'Touch your security key when its light flashes.')
                if not ready and streams == 0 and child.poll() is not None:
                    if child.returncode or not pin_sent:
                        raise EnrollmentFailure(tool_problem)
                    public = bytearray(validate_mapping(public.decode(), USER).encode())
                    ready = True
                    emit('ready', 'The key is ready. Choose Save security key, then approve the password prompt. This replaces any previous key. Your password still works.')
    except EnrollmentStopped:
        ok, message = verify_saved(public.decode()) if phase == 'saving' else (False, 'Nothing changed. Your password still works.')
        emit('done', message, ok)
        return 0 if ok else 1
    except EnrollmentFailure as error:
        emit('done', str(error), False)
        return 1
    except (OSError, ValueError, subprocess.SubprocessError):
        # A lost reply may follow a completed atomic write; inspect the public mapping.
        ok, message = (verify_saved(public.decode()) if phase == 'saving' else
                       (False, "Couldn't add the security key. Check that it's plugged in and its PIN is set, then try again. Your sign-in methods were not changed."))
        emit('done', message, ok)
        return 0 if ok else 1
    finally:
        signal.signal(signal.SIGTERM, old_handler)
        ctypes.CDLL(None).prctl(1, 0, 0, 0, 0)
        if child:
            if child.poll() is None:
                child.terminate()
                try: child.wait(timeout=3)
                except subprocess.TimeoutExpired: child.kill(); child.wait()
            child.stdout.close()
        for fd in (master, slave):
            if fd is not None: os.close(fd)


def main(args):
    if args in ([], ['--help'], ['-h']): print(__doc__); return 0
    if args == ['status']:
        print(json.dumps(dict(ok=True, available=bool(shutil.which('pamu2fcfg')), enrolled=MAPPING.is_file()))); return 0
    if args == ['enroll']:
        return enroll_dialog()
    if args == ['register']:
        print('Add a security key\n\nInsert a FIDO2 key with a PIN already set. Enter its PIN and touch it when asked.\nYour account password will still work. This replaces any previous security key.\n', flush=True)
        print('Plug in your security key now.', flush=True)
        try:
            result = subprocess.run(['pamu2fcfg', '-u', USER, '-o', 'pam://starchaser', '-i', 'pam://starchaser', '-N'],
                                    stdout=subprocess.PIPE, text=True, timeout=120)
            if result.returncode:
                print('No security key was found. Plug it in, then choose Add a security key again. Your sign-in methods were not changed.', flush=True)
                return 1
            result = subprocess.run(['pkexec', '/usr/local/lib/starchaser/starchaser-local-auth', 'add'],
                                    input=result.stdout, text=True, capture_output=True, timeout=120)
            data = json.loads(result.stdout)
            print(data.get('message') or data.get('errors') or 'The key could not be saved. Your password still works.', flush=True)
            return result.returncode
        except (OSError, ValueError, subprocess.SubprocessError):
            print('The security key did not finish. Choose Check again in Settings > Users before trying again. Your password still works.', flush=True)
            return 1
        finally:
            # Keep failures and cancellations readable in both terminal implementations.
            try: input('Press Enter to close. ')
            except EOFError: pass
    if args == ['remove']:
        result = subprocess.run(['pkexec', '/usr/local/lib/starchaser/starchaser-local-auth', 'remove'], capture_output=True, text=True)
        if result.returncode in (126, 127) and not result.stdout.strip():
            print(json.dumps(dict(ok=False, message='Nothing was removed. Your security key still works.')))
        else:
            sys.stdout.write(result.stdout)
        return result.returncode
    print(__doc__); return 2


if __name__ == '__main__':
    try: sys.exit(main(sys.argv[1:]))
    except (OSError, ValueError, subprocess.SubprocessError):
        print(json.dumps(dict(ok=False, errors="The security key didn't finish. Your password still works."))); sys.exit(1)
