aboutsummaryrefslogtreecommitdiffstats
path: root/shim_app.py
blob: 5b57b390526174ba4a74dada6b567f4ef5bb9566 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
#!/usr/bin/env python3

import mimetypes
import json
import os
import re
import secrets
import shutil
import sqlite3
import stat
import tarfile
import tempfile
import time
import uuid
import zipfile
from dataclasses import dataclass
from pathlib import Path
from typing import Callable, Optional
from urllib.parse import urlparse

from flask import (
    Flask,
    Response,
    abort,
    flash,
    g,
    make_response,
    redirect,
    render_template_string,
    request,
    send_file,
    url_for,
)

from auth_backend import AuthBackend, LocalMojicryptAuthBackend


# config
APP_NAME = "shim"
BIND_HOST = "0.0.0.0"
PORT = 8585

SESSION_TTL_SECONDS = 86400
MAX_UPLOAD_BYTES = 1024 * 1024 * 1024
MAX_EXTRACTED_BYTES = 2 * 1024 * 1024 * 1024
MAX_EXTRACTED_FILES = 20000
MAX_FORM_MEMORY_SIZE = 2 * 1024 * 1024

SQLITE_TIMEOUT_SECONDS = 30.0
SQLITE_BUSY_TIMEOUT_MS = 30000
SQLITE_CACHE_SIZE_KIB = 32768
SQLITE_MMAP_SIZE_BYTES = 256 * 1024 * 1024
SQLITE_WAL_AUTOCHECKPOINT_PAGES = 1000

SESSION_COOKIE = "shim_session"
ACTIVE_SITE_COOKIE = "shim_active_site"
MUTATING_METHODS = {"POST", "PUT", "PATCH", "DELETE"}
SLUG_RE = re.compile(r"^[a-z0-9](?:[a-z0-9-]{0,126}[a-z0-9])?$")
UUID_RE = re.compile(
    r"^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"
)
ARCHIVE_SUFFIXES = (
    ".zip",
    ".tar",
    ".tar.bz2",
    ".tar.gz",
    ".tar.xz",
    ".tbz2",
    ".tgz",
    ".txz",
)
ROOT_ATTR_RE = re.compile(r"(?i)\b(href|src|action|poster)=([\"'])/([^\"']*)\2")
CSS_URL_RE = re.compile(r"(?i)url\(\s*([\"']?)/([^\)'\"\s]+)\1\s*\)")


# template configs
SHELL_TEMPLATE = """<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="color-scheme" content="light dark">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <meta http-equiv="pragma" content="no-cache">
    <meta name="shim-csrf-token" content="{{ csrf_token or '' }}">
    <link rel="icon" href="{{ url_for('favicon') }}" type="image/svg+xml">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/kj-sh604/noir.css@latest/out/noir.min.css">
    <link rel="stylesheet" href="{{ url_for('noir_overrides_css') }}">
    <script nonce="{{ script_nonce or '' }}">
        if ("serviceWorker" in navigator && navigator.serviceWorker.getRegistrations) {
            navigator.serviceWorker.getRegistrations().then(function (registrations) {
                registrations.forEach(function (registration) {
                    try {
                        var scopePath = new URL(registration.scope).pathname;
                        if (scopePath === "/") {
                            registration.unregister();
                        }
                    } catch (_err) {
                    }
                });
            });
        }

        (function () {
            var scrollKey = "__shim_form_scroll_restore__";
            var csrfMeta = document.querySelector("meta[name='shim-csrf-token']");
            var csrfToken = csrfMeta ? (csrfMeta.getAttribute("content") || "") : "";

            try {
                var saved = sessionStorage.getItem(scrollKey);
                if (saved) {
                    sessionStorage.removeItem(scrollKey);
                    var parsed = JSON.parse(saved);
                    if (parsed && parsed.path === window.location.pathname) {
                        var y = Number(parsed.y);
                        if (!Number.isNaN(y)) {
                            window.requestAnimationFrame(function () {
                                window.scrollTo(0, y);
                            });
                        }
                    }
                }
            } catch (_err) {
            }

            document.addEventListener("submit", function (event) {
                var form = event.target;
                if (!(form instanceof HTMLFormElement)) {
                    return;
                }

                var confirmMessage = form.getAttribute("data-confirm");
                if (confirmMessage && !window.confirm(confirmMessage)) {
                    event.preventDefault();
                    return;
                }

                if (csrfToken && form.method && form.method.toUpperCase() === "POST") {
                    var hasToken = form.querySelector("input[name='_csrf_token']");
                    if (!hasToken) {
                        var hidden = document.createElement("input");
                        hidden.type = "hidden";
                        hidden.name = "_csrf_token";
                        hidden.value = csrfToken;
                        form.appendChild(hidden);
                    }
                }

                try {
                    sessionStorage.setItem(
                        scrollKey,
                        JSON.stringify({
                            path: window.location.pathname,
                            y: window.scrollY || window.pageYOffset || 0,
                        })
                    );
                } catch (_err) {
                }
            }, true);

            document.addEventListener("focusin", function (event) {
                var input = event.target;
                if (!(input instanceof HTMLInputElement)) {
                    return;
                }
                if (input.hasAttribute("data-unlock-readonly")) {
                    input.removeAttribute("readonly");
                }
            });
        })();
    </script>
    <title>{{ title }} - {{ app_name }}</title>
</head>
<body>
<main>
    <header class="topbar">
        <h1>{{ app_name }}</h1>
        <nav>
            {% if current_user %}
                <span class="quiet">{{ current_user['username'] }}{% if current_user['role'] == 'admin' %} ({{ current_user['role'] }}){% endif %}</span>
                <form method="post" action="{{ url_for('logout') }}" class="inline">
                    <button type="submit">logout</button>
                </form>
            {% else %}
                <a href="https://youtu.be/XGxIE1hr0w4" target="_blank" rel="noopener noreferrer">🧷</a>
            {% endif %}
        </nav>
    </header>
    {% with messages = get_flashed_messages(with_categories=true) %}
        {% if messages %}
            <section class="stack">
                {% for category, message in messages %}
                    <article class="flash {{ category }}">{{ message }}</article>
                {% endfor %}
            </section>
        {% endif %}
    {% endwith %}
    {{ body | safe }}
</main>
</body>
</html>
"""


