| 1 | #!/usr/bin/env python3 |
| 2 | """Manifest, pictogrammen en service worker, met de juiste scope onder /verhaaltjesboek/.""" |
| 3 | import json |
| 4 | import os |
| 5 | import socket |
| 6 | import struct |
| 7 | import subprocess |
| 8 | import tempfile |
| 9 | import time |
| 10 | import urllib.error |
| 11 | import urllib.request |
| 12 | from pathlib import Path |
| 13 | |
| 14 | WEB = Path(__file__).resolve().parents[1] |
| 15 | ROOT = WEB.parent |
| 16 | PREFIX = '/verhaaltjesboek' |
| 17 | checks = 0 |
| 18 | |
| 19 | def check(value, label): |
| 20 | global checks |
| 21 | checks += 1 |
| 22 | assert value, label |
| 23 | |
| 24 | def png_size(path): |
| 25 | data = path.read_bytes() |
| 26 | check(data.startswith(b'\x89PNG\r\n\x1a\n') and data[12:16] == b'IHDR', f'{path.name} is een PNG') |
| 27 | return struct.unpack('>II', data[16:24]) |
| 28 | |
| 29 | manifest = json.loads((WEB / 'manifest.webmanifest').read_text()) |
| 30 | check(manifest['name'] == 'Verhalenboek' and manifest['short_name'] == 'Verhalenboek', 'Naam van de webapp') |
| 31 | check(manifest['lang'] == 'nl' and manifest['display'] == 'standalone', 'Taal en standalone-weergave') |
| 32 | check(manifest['start_url'] == PREFIX + '/' and manifest['scope'] == PREFIX + '/', 'start_url en scope blijven in de submap') |
| 33 | check(manifest['id'] == PREFIX + '/', 'App-id blijft de submap') |
| 34 | check(manifest['start_url'].startswith(manifest['scope']), 'start_url valt binnen scope') |
| 35 | check(manifest['theme_color'] == '#f4efe6' and manifest['background_color'] == '#f4efe6', 'Kleuren volgen de pagina') |
| 36 | icons = {(icon['sizes'], icon['purpose']): icon for icon in manifest['icons']} |
| 37 | for size, purpose in [('192x192', 'any'), ('512x512', 'any'), ('192x192', 'maskable'), ('512x512', 'maskable')]: |
| 38 | icon = icons.get((size, purpose)) |
| 39 | check(icon is not None, f'Icoon {size} ({purpose})') |
| 40 | check(icon['src'].startswith(PREFIX + '/assets/'), f'Icoonpad blijft in de submap: {icon["src"]}') |
| 41 | file = WEB / icon['src'].removeprefix(PREFIX + '/') |
| 42 | check(file.is_file() and png_size(file) == tuple(int(part) for part in size.split('x')), f'{file.name} is {size}') |
| 43 | |
| 44 | check(png_size(WEB / 'assets/apple-touch-icon.png') == (180, 180), 'apple-touch-icon is 180') |
| 45 | check(png_size(WEB / 'assets/favicon-32.png') == (32, 32), 'favicon-32 is 32') |
| 46 | svg = (WEB / 'assets/favicon.svg').read_text() |
| 47 | check('f4a261' in svg.lower() and '3f63d4' in svg.lower(), 'Favicon blijft een blauw boek met oranje bladwijzer') |
| 48 | check('<svg' in (WEB / 'assets/mask-icon.svg').read_text(), 'mask-icon is svg') |
| 49 | |
| 50 | worker = (WEB / 'sw.js').read_text() |
| 51 | check("request.method !== 'GET'" in worker, 'Service worker laat schrijfacties met rust') |
| 52 | check('api' in worker and 'auth' in worker and 'callback' in worker, 'Service worker slaat api en login over') |
| 53 | check('wiki' in worker and '/api.php/wiki/' in worker, 'Service worker noemt wiki-schrijfacties via api.php') |
| 54 | import re |
| 55 | wiki_bypass = re.compile(r'/(?:api|auth|callback)\.php(?:/|$)', re.I) |
| 56 | check(wiki_bypass.search('/verhaaltjesboek/api.php/wiki/pages') and wiki_bypass.search('/verhaaltjesboek/api.php/wiki/categories'), 'Wiki-API valt onder de api.php-uitsluiting') |
| 57 | check(worker.index("request.method !== 'GET'") < worker.index('function bypass'), 'Een schrijfactie komt niet in de cache terecht') |
| 58 | check("pathname.endsWith('/sw.js')" in worker, 'Service worker cachet zichzelf niet') |
| 59 | registrar = (WEB / 'assets/pwa.js').read_text() |
| 60 | check("new URL('sw.js', scope)" in registrar and 'scope: scope.href' in registrar, 'Registratie gebruikt de map van de pagina') |
| 61 | |
| 62 | router = r'''<?php |
| 63 | declare(strict_types=1); |
| 64 | $root = getenv('VERHALENBOEK_WEBROOT'); |
| 65 | $prefix = '/verhaaltjesboek'; |
| 66 | $path = rawurldecode(parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/'); |
| 67 | if ($path === $prefix) { |
| 68 | header('Location: '.$prefix.'/'); |
| 69 | return true; |
| 70 | } |
| 71 | if (!is_string($root) || $root === '' || !str_starts_with($path, $prefix.'/')) { |
| 72 | http_response_code(404); |
| 73 | header('Content-Type: text/plain; charset=utf-8'); |
| 74 | echo 'Niet gevonden'; |
| 75 | return true; |
| 76 | } |
| 77 | $rel = substr($path, strlen($prefix)); |
| 78 | if (preg_match('#^/api\.php(?:/|$)#', $rel)) { |
| 79 | $_SERVER['SCRIPT_NAME'] = $prefix.'/api.php'; |
| 80 | require $root.'/api.php'; |
| 81 | return true; |
| 82 | } |
| 83 | if ($rel === '/' || $rel === '') { |
| 84 | $_SERVER['SCRIPT_NAME'] = $prefix.'/index.php'; |
| 85 | require $root.'/index.php'; |
| 86 | return true; |
| 87 | } |
| 88 | $file = $root.$rel; |
| 89 | if (str_ends_with(strtolower($rel), '.php') && is_file($file)) { |
| 90 | $_SERVER['SCRIPT_NAME'] = $prefix.$rel; |
| 91 | require $file; |
| 92 | return true; |
| 93 | } |
| 94 | if (is_file($file)) { |
| 95 | $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION)); |
| 96 | $type = match ($extension) { |
| 97 | 'webmanifest' => 'application/manifest+json; charset=utf-8', |
| 98 | 'js' => 'application/javascript; charset=utf-8', |
| 99 | 'css' => 'text/css; charset=utf-8', |
| 100 | 'svg' => 'image/svg+xml', |
| 101 | 'png' => 'image/png', |
| 102 | default => 'application/octet-stream', |
| 103 | }; |
| 104 | header('Content-Type: '.$type); |
| 105 | if ($extension === 'webmanifest' || basename($file) === 'sw.js') header('Cache-Control: no-cache'); |
| 106 | readfile($file); |
| 107 | return true; |
| 108 | } |
| 109 | http_response_code(404); |
| 110 | header('Content-Type: text/plain; charset=utf-8'); |
| 111 | echo 'Niet gevonden'; |
| 112 | return true; |
| 113 | ''' |
| 114 | |
| 115 | def free_port(): |
| 116 | with socket.socket() as sock: |
| 117 | sock.bind(('127.0.0.1', 0)) |
| 118 | return sock.getsockname()[1] |
| 119 | |
| 120 | def wait_for(url): |
| 121 | for _ in range(100): |
| 122 | try: |
| 123 | urllib.request.urlopen(url).close() |
| 124 | return |
| 125 | except urllib.error.URLError: |
| 126 | time.sleep(0.05) |
| 127 | raise RuntimeError('server startte niet: ' + url) |
| 128 | |
| 129 | def fetch(url, method='GET', data=None, headers=None): |
| 130 | request = urllib.request.Request(url, data=data, headers=headers or {}, method=method) |
| 131 | try: |
| 132 | response = urllib.request.urlopen(request) |
| 133 | except urllib.error.HTTPError as error: |
| 134 | response = error |
| 135 | with response: |
| 136 | body = response.read() |
| 137 | return response.status, {key.lower(): value for key, value in response.headers.items()}, body |
| 138 | |
| 139 | with tempfile.TemporaryDirectory(prefix='pwa-', dir=WEB / 'tests/artifacts') as tmp: |
| 140 | tmp_path = Path(tmp) |
| 141 | (tmp_path / 'data').mkdir() |
| 142 | router_path = tmp_path / 'router.php' |
| 143 | router_path.write_text(router) |
| 144 | port = free_port() |
| 145 | base = f'http://127.0.0.1:{port}{PREFIX}' |
| 146 | log = (tmp_path / 'server.log').open('w') |
| 147 | process = subprocess.Popen( |
| 148 | ['php', '-d', 'opcache.enable=0', '-S', f'127.0.0.1:{port}', '-t', str(tmp_path), str(router_path)], |
| 149 | stdout=log, stderr=log, start_new_session=True, |
| 150 | env={**os.environ, 'VERHALENBOEK_DATA_DIR': str(tmp_path / 'data'), 'VERHALENBOEK_WEBROOT': str(WEB)}, |
| 151 | ) |
| 152 | try: |
| 153 | wait_for(base + '/') |
| 154 | status, headers, body = fetch(base + '/manifest.webmanifest') |
| 155 | check(status == 200 and headers.get('content-type', '').startswith('application/manifest+json'), 'Manifest heeft het juiste type') |
| 156 | served = json.loads(body) |
| 157 | check(served['start_url'] == PREFIX + '/' and served['scope'] == PREFIX + '/', 'Geserveerd manifest blijft in de submap') |
| 158 | status, headers, html = fetch(base + '/') |
| 159 | page = html.decode() |
| 160 | check(status == 200 and '<title>Verhalenboek</title>' in page, 'Startpagina onder de submap') |
| 161 | check('rel="manifest" href="manifest.webmanifest"' in page, 'Manifestlink is relatief') |
| 162 | check('href="/manifest' not in page and 'href="/assets/' not in page and 'src="/' not in page, 'Geen absolute paden vanaf de domeinwortel') |
| 163 | check('apple-mobile-web-app-capable' in page and 'apple-mobile-web-app-title' in page and 'Verhalenboek' in page, 'iOS-meta voor toevoegen aan beginscherm') |
| 164 | check('assets/apple-touch-icon.png' in page and 'assets/favicon.svg' in page and 'assets/pwa.js' in page, 'Favicon, aanraakicoon en registratie') |
| 165 | check('name="theme-color"' in page and '#f4efe6' in page, 'Thema-kleur') |
| 166 | check(page.index('>Overzicht<') < page.index('>Wiki<') < page.index('>Instellingen<'), 'Wiki staat in het menu naast Overzicht') |
| 167 | for name in ['icon-192.png', 'icon-512.png', 'icon-maskable-512.png', 'apple-touch-icon.png', 'favicon.svg']: |
| 168 | status, headers, payload = fetch(base + '/assets/' + name) |
| 169 | check(status == 200 and len(payload) > 32, name + ' is bereikbaar') |
| 170 | status, headers, script = fetch(base + '/sw.js') |
| 171 | check(status == 200 and b"method !== 'GET'" in script and headers.get('content-type', '').startswith('application/javascript'), 'Service worker onder de submap') |
| 172 | status, _, me = fetch(base + '/api.php/me', headers={'Accept': 'application/json'}) |
| 173 | profile = json.loads(me) |
| 174 | check(status == 200 and profile['user']['name'] == 'test_user_1', 'API GET onder de submap blijft werken') |
| 175 | status, _, denied = fetch( |
| 176 | base + '/api.php/days', |
| 177 | method='POST', |
| 178 | data=b'{}', |
| 179 | headers={'Accept': 'application/json', 'Content-Type': 'application/json'}, |
| 180 | ) |
| 181 | check(status == 403 and 'Ongeldige sessie' in json.loads(denied)['error'], 'API POST onder de submap blijft naar PHP gaan') |
| 182 | status, _, wiki_denied = fetch( |
| 183 | base + '/api.php/wiki/categories', |
| 184 | method='POST', |
| 185 | data=b'{"title":"Plekken"}', |
| 186 | headers={'Accept': 'application/json', 'Content-Type': 'application/json'}, |
| 187 | ) |
| 188 | check(status == 403 and 'Ongeldige sessie' in json.loads(wiki_denied)['error'], 'Wiki-schrijven onder de submap blijft naar PHP gaan') |
| 189 | status, doc_headers, docs = fetch(base + '/docs.php') |
| 190 | check(status == 200 and 'rel="manifest" href="manifest.webmanifest"' in docs.decode(), 'Documentatie deelt het manifest') |
| 191 | finally: |
| 192 | process.kill() |
| 193 | process.wait(timeout=5) |
| 194 | log.close() |
| 195 | |
| 196 | root_port = free_port() |
| 197 | with tempfile.TemporaryDirectory(prefix='pwa-root-', dir=WEB / 'tests/artifacts') as tmp: |
| 198 | env = {**os.environ, 'VERHALENBOEK_DATA_DIR': str(Path(tmp) / 'data')} |
| 199 | Path(tmp, 'data').mkdir() |
| 200 | log = Path(tmp, 'server.log').open('w') |
| 201 | process = subprocess.Popen( |
| 202 | ['php', '-d', 'opcache.enable=0', '-S', f'127.0.0.1:{root_port}', '-t', str(WEB), str(WEB / 'router.php')], |
| 203 | stdout=log, stderr=log, start_new_session=True, env=env, |
| 204 | ) |
| 205 | try: |
| 206 | wait_for(f'http://127.0.0.1:{root_port}/') |
| 207 | status, headers, body = fetch(f'http://127.0.0.1:{root_port}/manifest.webmanifest') |
| 208 | check(status == 200 and headers.get('content-type', '').startswith('application/manifest+json'), 'Lokale router zet het manifest-type') |
| 209 | check(b'"scope"' in body, 'Lokale router levert het manifest') |
| 210 | finally: |
| 211 | process.kill() |
| 212 | process.wait(timeout=5) |
| 213 | log.close() |
| 214 | |
| 215 | print(f'PWA: {checks} controles geslaagd.') |
projects-timfalken-com verhalenboek