engawa-chat 0.6.0

A peer-to-peer chat lobby for editors and browsers
"""Opt-in real relay smoke: python tests/browser_invite.py <engawa executable>.

Requires a built invite site, Python Playwright with WebKit, and relay access.
The host uses a random room and does not announce it to the public lobby.
"""
import argparse
from contextlib import ExitStack
from functools import partial
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
import json
import os
from pathlib import Path
import re
import secrets
import subprocess
import tempfile
import threading
import tomllib
from urllib.parse import parse_qs, urlencode, urlsplit

from playwright.sync_api import expect, sync_playwright


class Static(SimpleHTTPRequestHandler):
    def log_message(self, *_):
        pass


def stop_node(node):
    node.stdin.close()
    try:
        node.wait(timeout=8)
    except subprocess.TimeoutExpired:
        node.kill()
        node.wait()
    finally:
        node.stdout.close()


def disconnect(page):
    page.locator('#session-menu > summary').click()
    page.locator('#leave').click()
    expect(page.locator('#picker')).to_be_visible()
    assert not urlsplit(page.url).fragment


def check_retention(writer, reader, lobby_url, phone_label):
    def reconnect(page):
        disconnect(page)
        page.goto('about:blank')  # Drop the Wasm instance; keep only the browser profile.
        page.goto(lobby_url)
        page.locator('#join').click()
        expect(page.locator('#directory')).to_be_visible(timeout=60000)

    def enter(page, name):
        page.locator('#rooms button').filter(has_text=name).click()
        expect(page.locator('#room-name')).to_contain_text(name)

    def post(page, text):
        page.locator('#draft').fill(text)
        page.locator('#send').click()
        expect(page.locator('#messages').get_by_text(text, exact=True)).to_have_count(1)

    enter(writer, '質問')
    post(writer, 'A wrote this alone')
    reconnect(writer)
    enter(reader, '質問')
    post(reader, 'B wrote while A was away')
    expect(reader.locator('#messages')).not_to_contain_text('A wrote this alone')
    enter(writer, '質問')
    owned = writer.locator('#messages li').filter(has_text='A wrote this alone')
    expect(owned.locator('.retract')).to_be_visible()
    for page in (reader, writer):
        for text in ('A wrote this alone', 'B wrote while A was away'):
            expect(page.get_by_text(text, exact=True)).to_have_count(1, timeout=60000)
    post(writer, 'Same trip after restart in another room')
    synced = reader.locator('#messages li').filter(has_text='Same trip after restart in another room')
    expect(synced.locator('small')).to_have_text(phone_label, timeout=30000)
    writer.locator('#identity-settings > summary').click()
    writer.locator('#handle').fill('つばめ')
    writer.locator('#trip').uncheck()
    writer.locator('#save-identity').click()
    post(writer, 'Just a name')
    expect(reader.locator('#messages li').filter(has_text='Just a name').locator('small')).to_have_text('つばめ', timeout=30000)
    expect(synced.locator('small')).to_have_text(phone_label)
    owned.locator('.retract').click()
    expect(reader.get_by_text('A wrote this alone', exact=True)).to_have_count(0, timeout=30000)
    reconnect(writer)
    reconnect(reader)
    enter(writer, '質問')
    expect(writer.get_by_text('B wrote while A was away', exact=True)).to_be_visible()
    expect(writer.get_by_text('A wrote this alone', exact=True)).to_have_count(0)
    writer.locator('#back-to-lobby').click()

    enter(reader, 'もくもく')
    post(reader, 'Live only, never restored')
    reconnect(reader)
    enter(reader, 'もくもく')
    expect(reader.locator('#empty')).to_be_visible()
    expect(reader.get_by_text('Live only, never restored', exact=True)).to_have_count(0)
    reader.locator('#back-to-lobby').click()