SETUP_BODY_TEMPLATE = """
<section class="stack">
    <p>first startup detected. <br><br> create the initial admin account to continue.</p>
    <form method="post" action="{{ url_for('setup_submit') }}" class="stack" autocomplete="off">
        <label>
           username <strong>(admin)</strong>
            <input name="username" type="text" required minlength="2" maxlength="254" autocomplete="new-password" autocapitalize="none" autocorrect="off" spellcheck="false" data-lpignore="true" data-unlock-readonly="1" readonly>
        </label>
        <label>
            password
            <input name="password" type="password" required minlength="2" autocomplete="new-password">
        </label>
        <label>
            confirm password
            <input name="confirm" type="password" required minlength="2" autocomplete="new-password">
        </label>
        <button type="submit">create admin account</button>
    </form>
</section>
"""


LOGIN_BODY_TEMPLATE = """
<section class="stack">
    <p>small static site host for archive uploads</p>
    <form method="post" action="{{ url_for('login_submit') }}" class="stack" autocomplete="off">
        <label>
            username
            <input name="username" type="text" required minlength="2" maxlength="254" autocomplete="new-password" autocapitalize="none" autocorrect="off" spellcheck="false" data-lpignore="true" data-unlock-readonly="1" readonly>
        </label>
        <label>
            password
            <input name="password" type="password" required minlength="2" autocomplete="current-password">
        </label>
        <button type="submit">sign in</button>
    </form>
</section>
"""


DASHBOARD_BODY_TEMPLATE = """
<section class="stack">
    <h2>upload static site</h2>
    <p>upload one archive containing your built static files. <br><br> this will generate a random 40 character slug, you can ask your admin to change it to a custom one.</p>
    <p class="quiet">accepted formats: {{ allowed_suffixes | join(', ') }}</p>
    <form method="post" action="{{ url_for('upload_site') }}" enctype="multipart/form-data" class="stack">
        <label>
            archive file
            <input type="file" name="archive" required>
        </label>
        <button type="submit">upload and publish</button>
    </form>
</section>

<section class="stack">
    <h2>{% if is_admin %}all uploaded sites{% else %}your uploaded sites{% endif %}</h2>
    {% if sites %}
        <table>
            <thead>
                <tr>
                    {% if is_admin %}<th>id</th>{% endif %}
                    <th>link</th>
                    {% if is_admin %}<th>owner</th>{% endif %}
                    <th>archive</th>
                    <th>created</th>
                    <th>actions</th>
                </tr>
            </thead>
            <tbody>
                {% for site in sites %}
                    <tr>
                        {% if is_admin %}<td>{{ site['id'] }}</td>{% endif %}
                        <td>
                            <a href="/s/{{ site['slug'] }}/" target="_blank" rel="noopener">{{ site['slug'] }}</a>
                        </td>
                        {% if is_admin %}<td>{{ site['owner_username'] }}</td>{% endif %}
                        <td>{{ site['original_filename'] }}</td>
                        <td>{{ site['created_at'] }}</td>
                        <td>
                            <form method="post" action="{{ url_for('delete_site', site_id=site['id']) }}" class="inline" data-confirm="delete this site?">
                                <button type="submit" style="all: revert;">delete</button>
                            </form>
                        </td>
                    </tr>
                {% endfor %}
            </tbody>
        </table>
    {% else %}
        <p>no sites uploaded yet.</p>
    {% endif %}
</section>

{% if is_admin %}
<section>
        <article class="stack">
            <h2>rename slugs</h2>
            {% if sites %}
                <table>
                    <thead>
                        <tr>
                            <th>archive</th>
                            <th>current slug</th>
                            <th>owner</th>
                            <th>rename</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for site in sites %}
                            <tr>
                                <td>{{ site['original_filename'] }}</td>
                                <td>{{ site['slug'] }}</td>
                                <td>{{ site['owner_username'] }}</td>
                                <td>
                                    <form method="post" action="{{ url_for('admin_update_slug', site_id=site['id']) }}" class="stack">
                                        <input type="text" name="slug" value="{{ site['slug'] }}" required minlength="1" maxlength="128" pattern="[a-z0-9][a-z0-9-]*" style="all: revert;" autocomplete="off">
                                        <button type="submit" style="all: revert;">rename slug</button>
                                    </form>
                                </td>
                            </tr>
                        {% endfor %}
                    </tbody>
                </table>
            {% else %}
                <p>no sites uploaded yet.</p>
            {% endif %}
        </article>

    <article class="stack">
        <h2>create user</h2>
        <form method="post" action="{{ url_for('admin_create_user') }}" class="stack" autocomplete="off">
            <label>
                username
                <input type="text" name="username" required minlength="2" maxlength="254" autocomplete="new-password" autocapitalize="none" autocorrect="off" spellcheck="false" data-lpignore="true" data-unlock-readonly="1" readonly>
            </label>
            <label>
                password
                <input type="password" name="password" required minlength="2" autocomplete="new-password">
            </label>
            <label>
                role
                <select name="role" required>
                    <option value="user" selected>user</option>
                    <option value="admin">admin</option>
                </select>
            </label>
            <button type="submit">create user</button>
        </form>
    </article>
    <article class="stack">
        <h2>users</h2>
        {% if users %}
            <table>
                <thead>
                    <tr>
                        <th>id</th>
                        <th>username</th>
                        <th>role</th>
                        <th>created</th>
                        <th>actions</th>
                    </tr>
                </thead>
                <tbody>
                    {% for user in users %}
                        <tr>
                            <td>{{ user['id'] }}</td>
                            <td>{{ user['username'] }}</td>
                            <td>{{ user['role'] }}</td>
                            <td>{{ user['created_at'] }}</td>
                            <td>
                                <form method="post" action="{{ url_for('admin_update_user_username', user_id=user['id']) }}" class="stack" autocomplete="off">
                                    <input type="text" name="username" value="{{ user['username'] }}" required minlength="2" maxlength="254" autocomplete="new-password" autocapitalize="none" autocorrect="off" spellcheck="false" data-lpignore="true" style="all: revert;">
                                    <button type="submit" style="all: revert;">rename user</button>
                                </form>
                                <br>
                                <form method="post" action="{{ url_for('admin_update_user_password', user_id=user['id']) }}" class="stack" autocomplete="off">
                                    <input type="password" name="password" required minlength="2" autocomplete="new-password" style="all: revert;">
                                    <button type="submit" style="all: revert;">set password</button>
                                </form><br>
                                {% if user['id'] != current_user['id'] %}
                                    <form method="post" action="{{ url_for('admin_delete_user', user_id=user['id']) }}" class="inline" data-confirm="delete this user and all owned sites?">
                                        <button type="submit" style="all: revert;">delete</button>
                                    </form>
                                {% else %}
                                    <strong>current account</strong>
                                {% endif %}
                            </td>
                        </tr>
                    {% endfor %}
                </tbody>
            </table>
        {% else %}
            <p>no users found.</p>
        {% endif %}
    </article>
</section>
{% endif %}
"""

