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
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
|
package main
import (
"bytes"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"database/sql"
"encoding/base64"
"encoding/json"
"flag"
"fmt"
"html/template"
"io"
"math/big"
mathrand "math/rand"
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
"text/template/parse"
"time"
_ "modernc.org/sqlite"
)
// PackageConfig holds configuration for the package subcommand
type PackageConfig struct {
AppName string
NixExpr string
OutputDB string
AppVersion string
AppDescription string
AppAuthor string
Verbose bool
}
// RuntimeConfig holds configuration for the run subcommand
type RuntimeConfig struct {
DatabasePath string
Verbose bool
KeepTemp bool
}
// AppInfo holds extracted application information
type AppInfo struct {
AppName string
EntryPoint string
BundleDir string
ContainerID string
}
func main() {
if len(os.Args) < 2 {
printMainUsage()
os.Exit(1)
}
subcommand := os.Args[1]
switch subcommand {
case "package":
if err := packageCommand(os.Args[2:]); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
case "run":
if err := runCommand(os.Args[2:]); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
case "serve":
if err := serveCommand(os.Args[2:]); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
case "template":
if err := templateCommand(os.Args[2:]); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
case "auth":
if err := authCommand(os.Args[2:]); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
case "-h", "--help", "help":
printMainUsage()
default:
fmt.Fprintf(os.Stderr, "Error: Unknown subcommand '%s'\n\n", subcommand)
printMainUsage()
os.Exit(1)
}
}
func printMainUsage() {
fmt.Print(`Usage: sqlite-apps <subcommand> [OPTIONS] [ARGS]
SQLite-embedded application packager and runtime
Subcommands:
package Package a Nix derivation into a SQLite-embedded application
run Extract and run a SQLite-embedded application
serve Serve a mildly dynamic website from database templates
template Manage page templates in the database
auth Manage authorized keys for edit mode
Options:
-h, --help Show this help message
Examples:
sqlite-apps package hello-world ./hello-world.nix hello-world.db
sqlite-apps run hello-world.db
sqlite-apps serve mysite.db --port 8080
sqlite-apps template edit mysite.db /about
For subcommand help:
sqlite-apps <subcommand> --help
`)
}
// ============================================================================
// PACKAGE SUBCOMMAND
// ============================================================================
func packageCommand(args []string) error {
fs := flag.NewFlagSet("package", flag.ExitOnError)
fs.Usage = printPackageUsage
version := fs.String("version", "1.0.0", "Application version")
versionShort := fs.String("v", "1.0.0", "Application version (short)")
description := fs.String("desc", "", "Application description")
descriptionShort := fs.String("d", "", "Application description (short)")
author := fs.String("author", "", "Application author")
authorShort := fs.String("a", "", "Application author (short)")
verbose := fs.Bool("verbose", false, "Enable verbose output")
if err := fs.Parse(args); err != nil {
return err
}
// Check positional arguments
if fs.NArg() != 3 {
printPackageUsage()
return fmt.Errorf("expected 3 positional arguments, got %d", fs.NArg())
}
// Merge short and long flag values (prefer explicit value)
finalVersion := *version
if *versionShort != "1.0.0" {
finalVersion = *versionShort
}
finalDescription := *description
if *descriptionShort != "" {
finalDescription = *descriptionShort
}
finalAuthor := *author
if *authorShort != "" {
finalAuthor = *authorShort
}
config := PackageConfig{
AppName: fs.Arg(0),
NixExpr: fs.Arg(1),
OutputDB: fs.Arg(2),
AppVersion: finalVersion,
AppDescription: finalDescription,
AppAuthor: finalAuthor,
Verbose: *verbose,
}
if err := validatePackageInputs(config); err != nil {
return err
}
if err := checkRequiredTools([]string{"nix-build", "nix", "sqlite3", "mksquashfs"}); err != nil {
return err
}
return packageApplication(config)
}
func printPackageUsage() {
fmt.Print(`Usage: sqlite-apps package [OPTIONS] <app-name> <nix-expr> <output.db>
Package a Nix derivation into a SQLite-embedded application.
Arguments:
app-name Name of the application (used for /bin/app-name)
nix-expr Nix expression file (e.g., ./myapp.nix)
output.db Output SQLite database file
Options:
-h, --help Show this help message
-v, --version VERSION Application version (default: 1.0.0)
-d, --desc DESCRIPTION Application description
-a, --author AUTHOR Application author
--verbose Enable verbose output
Note: Entry point is automatically set to /bin/app-name
Examples:
sqlite-apps package hello-world ./hello-world.nix hello-world.db
sqlite-apps package timetracker ./timetracker.nix timetracker.db
`)
}
func validatePackageInputs(config PackageConfig) error {
// Check nix expression exists
if _, err := os.Stat(config.NixExpr); os.IsNotExist(err) {
return fmt.Errorf("Nix expression file '%s' not found", config.NixExpr)
}
// Check output doesn't exist
if _, err := os.Stat(config.OutputDB); err == nil {
return fmt.Errorf("output file '%s' already exists", config.OutputDB)
}
return nil
}
func packageApplication(config PackageConfig) error {
// Build Nix derivation first to get the app store path
fmt.Println("Building Nix derivation...")
logPackage(config, "Running: nix-build %s --no-out-link", config.NixExpr)
appStorePath, err := runCommandOutput("nix-build", config.NixExpr, "--no-out-link")
if err != nil {
return fmt.Errorf("nix-build failed: %w", err)
}
appStorePath = strings.TrimSpace(appStorePath)
logPackage(config, "App build successful: %s", appStorePath)
// Validate entry point
entryPoint := fmt.Sprintf("/bin/%s", config.AppName)
fullEntryPoint := filepath.Join(appStorePath, entryPoint)
if _, err := os.Stat(fullEntryPoint); err != nil {
return fmt.Errorf("entry point '%s' not found or not accessible", fullEntryPoint)
}
logPackage(config, "Using entry point: %s", fullEntryPoint)
// Create temporary directory
tempDir := fmt.Sprintf("/tmp/sqlite-app-packager-%d", time.Now().Unix())
if err := runCommandSilent("mkdir", "-p", tempDir); err != nil {
return fmt.Errorf("failed to create temp directory: %w", err)
}
defer cleanupTempDir(tempDir)
logPackage(config, "Using temporary directory: %s", tempDir)
// Create squashfs image of the Nix store closure (all dependencies)
fmt.Println("Creating squashfs image...")
squashfsFile := filepath.Join(tempDir, "app.squashfs")
// Copy closure to temporary nix store directory using nix copy
nixDir := filepath.Join(tempDir, "nix")
if err := runCommandSilent("mkdir", "-p", nixDir); err != nil {
return fmt.Errorf("failed to create nix directory: %w", err)
}
logPackage(config, "Copying closure to temporary store: %s", nixDir)
if err := runCommandSilent("nix", "copy", "--to", nixDir, "--no-check-sigs", appStorePath); err != nil {
return fmt.Errorf("nix copy failed: %w", err)
}
// Create squashfs from the copied nix store
logPackage(config, "Creating squashfs from closure with zstd compression")
if err := runCommandSilent("mksquashfs", nixDir, squashfsFile, "-comp", "zstd"); err != nil {
return fmt.Errorf("mksquashfs failed: %w", err)
}
squashfsSize, err := runCommandOutput("du", "-h", squashfsFile)
if err == nil {
parts := strings.Fields(squashfsSize)
if len(parts) > 0 {
logPackage(config, "Squashfs image size: %s", parts[0])
}
}
// Create SQLite database
fmt.Println("Creating SQLite database...")
db, err := sql.Open("sqlite", config.OutputDB)
if err != nil {
return fmt.Errorf("failed to create database: %w", err)
}
defer db.Close()
// Create table
_, err = db.Exec(`
PRAGMA foreign_keys = ON;
CREATE TABLE __app (
name TEXT NOT NULL,
version TEXT NOT NULL,
entry_point TEXT NOT NULL,
description TEXT,
author TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
squashfs_data BLOB NOT NULL
);
`)
if err != nil {
return fmt.Errorf("failed to create table: %w", err)
}
// Read squashfs file
squashfsData, err := os.ReadFile(squashfsFile)
if err != nil {
return fmt.Errorf("failed to read squashfs file: %w", err)
}
// Insert application data
var description, author any
if config.AppDescription != "" {
description = config.AppDescription
} else {
description = nil
}
if config.AppAuthor != "" {
author = config.AppAuthor
} else {
author = nil
}
_, err = db.Exec(`
INSERT INTO __app (name, version, entry_point, description, author, squashfs_data)
VALUES (?, ?, ?, ?, ?, ?)
`, config.AppName, config.AppVersion, fullEntryPoint, description, author, squashfsData)
if err != nil {
return fmt.Errorf("failed to insert data: %w", err)
}
// Verify database
fmt.Println("Verifying database...")
dbSizeOutput, err := runCommandOutput("du", "-h", config.OutputDB)
var dbSize string
if err == nil {
parts := strings.Fields(dbSizeOutput)
if len(parts) > 0 {
dbSize = parts[0]
}
}
var count int
if err := db.QueryRow("SELECT COUNT(*) FROM __app").Scan(&count); err != nil {
return fmt.Errorf("database verification failed: %w", err)
}
if count != 1 {
return fmt.Errorf("database verification failed: expected 1 row, got %d", count)
}
// Success summary
fmt.Println("\n✓ Successfully packaged application!")
fmt.Println("Details:")
fmt.Printf(" Name: %s\n", config.AppName)
fmt.Printf(" Version: %s\n", config.AppVersion)
fmt.Printf(" Entry point: %s\n", fullEntryPoint)
fmt.Printf(" Database: %s (%s)\n", config.OutputDB, dbSize)
if config.AppDescription != "" {
fmt.Printf(" Description: %s\n", config.AppDescription)
}
if config.AppAuthor != "" {
fmt.Printf(" Author: %s\n", config.AppAuthor)
}
fmt.Printf("\nTo run: sqlite-apps run '%s'\n", config.OutputDB)
return nil
}
func logPackage(config PackageConfig, format string, args ...any) {
if config.Verbose {
timestamp := time.Now().Unix()
fmt.Printf("[%d] %s\n", timestamp, fmt.Sprintf(format, args...))
}
}
// ============================================================================
// RUN SUBCOMMAND
// ============================================================================
func runCommand(args []string) error {
fs := flag.NewFlagSet("run", flag.ExitOnError)
fs.Usage = printRunUsage
verbose := fs.Bool("verbose", false, "Enable verbose output")
keepTemp := fs.Bool("keep-temp", false, "Keep temporary files for debugging")
if err := fs.Parse(args); err != nil {
return err
}
if fs.NArg() != 1 {
printRunUsage()
return fmt.Errorf("expected 1 positional argument, got %d", fs.NArg())
}
config := RuntimeConfig{
DatabasePath: fs.Arg(0),
Verbose: *verbose,
KeepTemp: *keepTemp,
}
if err := validateDatabase(config); err != nil {
return err
}
appInfo, err := extractApplication(config)
if err != nil {
return err
}
defer cleanup(config, appInfo)
return runApplication(config, appInfo)
}
func printRunUsage() {
fmt.Print(`Usage: sqlite-apps run [OPTIONS] <database.db>
Extract and run SQLite-embedded applications.
Arguments:
database.db SQLite database containing embedded application
Options:
-h, --help Show this help message
--verbose Enable verbose output
--keep-temp Keep temporary files for debugging
Examples:
sqlite-apps run timetracker.db
sqlite-apps run --verbose hello-world.db
`)
}
func validateDatabase(config RuntimeConfig) error {
if _, err := os.Stat(config.DatabasePath); os.IsNotExist(err) {
return fmt.Errorf("database file '%s' not found", config.DatabasePath)
}
return nil
}
func extractApplication(config RuntimeConfig) (*AppInfo, error) {
logRuntime(config, "Reading application metadata from database")
// Create unique temporary directory
tempID := time.Now().Unix()
tempDir := fmt.Sprintf("/tmp/sqlite-app-runtime-%d", tempID)
if err := runCommandSilent("mkdir", "-p", tempDir); err != nil {
return nil, fmt.Errorf("failed to create temp directory: %w", err)
}
logRuntime(config, "Using temporary directory: %s", tempDir)
// Extract squashfs from database
squashfsFile := filepath.Join(tempDir, "app.squashfs")
logRuntime(config, "Extracting squashfs from database to: %s", squashfsFile)
extractSQL := fmt.Sprintf("SELECT writefile('%s', squashfs_data) FROM __app;", squashfsFile)
if err := runCommandSilent("sqlite3", config.DatabasePath, extractSQL); err != nil {
return nil, fmt.Errorf("failed to extract squashfs: %w", err)
}
// Get application metadata
db, err := sql.Open("sqlite", config.DatabasePath)
if err != nil {
return nil, fmt.Errorf("failed to open database: %w", err)
}
defer db.Close()
var appName, entryPoint string
err = db.QueryRow("SELECT name, entry_point FROM __app").Scan(&appName, &entryPoint)
if err != nil {
return nil, fmt.Errorf("failed to read metadata: %w", err)
}
logRuntime(config, "Application: %s, Entry point: %s", appName, entryPoint)
// Extract squashfs directly into rootfs
bundleDir := filepath.Join(tempDir, "bundle")
rootfsDir := filepath.Join(bundleDir, "rootfs")
if err := runCommandSilent("mkdir", "-p", bundleDir); err != nil {
return nil, fmt.Errorf("failed to create bundle directory: %w", err)
}
logRuntime(config, "Extracting squashfs to: %s", rootfsDir)
if err := runCommandSilent("unsquashfs", "-f", "-d", rootfsDir, squashfsFile); err != nil {
return nil, fmt.Errorf("failed to extract squashfs: %w", err)
}
// Generate OCI config.json dynamically
logRuntime(config, "Generating OCI config.json")
if err := generateOCIConfig(config, bundleDir, entryPoint); err != nil {
return nil, fmt.Errorf("failed to generate OCI config: %w", err)
}
// Generate unique container ID
containerID := fmt.Sprintf("sqlite-app-%d", tempID)
return &AppInfo{
AppName: appName,
EntryPoint: entryPoint,
BundleDir: bundleDir,
ContainerID: containerID,
}, nil
}
func generateOCIConfig(config RuntimeConfig, bundleDir, entryPoint string) error {
dbAbsPath, err := filepath.Abs(config.DatabasePath)
if err != nil {
return fmt.Errorf("failed to get absolute database path: %w", err)
}
// Create additional container directories (squashfs already extracted to rootfs)
rootfsDir := filepath.Join(bundleDir, "rootfs")
dirs := []string{"dev", "proc", "sys", "tmp", "data"}
for _, dir := range dirs {
dirPath := filepath.Join(rootfsDir, dir)
if err := runCommandSilent("mkdir", "-p", dirPath); err != nil {
return fmt.Errorf("failed to create directory %s: %w", dir, err)
}
}
// Generate OCI config.json
configJSON := fmt.Sprintf(`{
"ociVersion": "1.0.0",
"platform": {
"os": "linux",
"arch": "x86_64"
},
"root": {
"path": "rootfs",
"readonly": false
},
"process": {
"args": ["%s"],
"user": {
"uid": 0,
"gid": 0
},
"cwd": "/"
},
"linux": {
"uidMappings": [{
"containerID": 0,
"hostID": 1000,
"size": 1
}],
"gidMappings": [{
"containerID": 0,
"hostID": 100,
"size": 1
}],
"namespaces": [
{"type": "pid"},
{"type": "ipc"},
{"type": "mount"},
{"type": "uts"},
{"type": "cgroup"},
{"type": "user"}
]
},
"mounts": [
{
"destination": "/proc",
"type": "proc",
"source": "proc"
},
{
"destination": "/dev",
"type": "tmpfs",
"source": "tmpfs",
"options": ["nosuid", "strictatime", "mode=755", "size=65536k"]
},
{
"destination": "/dev/pts",
"type": "devpts",
"source": "devpts",
"options": ["nosuid", "noexec", "newinstance", "ptmxmode=0666", "mode=0620"]
},
{
"destination": "/dev/shm",
"type": "tmpfs",
"source": "shm",
"options": ["nosuid", "noexec", "nodev", "mode=1777", "size=65536k"]
},
{
"destination": "/sys",
"type": "none",
"source": "/sys",
"options": ["rbind", "nosuid", "noexec", "nodev", "ro"]
},
{
"destination": "/data/db.sqlite",
"type": "none",
"source": "%s",
"options": ["bind", "rw"]
}
]
}`, entryPoint, dbAbsPath)
configFile := filepath.Join(bundleDir, "config.json")
if err := os.WriteFile(configFile, []byte(configJSON), 0644); err != nil {
return fmt.Errorf("failed to write config.json: %w", err)
}
logRuntime(config, "Generated config.json at: %s", configFile)
return nil
}
func runApplication(config RuntimeConfig, appInfo *AppInfo) error {
dbAbsPath, err := filepath.Abs(config.DatabasePath)
if err != nil {
return fmt.Errorf("failed to get absolute database path: %w", err)
}
logRuntime(config, "Executing OCI container with runc")
fmt.Printf("Starting application '%s'...\n", appInfo.AppName)
fmt.Printf("Database: %s\n", dbAbsPath)
fmt.Printf("Entry point: %s\n", appInfo.EntryPoint)
fmt.Printf("Container ID: %s\n", appInfo.ContainerID)
fmt.Println("\n--- Application Output ---")
// Run with runc
cmd := exec.Command("runc", "--rootless", "true", "run", "-b", appInfo.BundleDir, appInfo.ContainerID)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
logRuntime(config, "Running with runc: %s", strings.Join(cmd.Args, " "))
if err := cmd.Run(); err != nil {
fmt.Println("\n--- Application Terminated ---")
return fmt.Errorf("runc failed: %w", err)
}
fmt.Println("\n--- Application Exited ---")
fmt.Println("Exit code: 0")
return nil
}
func cleanup(config RuntimeConfig, appInfo *AppInfo) {
if config.KeepTemp {
fmt.Printf("Keeping temporary files at: %s\n", appInfo.BundleDir)
return
}
logRuntime(config, "Cleaning up temporary files")
// Stop and delete runc container if it exists
if err := runCommandSilent("runc", "delete", "-f", appInfo.ContainerID); err != nil {
logRuntime(config, "Warning: Failed to delete runc container %s: %v", appInfo.ContainerID, err)
}
// Remove temporary directory (includes both original and modified bundle)
tempDir := filepath.Dir(appInfo.BundleDir)
// First make everything writable (extracted squashfs has restrictive permissions)
_ = runCommandSilent("chmod", "-R", "u+w", tempDir)
if err := runCommandSilent("rm", "-rf", tempDir); err != nil {
fmt.Printf("Warning: Failed to remove temporary directory %s: %v\n", tempDir, err)
}
}
func logRuntime(config RuntimeConfig, format string, args ...any) {
if config.Verbose {
timestamp := time.Now().Unix()
fmt.Printf("[%d] %s\n", timestamp, fmt.Sprintf(format, args...))
}
}
// ============================================================================
// SERVE SUBCOMMAND
// ============================================================================
func serveCommand(args []string) error {
fs := flag.NewFlagSet("serve", flag.ExitOnError)
fs.Usage = printServeUsage
port := fs.Int("port", 8080, "Port to listen on")
bind := fs.String("bind", "localhost", "Address to bind to")
if err := fs.Parse(args); err != nil {
return err
}
if fs.NArg() != 1 {
printServeUsage()
return fmt.Errorf("expected 1 positional argument, got %d", fs.NArg())
}
dbPath := fs.Arg(0)
// Check database exists
if _, err := os.Stat(dbPath); os.IsNotExist(err) {
return fmt.Errorf("database file '%s' not found", dbPath)
}
// Open database with WAL mode and busy timeout for better concurrency
db, err := sql.Open("sqlite", dbPath+"?_journal_mode=WAL&_busy_timeout=5000")
if err != nil {
return fmt.Errorf("failed to open database: %w", err)
}
defer db.Close()
// Migrate old schema if needed, then ensure table exists
if err := migratePages(db); err != nil {
return fmt.Errorf("failed to migrate __pages table: %w", err)
}
// Ensure auth tables exist
if err := migrateAuth(db); err != nil {
return fmt.Errorf("failed to create auth tables: %w", err)
}
// Create HTTP handler
handler := createHandler(db)
fmt.Printf("Serving %s on http://%s:%d\n", dbPath, *bind, *port)
fmt.Println("Press Ctrl+C to stop")
return http.ListenAndServe(fmt.Sprintf("%s:%d", *bind, *port), handler)
}
func printServeUsage() {
fmt.Print(`Usage: sqlite-apps serve [OPTIONS] <database.db>
Serve a mildly dynamic website from database templates.
Arguments:
database.db SQLite database containing page templates
Options:
-h, --help Show this help message
--port PORT Port to listen on (default: 8080)
Templates can use these functions:
sql "query" args... Execute query, return []map[string]any
sql1 "query" args... Execute query, return first row as map
exec "query" args... Execute INSERT/UPDATE/DELETE, return rows affected
Request context available as:
.Path - request path
.Query - URL query parameters (map)
.Method - HTTP method
.Form - POST form data (map)
Examples:
sqlite-apps serve mysite.db
sqlite-apps serve --port 3000 mysite.db
`)
}
func createHandler(db *sql.DB) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
// Handle special __ routes (reserved for system use)
if strings.HasPrefix(path, "/__") {
// API endpoints
if strings.HasPrefix(path, "/__api/") {
handleEditAPI(db, w, r)
return
}
// Auth page
if path == "/__auth" {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
authPage := strings.Replace(authPageHTML, "</head>", baseCSS+"</head>", 1)
w.Write([]byte(authPage))
return
}
// Delegate page
if path == "/__delegate" {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
delegatePage := strings.Replace(delegatePageHTML, "</head>", baseCSS+"</head>", 1)
w.Write([]byte(delegatePage))
return
}
// Account page
if path == "/__account" {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
accountPage := strings.Replace(accountPageHTML, "</head>", baseCSS+"</head>", 1)
w.Write([]byte(accountPage))
return
}
// Unknown __ route
http.NotFound(w, r)
return
}
// Query for latest version of template
var tmplContent, contentType string
err := db.QueryRow("SELECT template, content_type FROM __pages WHERE path = ? ORDER BY created_at DESC LIMIT 1", path).Scan(&tmplContent, &contentType)
if err == sql.ErrNoRows {
// Check if direct edit mode - show editor with starter template
if r.URL.Query().Has("__edit") && r.URL.Query().Has("__direct") {
if !isAuthenticated(db, r) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
authPage := strings.Replace(authPageHTML, "</head>", baseCSS+"</head>", 1)
w.Write([]byte(authPage))
return
}
// Use starter template for new page
tmplContent = fmt.Sprintf(`<!DOCTYPE html>
<html>
<head>
<title>%s</title>
</head>
<body>
<h1>%s</h1>
<p>Content goes here</p>
</body>
</html>`, path, path)
err = nil // Clear error so we fall through to direct edit mode
} else if isAuthenticated(db, r) {
// Show 404 with create option
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusNotFound)
w.Write(fmt.Appendf(nil, `<!DOCTYPE html>
<html>
<head>
<title>Page Not Found</title>
%s
<style>
body { font-family: system-ui, sans-serif; max-width: 600px; margin: 50px auto; padding: 20px; }
.create-section { margin-top: 30px; padding: 20px; border: 1px solid var(--border); border-radius: 5px; background: var(--bg-secondary); }
</style>
</head>
<body>
<h1>Page Not Found</h1>
<p>The page <code>%s</code> does not exist.</p>
<div class="create-section">
<h3>Create this page?</h3>
<p>You're logged in and can create this page.</p>
<button class="primary" onclick="window.location.href='%s?__edit&__direct'">Create Page</button>
</div>
</body>
</html>`, baseCSS, template.HTMLEscapeString(path), path))
return
} else {
http.NotFound(w, r)
return
}
}
if err != nil {
http.Error(w, fmt.Sprintf("Database error: %v", err), http.StatusInternalServerError)
return
}
// Parse form data
r.ParseForm()
// Build context
ctx := map[string]any{
"Path": path,
"Method": r.Method,
"Query": mapValues(r.URL.Query()),
"Form": mapValues(r.Form),
}
// Debug: print AST if ?debug=tree
if r.URL.Query().Get("debug") == "tree" {
tmpl, err := template.New("page").Funcs(createTemplateFuncs(db)).Parse(tmplContent)
if err != nil {
http.Error(w, fmt.Sprintf("Template parse error: %v", err), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/plain")
fmt.Fprintln(w, "Template AST:")
fmt.Fprintln(w, "")
debugPrintTreeToWriter(w, tmpl.Tree.Root, 0)
return
}
// Check if edit mode is enabled
editMode := r.URL.Query().Has("__edit")
directMode := r.URL.Query().Has("__direct")
// If edit mode requested, check authentication
if editMode && !isAuthenticated(db, r) {
// Show auth page with baseCSS injected
w.Header().Set("Content-Type", "text/html; charset=utf-8")
authPage := strings.Replace(authPageHTML, "</head>", baseCSS+"</head>", 1)
w.Write([]byte(authPage))
return
}
// Direct edit mode - show full template in textarea
if editMode && directMode {
// Get database schema
schemaHTML := getSchemaHTML(db)
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Write(fmt.Appendf(nil, `<!DOCTYPE html>
<html>
<head>
<title>Edit: %s</title>
%s
<style>
* { box-sizing: border-box; }
body { margin: 0; padding: 20px 20px 0 20px; font-family: system-ui, sans-serif; display: flex; gap: 20px; height: 100vh; }
.editor { flex: 1; display: flex; flex-direction: column; }
.reference { width: 300px; font-size: 12px; overflow-y: auto; margin-top: 40px; }
h3 { margin-top: 0; }
textarea { width: 100%%; flex: 1; font-family: monospace; font-size: 14px; padding: 10px; background: var(--bg-secondary); color: var(--text); border: 1px solid var(--border); resize: none; }
.controls { margin-top: 5px; }
.controls button { padding: 8px 16px; }
.error { color: red; margin-top: 10px; }
.reference h4 { margin: 10px 0 5px 0; border-bottom: 1px solid var(--border); padding-bottom: 5px; }
.reference code { padding: 2px 4px; border-radius: 3px; background: var(--bg-secondary); }
.reference pre { padding: 8px; border-radius: 3px; overflow-x: auto; margin: 5px 0; background: var(--bg-secondary); }
.reference ul { margin: 5px 0; padding-left: 20px; }
.reference li { margin: 3px 0; }
</style>
</head>
<body>
<div class="editor">
<h3>Editing: %s</h3>
<textarea id="source">%s</textarea>
<div class="controls">
<button onclick="save()">Save (Ctrl+S)</button>
<button onclick="cancel()">Cancel (Esc)</button>
</div>
<div id="error" class="error"></div>
</div>
<div class="reference">
<h4>Template Functions</h4>
<ul>
<li><code>sql "query" args...</code> - returns []row</li>
<li><code>sql1 "query" args...</code> - returns single row</li>
<li><code>exec "query" args...</code> - returns rows affected</li>
</ul>
<h4>Context Variables</h4>
<ul>
<li><code>.Path</code> - request path</li>
<li><code>.Method</code> - HTTP method</li>
<li><code>.Query.key</code> - URL query params</li>
<li><code>.Form.key</code> - POST form data</li>
</ul>
<h4>Database Schema</h4>
%s
</div>
<script>
const textarea = document.getElementById('source');
const errorDiv = document.getElementById('error');
document.addEventListener('keydown', function(e) {
if (e.key === 's' && e.ctrlKey) {
e.preventDefault();
save();
}
if (e.key === 'Escape') {
e.preventDefault();
cancel();
}
});
async function save() {
const content = textarea.value;
const resp = await fetch('/__api/save-full', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({content: content})
});
if (!resp.ok) {
errorDiv.textContent = await resp.text();
return;
}
// Go back to edit mode view
window.location.href = window.location.pathname + '?__edit';
}
function cancel() {
window.location.href = window.location.pathname + '?__edit';
}
function stopEdit() {
window.location.href = window.location.pathname;
}
// Create auth bar
(async function() {
const resp = await fetch('/__api/auth/status');
const data = await resp.json();
if (data.authenticated) {
const bar = document.createElement('div');
bar.className = 'auth-bar';
const name = data.name || 'unknown';
bar.innerHTML = 'Editing. Logged in as <a href="/__account"><strong>' + name + '</strong></a><button onclick="stopEdit()">Stop Editing</button>';
document.body.appendChild(bar);
}
})();
</script>
</body>
</html>`, path, baseCSS, path, template.HTMLEscapeString(tmplContent), schemaHTML))
return
}
// Only wrap text with spans when in edit mode
var tmplSource string
if editMode {
tmplSource = wrapTextForEditing(tmplContent)
} else {
tmplSource = tmplContent
}
// Create template with SQL functions
tmpl, err := template.New("page").Funcs(createTemplateFuncs(db)).Parse(tmplSource)
if err != nil {
http.Error(w, fmt.Sprintf("Template parse error: %v", err), http.StatusInternalServerError)
return
}
// Set content type with explicit charset
if contentType == "text/html" {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
} else {
w.Header().Set("Content-Type", contentType)
}
// Execute template to buffer so we can append editor JS
var buf bytes.Buffer
if err := tmpl.Execute(&buf, ctx); err != nil {
http.Error(w, fmt.Sprintf("Template execution error: %v", err), http.StatusInternalServerError)
return
}
// Inject CSS into head and JS at end
output := buf.String()
if contentType == "text/html" {
// Inject baseCSS into </head>
output = strings.Replace(output, "</head>", baseCSS+"</head>", 1)
// Append editor JS at end
if editMode {
output += editorJS
} else {
// Inject just the keyboard shortcuts for entering edit mode
output += editShortcutsJS
}
}
w.Write([]byte(output))
})
}
// handleEditAPI handles the inline editing API endpoints
func handleEditAPI(db *sql.DB, w http.ResponseWriter, r *http.Request) {
// Handle auth endpoints first (don't require referer)
switch r.URL.Path {
case "/__api/auth/challenge":
// Generate a challenge for authentication
sessionID := generateChallenge()
challenge := generateChallenge()
// Store in database
_, err := db.Exec("INSERT INTO __auth_sessions (session_id, challenge) VALUES (?, ?)", sessionID, challenge)
if err != nil {
http.Error(w, "Failed to create session", http.StatusInternalServerError)
return
}
// Set session cookie (24 hour expiry)
http.SetCookie(w, &http.Cookie{
Name: "__auth_session",
Value: sessionID,
Path: "/",
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
MaxAge: 86400,
})
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"challenge": challenge})
return
case "/__api/auth/verify":
// Verify signature against authorized keys
var req struct {
Signature string `json:"signature"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "Invalid JSON", http.StatusBadRequest)
return
}
// Get session
cookie, err := r.Cookie("__auth_session")
if err != nil {
http.Error(w, "No session", http.StatusUnauthorized)
return
}
var challenge string
err = db.QueryRow("SELECT challenge FROM __auth_sessions WHERE session_id = ? AND authenticated = 0", cookie.Value).Scan(&challenge)
if err != nil {
http.Error(w, "Invalid session", http.StatusUnauthorized)
return
}
// Try all authorized keys
rows, err := db.Query("SELECT public_key, name FROM __authorized_keys")
if err != nil {
http.Error(w, "Database error", http.StatusInternalServerError)
return
}
verified := false
var lastError string
var keyName string
for rows.Next() {
var pubKeyJSON string
var name sql.NullString
rows.Scan(&pubKeyJSON, &name)
var pubKey map[string]any
if err := json.Unmarshal([]byte(pubKeyJSON), &pubKey); err != nil {
lastError = fmt.Sprintf("JSON parse error: %v", err)
continue
}
if verifySignature(pubKey, challenge, req.Signature) {
verified = true
if name.Valid {
keyName = name.String
}
break
} else {
lastError = fmt.Sprintf("Signature verification failed for key")
}
}
rows.Close() // Close before UPDATE to avoid database lock
if !verified {
if lastError != "" {
http.Error(w, fmt.Sprintf("Invalid signature: %s", lastError), http.StatusUnauthorized)
} else {
http.Error(w, "Invalid signature: no keys to try", http.StatusUnauthorized)
}
return
}
// Mark session as authenticated with key name
_, err = db.Exec("UPDATE __auth_sessions SET authenticated = 1, key_name = ? WHERE session_id = ?", keyName, cookie.Value)
if err != nil {
http.Error(w, "Failed to update session", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]bool{"authenticated": true})
return
case "/__api/auth/status":
// Check if current session is authenticated
cookie, err := r.Cookie("__auth_session")
if err != nil {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]any{"authenticated": false})
return
}
var authenticated int
var keyName sql.NullString
err = db.QueryRow("SELECT authenticated, key_name FROM __auth_sessions WHERE session_id = ?", cookie.Value).Scan(&authenticated, &keyName)
if err != nil || authenticated == 0 {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]any{"authenticated": false})
return
}
w.Header().Set("Content-Type", "application/json")
result := map[string]any{"authenticated": true}
if keyName.Valid {
result["name"] = keyName.String
}
json.NewEncoder(w).Encode(result)
return
case "/__api/auth/logout":
// Clear the session
cookie, err := r.Cookie("__auth_session")
if err == nil {
db.Exec("DELETE FROM __auth_sessions WHERE session_id = ?", cookie.Value)
}
// Clear cookie
http.SetCookie(w, &http.Cookie{
Name: "__auth_session",
Value: "",
Path: "/",
HttpOnly: true,
MaxAge: -1,
})
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]bool{"success": true})
return
case "/__api/auth/delegate/create":
// Step 1: Trusted device creates delegation and gets PIN-A
// Requires authenticated session
if !isAuthenticated(db, r) {
http.Error(w, "Not authenticated", http.StatusUnauthorized)
return
}
// Generate 6-digit PIN-A
pin := fmt.Sprintf("%06d", mathrand.Intn(1000000))
// Get session ID
cookie, _ := r.Cookie("__auth_session")
// Store delegation with 5-minute expiry, status = 'pending'
_, err := db.Exec(`
INSERT INTO __auth_delegations (pin, session_id, expires_at, status)
VALUES (?, ?, datetime('now', '+5 minutes'), 'pending')
`, pin, cookie.Value)
if err != nil {
http.Error(w, "Failed to create delegation", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"pin": pin})
return
case "/__api/auth/delegate/submit":
// Step 2: New device submits PIN-A, PIN-B (verification code), public key
var req struct {
PIN string `json:"pin"`
VerificationCode string `json:"verificationCode"`
PublicKey map[string]any `json:"publicKey"`
Signature string `json:"signature"`
Name string `json:"name"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "Invalid JSON", http.StatusBadRequest)
return
}
// Validate verification code format (6 digits)
if len(req.VerificationCode) != 6 {
http.Error(w, "Verification code must be 6 digits", http.StatusBadRequest)
return
}
// Check PIN exists, hasn't expired, and is in 'pending' state
var status string
err := db.QueryRow(`
SELECT status FROM __auth_delegations
WHERE pin = ? AND datetime('now') < expires_at
`, req.PIN).Scan(&status)
if err != nil {
http.Error(w, "Invalid or expired PIN", http.StatusUnauthorized)
return
}
if status != "pending" {
http.Error(w, "Delegation already submitted or completed", http.StatusBadRequest)
return
}
// Verify the new device signed the verification code
if !verifySignature(req.PublicKey, req.VerificationCode, req.Signature) {
http.Error(w, "Invalid signature", http.StatusUnauthorized)
return
}
// Store verification code, public key, and device name
// Update status to 'awaiting_confirmation'
pubKeyJSON, _ := json.Marshal(req.PublicKey)
_, err = db.Exec(`
UPDATE __auth_delegations
SET verification_code = ?, public_key_json = ?, device_name = ?, status = 'awaiting_confirmation'
WHERE pin = ?
`, req.VerificationCode, string(pubKeyJSON), req.Name, req.PIN)
if err != nil {
http.Error(w, "Failed to store delegation", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]bool{"success": true})
return
case "/__api/auth/delegate/poll":
// Step 3: Trusted device polls for verification code (PIN-B)
// Requires authenticated session
if !isAuthenticated(db, r) {
http.Error(w, "Not authenticated", http.StatusUnauthorized)
return
}
pin := r.URL.Query().Get("pin")
if pin == "" {
http.Error(w, "Missing pin parameter", http.StatusBadRequest)
return
}
// Get session ID to verify this delegation belongs to this user
cookie, _ := r.Cookie("__auth_session")
var verificationCode sql.NullString
var deviceName sql.NullString
var status string
err := db.QueryRow(`
SELECT status, verification_code, device_name FROM __auth_delegations
WHERE pin = ? AND session_id = ? AND datetime('now') < expires_at
`, pin, cookie.Value).Scan(&status, &verificationCode, &deviceName)
if err != nil {
// Delegation not found or expired
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]any{
"status": "not_found",
})
return
}
if status == "pending" {
// Still waiting for new device to submit
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]any{
"status": "pending",
})
return
}
if status == "awaiting_confirmation" && verificationCode.Valid {
// New device has submitted - show verification code to user
deviceNameStr := "Unknown"
if deviceName.Valid {
deviceNameStr = deviceName.String
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]any{
"status": "awaiting_confirmation",
"verificationCode": verificationCode.String,
"deviceName": deviceNameStr,
})
return
}
if status == "confirmed" {
// Already confirmed
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]any{
"status": "confirmed",
})
return
}
// Unknown status
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]any{
"status": "error",
})
return
case "/__api/auth/delegate/confirm":
// Step 4: Trusted device confirms the verification code matches
// Requires authenticated session
if !isAuthenticated(db, r) {
http.Error(w, "Not authenticated", http.StatusUnauthorized)
return
}
var req struct {
PIN string `json:"pin"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "Invalid JSON", http.StatusBadRequest)
return
}
// Get session ID to verify this delegation belongs to this user
cookie, _ := r.Cookie("__auth_session")
// Get the stored public key and device name
var publicKeyJSON, deviceName string
err := db.QueryRow(`
SELECT public_key_json, device_name FROM __auth_delegations
WHERE pin = ? AND session_id = ? AND status = 'awaiting_confirmation' AND datetime('now') < expires_at
`, req.PIN, cookie.Value).Scan(&publicKeyJSON, &deviceName)
if err != nil {
http.Error(w, "Invalid or expired delegation", http.StatusBadRequest)
return
}
// Add the new public key to authorized keys
_, err = db.Exec(`
INSERT OR REPLACE INTO __authorized_keys (public_key, name)
VALUES (?, ?)
`, publicKeyJSON, deviceName)
if err != nil {
http.Error(w, "Failed to add key", http.StatusInternalServerError)
return
}
// Mark as confirmed and delete after short delay (or delete immediately)
db.Exec("UPDATE __auth_delegations SET status = 'confirmed' WHERE pin = ?", req.PIN)
db.Exec("DELETE FROM __auth_delegations WHERE pin = ?", req.PIN)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]bool{"success": true})
return
case "/__api/auth/delegate/cancel":
// Cancel an active delegation
// Requires authenticated session
if !isAuthenticated(db, r) {
http.Error(w, "Not authenticated", http.StatusUnauthorized)
return
}
var req struct {
PIN string `json:"pin"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "Invalid JSON", http.StatusBadRequest)
return
}
// Get session ID to verify this delegation belongs to this user
cookie, _ := r.Cookie("__auth_session")
// Delete the delegation
_, err := db.Exec(`
DELETE FROM __auth_delegations
WHERE pin = ? AND session_id = ?
`, req.PIN, cookie.Value)
if err != nil {
http.Error(w, "Failed to cancel delegation", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]bool{"success": true})
return
case "/__api/auth/delete":
// Delete the current user's key from server
// Requires authenticated session
if !isAuthenticated(db, r) {
http.Error(w, "Not authenticated", http.StatusUnauthorized)
return
}
// Get the key name from session to find the public key
cookie, _ := r.Cookie("__auth_session")
var keyName sql.NullString
db.QueryRow("SELECT key_name FROM __auth_sessions WHERE session_id = ?", cookie.Value).Scan(&keyName)
if !keyName.Valid || keyName.String == "" {
http.Error(w, "No key associated with session", http.StatusBadRequest)
return
}
// Delete the key
_, err := db.Exec("DELETE FROM __authorized_keys WHERE name = ?", keyName.String)
if err != nil {
http.Error(w, "Failed to delete key", http.StatusInternalServerError)
return
}
// Also delete the session
db.Exec("DELETE FROM __auth_sessions WHERE session_id = ?", cookie.Value)
// Clear cookie
http.SetCookie(w, &http.Cookie{
Name: "__auth_session",
Value: "",
Path: "/",
HttpOnly: true,
MaxAge: -1,
})
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]bool{"success": true})
return
}
// For other API endpoints, require referer
referer := r.Header.Get("Referer")
if referer == "" {
http.Error(w, "Missing Referer header", http.StatusBadRequest)
return
}
// Extract path from referer URL
refURL, err := r.URL.Parse(referer)
if err != nil {
http.Error(w, "Invalid Referer", http.StatusBadRequest)
return
}
pagePath := refURL.Path
// Get current template (may not exist for new pages)
var tmplContent string
err = db.QueryRow("SELECT template FROM __pages WHERE path = ? ORDER BY created_at DESC LIMIT 1", pagePath).Scan(&tmplContent)
pageExists := err == nil
if err != nil && err != sql.ErrNoRows {
http.Error(w, "Database error", http.StatusInternalServerError)
return
}
// For endpoints that require existing page, check later
// Require authentication for all mutation endpoints
if !isAuthenticated(db, r) {
http.Error(w, "Not authenticated", http.StatusUnauthorized)
return
}
switch r.URL.Path {
case "/__api/source":
// Return template source for given position
if !pageExists {
http.Error(w, "Page not found", http.StatusNotFound)
return
}
pos, _ := parseInt(r.URL.Query().Get("pos"))
length, _ := parseInt(r.URL.Query().Get("len"))
if pos < 0 || pos+length > len(tmplContent) {
http.Error(w, "Invalid position", http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte(tmplContent[pos : pos+length]))
case "/__api/validate":
// Validate edited template chunk
if !pageExists {
http.Error(w, "Page not found", http.StatusNotFound)
return
}
var req struct {
Pos int `json:"pos"`
Len int `json:"len"`
Content string `json:"content"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "Invalid JSON", http.StatusBadRequest)
return
}
// Splice new content into template
if req.Pos < 0 || req.Pos+req.Len > len(tmplContent) {
http.Error(w, "Invalid position", http.StatusBadRequest)
return
}
newTemplate := tmplContent[:req.Pos] + req.Content + tmplContent[req.Pos+req.Len:]
// Try to parse it
_, err := template.New("test").Funcs(createTemplateFuncs(db)).Parse(newTemplate)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusOK)
case "/__api/save":
// Save edited template (inline edit - requires existing page)
if !pageExists {
http.Error(w, "Page not found", http.StatusNotFound)
return
}
var req struct {
Pos int `json:"pos"`
Len int `json:"len"`
Content string `json:"content"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "Invalid JSON", http.StatusBadRequest)
return
}
// Splice new content into template
if req.Pos < 0 || req.Pos+req.Len > len(tmplContent) {
http.Error(w, "Invalid position", http.StatusBadRequest)
return
}
newTemplate := tmplContent[:req.Pos] + req.Content + tmplContent[req.Pos+req.Len:]
// Validate: parse template
funcs, sqlErrors := createTemplateFuncsWithErrors(db)
tmpl, err := template.New("test").Funcs(funcs).Parse(newTemplate)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Validate: test render with mock context
testCtx := map[string]any{
"Path": pagePath,
"Method": "GET",
"Query": map[string]string{},
"Form": map[string]string{},
}
var testBuf bytes.Buffer
if err := tmpl.Execute(&testBuf, testCtx); err != nil {
http.Error(w, fmt.Sprintf("Render error: %v", err), http.StatusBadRequest)
return
}
// Check for SQL errors
if len(*sqlErrors) > 0 {
http.Error(w, fmt.Sprintf("SQL errors: %s", strings.Join(*sqlErrors, "; ")), http.StatusBadRequest)
return
}
// Get content_type from current version
var contentType string
db.QueryRow("SELECT content_type FROM __pages WHERE path = ? ORDER BY created_at DESC LIMIT 1", pagePath).Scan(&contentType)
// Save as new version
_, err = db.Exec("INSERT INTO __pages (path, template, content_type) VALUES (?, ?, ?)", pagePath, newTemplate, contentType)
if err != nil {
http.Error(w, fmt.Sprintf("Failed to save: %v", err), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
case "/__api/save-full":
// Save entire template (for direct edit mode)
var req struct {
Content string `json:"content"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "Invalid JSON", http.StatusBadRequest)
return
}
// Validate: parse template
funcs, sqlErrors := createTemplateFuncsWithErrors(db)
tmpl, err := template.New("test").Funcs(funcs).Parse(req.Content)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Validate: test render with mock context
testCtx := map[string]any{
"Path": pagePath,
"Method": "GET",
"Query": map[string]string{},
"Form": map[string]string{},
}
var testBuf bytes.Buffer
if err := tmpl.Execute(&testBuf, testCtx); err != nil {
http.Error(w, fmt.Sprintf("Render error: %v", err), http.StatusBadRequest)
return
}
// Check for SQL errors
if len(*sqlErrors) > 0 {
http.Error(w, fmt.Sprintf("SQL errors: %s", strings.Join(*sqlErrors, "; ")), http.StatusBadRequest)
return
}
// Get content_type from current version, default to text/html for new pages
var contentType string
err = db.QueryRow("SELECT content_type FROM __pages WHERE path = ? ORDER BY created_at DESC LIMIT 1", pagePath).Scan(&contentType)
if err == sql.ErrNoRows {
contentType = "text/html"
}
// Save as new version
_, err = db.Exec("INSERT INTO __pages (path, template, content_type) VALUES (?, ?, ?)", pagePath, req.Content, contentType)
if err != nil {
http.Error(w, fmt.Sprintf("Failed to save: %v", err), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
default:
http.NotFound(w, r)
}
}
func parseInt(s string) (int, error) {
var n int
_, err := fmt.Sscanf(s, "%d", &n)
return n, err
}
// TemplateFuncsWithErrors returns template functions and a way to retrieve collected errors
func createTemplateFuncsWithErrors(db *sql.DB) (template.FuncMap, *[]string) {
errors := &[]string{}
funcs := template.FuncMap{
// sql returns multiple rows as []map[string]any
"sql": func(query string, args ...any) []map[string]any {
rows, err := db.Query(query, args...)
if err != nil {
// Truncate long queries for readability
displayQuery := query
if len(displayQuery) > 50 {
displayQuery = displayQuery[:50] + "..."
}
*errors = append(*errors, fmt.Sprintf("%v (query: %s)", err, displayQuery))
return nil
}
defer rows.Close()
return rowsToMaps(rows)
},
// sql1 returns single row as map[string]any (or nil)
"sql1": func(query string, args ...any) map[string]any {
rows, err := db.Query(query, args...)
if err != nil {
displayQuery := query
if len(displayQuery) > 50 {
displayQuery = displayQuery[:50] + "..."
}
*errors = append(*errors, fmt.Sprintf("%v (query: %s)", err, displayQuery))
return nil
}
defer rows.Close()
results := rowsToMaps(rows)
if len(results) > 0 {
return results[0]
}
return nil
},
// exec runs INSERT/UPDATE/DELETE and returns rows affected
"exec": func(query string, args ...any) int64 {
result, err := db.Exec(query, args...)
if err != nil {
displayQuery := query
if len(displayQuery) > 50 {
displayQuery = displayQuery[:50] + "..."
}
*errors = append(*errors, fmt.Sprintf("%v (query: %s)", err, displayQuery))
return 0
}
affected, _ := result.RowsAffected()
return affected
},
}
return funcs, errors
}
// createTemplateFuncs returns template functions (errors are discarded)
func createTemplateFuncs(db *sql.DB) template.FuncMap {
funcs, _ := createTemplateFuncsWithErrors(db)
return funcs
}
func rowsToMaps(rows *sql.Rows) []map[string]any {
columns, err := rows.Columns()
if err != nil {
return nil
}
var results []map[string]any
for rows.Next() {
values := make([]any, len(columns))
valuePtrs := make([]any, len(columns))
for i := range values {
valuePtrs[i] = &values[i]
}
if err := rows.Scan(valuePtrs...); err != nil {
continue
}
row := make(map[string]any)
for i, col := range columns {
row[col] = values[i]
}
results = append(results, row)
}
return results
}
// getSchemaHTML returns HTML showing database tables and columns
func getSchemaHTML(db *sql.DB) string {
var html strings.Builder
// Get all tables (excluding internal __ tables)
rows, err := db.Query(`
SELECT name FROM sqlite_master
WHERE type='table' AND name NOT LIKE '@_@_%' ESCAPE '@'
ORDER BY name
`)
if err != nil {
return "<p>Error reading schema</p>"
}
defer rows.Close()
var tables []string
for rows.Next() {
var name string
rows.Scan(&name)
tables = append(tables, name)
}
if len(tables) == 0 {
html.WriteString("<p><em>No tables</em></p>")
return html.String()
}
for _, table := range tables {
html.WriteString(fmt.Sprintf("<strong>%s</strong><ul>", template.HTMLEscapeString(table)))
// Get columns for this table
colRows, err := db.Query(fmt.Sprintf("PRAGMA table_info(%s)", table))
if err != nil {
html.WriteString("<li>Error reading columns</li>")
html.WriteString("</ul>")
continue
}
for colRows.Next() {
var cid int
var name, colType string
var notNull, pk int
var dfltValue any
colRows.Scan(&cid, &name, &colType, ¬Null, &dfltValue, &pk)
pkMarker := ""
if pk > 0 {
pkMarker = " (PK)"
}
html.WriteString(fmt.Sprintf("<li><code>%s</code> %s%s</li>",
template.HTMLEscapeString(name),
template.HTMLEscapeString(colType),
pkMarker))
}
colRows.Close()
html.WriteString("</ul>")
}
return html.String()
}
func mapValues(m map[string][]string) map[string]string {
result := make(map[string]string)
for k, v := range m {
if len(v) > 0 {
result[k] = v[0]
}
}
return result
}
// ============================================================================
// INLINE TEMPLATE EDITING
// ============================================================================
// wrapTextForEditing pre-processes template source to wrap text content with spans
// Returns the modified template source with position markers
func wrapTextForEditing(source string) string {
var result strings.Builder
i := 0
// States: 0=normal, 1=in tag, 2=in template action
inTag := false
inAction := false
textStart := -1
for i < len(source) {
// Check for template action start
if i+1 < len(source) && source[i] == '{' && source[i+1] == '{' {
// End any current text span
if textStart >= 0 && !inTag {
text := source[textStart:i]
if strings.TrimSpace(text) != "" {
result.WriteString(fmt.Sprintf(`<span data-tmpl-pos="%d" data-tmpl-len="%d">`, textStart, len(text)))
result.WriteString(text)
result.WriteString(`</span>`)
} else {
result.WriteString(text)
}
textStart = -1
}
// Find the end of this template action
actionStart := i
i += 2 // Skip {{
for i+1 < len(source) && !(source[i] == '}' && source[i+1] == '}') {
i++
}
if i+1 < len(source) {
i += 2 // Include }}
}
action := source[actionStart:i]
// Check if this is a block-level construct (range, if, with, define, block)
actionContent := strings.TrimSpace(action[2 : len(action)-2]) // Remove {{ and }}
isBlock := strings.HasPrefix(actionContent, "range") ||
strings.HasPrefix(actionContent, "if") ||
strings.HasPrefix(actionContent, "with") ||
strings.HasPrefix(actionContent, "define") ||
strings.HasPrefix(actionContent, "block")
if isBlock {
// Find matching {{ end }} considering nesting
blockStart := actionStart
nesting := 1
for nesting > 0 && i < len(source) {
if i+1 < len(source) && source[i] == '{' && source[i+1] == '{' {
// Find end of this action
j := i + 2
for j+1 < len(source) && !(source[j] == '}' && source[j+1] == '}') {
j++
}
if j+1 < len(source) {
j += 2
}
innerAction := strings.TrimSpace(source[i+2 : j-2])
if strings.HasPrefix(innerAction, "range") ||
strings.HasPrefix(innerAction, "if") ||
strings.HasPrefix(innerAction, "with") ||
strings.HasPrefix(innerAction, "define") ||
strings.HasPrefix(innerAction, "block") {
nesting++
} else if strings.HasPrefix(innerAction, "end") {
nesting--
}
i = j
} else {
i++
}
}
// Wrap entire block in div
result.WriteString(`<div data-tmpl-dynamic>`)
result.WriteString(source[blockStart:i])
result.WriteString(`</div>`)
} else {
// Simple action - wrap in span
result.WriteString(`<span data-tmpl-dynamic>`)
result.WriteString(action)
result.WriteString(`</span>`)
}
textStart = i // Start new text after action
continue
}
// Inside template action - should not reach here anymore
if inAction {
result.WriteByte(source[i])
i++
continue
}
// Check for HTML tag start
if source[i] == '<' {
// End any current text span
if textStart >= 0 && !inTag {
text := source[textStart:i]
if strings.TrimSpace(text) != "" {
result.WriteString(fmt.Sprintf(`<span data-tmpl-pos="%d" data-tmpl-len="%d">`, textStart, len(text)))
result.WriteString(text)
result.WriteString(`</span>`)
} else {
result.WriteString(text)
}
textStart = -1
}
inTag = true
result.WriteByte(source[i])
i++
continue
}
// Check for HTML tag end
if source[i] == '>' && inTag {
inTag = false
result.WriteByte(source[i])
i++
textStart = i // Start new text after tag
continue
}
// Inside tag - just copy
if inTag {
result.WriteByte(source[i])
i++
continue
}
// Regular text - mark start if needed
if textStart < 0 {
textStart = i
}
i++
}
// Handle trailing text
if textStart >= 0 && textStart < len(source) {
text := source[textStart:]
if strings.TrimSpace(text) != "" {
result.WriteString(fmt.Sprintf(`<span data-tmpl-pos="%d" data-tmpl-len="%d">`, textStart, len(text)))
result.WriteString(text)
result.WriteString(`</span>`)
} else {
result.WriteString(text)
}
}
return result.String()
}
// baseCSS contains common CSS for dark theme support
const baseCSS = `
<style>
:root {
--bg: white;
--bg-secondary: #e8e8e8;
--text: black;
--border: #ccc;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #1a1a1a;
--bg-secondary: #2a2a2a;
--text: #eee;
--border: #555;
}
a {
color: #6bf;
}
a:visited {
color: #c9f;
}
}
html {
background: var(--bg);
color: var(--text);
}
button {
background: var(--bg-secondary);
color: var(--text);
border: 1px solid var(--border);
border-radius: 3px;
cursor: pointer;
padding: 10px 20px;
margin: 5px;
}
button.primary {
background: #007bff;
color: white;
border: none;
}
button.secondary {
background: #6c757d;
color: white;
border: none;
}
.auth-bar {
position: fixed;
top: 0;
right: 0;
background: var(--bg-secondary);
border: 1px solid var(--border);
border-radius: 0 0 0 5px;
padding: 0px 10px;
font-size: 12px;
z-index: 10001;
font-family: system-ui, sans-serif;
}
.auth-bar button {
margin-left: 10px;
padding: 4px 10px;
}
</style>
`
// debugPrintTreeToWriter prints the template AST structure to a writer
func debugPrintTreeToWriter(w io.Writer, list *parse.ListNode, indent int) {
if list == nil {
return
}
for _, node := range list.Nodes {
prefix := strings.Repeat(" ", indent)
switch n := node.(type) {
case *parse.TextNode:
text := string(n.Text)
// Escape newlines for display
text = strings.ReplaceAll(text, "\n", "\\n")
if len(text) > 60 {
text = text[:60] + "..."
}
fmt.Fprintf(w, "%sTextNode[pos=%d, len=%d]: %q\n", prefix, n.Pos, len(n.Text), text)
case *parse.ActionNode:
fmt.Fprintf(w, "%sActionNode[pos=%d]: %s\n", prefix, n.Pos, n.String())
case *parse.IfNode:
fmt.Fprintf(w, "%sIfNode[pos=%d]\n", prefix, n.Pos)
fmt.Fprintf(w, "%s List:\n", prefix)
debugPrintTreeToWriter(w, n.List, indent+2)
if n.ElseList != nil {
fmt.Fprintf(w, "%s ElseList:\n", prefix)
debugPrintTreeToWriter(w, n.ElseList, indent+2)
}
case *parse.RangeNode:
fmt.Fprintf(w, "%sRangeNode[pos=%d]\n", prefix, n.Pos)
fmt.Fprintf(w, "%s List:\n", prefix)
debugPrintTreeToWriter(w, n.List, indent+2)
if n.ElseList != nil {
fmt.Fprintf(w, "%s ElseList:\n", prefix)
debugPrintTreeToWriter(w, n.ElseList, indent+2)
}
case *parse.WithNode:
fmt.Fprintf(w, "%sWithNode[pos=%d]\n", prefix, n.Pos)
fmt.Fprintf(w, "%s List:\n", prefix)
debugPrintTreeToWriter(w, n.List, indent+2)
if n.ElseList != nil {
fmt.Fprintf(w, "%s ElseList:\n", prefix)
debugPrintTreeToWriter(w, n.ElseList, indent+2)
}
default:
fmt.Fprintf(w, "%s%T[pos=%d]\n", prefix, node, node.Position())
}
}
}
// authPageHTML contains the authentication page with key generation
const authPageHTML = `<!DOCTYPE html>
<html>
<head>
<title>Authentication Required</title>
<style>
body { font-family: system-ui, sans-serif; max-width: 600px; margin: 25px auto; padding: 20px; }
.section { margin: 20px 0; padding: 15px; border: 1px solid var(--border); border-radius: 5px; background: var(--bg-secondary); }
pre { background: var(--bg); padding: 10px; overflow-x: auto; font-size: 12px; border: 1px solid var(--border); }
.status { padding: 10px; margin: 10px 0; border-radius: 3px; }
.success { background: #d4edda; color: #155724; }
.error { background: #f8d7da; color: #721c24; }
.info { background: #d1ecf1; color: #0c5460; }
#public-key { word-break: break-all; }
</style>
</head>
<body>
<h1>Authentication Required</h1>
<p>Edit mode requires authentication. You need a keypair stored in your browser.</p>
<div class="section">
<h3>Step 1: Check for existing key</h3>
<div id="key-status"></div>
<button class="secondary" onclick="checkKey()">Check Key</button>
</div>
<div class="section">
<h3>Step 2: Generate or authenticate</h3>
<div id="auth-actions"></div>
</div>
<div class="section">
<h3>Your Public Key</h3>
<p>Give this to the admin to authorize your key:</p>
<pre id="public-key">(generate a key first)</pre>
<button class="secondary" onclick="copyKey()">Copy to Clipboard</button>
</div>
<script>
const STORAGE_KEY = '__sqlite_apps_keypair';
async function checkKey() {
const stored = localStorage.getItem(STORAGE_KEY);
const statusDiv = document.getElementById('key-status');
const actionsDiv = document.getElementById('auth-actions');
const keyDiv = document.getElementById('public-key');
if (!stored) {
statusDiv.innerHTML = '<div class="status info">No key found in browser storage.</div>';
actionsDiv.innerHTML = '<button class="primary" onclick="generateKey()">Generate New Keypair</button>';
return;
}
try {
const keypair = JSON.parse(stored);
statusDiv.innerHTML = '<div class="status success">Key found in browser storage.</div>';
actionsDiv.innerHTML = '<button class="primary" onclick="authenticate()">Authenticate</button> <button class="secondary" onclick="generateKey()">Generate New Key</button>';
keyDiv.textContent = JSON.stringify(keypair.publicKey, null, 2);
} catch (e) {
statusDiv.innerHTML = '<div class="status error">Invalid key in storage: ' + e.message + '</div>';
actionsDiv.innerHTML = '<button class="primary" onclick="generateKey()">Generate New Keypair</button>';
}
}
async function generateKey() {
// Check if crypto.subtle is available
if (!window.crypto || !window.crypto.subtle) {
document.getElementById('key-status').innerHTML = '<div class="status error">Web Crypto API not available. This requires HTTPS or localhost.</div>';
return;
}
try {
// Generate ECDSA P-256 keypair
const keyPair = await crypto.subtle.generateKey(
{ name: 'ECDSA', namedCurve: 'P-256' },
true,
['sign', 'verify']
);
// Export keys
const publicKeyJWK = await crypto.subtle.exportKey('jwk', keyPair.publicKey);
const privateKeyJWK = await crypto.subtle.exportKey('jwk', keyPair.privateKey);
// Store in localStorage
const keypair = {
publicKey: publicKeyJWK,
privateKey: privateKeyJWK
};
localStorage.setItem(STORAGE_KEY, JSON.stringify(keypair));
// Update UI
document.getElementById('key-status').innerHTML = '<div class="status success">New keypair generated and saved.</div>';
document.getElementById('auth-actions').innerHTML = '<button class="primary" onclick="authenticate()">Authenticate</button> <button class="secondary" onclick="generateKey()">Generate New Key</button>';
document.getElementById('public-key').textContent = JSON.stringify(publicKeyJWK, null, 2);
} catch (e) {
document.getElementById('key-status').innerHTML = '<div class="status error">Failed to generate key: ' + e.message + '</div>';
}
}
async function authenticate() {
const statusDiv = document.getElementById('key-status');
// Check if crypto.subtle is available
if (!window.crypto || !window.crypto.subtle) {
statusDiv.innerHTML = '<div class="status error">Web Crypto API not available. This requires HTTPS or localhost.</div>';
return;
}
try {
// Get keypair from storage
const stored = localStorage.getItem(STORAGE_KEY);
if (!stored) {
statusDiv.innerHTML = '<div class="status error">No key found. Generate one first.</div>';
return;
}
const keypair = JSON.parse(stored);
// Import private key for signing
const privateKey = await crypto.subtle.importKey(
'jwk',
keypair.privateKey,
{ name: 'ECDSA', namedCurve: 'P-256' },
false,
['sign']
);
// Get challenge from server
const challengeResp = await fetch('/__api/auth/challenge');
if (!challengeResp.ok) {
throw new Error('Failed to get challenge');
}
const { challenge } = await challengeResp.json();
// Sign the challenge
const encoder = new TextEncoder();
const data = encoder.encode(challenge);
const signature = await crypto.subtle.sign(
{ name: 'ECDSA', hash: 'SHA-256' },
privateKey,
data
);
// Convert signature to base64url
const sigArray = new Uint8Array(signature);
const sigB64 = btoa(String.fromCharCode(...sigArray))
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '');
// Verify with server
const verifyResp = await fetch('/__api/auth/verify', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ signature: sigB64 })
});
if (!verifyResp.ok) {
const error = await verifyResp.text();
statusDiv.innerHTML = '<div class="status error">Authentication failed: ' + error + '</div>';
return;
}
statusDiv.innerHTML = '<div class="status success">Authenticated! Redirecting...</div>';
// Redirect to home
setTimeout(() => {
window.location.href = '/';
}, 1000);
} catch (e) {
statusDiv.innerHTML = '<div class="status error">Authentication error: ' + e.message + '</div>';
}
}
function copyKey() {
const keyText = document.getElementById('public-key').textContent;
navigator.clipboard.writeText(keyText).then(() => {
alert('Public key copied to clipboard');
});
}
// Check if user is already authenticated (to show delegate link)
async function checkAuthForDelegate() {
const resp = await fetch('/__api/auth/status');
const data = await resp.json();
if (data.authenticated) {
const link = document.createElement('div');
link.className = 'section';
link.innerHTML = '<h3>Share Login</h3><p>Want to authorize another device? <a href="/__delegate?share">Generate a share link</a></p>';
document.body.appendChild(link);
}
}
// Check key on load
checkKey();
checkAuthForDelegate();
</script>
</body>
</html>
`
// delegatePageHTML contains the delegation page for sharing login
const delegatePageHTML = `<!DOCTYPE html>
<html>
<head>
<title>Share Login</title>
<style>
body { font-family: system-ui, sans-serif; max-width: 600px; margin: 25px auto; padding: 20px; }
.section { margin: 20px 0; padding: 15px; border: 1px solid var(--border); border-radius: 5px; background: var(--bg-secondary); }
.status { padding: 10px; margin: 10px 0; border-radius: 3px; }
.success { background: #d4edda; color: #155724; }
.error { background: #f8d7da; color: #721c24; }
.info { background: #d1ecf1; color: #0c5460; }
.warning { background: #fff3cd; color: #856404; }
input[type="text"] { width: 100%; padding: 8px; margin: 10px 0; box-sizing: border-box; background: var(--bg); color: var(--text); border: 1px solid var(--border); }
.pin-display { font-size: 48px; font-weight: bold; text-align: center; padding: 20px; margin: 20px 0; background: var(--bg); border: 2px solid var(--border); border-radius: 8px; letter-spacing: 8px; font-family: monospace; }
.verification-code { font-size: 36px; font-weight: bold; text-align: center; padding: 15px; margin: 15px 0; background: #fff3cd; border: 2px solid #ffc107; border-radius: 8px; letter-spacing: 6px; font-family: monospace; color: #856404; }
</style>
</head>
<body>
<div id="share-page" style="display: none;">
<h1>Share Login - Step 1</h1>
<div class="section">
<p><strong>Generate a PIN to share with your other device.</strong></p>
<p>The other device will show you a verification code that you must confirm here.</p>
<div id="share-status"></div>
<button class="primary" onclick="createShareLink()">Generate PIN</button>
</div>
<div id="waiting-section" style="display: none;">
<div class="section">
<h3>Your PIN (share this with your other device):</h3>
<div class="pin-display" id="pin-display"></div>
<p>Or share this link: <a id="share-link" href="#"></a></p>
</div>
<div class="section">
<h3>Waiting for other device...</h3>
<div id="poll-status" class="status info">Waiting for the other device to submit their verification code...</div>
</div>
<div id="verification-section" style="display: none;">
<div class="section">
<h3>⚠️ Verification Required</h3>
<p><strong>Does your other device show this code?</strong></p>
<div class="verification-code" id="verification-display"></div>
<p>Device name: <strong id="device-name-display"></strong></p>
<button class="primary" onclick="confirmDelegation()">Yes, Authorize Device</button>
<button class="secondary" onclick="cancelDelegation()">No, Cancel</button>
</div>
</div>
</div>
</div>
<div id="confirm-page" style="display: none;">
<h1>Complete Login Delegation - Step 2</h1>
<div class="section">
<p><strong>You're joining from a new device.</strong></p>
<p>Enter a name for this device and submit. You'll then see a verification code to confirm with your trusted device.</p>
<input type="text" id="delegate-name" placeholder="Device name (e.g., 'Work Laptop')">
<div id="delegate-status"></div>
<button class="primary" onclick="submitDelegation()">Submit</button>
</div>
<div id="verification-code-section" style="display: none;">
<div class="section">
<h3>✓ Your Verification Code:</h3>
<div class="verification-code" id="my-verification-display"></div>
<p><strong>Check that this code appears on your trusted device, then confirm there.</strong></p>
<div id="waiting-status" class="status info">Waiting for confirmation from trusted device...</div>
</div>
</div>
</div>
<script>
const STORAGE_KEY = '__sqlite_apps_keypair';
let currentPin = null;
let pollInterval = null;
async function createShareLink() {
const statusDiv = document.getElementById('share-status');
try {
const resp = await fetch('/__api/auth/delegate/create', { method: 'POST' });
if (!resp.ok) {
throw new Error(await resp.text());
}
const { pin } = await resp.json();
currentPin = pin;
// Show PIN and start polling
document.getElementById('pin-display').textContent = pin;
const url = window.location.origin + '/__delegate?confirm=' + pin;
const linkEl = document.getElementById('share-link');
linkEl.href = url;
linkEl.textContent = url;
document.getElementById('share-status').style.display = 'none';
document.querySelector('#share-page button').style.display = 'none';
document.getElementById('waiting-section').style.display = 'block';
// Start polling for verification code
startPolling();
} catch (e) {
statusDiv.innerHTML = '<div class="status error">Failed to create delegation: ' + e.message + '</div>';
}
}
function startPolling() {
pollInterval = setInterval(async () => {
try {
const resp = await fetch('/__api/auth/delegate/poll?pin=' + currentPin);
if (!resp.ok) return;
const data = await resp.json();
if (data.status === 'awaiting_confirmation') {
// Show verification code
clearInterval(pollInterval);
document.getElementById('verification-display').textContent = data.verificationCode;
document.getElementById('device-name-display').textContent = data.deviceName;
document.getElementById('verification-section').style.display = 'block';
document.getElementById('poll-status').style.display = 'none';
} else if (data.status === 'confirmed') {
clearInterval(pollInterval);
document.getElementById('poll-status').innerHTML = '<div class="status success">Device authorized successfully!</div>';
setTimeout(() => window.location.href = '/', 2000);
} else if (data.status === 'not_found') {
clearInterval(pollInterval);
document.getElementById('poll-status').innerHTML = '<div class="status error">Delegation expired or cancelled</div>';
}
} catch (e) {
console.error('Poll error:', e);
}
}, 1000);
}
async function confirmDelegation() {
try {
const resp = await fetch('/__api/auth/delegate/confirm', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ pin: currentPin })
});
if (!resp.ok) {
throw new Error(await resp.text());
}
document.getElementById('verification-section').innerHTML = '<div class="status success">Device authorized! Redirecting...</div>';
setTimeout(() => window.location.href = '/', 2000);
} catch (e) {
alert('Failed to confirm: ' + e.message);
}
}
async function cancelDelegation() {
try {
await fetch('/__api/auth/delegate/cancel', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ pin: currentPin })
});
window.location.reload();
} catch (e) {
alert('Failed to cancel: ' + e.message);
}
}
async function submitDelegation() {
const statusDiv = document.getElementById('delegate-status');
const name = document.getElementById('delegate-name').value.trim();
if (!name) {
statusDiv.innerHTML = '<div class="status error">Please enter a device name</div>';
return;
}
// Check if crypto.subtle is available
if (!window.crypto || !window.crypto.subtle) {
statusDiv.innerHTML = '<div class="status error">Web Crypto API not available. This requires HTTPS or localhost.</div>';
return;
}
const pin = new URL(window.location).searchParams.get('confirm');
try {
// Generate verification code (6 digits)
const verificationCode = String(Math.floor(Math.random() * 1000000)).padStart(6, '0');
// Ensure we have a keypair
let stored = localStorage.getItem(STORAGE_KEY);
if (!stored) {
// Generate one
const keyPair = await crypto.subtle.generateKey(
{ name: 'ECDSA', namedCurve: 'P-256' },
true,
['sign', 'verify']
);
const publicKeyJWK = await crypto.subtle.exportKey('jwk', keyPair.publicKey);
const privateKeyJWK = await crypto.subtle.exportKey('jwk', keyPair.privateKey);
const keypair = { publicKey: publicKeyJWK, privateKey: privateKeyJWK };
localStorage.setItem(STORAGE_KEY, JSON.stringify(keypair));
stored = JSON.stringify(keypair);
}
const keypair = JSON.parse(stored);
// Import private key for signing
const privateKey = await crypto.subtle.importKey(
'jwk',
keypair.privateKey,
{ name: 'ECDSA', namedCurve: 'P-256' },
false,
['sign']
);
// Sign the verification code (not the PIN!)
const encoder = new TextEncoder();
const data = encoder.encode(verificationCode);
const signature = await crypto.subtle.sign(
{ name: 'ECDSA', hash: 'SHA-256' },
privateKey,
data
);
// Convert signature to base64url
const sigArray = new Uint8Array(signature);
const sigB64 = btoa(String.fromCharCode(...sigArray))
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '');
// Submit delegation
const resp = await fetch('/__api/auth/delegate/submit', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
pin: pin,
verificationCode: verificationCode,
publicKey: keypair.publicKey,
signature: sigB64,
name: name
})
});
if (!resp.ok) {
throw new Error(await resp.text());
}
// Show verification code and wait for confirmation
document.getElementById('my-verification-display').textContent = verificationCode;
document.querySelector('#confirm-page .section').style.display = 'none';
document.getElementById('verification-code-section').style.display = 'block';
// Poll for confirmation by trying to authenticate
const pollConfirm = setInterval(async () => {
try {
// Try to authenticate - this will only succeed after trusted device confirms
const challengeResp = await fetch('/__api/auth/challenge');
if (!challengeResp.ok) return;
const { challenge } = await challengeResp.json();
// Sign the challenge
const privateKey = await crypto.subtle.importKey(
'jwk',
keypair.privateKey,
{ name: 'ECDSA', namedCurve: 'P-256' },
false,
['sign']
);
const encoder = new TextEncoder();
const data = encoder.encode(challenge);
const signature = await crypto.subtle.sign(
{ name: 'ECDSA', hash: 'SHA-256' },
privateKey,
data
);
const sigArray = new Uint8Array(signature);
const sigB64 = btoa(String.fromCharCode(...sigArray))
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '');
// Try to verify - this will succeed once the key is authorized
const verifyResp = await fetch('/__api/auth/verify', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ signature: sigB64 })
});
if (verifyResp.ok) {
clearInterval(pollConfirm);
document.getElementById('waiting-status').innerHTML = '<div class="status success">Authorized! Redirecting...</div>';
setTimeout(() => window.location.href = '/', 1000);
}
} catch (e) {
// Ignore errors during polling
console.log('Still waiting for confirmation...');
}
}, 2000);
} catch (e) {
statusDiv.innerHTML = '<div class="status error">Delegation failed: ' + e.message + '</div>';
}
}
// Show correct page based on query params
async function init() {
const params = new URL(window.location).searchParams;
if (params.has('share')) {
document.getElementById('share-page').style.display = 'block';
} else if (params.has('confirm')) {
document.getElementById('confirm-page').style.display = 'block';
// Check if user already has an authorized key
const resp = await fetch('/__api/auth/status');
const data = await resp.json();
if (data.authenticated) {
const btn = document.querySelector('#confirm-page button');
btn.disabled = true;
btn.style.opacity = '0.5';
btn.style.cursor = 'not-allowed';
document.getElementById('delegate-status').innerHTML = '<div class="status info">You already have an authorized key. <a href="/__auth">Go to authentication page</a></div>';
}
} else {
document.body.innerHTML = '<h1>Invalid Request</h1><p>Use <a href="/__delegate?share">/__delegate?share</a> to generate a share link.</p>';
}
}
init();
</script>
</body>
</html>
`
// accountPageHTML contains the account management page
const accountPageHTML = `<!DOCTYPE html>
<html>
<head>
<title>Account</title>
<style>
body { font-family: system-ui, sans-serif; max-width: 600px; margin: 25px auto; padding: 20px; }
.section { margin: 20px 0; padding: 15px; border: 1px solid var(--border); border-radius: 5px; background: var(--bg-secondary); }
.status { padding: 10px; margin: 10px 0; border-radius: 3px; }
.success { background: #d4edda; color: #155724; }
.error { background: #f8d7da; color: #721c24; }
.info { background: #d1ecf1; color: #0c5460; }
.danger { background: #dc3545; color: white; border: none; }
.danger:hover { background: #c82333; }
</style>
</head>
<body>
<h1>Account</h1>
<div id="not-authenticated" style="display: none;">
<div class="section">
<p>You are not logged in.</p>
<p><a href="/__auth">Go to authentication page</a></p>
</div>
</div>
<div id="authenticated" style="display: none;">
<div class="section">
<h3>Account Info</h3>
<p>Logged in as: <strong id="key-name"></strong></p>
</div>
<div class="section">
<h3>Share Login</h3>
<p>Authorize another device to use your account.</p>
<p><a href="/__delegate?share">Generate share link</a></p>
</div>
<div class="section">
<h3>Logout</h3>
<p>End your current session. Your keypair will remain in your browser.</p>
<div id="logout-status"></div>
<button class="secondary" onclick="logout()">Logout</button>
</div>
<div class="section">
<h3>Delete Account</h3>
<p>This will remove your public key from the server and clear your local key. You will need to be re-authorized to edit again.</p>
<div id="delete-status"></div>
<button class="danger" onclick="deleteAccount()">Delete Account</button>
</div>
</div>
<script>
const STORAGE_KEY = '__sqlite_apps_keypair';
async function checkAuth() {
const resp = await fetch('/__api/auth/status');
const data = await resp.json();
if (data.authenticated) {
document.getElementById('authenticated').style.display = 'block';
document.getElementById('key-name').textContent = data.name || 'Unknown';
} else {
document.getElementById('not-authenticated').style.display = 'block';
}
}
async function logout() {
const statusDiv = document.getElementById('logout-status');
try {
const resp = await fetch('/__api/auth/logout', { method: 'POST' });
if (!resp.ok) {
throw new Error(await resp.text());
}
statusDiv.innerHTML = '<div class="status success">Logged out. Redirecting...</div>';
setTimeout(() => {
window.location.href = '/';
}, 1000);
} catch (e) {
statusDiv.innerHTML = '<div class="status error">Failed to logout: ' + e.message + '</div>';
}
}
async function deleteAccount() {
if (!confirm('Are you sure you want to delete your account? This cannot be undone.')) {
return;
}
const statusDiv = document.getElementById('delete-status');
try {
const resp = await fetch('/__api/auth/delete', { method: 'POST' });
if (!resp.ok) {
throw new Error(await resp.text());
}
// Clear local storage
localStorage.removeItem(STORAGE_KEY);
statusDiv.innerHTML = '<div class="status success">Account deleted. Redirecting...</div>';
setTimeout(() => {
window.location.href = '/';
}, 1500);
} catch (e) {
statusDiv.innerHTML = '<div class="status error">Failed to delete account: ' + e.message + '</div>';
}
}
checkAuth();
</script>
</body>
</html>
`
// editShortcutsJS contains just the keyboard shortcuts for entering edit mode
const editShortcutsJS = `
<style>
</style>
<script>
(function() {
const STORAGE_KEY = '__sqlite_apps_keypair';
// Authenticate with stored keypair
async function authenticate() {
// Check if crypto.subtle is available
if (!window.crypto || !window.crypto.subtle) {
console.error('Web Crypto API not available');
return false;
}
try {
// Get keypair from storage
const stored = localStorage.getItem(STORAGE_KEY);
if (!stored) {
return false;
}
const keypair = JSON.parse(stored);
// Import private key for signing
const privateKey = await crypto.subtle.importKey(
'jwk',
keypair.privateKey,
{ name: 'ECDSA', namedCurve: 'P-256' },
false,
['sign']
);
// Get challenge from server
const challengeResp = await fetch('/__api/auth/challenge');
if (!challengeResp.ok) {
return false;
}
const { challenge } = await challengeResp.json();
// Sign the challenge
const encoder = new TextEncoder();
const data = encoder.encode(challenge);
const signature = await crypto.subtle.sign(
{ name: 'ECDSA', hash: 'SHA-256' },
privateKey,
data
);
// Convert signature to base64url
const sigArray = new Uint8Array(signature);
const sigB64 = btoa(String.fromCharCode(...sigArray))
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '');
// Verify with server
const verifyResp = await fetch('/__api/auth/verify', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ signature: sigB64 })
});
return verifyResp.ok;
} catch (e) {
console.error('Authentication error:', e);
return false;
}
}
// Check if user has a session and show edit button
async function checkAuthAndShowButton() {
const resp = await fetch('/__api/auth/status');
const data = await resp.json();
if (data.authenticated) {
const btn = document.createElement('div');
btn.className = 'auth-bar';
btn.innerHTML = '<button onclick="window.__tmplStartEdit()">Edit</button>';
document.body.appendChild(btn);
}
}
window.__tmplStartEdit = async function() {
// Check if already authenticated
const statusResp = await fetch('/__api/auth/status');
const statusData = await statusResp.json();
if (!statusData.authenticated) {
// Try to authenticate with stored key
const authed = await authenticate();
if (!authed) {
// No key or auth failed - redirect to auth page
window.location.href = '/__auth';
return;
}
}
// Now authenticated, enter edit mode
const url = new URL(window.location);
url.searchParams.set('__edit', '');
window.location.href = url.toString();
};
window.__tmplStartDirectEdit = async function() {
// Check if already authenticated
const statusResp = await fetch('/__api/auth/status');
const statusData = await statusResp.json();
if (!statusData.authenticated) {
// Try to authenticate with stored key
const authed = await authenticate();
if (!authed) {
// No key or auth failed - redirect to auth page
window.location.href = '/__auth';
return;
}
}
// Now authenticated, enter direct edit mode
const url = new URL(window.location);
url.searchParams.set('__edit', '');
url.searchParams.set('__direct', '');
window.location.href = url.toString();
};
checkAuthAndShowButton();
document.addEventListener('keydown', function(e) {
// Ctrl+. - enter edit mode
if (e.key === '.' && e.ctrlKey && !e.shiftKey) {
e.preventDefault();
window.__tmplStartEdit();
}
// Ctrl+Shift+. - direct edit mode
if (e.key === '.' && e.ctrlKey && e.shiftKey) {
e.preventDefault();
window.__tmplStartDirectEdit();
}
});
})();
</script>
`
// editorJS contains the JavaScript and CSS for inline template editing
const editorJS = `
<style>
[data-tmpl-pos] {
transition: background-color 0.2s;
}
[data-tmpl-pos]:hover {
background-color: rgba(0, 0, 0, 0.1);
cursor: pointer;
}
[data-tmpl-dynamic] {
border: 1px dashed #999;
border-radius: 3px;
cursor: pointer;
}
span[data-tmpl-dynamic] {
padding: 1px 3px;
}
div[data-tmpl-dynamic] {
margin: 0;
padding: 0;
}
[data-tmpl-dynamic]:hover {
background-color: rgba(0, 0, 0, 0.05);
}
@media (prefers-color-scheme: dark) {
[data-tmpl-pos]:hover {
background-color: rgba(255, 255, 255, 0.1);
}
[data-tmpl-dynamic] {
border-color: #666;
}
[data-tmpl-dynamic]:hover {
background-color: rgba(255, 255, 255, 0.05);
}
}
#tmpl-context-menu {
position: fixed;
background: var(--bg-secondary);
color: var(--text);
border: 1px solid var(--border);
box-shadow: 2px 2px 5px rgba(0,0,0,0.3);
padding: 5px 0;
z-index: 10000;
display: none;
border-radius: 3px;
}
#tmpl-context-menu div {
padding: 5px 15px;
cursor: pointer;
}
#tmpl-context-menu div:hover {
background: var(--bg);
}
</style>
<script>
(function() {
let currentEdit = null;
let originalHTML = null;
let originalSource = null;
let contextMenu = null;
// Create auth status bar
async function createAuthBar() {
const resp = await fetch('/__api/auth/status');
const data = await resp.json();
if (data.authenticated) {
const bar = document.createElement('div');
bar.className = 'auth-bar';
const name = data.name || 'unknown';
bar.innerHTML = 'Editing. Logged in as <a href="/__account"><strong>' + name + '</strong></a><button onclick="window.__tmplStopEdit()">Stop Editing</button>';
document.body.appendChild(bar);
}
}
// Stop editing function
window.__tmplStopEdit = function() {
const url = new URL(window.location);
url.searchParams.delete('__edit');
url.searchParams.delete('__direct');
window.location.href = url.toString();
};
// Initialize auth bar
createAuthBar();
// Create context menu element
function createContextMenu() {
const menu = document.createElement('div');
menu.id = 'tmpl-context-menu';
document.body.appendChild(menu);
return menu;
}
// Start editing an element
let disabledElements = [];
async function startEdit(el) {
// Cancel any existing edit
if (currentEdit) {
cancelEdit();
}
const pos = el.dataset.tmplPos;
const len = el.dataset.tmplLen;
// Fetch template source
const resp = await fetch('/__api/source?pos=' + pos + '&len=' + len);
if (!resp.ok) {
console.error('Failed to fetch source');
return;
}
const source = await resp.text();
// Store state
currentEdit = el;
originalHTML = el.innerHTML;
originalSource = source;
// Prevent clicks on parent links/buttons while editing
disabledElements = [];
const blockElements = ['DIV', 'P', 'LI', 'TD', 'TH', 'ARTICLE', 'SECTION', 'HEADER', 'FOOTER', 'MAIN', 'ASIDE', 'BLOCKQUOTE', 'BODY'];
let parent = el.parentElement;
while (parent && !blockElements.includes(parent.tagName)) {
// Add click handler to prevent default action (but allow clicks inside editable)
const preventHandler = function(e) {
// Always prevent default on links/buttons while editing
e.preventDefault();
};
parent.addEventListener('click', preventHandler);
disabledElements.push({el: parent, handler: preventHandler});
parent = parent.parentElement;
}
// Replace with editable source
el.textContent = source;
el.contentEditable = 'true';
el.focus();
// Handle keyboard shortcuts on the editable element directly
el.onkeydown = function(e) {
if (e.key === 'Escape') {
e.preventDefault();
cancelEdit();
}
if (e.key === 'Enter' && e.ctrlKey) {
e.preventDefault();
saveEdit();
}
};
// Add controls - find a block-level parent to insert after
const controls = document.createElement('div');
controls.id = 'tmpl-edit-controls';
controls.innerHTML = '<button id="tmpl-save">Save</button> <button id="tmpl-cancel">Cancel</button>';
// Walk up to find block-level container (reuse blockElements from above)
let insertTarget = el;
parent = el.parentElement;
while (parent && !blockElements.includes(parent.tagName)) {
insertTarget = parent;
parent = parent.parentElement;
}
insertTarget.insertAdjacentElement('afterend', controls);
document.getElementById('tmpl-save').onclick = saveEdit;
document.getElementById('tmpl-cancel').onclick = cancelEdit;
}
document.addEventListener('dblclick', async function(e) {
// Find nearest editable text element
let el = e.target;
while (el && !el.dataset.tmplPos) {
el = el.parentElement;
}
// If we found an editable element, edit it
if (el) {
await startEdit(el);
return;
}
// Otherwise check for dynamic element - go to direct edit mode
let dynEl = e.target;
while (dynEl && dynEl.dataset.tmplDynamic === undefined) {
dynEl = dynEl.parentElement;
}
if (dynEl) {
const url = new URL(window.location);
url.searchParams.set('__edit', '');
url.searchParams.set('__direct', '');
window.location.href = url.toString();
return;
}
});
// Context menu for right-click
document.addEventListener('contextmenu', function(e) {
// Find nearest editable element
let el = e.target;
while (el && !el.dataset.tmplPos) {
el = el.parentElement;
}
// Check for dynamic element
let dynEl = e.target;
while (dynEl && dynEl.dataset.tmplDynamic === undefined) {
dynEl = dynEl.parentElement;
}
if (!el && !dynEl) return;
e.preventDefault();
// Create menu if needed
if (!contextMenu) {
contextMenu = createContextMenu();
}
// Position and show menu
contextMenu.style.left = e.clientX + 'px';
contextMenu.style.top = e.clientY + 'px';
contextMenu.style.display = 'block';
// Update menu content based on what was clicked
if (el) {
contextMenu.innerHTML = '<div id="ctx-inline">Edit inline</div><div id="ctx-template">Edit in template editor</div>';
contextMenu.querySelector('#ctx-inline').onclick = async function() {
contextMenu.style.display = 'none';
await startEdit(el);
};
contextMenu.querySelector('#ctx-template').onclick = function() {
contextMenu.style.display = 'none';
const url = new URL(window.location);
url.searchParams.set('__edit', '');
url.searchParams.set('__direct', '');
window.location.href = url.toString();
};
} else if (dynEl) {
contextMenu.innerHTML = '<div>Edit in template editor</div>';
contextMenu.onclick = function() {
contextMenu.style.display = 'none';
const url = new URL(window.location);
url.searchParams.set('__edit', '');
url.searchParams.set('__direct', '');
window.location.href = url.toString();
};
}
});
// Hide context menu on click elsewhere
document.addEventListener('click', function() {
if (contextMenu) {
contextMenu.style.display = 'none';
}
});
// Fallback keyboard handler at document level
document.addEventListener('keydown', function(e) {
// Ctrl+. - toggle edit mode
if (e.key === '.' && e.ctrlKey && !e.shiftKey) {
e.preventDefault();
const url = new URL(window.location);
if (url.searchParams.has('__edit')) {
url.searchParams.delete('__edit');
url.searchParams.delete('__direct');
} else {
url.searchParams.set('__edit', '');
}
window.location.href = url.toString();
return;
}
// Ctrl+Shift+. - direct edit mode
if (e.key === '.' && e.ctrlKey && e.shiftKey) {
e.preventDefault();
const url = new URL(window.location);
url.searchParams.set('__edit', '');
url.searchParams.set('__direct', '');
window.location.href = url.toString();
return;
}
if (!currentEdit) return;
if (e.key === 'Escape') {
e.preventDefault();
cancelEdit();
}
// Note: Ctrl+Enter is handled by el.onkeydown to avoid double-firing
});
// Validate on blur (but not when clicking save/cancel)
document.addEventListener('focusout', async function(e) {
if (!currentEdit || e.target !== currentEdit) return;
// Check if focus went to our controls
const related = e.relatedTarget;
if (related && (related.id === 'tmpl-save' || related.id === 'tmpl-cancel')) {
return;
}
await validateEdit();
});
async function validateEdit() {
if (!currentEdit) return;
// Normalize: replace NBSP with regular space
const newSource = currentEdit.textContent.replace(/\u00A0/g, ' ');
const pos = currentEdit.dataset.tmplPos;
const len = currentEdit.dataset.tmplLen;
const resp = await fetch('/__api/validate', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({pos: parseInt(pos), len: parseInt(len), content: newSource})
});
// Remove existing error
const existingError = document.getElementById('tmpl-edit-error');
if (existingError) existingError.remove();
if (!resp.ok) {
const error = await resp.text();
const errorDiv = document.createElement('div');
errorDiv.id = 'tmpl-edit-error';
errorDiv.style.color = 'red';
errorDiv.style.padding = '5px';
errorDiv.style.marginTop = '5px';
errorDiv.textContent = error;
currentEdit.insertAdjacentElement('afterend', errorDiv);
}
}
async function saveEdit() {
if (!currentEdit) return;
// Normalize: replace NBSP with regular space
const newSource = currentEdit.textContent.replace(/\u00A0/g, ' ');
const pos = currentEdit.dataset.tmplPos;
const len = currentEdit.dataset.tmplLen;
const resp = await fetch('/__api/save', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({pos: parseInt(pos), len: parseInt(len), content: newSource})
});
if (!resp.ok) {
const error = await resp.text();
// Show error
const existingError = document.getElementById('tmpl-edit-error');
if (existingError) existingError.remove();
const errorDiv = document.createElement('div');
errorDiv.id = 'tmpl-edit-error';
errorDiv.style.color = 'red';
errorDiv.style.padding = '5px';
errorDiv.style.marginTop = '5px';
errorDiv.textContent = error;
currentEdit.insertAdjacentElement('afterend', errorDiv);
return;
}
// Reload page to see changes
window.location.reload();
}
function cancelEdit() {
if (!currentEdit) return;
currentEdit.innerHTML = originalHTML;
currentEdit.contentEditable = 'false';
// Remove click prevention handlers from parent elements
disabledElements.forEach(item => item.el.removeEventListener('click', item.handler, true));
disabledElements = [];
// Remove controls and error
const controls = document.getElementById('tmpl-edit-controls');
if (controls) controls.remove();
const error = document.getElementById('tmpl-edit-error');
if (error) error.remove();
currentEdit = null;
originalHTML = null;
originalSource = null;
}
})();
</script>
`
// ============================================================================
// TEMPLATE SUBCOMMAND
// ============================================================================
func templateCommand(args []string) error {
if len(args) < 1 {
printTemplateUsage()
return fmt.Errorf("expected subcommand (edit, list, new)")
}
subcmd := args[0]
subargs := args[1:]
switch subcmd {
case "edit":
return templateEdit(subargs)
case "list":
return templateList(subargs)
case "new":
return templateNew(subargs)
case "-h", "--help":
printTemplateUsage()
return nil
default:
printTemplateUsage()
return fmt.Errorf("unknown template subcommand: %s", subcmd)
}
}
func printTemplateUsage() {
fmt.Print(`Usage: sqlite-apps template <command> [OPTIONS] [ARGS]
Manage page templates in the database.
Commands:
edit <database.db> <path> Edit a template with $EDITOR
list <database.db> List all page templates
new <database.db> <path> Create a new empty template
Examples:
sqlite-apps template list mysite.db
sqlite-apps template new mysite.db /about
sqlite-apps template edit mysite.db /about
`)
}
func templateEdit(args []string) error {
if len(args) != 2 {
return fmt.Errorf("usage: sqlite-apps template edit <database.db> <path>")
}
dbPath := args[0]
pagePath := args[1]
db, err := sql.Open("sqlite", dbPath)
if err != nil {
return fmt.Errorf("failed to open database: %w", err)
}
defer db.Close()
// Migrate old schema if needed
if err := migratePages(db); err != nil {
return fmt.Errorf("failed to migrate __pages table: %w", err)
}
// Get current template content (latest version)
var content, contentType string
err = db.QueryRow("SELECT template, content_type FROM __pages WHERE path = ? ORDER BY created_at DESC LIMIT 1", pagePath).Scan(&content, &contentType)
if err == sql.ErrNoRows {
return fmt.Errorf("page '%s' not found (use 'template new' to create)", pagePath)
}
if err != nil {
return fmt.Errorf("failed to read template: %w", err)
}
// Write to temp file
tmpFile, err := os.CreateTemp("", "sqlite-apps-template-*.html")
if err != nil {
return fmt.Errorf("failed to create temp file: %w", err)
}
tmpPath := tmpFile.Name()
defer os.Remove(tmpPath)
if _, err := tmpFile.WriteString(content); err != nil {
tmpFile.Close()
return fmt.Errorf("failed to write temp file: %w", err)
}
tmpFile.Close()
// Open in editor
editor := os.Getenv("EDITOR")
if editor == "" {
editor = "vi"
}
cmd := exec.Command(editor, tmpPath)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return fmt.Errorf("editor failed: %w", err)
}
// Read edited content
newContent, err := os.ReadFile(tmpPath)
if err != nil {
return fmt.Errorf("failed to read edited file: %w", err)
}
// Skip if content unchanged
if string(newContent) == content {
fmt.Printf("No changes to '%s'\n", pagePath)
return nil
}
// Insert new version (preserving content_type from previous version)
_, err = db.Exec("INSERT INTO __pages (path, template, content_type) VALUES (?, ?, ?)", pagePath, string(newContent), contentType)
if err != nil {
return fmt.Errorf("failed to save template: %w", err)
}
fmt.Printf("Saved new version of '%s'\n", pagePath)
return nil
}
func templateList(args []string) error {
if len(args) != 1 {
return fmt.Errorf("usage: sqlite-apps template list <database.db>")
}
dbPath := args[0]
db, err := sql.Open("sqlite", dbPath)
if err != nil {
return fmt.Errorf("failed to open database: %w", err)
}
defer db.Close()
// Migrate old schema if needed
if err := migratePages(db); err != nil {
return fmt.Errorf("failed to migrate __pages table: %w", err)
}
// Get latest version of each page with version count
rows, err := db.Query(`
SELECT
p.path,
p.content_type,
length(p.template) as size,
p.created_at,
(SELECT COUNT(*) FROM __pages WHERE path = p.path) as versions
FROM __pages p
WHERE p.created_at = (
SELECT MAX(created_at) FROM __pages WHERE path = p.path
)
ORDER BY p.path
`)
if err != nil {
return fmt.Errorf("failed to list pages: %w", err)
}
defer rows.Close()
fmt.Println("Pages:")
count := 0
for rows.Next() {
var path, contentType, createdAt string
var size, versions int
rows.Scan(&path, &contentType, &size, &createdAt, &versions)
fmt.Printf(" %s (%s, %d bytes, %d versions, latest: %s)\n", path, contentType, size, versions, createdAt)
count++
}
if count == 0 {
fmt.Println(" (no pages)")
}
return nil
}
func templateNew(args []string) error {
if len(args) != 2 {
return fmt.Errorf("usage: sqlite-apps template new <database.db> <path>")
}
dbPath := args[0]
pagePath := args[1]
db, err := sql.Open("sqlite", dbPath)
if err != nil {
return fmt.Errorf("failed to open database: %w", err)
}
defer db.Close()
// Migrate old schema if needed, then ensure table exists
if err := migratePages(db); err != nil {
return fmt.Errorf("failed to migrate __pages table: %w", err)
}
// Check if page already exists (any version)
var exists int
db.QueryRow("SELECT 1 FROM __pages WHERE path = ? LIMIT 1", pagePath).Scan(&exists)
if exists == 1 {
return fmt.Errorf("page '%s' already exists", pagePath)
}
// Create default template
defaultTemplate := fmt.Sprintf(`<!DOCTYPE html>
<html>
<head>
<title>%s</title>
</head>
<body>
<h1>%s</h1>
<p>Edit this template with: sqlite-apps template edit %s %s</p>
</body>
</html>
`, pagePath, pagePath, dbPath, pagePath)
_, err = db.Exec("INSERT INTO __pages (path, template) VALUES (?, ?)", pagePath, defaultTemplate)
if err != nil {
return fmt.Errorf("failed to create page: %w", err)
}
fmt.Printf("Created page '%s'\n", pagePath)
fmt.Printf("Edit with: sqlite-apps template edit %s %s\n", dbPath, pagePath)
return nil
}
// ============================================================================
// AUTH SUBCOMMAND
// ============================================================================
func authCommand(args []string) error {
if len(args) < 1 {
printAuthUsage()
return fmt.Errorf("expected subcommand (add, list, remove)")
}
subcmd := args[0]
subargs := args[1:]
switch subcmd {
case "add":
return authAdd(subargs)
case "list":
return authList(subargs)
case "remove":
return authRemove(subargs)
case "-h", "--help":
printAuthUsage()
return nil
default:
printAuthUsage()
return fmt.Errorf("unknown auth subcommand: %s", subcmd)
}
}
func printAuthUsage() {
fmt.Print(`Usage: sqlite-apps auth <command> [OPTIONS] [ARGS]
Manage authorized keys for edit mode authentication.
Commands:
add <database.db> <name> <public-key-json> Add an authorized public key
list <database.db> List authorized keys
remove <database.db> <name> Remove an authorized key
Examples:
sqlite-apps auth list mysite.db
sqlite-apps auth add mysite.db "alice" '{"kty":"EC","crv":"P-256","x":"...","y":"..."}'
sqlite-apps auth remove mysite.db "alice"
`)
}
func authAdd(args []string) error {
if len(args) != 3 {
return fmt.Errorf("usage: sqlite-apps auth add <database.db> <name> <public-key-json>")
}
dbPath := args[0]
name := args[1]
publicKeyJSON := args[2]
// Validate JSON
var pubKey map[string]any
if err := json.Unmarshal([]byte(publicKeyJSON), &pubKey); err != nil {
return fmt.Errorf("invalid JSON: %w", err)
}
// Check required JWK fields for EC key
if pubKey["kty"] != "EC" {
return fmt.Errorf("key type must be EC (got %v)", pubKey["kty"])
}
if pubKey["crv"] != "P-256" {
return fmt.Errorf("curve must be P-256 (got %v)", pubKey["crv"])
}
if _, ok := pubKey["x"].(string); !ok {
return fmt.Errorf("missing or invalid 'x' coordinate")
}
if _, ok := pubKey["y"].(string); !ok {
return fmt.Errorf("missing or invalid 'y' coordinate")
}
db, err := sql.Open("sqlite", dbPath)
if err != nil {
return fmt.Errorf("failed to open database: %w", err)
}
defer db.Close()
// Ensure auth tables exist
if err := migrateAuth(db); err != nil {
return fmt.Errorf("failed to create auth tables: %w", err)
}
// Insert key
_, err = db.Exec("INSERT INTO __authorized_keys (public_key, name) VALUES (?, ?)", publicKeyJSON, name)
if err != nil {
return fmt.Errorf("failed to add key: %w", err)
}
fmt.Printf("Added authorized key '%s'\n", name)
return nil
}
func authList(args []string) error {
if len(args) != 1 {
return fmt.Errorf("usage: sqlite-apps auth list <database.db>")
}
dbPath := args[0]
db, err := sql.Open("sqlite", dbPath)
if err != nil {
return fmt.Errorf("failed to open database: %w", err)
}
defer db.Close()
// Ensure auth tables exist
if err := migrateAuth(db); err != nil {
return fmt.Errorf("failed to create auth tables: %w", err)
}
rows, err := db.Query("SELECT name, created_at FROM __authorized_keys ORDER BY created_at")
if err != nil {
return fmt.Errorf("failed to list keys: %w", err)
}
defer rows.Close()
fmt.Println("Authorized keys:")
count := 0
for rows.Next() {
var name, createdAt string
rows.Scan(&name, &createdAt)
fmt.Printf(" %s (added: %s)\n", name, createdAt)
count++
}
if count == 0 {
fmt.Println(" (no keys)")
}
return nil
}
func authRemove(args []string) error {
if len(args) != 2 {
return fmt.Errorf("usage: sqlite-apps auth remove <database.db> <name>")
}
dbPath := args[0]
name := args[1]
db, err := sql.Open("sqlite", dbPath)
if err != nil {
return fmt.Errorf("failed to open database: %w", err)
}
defer db.Close()
// Ensure auth tables exist
if err := migrateAuth(db); err != nil {
return fmt.Errorf("failed to create auth tables: %w", err)
}
result, err := db.Exec("DELETE FROM __authorized_keys WHERE name = ?", name)
if err != nil {
return fmt.Errorf("failed to remove key: %w", err)
}
affected, _ := result.RowsAffected()
if affected == 0 {
return fmt.Errorf("key '%s' not found", name)
}
fmt.Printf("Removed authorized key '%s'\n", name)
return nil
}
// ============================================================================
// DATABASE MIGRATION
// ============================================================================
// migratePages ensures __pages table has the versioned schema
// If the old schema (path as PRIMARY KEY) exists, it migrates data to new schema
func migratePages(db *sql.DB) error {
// Check if __pages table exists
var tableName string
err := db.QueryRow("SELECT name FROM sqlite_master WHERE type='table' AND name='__pages'").Scan(&tableName)
if err == sql.ErrNoRows {
// Table doesn't exist, create it fresh
_, err = db.Exec(`
CREATE TABLE __pages (
path TEXT NOT NULL,
template TEXT NOT NULL,
content_type TEXT DEFAULT 'text/html',
created_at TEXT NOT NULL DEFAULT (datetime('now')),
PRIMARY KEY (path, created_at)
);
CREATE INDEX __pages_path_latest ON __pages (path, created_at DESC);
`)
return err
}
if err != nil {
return err
}
// Table exists, check if it has created_at column (new schema)
var hasCreatedAt bool
rows, err := db.Query("PRAGMA table_info(__pages)")
if err != nil {
return err
}
defer rows.Close()
for rows.Next() {
var cid int
var name, colType string
var notNull, pk int
var dfltValue any
if err := rows.Scan(&cid, &name, &colType, ¬Null, &dfltValue, &pk); err != nil {
return err
}
if name == "created_at" {
hasCreatedAt = true
break
}
}
if hasCreatedAt {
// Already migrated, just ensure index exists
_, err = db.Exec("CREATE INDEX IF NOT EXISTS __pages_path_latest ON __pages (path, created_at DESC)")
return err
}
// Need to migrate: old schema has path as PRIMARY KEY
fmt.Println("Migrating __pages table to versioned schema...")
_, err = db.Exec(`
-- Create new table with versioned schema
CREATE TABLE __pages_new (
path TEXT NOT NULL,
template TEXT NOT NULL,
content_type TEXT DEFAULT 'text/html',
created_at TEXT NOT NULL DEFAULT (datetime('now')),
PRIMARY KEY (path, created_at)
);
-- Copy existing data with current timestamp
INSERT INTO __pages_new (path, template, content_type, created_at)
SELECT path, template, content_type, datetime('now')
FROM __pages;
-- Drop old table and rename new one
DROP TABLE __pages;
ALTER TABLE __pages_new RENAME TO __pages;
-- Create index
CREATE INDEX __pages_path_latest ON __pages (path, created_at DESC);
`)
if err != nil {
return err
}
fmt.Println("Migration complete.")
return nil
}
// migrateAuth ensures __authorized_keys and __auth_sessions tables exist
func migrateAuth(db *sql.DB) error {
_, err := db.Exec(`
CREATE TABLE IF NOT EXISTS __authorized_keys (
public_key TEXT PRIMARY KEY,
name TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS __auth_sessions (
session_id TEXT PRIMARY KEY,
challenge TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
authenticated INTEGER DEFAULT 0,
key_name TEXT
);
CREATE TABLE IF NOT EXISTS __auth_delegations (
pin TEXT PRIMARY KEY,
session_id TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
expires_at TEXT NOT NULL,
verification_code TEXT,
public_key_json TEXT,
device_name TEXT,
status TEXT NOT NULL DEFAULT 'pending'
);
`)
if err != nil {
return err
}
// Add key_name column if it doesn't exist (for existing databases)
_, _ = db.Exec(`ALTER TABLE __auth_sessions ADD COLUMN key_name TEXT`)
// Add new delegation columns if they don't exist (for existing databases)
_, _ = db.Exec(`ALTER TABLE __auth_delegations ADD COLUMN verification_code TEXT`)
_, _ = db.Exec(`ALTER TABLE __auth_delegations ADD COLUMN public_key_json TEXT`)
_, _ = db.Exec(`ALTER TABLE __auth_delegations ADD COLUMN device_name TEXT`)
_, _ = db.Exec(`ALTER TABLE __auth_delegations ADD COLUMN status TEXT NOT NULL DEFAULT 'pending'`)
return nil
}
// verifySignature verifies an ECDSA P-256 signature
func verifySignature(publicKeyJWK map[string]any, challenge string, signatureB64 string) bool {
// Extract x and y coordinates from JWK
xB64, ok := publicKeyJWK["x"].(string)
if !ok {
return false
}
yB64, ok := publicKeyJWK["y"].(string)
if !ok {
return false
}
// Decode base64url
xBytes, err := base64.RawURLEncoding.DecodeString(xB64)
if err != nil {
return false
}
yBytes, err := base64.RawURLEncoding.DecodeString(yB64)
if err != nil {
return false
}
// Reconstruct public key
x := new(big.Int).SetBytes(xBytes)
y := new(big.Int).SetBytes(yBytes)
pubKey := &ecdsa.PublicKey{
Curve: elliptic.P256(),
X: x,
Y: y,
}
// Decode signature (r || s, each 32 bytes for P-256)
sigBytes, err := base64.RawURLEncoding.DecodeString(signatureB64)
if err != nil {
return false
}
if len(sigBytes) != 64 {
return false
}
r := new(big.Int).SetBytes(sigBytes[:32])
s := new(big.Int).SetBytes(sigBytes[32:])
// Hash the challenge
hash := sha256.Sum256([]byte(challenge))
// Verify
return ecdsa.Verify(pubKey, hash[:], r, s)
}
// generateChallenge creates a random challenge string
func generateChallenge() string {
b := make([]byte, 32)
rand.Read(b)
return base64.RawURLEncoding.EncodeToString(b)
}
// isAuthenticated checks if the current request has a valid authenticated session
func isAuthenticated(db *sql.DB, r *http.Request) bool {
cookie, err := r.Cookie("__auth_session")
if err != nil {
return false
}
var authenticated int
err = db.QueryRow("SELECT authenticated FROM __auth_sessions WHERE session_id = ?", cookie.Value).Scan(&authenticated)
if err != nil || authenticated == 0 {
return false
}
return true
}
// ============================================================================
// UTILITY FUNCTIONS
// ============================================================================
func runCommandOutput(name string, args ...string) (string, error) {
cmd := exec.Command(name, args...)
// Capture stdout and stderr separately - nix-build outputs build logs to stderr
// but the actual result (store path) goes to stdout
var stdout, stderr strings.Builder
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
if err != nil {
return "", fmt.Errorf("command failed: %s: %w\nstderr: %s", name, err, stderr.String())
}
return stdout.String(), nil
}
func runCommandSilent(name string, args ...string) error {
cmd := exec.Command(name, args...)
if err := cmd.Run(); err != nil {
return fmt.Errorf("command failed: %s: %w", name, err)
}
return nil
}
func checkRequiredTools(tools []string) error {
for _, tool := range tools {
if _, err := exec.LookPath(tool); err != nil {
return fmt.Errorf("required tool '%s' not found in PATH", tool)
}
}
return nil
}
func cleanupTempDir(tempDir string) {
// First make everything writable (nix store copies have restrictive permissions)
_ = runCommandSilent("chmod", "-R", "u+w", tempDir)
if err := runCommandSilent("rm", "-rf", tempDir); err != nil {
fmt.Printf("Warning: Failed to remove temporary directory %s: %v\n", tempDir, err)
}
}
|