def check_lobby(engine, host, guest, room_url, lobby_url, desktop_room, phone_label):
    back = guest.locator('#back-to-lobby')
    expect(back).to_have_text('← 部屋一覧')
    back.click()
    expect(guest.locator('#directory')).to_be_visible(timeout=60000)
    guest.locator('#rooms button').filter(has_text=desktop_room).click(timeout=60000)
    expect(guest.locator('#messages')).to_contain_text('Before the phone joined', timeout=60000)
    guest.locator('#back-to-lobby').click()
    expect(guest.locator('#directory')).to_be_visible()

    other = engine.new_page(viewport={'width': 390, 'height': 844}, is_mobile=True, has_touch=True)
    try:
        other.goto(room_url)
        expect(other.locator('#invite-target')).to_contain_text(desktop_room)
        other.locator('#open-lobby').click()
        expect(other.locator('#directory')).to_be_visible(timeout=60000)
        check_retention(guest, other, lobby_url, phone_label)
        # Create the room on a phone: its advertised endpoint is not the inviting PC.
        phone_room = 'from-phone-' + secrets.token_hex(5)
        if not guest.locator('#name').is_visible():
            guest.locator('#directory details > summary').click()
        guest.locator('#name').fill(phone_room)
        guest.locator('#history').select_option('on')
        guest.locator('#create button[type=submit]').click()
        other.locator('#rooms button').filter(has_text=phone_room).click(timeout=60000)
        expect(host.locator('#title')).to_contain_text(desktop_room)
        other.locator('#draft').fill('a different mobile peer joined')
        other.locator('#send').click()
        expect(guest.locator('#messages')).to_contain_text('a different mobile peer joined', timeout=30000)
        expect(host.locator('#messages')).not_to_contain_text('a different mobile peer joined')
        host.locator('#rooms button').filter(has_text=phone_room).click(timeout=60000)
        expect(host.locator('#title')).to_contain_text(phone_room)
        expect(host.locator('#messages')).to_contain_text('a different mobile peer joined', timeout=60000)
        host.locator('#draft').fill('desktop joined the phone-created room')
        host.locator('#compose button').click()
        expect(other.locator('#messages')).to_contain_text('desktop joined the phone-created room', timeout=30000)
        guest.locator('#back-to-lobby').click()
        expect(guest.locator('#directory')).to_be_visible()
        expect(guest.locator('#messages li')).to_have_count(0)
        disconnect(guest)
    finally:
        other.close()


def check_private_invite(engine, invite, lobby_url, key, name):
    # A copied endpoint/room ID without the correct key cannot be used as a room invite.
    probe = engine.new_page()
    try:
        for malformed in (invite.replace('#', '?key=not-a-real-secret#', 1),
                          invite.replace('v=2', 'v=1', 1)):
            probe.goto(malformed)
            expect(probe.locator('#error')).to_be_visible(timeout=30000)
            expect(probe.locator('#join')).to_be_disabled()
            assert key not in probe.locator('body').inner_text()
        for wrong in (secrets.token_hex(32), None):
            fields = {k: v[0] for k, v in parse_qs(urlsplit(invite).fragment).items()}
            if wrong is None:
                fields.pop('key')
                fields.pop('veranda')
                fields['v'] = '1'
            else:
                fields['key'] = wrong
            probe.goto(invite.split('#')[0] + '#' + urlencode(fields))
            expect(probe.locator('#error')).to_be_visible(timeout=30000)
            expect(probe.locator('#join')).to_be_disabled()
        # With a different valid key and the right sign/endpoint, even the lobby
        # bootstrap fails: no private room list or history is available.
        probe.goto(lobby_url.replace(key, secrets.token_hex(32)))
        probe.locator('#join').click()
        expect(probe.locator('#retry')).to_be_visible(timeout=55000)
        expect(probe.locator('#directory')).to_be_hidden()
        expect(probe.locator('#messages li')).to_have_count(0)
        expect(probe.locator('#veranda-name')).to_contain_text(name)
    finally:
        probe.close()