# code and server logic
@dataclass(frozen=True)
class AppConfig:
    base_dir: Path
    app_name: str
    db_path: Path
    sites_dir: Path
    mojicrypt_bin: Path
    bind: str
    port: int


ConnectFn = Callable[[], sqlite3.Connection]


def slug_is_valid(slug: str) -> bool:
    return bool(slug) and bool(SLUG_RE.fullmatch(slug))


def uuid_is_valid(value: str) -> bool:
    value = (value or "").strip().lower()
    return bool(UUID_RE.fullmatch(value))


def request_path_is_suspicious(path: str) -> bool:
    if "\x00" in path:
        return True
    return any(part in {".", ".."} for part in path.split("/"))


def detect_archive_suffix(filename: str) -> Optional[str]:
    lower = filename.lower()
    for suffix in ARCHIVE_SUFFIXES:
        if lower.endswith(suffix):
            return suffix
    return None


def normalize_archive_member_path(raw_name: str) -> Optional[Path]:
    name = raw_name.replace("\\", "/").strip()
    if not name:
        return None
    if "\x00" in name:
        raise ValueError("archive contains invalid null byte path")
    while name.startswith("./"):
        name = name[2:]
    if not name:
        return None
    if name.startswith("/"):
        raise ValueError("archive contains absolute paths")
    parts = [part for part in name.split("/") if part not in ("", ".")]
    if not parts:
        return None
    if any(len(part) > 255 for part in parts):
        raise ValueError("archive contains overlong path component")
    if len(parts) > 64:
        raise ValueError("archive path depth is too large")
    if any(part == ".." for part in parts):
        raise ValueError("archive contains parent path traversal")
    if ":" in parts[0]:
        raise ValueError("archive contains invalid drive path")
    return Path(*parts)


def ensure_path_under(root: Path, candidate: Path) -> None:
    # raises when candidate escapes root via traversal or symlink tricks.
    root_real = root.resolve()
    candidate_real = candidate.resolve()
    candidate_real.relative_to(root_real)


def rewrite_root_path(path_without_leading_slash: str, slug: str) -> str:
    value = path_without_leading_slash
    lowered = value.lower()
    if value.startswith("/"):
        return "/" + value
    if lowered.startswith("api/"):
        return "/" + value
    if lowered.startswith("app/"):
        return "/" + value
    if lowered.startswith("s/"):
        return "/" + value
    if lowered.startswith("_site/"):
        return "/" + value
    if not value:
        return f"/s/{slug}/"
    return f"/s/{slug}/{value}"


def build_slug_runtime_guard(slug: str) -> str:
    # browser storage is origin-scoped, so this injects a best-effort slug namespace shim.
    slug_json = json.dumps(slug)
    return (
        '<script id="shim-slug-runtime-guard">'
        "(function(){"
        f"const slug={slug_json};"
        "const prefix='__shim_store__'+slug+'__:';"
        "function patchStorage(storage, namespace){"
        "if(!storage){return;}"
        "const ns=prefix+namespace+':';"
        "try{"
        "const rawGet=storage.getItem.bind(storage);"
        "const rawSet=storage.setItem.bind(storage);"
        "const rawRemove=storage.removeItem.bind(storage);"
        "const rawKey=storage.key.bind(storage);"
        "storage.getItem=function(key){return rawGet(ns+String(key));};"
        "storage.setItem=function(key,value){return rawSet(ns+String(key),String(value));};"
        "storage.removeItem=function(key){return rawRemove(ns+String(key));};"
        "storage.clear=function(){var keys=[];for(var i=0;i<storage.length;i++){var current=rawKey(i);if(current&&current.indexOf(ns)===0){keys.push(current);}}for(var j=0;j<keys.length;j++){rawRemove(keys[j]);}};"
        "storage.key=function(index){var keys=[];for(var i=0;i<storage.length;i++){var current=rawKey(i);if(current&&current.indexOf(ns)===0){keys.push(current.slice(ns.length));}}return (typeof keys[index]==='undefined')?null:keys[index];};"
        "}catch(_err){}"
        "}"
        "patchStorage(window.localStorage,'l');"
        "patchStorage(window.sessionStorage,'s');"
        "if('serviceWorker' in navigator && navigator.serviceWorker && navigator.serviceWorker.register){"
        "const rawRegister=navigator.serviceWorker.register.bind(navigator.serviceWorker);"
        "navigator.serviceWorker.register=function(scriptURL, options){"
        "var nextScript=scriptURL;"
        "try{var raw=String(scriptURL||'');if(raw.indexOf('/')===0){nextScript='/s/'+slug+raw;}}catch(_err){}"
        "var nextOptions=Object.assign({}, options||{});"
        "if(!nextOptions.scope){nextOptions.scope='/s/'+slug+'/';}"
        "return rawRegister(nextScript, nextOptions);"
        "};"
        "}"
        "})();"
        "</script>"
    )


def rewrite_html_for_slug(html_text: str, slug: str) -> str:
    def repl(match: re.Match[str]) -> str:
        attr = match.group(1)
        quote = match.group(2)
        path_value = match.group(3)
        rewritten = rewrite_root_path(path_value, slug)
        return f"{attr}={quote}{rewritten}{quote}"

    # rewrite absolute-root links so hosted apps stay inside /s/<slug>/.
    updated = ROOT_ATTR_RE.sub(repl, html_text)
    head_match = re.search(r"(?i)<head[^>]*>", updated)
    if head_match:
        inject_parts = []
        if "id=\"shim-slug-runtime-guard\"" not in updated:
            inject_parts.append("\n    " + build_slug_runtime_guard(slug))
        if "<base " not in updated.lower():
            inject_parts.append(f"\n    <base href=\"/s/{slug}/\">")
        if inject_parts:
            insert_at = head_match.end()
            updated = updated[:insert_at] + "".join(inject_parts) + updated[insert_at:]
    return updated


def rewrite_css_for_slug(css_text: str, slug: str) -> str:
    def repl(match: re.Match[str]) -> str:
        quote = match.group(1)
        path_value = match.group(2)
        rewritten = rewrite_root_path(path_value, slug)
        return f"url({quote}{rewritten}{quote})"

    return CSS_URL_RE.sub(repl, css_text)


def looks_like_spa_route(subpath: str) -> bool:
    if not subpath:
        return True
    name = Path(subpath).name
    return "." not in name


def random_slug(length: int = 40) -> str:
    alphabet = "abcdefghijklmnopqrstuvwxyz0123456789"
    return "".join(secrets.choice(alphabet) for _ in range(length))


def reserve_random_slug(connect_db: ConnectFn) -> str:
    for _ in range(30):
        slug = random_slug(40)
        with connect_db() as conn:
            row = conn.execute("SELECT 1 FROM sites WHERE slug = ?", (slug,)).fetchone()
        if not row:
            return slug
    raise RuntimeError("failed to reserve a unique slug")


def extract_slug_from_referer(referer: Optional[str]) -> Optional[str]:
    if not referer:
        return None
    try:
        path = urlparse(referer).path
    except ValueError:
        return None
    for prefix in ("/s/", "/_site/"):
        if path.startswith(prefix):
            remainder = path[len(prefix) :]
            slug = remainder.split("/", 1)[0]
            if slug_is_valid(slug):
                return slug
    return None


def extract_zip_secure(archive_path: Path, destination: Path) -> None:
    total_size = 0
    total_files = 0
    with zipfile.ZipFile(archive_path, "r") as zf:
        for info in zf.infolist():
            member_path = normalize_archive_member_path(info.filename)
            if member_path is None:
                continue

            # reject symlink entries
            mode = (info.external_attr >> 16) & 0o170000
            if mode == stat.S_IFLNK:
                raise ValueError("zip symlinks are not allowed")

            target = destination / member_path
            ensure_path_under(destination, target)
            if info.is_dir():
                target.mkdir(parents=True, exist_ok=True)
                continue

            total_files += 1
            if total_files > MAX_EXTRACTED_FILES:
                raise ValueError("archive has too many files")

            total_size += int(info.file_size)
            if total_size > MAX_EXTRACTED_BYTES:
                raise ValueError("extracted archive size exceeds limit")

            target.parent.mkdir(parents=True, exist_ok=True)
            with zf.open(info, "r") as src, open(target, "wb") as dst:
                shutil.copyfileobj(src, dst, length=1024 * 1024)


def extract_tar_secure(archive_path: Path, destination: Path) -> None:
    total_size = 0
    total_files = 0
    with tarfile.open(archive_path, "r:*") as tf:
        for member in tf.getmembers():
            member_path = normalize_archive_member_path(member.name)
            if member_path is None:
                continue
            if member.issym() or member.islnk() or member.isdev():
                raise ValueError("tar links and device files are not allowed")

            target = destination / member_path
            ensure_path_under(destination, target)

            if member.isdir():
                target.mkdir(parents=True, exist_ok=True)
                continue

            if not member.isfile():
                raise ValueError("unsupported tar member type")

            total_files += 1
            if total_files > MAX_EXTRACTED_FILES:
                raise ValueError("archive has too many files")

            total_size += int(member.size)
            if total_size > MAX_EXTRACTED_BYTES:
                raise ValueError("extracted archive size exceeds limit")

            source = tf.extractfile(member)
            if source is None:
                raise ValueError("failed to extract tar file member")

            target.parent.mkdir(parents=True, exist_ok=True)
            with source, open(target, "wb") as dst:
                shutil.copyfileobj(source, dst, length=1024 * 1024)


def extract_archive_secure(archive_path: Path, suffix: str, destination: Path) -> None:
    if suffix == ".zip":
        extract_zip_secure(archive_path, destination)
        return
    extract_tar_secure(archive_path, destination)


def find_site_root(extracted_dir: Path) -> Path:
    root_index = extracted_dir / "index.html"
    if root_index.is_file():
        return extracted_dir

    candidates = sorted(
        extracted_dir.rglob("index.html"),
        key=lambda path: len(path.relative_to(extracted_dir).parts),
    )
    if not candidates:
        raise ValueError("archive must include an index.html file")
    return candidates[0].parent


def env_bool(name: str, default: bool) -> bool:
    raw = os.getenv(name, "true" if default else "false").strip().lower()
    if raw in {"1", "true", "yes", "on"}:
        return True
    if raw in {"0", "false", "no", "off"}:
        return False
    return default