def smoke(binary, relay, base=None, private=False):
    with ExitStack() as stack:
        if not base:
            site = Path(__file__).resolve().parents[1] / 'target/invite-site'
            if not (site / 'pkg/engawa_browser_bg.wasm').is_file():
                raise SystemExit('Run python browser/build.py first')
            server = stack.enter_context(ThreadingHTTPServer(('127.0.0.1', 0), partial(Static, directory=str(site))))
            threading.Thread(target=server.serve_forever, daemon=True).start()
            stack.callback(server.shutdown)
            base = f'http://127.0.0.1:{server.server_port}/'
        invite_pattern = re.compile('^' + re.escape(base) + '#.+')
        env = {**os.environ, 'ENGAWA_INVITE_BASE': base, 'ENGAWA_INVITE_RELAY': relay, 'ENGAWA_NO_AUTOUPDATE': '1'}
        env.pop('ENGAWA_PEER', None)
        profile = stack.enter_context(tempfile.TemporaryDirectory())
        conf = Path(profile) / 'engawa.toml'
        key = None
        veranda = 'テストさん家の縁側'
        if private:
            subprocess.run([str(binary.resolve()), 'veranda', 'new', veranda, '--out', str(conf)], check=True)
            key = tomllib.loads(conf.read_text(encoding='utf-8'))['veranda']['key']
        else:
            conf.touch()
        with conf.open('a', encoding='utf-8') as f:
            f.write('\n[identity]\nname = "ゆき"\ntrip = true\n')
        node = subprocess.Popen([str(binary.resolve()), '--config', str(conf), '--data-dir', profile, 'serve', '--stdio'],
                                env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
        stack.callback(stop_node, node)
        session = json.loads(node.stdout.readline())
        pw = stack.enter_context(sync_playwright())
        engine = pw.webkit.launch()
        stack.callback(engine.close)
        host = engine.new_page()
        guest = engine.new_page(viewport={'width': 390, 'height': 844}, is_mobile=True, has_touch=True)
        guest.set_default_timeout(60000)
        requests = []
        guest.on('request', lambda req: requests.append(req.url))
        host.goto(session['url'] + '/#token=' + session['token'])
        host.locator('#rooms button').first.wait_for()
        host.locator('#lobby-invite-details > summary').click()
        field = host.locator('#lobby-invite-url')
        expect(field).to_have_value(invite_pattern, timeout=60000)
        lobby_url = field.input_value()
        fields = parse_qs(urlsplit(lobby_url).fragment)
        expected = {'v', 'kind', 'peer', 'relay'}
        if private:
            expected.update({'key', 'veranda'})
            assert fields['key'] == [key] and fields['veranda'] == [veranda]
        assert set(fields) == expected and fields['kind'] == ['lobby'] and fields['v'] == ['2' if private else '1']
        assert lobby_url.startswith(base + '#') and session['token'] not in lobby_url
        host.locator('#create').locator('..').locator('summary').click()
        name = 'phone-' + secrets.token_hex(6)
        host.locator('#name').fill(name)
        host.locator('#policy').select_option('on')
        host.locator('#create button').click()
        host.locator('#draft').fill('Before the phone joined')
        host.locator('#compose button').click()
        host.locator('#chat details > summary').click()
        expect(host.locator('#invite-link')).to_have_value(invite_pattern, timeout=60000)
        invite = host.locator('#invite-link').input_value()
        assert invite.startswith(base + '#') and session['token'] not in invite
        if private:
            check_private_invite(engine, invite, lobby_url, key, veranda)
        guest.goto(invite)
        target = guest.locator('#invite-target')
        expect(target).to_be_visible(timeout=30000)
        expect(target).to_contain_text(name)
        policy = guest.locator('#policy')
        expect(policy).to_be_visible()
        expect(policy).to_contain_text('履歴あり')
        expect(guest.locator('#visibility')).to_contain_text('招待制' if private else '公開')
        expect(guest.locator('#join')).to_be_enabled()
        expect(guest.locator('#directory')).to_be_hidden()
        expect(guest.locator('#chat')).to_be_hidden()
        guest.locator('#join').click()
        expect(guest.locator('#messages')).to_contain_text('Before the phone joined', timeout=60000)
        guest.locator('#draft').fill('こんにちは from the phone')
        guest.locator('#send').click()
        remote = host.locator('#messages li').filter(has_text='こんにちは from the phone')
        expect(remote).to_be_visible(timeout=20000)
        expect(remote.locator('.retract')).to_be_hidden()
        expect(remote.locator('small')).to_have_text('名無しさん')
        native = guest.locator('#messages li').filter(has_text='Before the phone joined').locator('small')
        trip = re.compile(r'^ゆき ◆[0-9a-f]{16}$')
        expect(native).to_have_text(trip)
        native_label = native.inner_text()
        guest.locator('#identity-settings > summary').click()
        guest.locator('#handle').fill('ゆき')
        guest.locator('#trip').check()
        guest.locator('#save-identity').click()
        guest.locator('#draft').fill('Same handle, another device')
        guest.locator('#send').click()
        phone = host.locator('#messages li').filter(has_text='Same handle, another device').locator('small')
        expect(phone).to_have_text(trip, timeout=30000)
        assert phone.inner_text() != native_label
        host.locator('#draft').fill('Hello from the desktop')
        host.locator('#compose button').click()
        expect(guest.locator('#messages')).to_contain_text('Hello from the desktop', timeout=20000)
        guest.locator('#messages li').filter(has_text='こんにちは from the phone').locator('.retract').click()
        expect(remote).to_have_count(0, timeout=20000)
        check_lobby(engine, host, guest, invite, lobby_url, name, phone.inner_text())
        assert not any(urlsplit(url).netloc == urlsplit(session['url']).netloc for url in requests)
        if private:
            assert all(key not in u.split('#')[0] for u in requests)
    print('PASS: mobile lobby, solo posts after reload, offline histories merge once, withdrawal survives restart, live-only isolation, cross-peer chat')


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('binary', type=Path)
    parser.add_argument('--relay', default='https://aps1-1.relay.n0.iroh.link/')
    parser.add_argument('--site', help='Test an already-deployed invite site instead of the local bundle')
    parser.add_argument('--private', action='store_true', help='Use a new private veranda and test membership isolation')
    args = parser.parse_args()
    smoke(args.binary, args.relay, args.site, args.private)