def create_app(base_dir: Optional[Path] = None) -> Flask:
    project_dir = Path(base_dir or Path(__file__).parent).resolve()
    app_name = APP_NAME
    db_path = project_dir / "data" / "shim.db"
    sites_dir = project_dir / "data" / "sites"
    mojicrypt_bin = (project_dir / "vendor" / "mojicrypt").resolve()

    cfg = AppConfig(
        base_dir=project_dir,
        app_name=app_name,
        db_path=db_path,
        sites_dir=sites_dir,
        mojicrypt_bin=mojicrypt_bin,
        bind=BIND_HOST,
        port=PORT,
    )

    cfg.db_path.parent.mkdir(parents=True, exist_ok=True)
    cfg.sites_dir.mkdir(parents=True, exist_ok=True)

    app = Flask(__name__, static_folder=None)
    app.config["MAX_CONTENT_LENGTH"] = MAX_UPLOAD_BYTES
    app.config["MAX_FORM_MEMORY_SIZE"] = MAX_FORM_MEMORY_SIZE
    app.config["SECRET_KEY"] = os.getenv("SECRET_KEY", secrets.token_hex(32))
    app.config["PORT"] = cfg.port
    app.config["BIND"] = cfg.bind
    app.config["APP_NAME"] = cfg.app_name
    app.config["MOJICRYPT_BIN"] = str(cfg.mojicrypt_bin)

    sqlite_timeout_seconds = SQLITE_TIMEOUT_SECONDS
    sqlite_busy_timeout_ms = SQLITE_BUSY_TIMEOUT_MS
    sqlite_cache_size_kib = SQLITE_CACHE_SIZE_KIB
    sqlite_mmap_size_bytes = SQLITE_MMAP_SIZE_BYTES
    sqlite_wal_autocheckpoint_pages = SQLITE_WAL_AUTOCHECKPOINT_PAGES
    enforce_app_request_guards = env_bool("ENFORCE_APP_REQUEST_GUARDS", False)

    def connect_db() -> sqlite3.Connection:
        conn = sqlite3.connect(str(cfg.db_path), timeout=sqlite_timeout_seconds)
        # row objects keep query call sites readable and less index-fragile.
        conn.row_factory = sqlite3.Row
        # wal + busy timeout gives sqlite much better mixed read/write concurrency.
        conn.execute("PRAGMA journal_mode = WAL")
        conn.execute("PRAGMA synchronous = NORMAL")
        conn.execute(f"PRAGMA busy_timeout = {sqlite_busy_timeout_ms}")
        conn.execute("PRAGMA temp_store = MEMORY")
        conn.execute(f"PRAGMA cache_size = {-sqlite_cache_size_kib}")
        conn.execute(f"PRAGMA wal_autocheckpoint = {sqlite_wal_autocheckpoint_pages}")
        try:
            conn.execute(f"PRAGMA mmap_size = {sqlite_mmap_size_bytes}")
        except sqlite3.DatabaseError:
            pass
        # keep fk checks enabled even on sqlite defaults that disable them.
        conn.execute("PRAGMA foreign_keys = ON")
        try:
            conn.enable_load_extension(False)
        except (AttributeError, sqlite3.OperationalError):
            pass
        try:
            conn.execute("PRAGMA trusted_schema = OFF")
        except sqlite3.DatabaseError:
            pass
        return conn

    with connect_db() as conn:
        conn.executescript(
            """
            CREATE TABLE IF NOT EXISTS users (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                user_uuid TEXT UNIQUE NOT NULL,
                username TEXT UNIQUE NOT NULL,
                role TEXT NOT NULL CHECK (role IN ('admin', 'user')),
                encrypted_challenge TEXT NOT NULL,
                created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
            );

            CREATE TABLE IF NOT EXISTS sessions (
                token TEXT PRIMARY KEY,
                user_id INTEGER NOT NULL,
                csrf_token TEXT NOT NULL,
                expires_at INTEGER NOT NULL,
                created_at INTEGER NOT NULL,
                FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
            );

            CREATE TABLE IF NOT EXISTS sites (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                site_uuid TEXT UNIQUE NOT NULL,
                owner_user_id INTEGER NOT NULL,
                slug TEXT UNIQUE NOT NULL,
                storage_key TEXT UNIQUE NOT NULL,
                original_filename TEXT NOT NULL,
                created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
                updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
                FOREIGN KEY (owner_user_id) REFERENCES users(id) ON DELETE CASCADE
            );

            CREATE INDEX IF NOT EXISTS idx_sessions_user ON sessions(user_id);
            CREATE INDEX IF NOT EXISTS idx_sessions_expiry ON sessions(expires_at);
            CREATE INDEX IF NOT EXISTS idx_sites_owner ON sites(owner_user_id);
            """
        )

    # auth provider is injected as a single backend to keep swap-over simple.
    auth_backend: AuthBackend = LocalMojicryptAuthBackend(
        connect_db=connect_db,
        mojicrypt_bin=cfg.mojicrypt_bin,
    )

    def render_page(title: str, body_template: str, **context: object) -> str:
        body = render_template_string(body_template, **context)
        csrf_token = ""
        script_nonce = secrets.token_urlsafe(16)
        g.script_nonce = script_nonce
        if g.current_user is not None:
            csrf_token = g.current_user["csrf_token"]
        return render_template_string(
            SHELL_TEMPLATE,
            title=title,
            app_name=cfg.app_name,
            current_user=g.current_user,
            csrf_token=csrf_token,
            script_nonce=script_nonce,
            body=body,
        )

    def cookie_secure_enabled() -> bool:
        if request.is_secure:
            return True
        xfp = request.headers.get("X-Forwarded-Proto", "")
        forwarded_proto = xfp.split(",", 1)[0].strip().lower()
        return forwarded_proto == "https"

    def create_session(user_id: int) -> str:
        token = secrets.token_urlsafe(48)
        csrf_token = secrets.token_urlsafe(32)
        now = int(time.time())
        with connect_db() as conn:
            conn.execute(
                """
                INSERT INTO sessions (token, user_id, csrf_token, expires_at, created_at)
                VALUES (?, ?, ?, ?, ?)
                """,
                (token, user_id, csrf_token, now + SESSION_TTL_SECONDS, now),
            )
        return token

    def destroy_session(token: str) -> None:
        with connect_db() as conn:
            conn.execute("DELETE FROM sessions WHERE token = ?", (token,))

    def user_from_token(token: str) -> Optional[sqlite3.Row]:
        now = int(time.time())
        with connect_db() as conn:
            conn.execute("DELETE FROM sessions WHERE expires_at <= ?", (now,))
            row = conn.execute(
                """
                SELECT u.id AS internal_id, u.user_uuid AS id, u.username, u.role, s.csrf_token
                FROM sessions s
                JOIN users u ON u.id = s.user_id
                WHERE s.token = ? AND s.expires_at > ?
                """,
                (token, now),
            ).fetchone()
            if row is None:
                return None
            if not row["csrf_token"]:
                conn.execute(
                    "UPDATE sessions SET csrf_token = ? WHERE token = ?",
                    (secrets.token_urlsafe(32), token),
                )
                row = conn.execute(
                    """
                    SELECT u.id AS internal_id, u.user_uuid AS id, u.username, u.role, s.csrf_token
                    FROM sessions s
                    JOIN users u ON u.id = s.user_id
                    WHERE s.token = ? AND s.expires_at > ?
                    """,
                    (token, now),
                ).fetchone()
            return row

    def is_same_origin_request() -> bool:
        forwarded_proto = request.headers.get("X-Forwarded-Proto", "")
        external_scheme = forwarded_proto.split(",", 1)[0].strip().lower()
        if external_scheme not in {"http", "https"}:
            external_scheme = request.scheme
        external_netloc = request.host

        origin = request.headers.get("Origin")
        if origin:
            try:
                parsed_origin = urlparse(origin)
            except ValueError:
                return False
            return (
                parsed_origin.scheme == external_scheme
                and parsed_origin.netloc == external_netloc
            )

        referer = request.headers.get("Referer")
        if referer:
            try:
                parsed_referer = urlparse(referer)
            except ValueError:
                return False
            return (
                parsed_referer.scheme == external_scheme
                and parsed_referer.netloc == external_netloc
            )

        return True

    def is_valid_csrf_for_request() -> bool:
        if g.current_user is None:
            return True
        expected = g.current_user["csrf_token"] or ""
        if not expected:
            return False

        supplied = request.form.get("_csrf_token", "")
        if not supplied:
            supplied = request.headers.get("X-CSRF-Token", "")

        if not supplied:
            return False
        return secrets.compare_digest(expected, supplied)

    def require_auth() -> Optional[Response]:
        if g.current_user is not None:
            return None
        flash("login required", "error")
        return redirect(url_for("login"))

    def require_admin() -> Optional[Response]:
        auth_redirect = require_auth()
        if auth_redirect is not None:
            return auth_redirect
        if g.current_user["role"] != "admin":
            flash("admin access required", "error")
            return redirect(url_for("dashboard"))
        return None

    def get_site_by_slug(slug: str) -> Optional[sqlite3.Row]:
        with connect_db() as conn:
            return conn.execute(
                "SELECT id, owner_user_id, slug, storage_key FROM sites WHERE slug = ?",
                (slug,),
            ).fetchone()

    def send_site_file(file_path: Path, slug: str) -> Response:
        ext = file_path.suffix.lower()
        mime, _ = mimetypes.guess_type(str(file_path))
        if ext == ".html":
            html = file_path.read_text(encoding="utf-8", errors="replace")
            body = rewrite_html_for_slug(html, slug)
            response = make_response(body)
            response.mimetype = "text/html"
            response.headers["Cache-Control"] = "no-cache"
        elif ext == ".css":
            css = file_path.read_text(encoding="utf-8", errors="replace")
            body = rewrite_css_for_slug(css, slug)
            response = make_response(body)
            response.mimetype = "text/css"
            response.headers["Cache-Control"] = "public, max-age=300"
        else:
            response = make_response(
                send_file(file_path, mimetype=mime or "application/octet-stream", conditional=True)
            )
            if ext in {".js", ".mjs"}:
                response.headers["Cache-Control"] = "public, max-age=300"
            elif ext in {".png", ".jpg", ".jpeg", ".gif", ".svg", ".webp", ".ico"}:
                response.headers["Cache-Control"] = "public, max-age=86400, immutable"
            else:
                response.headers["Cache-Control"] = "public, max-age=3600"
        response.headers["X-Content-Type-Options"] = "nosniff"
        response.set_cookie(
            ACTIVE_SITE_COOKIE,
            slug,
            max_age=1800,
            httponly=True,
            samesite="Lax",
            secure=cookie_secure_enabled(),
            path="/",
        )
        return response

    def resolve_site_path(site_root: Path, subpath: str) -> Optional[Path]:
        cleaned = subpath.lstrip("/")
        candidate = (site_root / cleaned).resolve()
        try:
            candidate.relative_to(site_root.resolve())
        except ValueError:
            return None
        return candidate

    def serve_site_resource(site: sqlite3.Row, subpath: str, allow_spa: bool = True) -> Response:
        g.is_hosted_site_response = True
        site_root = (cfg.sites_dir / site["storage_key"]).resolve()
        if not site_root.is_dir():
            abort(404)

        target = resolve_site_path(site_root, subpath)
        if target is None:
            abort(404)

        if target.is_dir():
            index_path = target / "index.html"
            if index_path.is_file():
                return send_site_file(index_path, site["slug"])
        elif target.is_file():
            return send_site_file(target, site["slug"])

        if allow_spa and looks_like_spa_route(subpath):
            index_path = site_root / "index.html"
            if index_path.is_file():
                return send_site_file(index_path, site["slug"])

        abort(404)

    @app.before_request
    def load_current_user() -> None:
        if request_path_is_suspicious(request.path or "/"):
            abort(400)

        g.current_user = None
        g.is_hosted_site_response = False
        token = request.cookies.get(SESSION_COOKIE)
        if token:
            user = user_from_token(token)
            if user is not None:
                g.current_user = user

        if (
            enforce_app_request_guards
            and g.current_user is not None
            and request.method in MUTATING_METHODS
            and request.path.startswith("/app/")
        ):
            if not is_same_origin_request():
                abort(403)
            if not is_valid_csrf_for_request():
                abort(403)

    @app.after_request
    def add_security_headers(response: Response) -> Response:
        response.headers.setdefault("X-Content-Type-Options", "nosniff")
        response.headers.setdefault("Referrer-Policy", "strict-origin-when-cross-origin")
        response.headers.setdefault("X-Permitted-Cross-Domain-Policies", "none")

        if cookie_secure_enabled():
            response.headers.setdefault(
                "Strict-Transport-Security",
                "max-age=31536000; includeSubDomains",
            )

        if not getattr(g, "is_hosted_site_response", False):
            nonce = getattr(g, "script_nonce", "")
            script_src = "script-src 'self'"
            if nonce:
                script_src += f" 'nonce-{nonce}'"
            response.headers.setdefault("X-Frame-Options", "DENY")
            response.headers.setdefault(
                "Permissions-Policy",
                "camera=(), microphone=(), geolocation=(), payment=()",
            )
            response.headers.setdefault("Cross-Origin-Opener-Policy", "same-origin")
            response.headers.setdefault("Cross-Origin-Resource-Policy", "same-origin")
            response.headers.setdefault(
                "Content-Security-Policy",
                "default-src 'self'; "
                + script_src
                + "; "
                "style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
                "img-src 'self' data: blob: https:; "
                "font-src 'self' data:; "
                "connect-src 'self'; "
                "object-src 'none'; "
                "base-uri 'self'; "
                "frame-ancestors 'none'; "
                "form-action 'self'",
            )
            if request.path.startswith("/app") and response.mimetype == "text/html":
                response.headers["Cache-Control"] = "no-store"

        return response

    @app.errorhandler(413)
    def too_large(_: Exception) -> tuple[str, int]:
        return "upload exceeds configured max size", 413

    @app.get("/")
    def root() -> Response:
        return redirect(url_for("dashboard"))

    @app.get("/healthz")
    def healthz() -> tuple[str, int]:
        return "ok", 200

    @app.get("/favicon.svg")
    def favicon() -> Response:
        icon_path = cfg.base_dir / "favicon.svg"
        if not icon_path.is_file():
            abort(404)
        response = make_response(send_file(icon_path, mimetype="image/svg+xml", conditional=True))
        response.headers["Cache-Control"] = "public, max-age=3600"
        return response

    @app.get("/app/noir-overrides.css")
    def noir_overrides_css() -> Response:
        css_path = cfg.base_dir / "noir-overrides.css"
        if not css_path.is_file():
            abort(404)
        response = make_response(send_file(css_path, mimetype="text/css", conditional=True))
        response.headers["Cache-Control"] = "no-cache"
        return response

    @app.get("/app")
    def dashboard() -> Response:
        if auth_backend.bootstrap_required():
            return redirect(url_for("setup"))
        auth_redirect = require_auth()
        if auth_redirect is not None:
            return auth_redirect

        is_admin = g.current_user["role"] == "admin"
        with connect_db() as conn:
            if is_admin:
                sites = conn.execute(
                    """
                    SELECT s.site_uuid AS id, s.slug, s.original_filename, s.created_at, u.username AS owner_username
                    FROM sites s
                    JOIN users u ON u.id = s.owner_user_id
                    ORDER BY s.id DESC
                    """
                ).fetchall()
                users = conn.execute(
                    "SELECT user_uuid AS id, username, role, created_at FROM users ORDER BY id ASC"
                ).fetchall()
            else:
                sites = conn.execute(
                    """
                    SELECT site_uuid AS id, slug, original_filename, created_at
                    FROM sites
                    WHERE owner_user_id = ?
                    ORDER BY id DESC
                    """,
                    (g.current_user["internal_id"],),
                ).fetchall()
                users = []

        return render_page(
            title="dashboard",
            body_template=DASHBOARD_BODY_TEMPLATE,
            allowed_suffixes=ARCHIVE_SUFFIXES,
            is_admin=is_admin,
            sites=sites,
            users=users,
            current_user=g.current_user,
        )

    @app.get("/app/setup")
    def setup() -> Response:
        if not auth_backend.bootstrap_required():
            return redirect(url_for("dashboard"))
        return render_page(title="setup", body_template=SETUP_BODY_TEMPLATE)

    @app.post("/app/setup")
    def setup_submit() -> Response:
        if not auth_backend.bootstrap_required():
            flash("setup already completed", "error")
            return redirect(url_for("login"))

        username = request.form.get("username", "")
        password = request.form.get("password", "")
        confirm = request.form.get("confirm", "")

        if password != confirm:
            flash("passwords do not match", "error")
            return redirect(url_for("setup"))

        ok, message = auth_backend.create_user(username=username, password=password, role="admin")
        if not ok:
            flash(message, "error")
            return redirect(url_for("setup"))

        user = auth_backend.authenticate(username=username, password=password)
        if user is None:
            flash("admin created but login failed", "error")
            return redirect(url_for("login"))

        existing_token = request.cookies.get(SESSION_COOKIE)
        if existing_token:
            destroy_session(existing_token)

        token = create_session(user["id"])
        response = redirect(url_for("dashboard"))
        response.set_cookie(
            SESSION_COOKIE,
            token,
            max_age=SESSION_TTL_SECONDS,
            httponly=True,
            samesite="Lax",
            secure=cookie_secure_enabled(),
            path="/",
        )
        flash("admin account created", "success")
        return response

    @app.get("/app/login")
    def login() -> Response:
        if auth_backend.bootstrap_required():
            return redirect(url_for("setup"))
        if g.current_user is not None:
            return redirect(url_for("dashboard"))
        return render_page(title="login", body_template=LOGIN_BODY_TEMPLATE)

    @app.post("/app/login")
    def login_submit() -> Response:
        if auth_backend.bootstrap_required():
            flash("run setup first", "error")
            return redirect(url_for("setup"))

        username = request.form.get("username", "")
        password = request.form.get("password", "")
        user = auth_backend.authenticate(username=username, password=password)
        if user is None:
            flash("invalid credentials", "error")
            return redirect(url_for("login"))

        existing_token = request.cookies.get(SESSION_COOKIE)
        if existing_token:
            destroy_session(existing_token)

        token = create_session(user["id"])
        response = redirect(url_for("dashboard"))
        response.set_cookie(
            SESSION_COOKIE,
            token,
            max_age=SESSION_TTL_SECONDS,
            httponly=True,
            samesite="Lax",
            secure=cookie_secure_enabled(),
            path="/",
        )
        flash("signed in", "success")
        return response

    @app.post("/app/logout")
    def logout() -> Response:
        token = request.cookies.get(SESSION_COOKIE)
        if token:
            destroy_session(token)
        response = redirect(url_for("login"))
        response.set_cookie(
            SESSION_COOKIE,
            "",
            max_age=0,
            httponly=True,
            samesite="Lax",
            secure=cookie_secure_enabled(),
            path="/",
        )
        response.set_cookie(
            ACTIVE_SITE_COOKIE,
            "",
            max_age=0,
            httponly=True,
            samesite="Lax",
            secure=cookie_secure_enabled(),
            path="/",
        )
        return response

    @app.post("/app/upload")
    def upload_site() -> Response:
        auth_redirect = require_auth()
        if auth_redirect is not None:
            return auth_redirect

        archive = request.files.get("archive")
        if archive is None or not archive.filename:
            flash("select an archive file", "error")
            return redirect(url_for("dashboard"))

        suffix = detect_archive_suffix(archive.filename)
        if suffix is None:
            flash("unsupported archive format", "error")
            return redirect(url_for("dashboard"))

        original_filename = Path(archive.filename).name.strip()
        if not original_filename:
            flash("invalid archive filename", "error")
            return redirect(url_for("dashboard"))
        if len(original_filename) > 255:
            flash("archive filename is too long", "error")
            return redirect(url_for("dashboard"))
        if any(ord(ch) < 32 for ch in original_filename):
            flash("archive filename contains invalid characters", "error")
            return redirect(url_for("dashboard"))

        temp_dir = Path(tempfile.mkdtemp(prefix="shim-upload-"))
        archive_path = temp_dir / f"upload{suffix}"
        extract_dir = temp_dir / "extract"
        extract_dir.mkdir(parents=True, exist_ok=True)

        final_dir: Optional[Path] = None
        try:
            archive.save(archive_path)
            extract_archive_secure(archive_path, suffix, extract_dir)
            site_root = find_site_root(extract_dir)

            slug = reserve_random_slug(connect_db)
            site_uuid = str(uuid.uuid4())
            storage_key = secrets.token_hex(24)
            final_dir = cfg.sites_dir / storage_key

            shutil.copytree(site_root, final_dir)

            with connect_db() as conn:
                conn.execute(
                    """
                    INSERT INTO sites (site_uuid, owner_user_id, slug, storage_key, original_filename, created_at, updated_at)
                    VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
                    """,
                    (
                        site_uuid,
                        int(g.current_user["internal_id"]),
                        slug,
                        storage_key,
                        original_filename,
                    ),
                )
        except ValueError as exc:
            flash(str(exc), "error")
            if final_dir is not None:
                shutil.rmtree(final_dir, ignore_errors=True)
            return redirect(url_for("dashboard"))
        except sqlite3.IntegrityError:
            flash("failed to save site record", "error")
            if final_dir is not None:
                shutil.rmtree(final_dir, ignore_errors=True)
            return redirect(url_for("dashboard"))
        except (tarfile.TarError, zipfile.BadZipFile):
            flash("archive is invalid or corrupted", "error")
            if final_dir is not None:
                shutil.rmtree(final_dir, ignore_errors=True)
            return redirect(url_for("dashboard"))
        finally:
            shutil.rmtree(temp_dir, ignore_errors=True)

        flash("site uploaded", "success")
        return redirect(url_for("dashboard"))

    @app.post("/app/sites/<site_id>/delete")
    def delete_site(site_id: str) -> Response:
        auth_redirect = require_auth()
        if auth_redirect is not None:
            return auth_redirect

        if not uuid_is_valid(site_id):
            flash("invalid site id", "error")
            return redirect(url_for("dashboard"))

        with connect_db() as conn:
            site = conn.execute(
                "SELECT site_uuid, owner_user_id, slug, storage_key FROM sites WHERE site_uuid = ?",
                (site_id,),
            ).fetchone()
            if site is None:
                flash("site not found", "error")
                return redirect(url_for("dashboard"))

            is_admin = g.current_user["role"] == "admin"
            if not is_admin and int(site["owner_user_id"]) != int(g.current_user["internal_id"]):
                flash("not allowed", "error")
                return redirect(url_for("dashboard"))

            conn.execute("DELETE FROM sites WHERE site_uuid = ?", (site_id,))

        shutil.rmtree(cfg.sites_dir / site["storage_key"], ignore_errors=True)
        flash("site deleted", "success")
        return redirect(url_for("dashboard"))

    @app.post("/app/admin/users/create")
    def admin_create_user() -> Response:
        admin_redirect = require_admin()
        if admin_redirect is not None:
            return admin_redirect

        username = request.form.get("username", "")
        password = request.form.get("password", "")
        role = request.form.get("role", "user").strip().lower()

        ok, message = auth_backend.create_user(username=username, password=password, role=role)
        flash(message, "success" if ok else "error")
        return redirect(url_for("dashboard"))

    @app.post("/app/admin/users/<user_id>/username")
    def admin_update_user_username(user_id: str) -> Response:
        admin_redirect = require_admin()
        if admin_redirect is not None:
            return admin_redirect

        if not uuid_is_valid(user_id):
            flash("invalid user id", "error")
            return redirect(url_for("dashboard"))

        username = request.form.get("username", "")
        ok, message = auth_backend.update_username(user_uuid=user_id, new_username=username)
        flash(message, "success" if ok else "error")
        return redirect(url_for("dashboard"))

    @app.post("/app/admin/users/<user_id>/password")
    def admin_update_user_password(user_id: str) -> Response:
        admin_redirect = require_admin()
        if admin_redirect is not None:
            return admin_redirect

        if not uuid_is_valid(user_id):
            flash("invalid user id", "error")
            return redirect(url_for("dashboard"))

        password = request.form.get("password", "")
        ok, message = auth_backend.update_password(user_uuid=user_id, new_password=password)
        flash(message, "success" if ok else "error")
        return redirect(url_for("dashboard"))

    @app.post("/app/admin/users/<user_id>/delete")
    def admin_delete_user(user_id: str) -> Response:
        admin_redirect = require_admin()
        if admin_redirect is not None:
            return admin_redirect

        if not uuid_is_valid(user_id):
            flash("invalid user id", "error")
            return redirect(url_for("dashboard"))

        if g.current_user["id"] == user_id:
            flash("you cannot delete your own account", "error")
            return redirect(url_for("dashboard"))

        with connect_db() as conn:
            user = conn.execute(
                "SELECT id AS internal_id, user_uuid, username FROM users WHERE user_uuid = ?",
                (user_id,),
            ).fetchone()
            if user is None:
                flash("user not found", "error")
                return redirect(url_for("dashboard"))

            owned_site_keys = conn.execute(
                "SELECT storage_key FROM sites WHERE owner_user_id = ?",
                (user["internal_id"],),
            ).fetchall()

            conn.execute("DELETE FROM users WHERE id = ?", (user["internal_id"],))

        for row in owned_site_keys:
            shutil.rmtree(cfg.sites_dir / row["storage_key"], ignore_errors=True)

        flash("user deleted", "success")
        return redirect(url_for("dashboard"))

    @app.post("/app/admin/sites/<site_id>/slug")
    def admin_update_slug(site_id: str) -> Response:
        admin_redirect = require_admin()
        if admin_redirect is not None:
            return admin_redirect

        if not uuid_is_valid(site_id):
            flash("invalid site id", "error")
            return redirect(url_for("dashboard"))

        new_slug = request.form.get("slug", "").strip().lower()
        if not slug_is_valid(new_slug):
            flash("invalid slug format", "error")
            return redirect(url_for("dashboard"))

        try:
            with connect_db() as conn:
                cursor = conn.execute(
                    """
                    UPDATE sites
                    SET slug = ?, updated_at = CURRENT_TIMESTAMP
                    WHERE site_uuid = ?
                    """,
                    (new_slug, site_id),
                )
                if cursor.rowcount == 0:
                    flash("site not found", "error")
                    return redirect(url_for("dashboard"))
        except sqlite3.IntegrityError:
            flash("slug is already in use", "error")
            return redirect(url_for("dashboard"))

        flash("slug updated", "success")
        return redirect(url_for("dashboard"))

    @app.get("/s/<slug>/")
    def serve_site_root(slug: str) -> Response:
        if not slug_is_valid(slug):
            abort(404)
        site = get_site_by_slug(slug)
        if site is None:
            abort(404)
        return serve_site_resource(site, subpath="", allow_spa=True)

    @app.get("/s/<slug>/<path:subpath>")
    def serve_site_subpath(slug: str, subpath: str) -> Response:
        if not slug_is_valid(slug):
            abort(404)
        site = get_site_by_slug(slug)
        if site is None:
            abort(404)
        return serve_site_resource(site, subpath=subpath, allow_spa=True)

    @app.get("/_site/<slug>/")
    def serve_site_alias_root(slug: str) -> Response:
        return serve_site_root(slug)

    @app.get("/_site/<slug>/<path:subpath>")
    def serve_site_alias_subpath(slug: str, subpath: str) -> Response:
        return serve_site_subpath(slug, subpath)

    @app.get("/<path:subpath>")
    def site_root_relative_fallback(subpath: str) -> Response:
        # handle absolute root paths from hosted apps by resolving the slug from referer/cookie
        first = subpath.split("/", 1)[0].lower()
        if first in {"app", "api", "s", "_site", "healthz", "favicon.svg", "robots.txt"}:
            abort(404)

        slug = extract_slug_from_referer(request.headers.get("Referer"))
        if slug is None:
            cookie_slug = request.cookies.get(ACTIVE_SITE_COOKIE)
            if cookie_slug and slug_is_valid(cookie_slug):
                slug = cookie_slug

        if slug is None:
            abort(404)

        site = get_site_by_slug(slug)
        if site is None:
            abort(404)
        return serve_site_resource(site, subpath=subpath, allow_spa=True)

    return app