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
// Package pdfjs keeps a copy of Mozilla's pdf.js viewer in an application's
// SQLite database and serves it, so that a PDF can be read in a sandboxed frame
// instead of being downloaded.
//
// It was written for mailweb and moved here when campusweb needed the same
// thing; the reasoning below is mailweb's and holds for both. Each application
// keeps the two tables in its own database (Schema is its migration), calls Sync
// once at startup, mounts Handler at /static/pdfjs/, and serves the document
// itself through ServePDF.
//
// mailweb does not read PDFs. That line is drawn in mailweb(7): iCalendar gets
// a parser because it is a line-based text format whose reader is a couple of
// hundred lines, and PDF does not, because its reader is a JIT-compiling engine
// for a container with fonts, an imaging model and its own scripting language.
// Nothing here parses a PDF either — what this package does is keep a copy of
// somebody else's engine and serve it to the browser, which then does the
// reading in a frame.
package pdfjs

// The vendored PDF viewer.
//
// The reason it is vendored rather than delegated to the browser's own viewer
// is measured and unpleasant: Chromium refuses to instantiate its built-in PDF
// viewer inside *any* sandboxed iframe. The bytes arrive with a 200 and the
// load then fails with ERR_BLOCKED_BY_CLIENT. Adding allow-same-origin does not
// help — a frame with both flags fails identically — because what blocks it is
// the HTML specification's sandboxed plugins browsing context flag, for which
// no allow- keyword exists. Any sandbox attribute at all is enough. Firefox is
// unaffected, since its viewer is pdf.js and pdf.js is ordinary web content.
//
// So mailweb ships the thing Firefox already has, which is what makes the frame
// work in both. pdf.js is ordinary JavaScript and never engages that flag.
//
// What this costs is written down rather than left implicit: it is ~4.7MB of
// third-party JavaScript, fetched over the network without a human looking at
// it, executing in an origin that has no authentication and no CSRF protection
// and that holds the whole mirrored archive. A bad release is not a rendering
// bug, it is script that can read the mail and POST /send. See "CAVEATS" in
// mailweb(1).

import (
	"archive/zip"
	"bytes"
	"database/sql"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"mime"
	"net"
	"net/http"
	"net/url"
	"path"
	"regexp"
	"strconv"
	"strings"
	"time"
)

const (
	// pdfjsReleaseAPI names the release to track. The GitHub release is the
	// only place the *viewer* exists: the npm package (pdfjs-dist, which is
	// what jsDelivr, unpkg and cdnjs serve) ships the library and a component
	// toolkit, but no viewer.html, viewer.mjs or viewer.css.
	pdfjsReleaseAPI = "https://api.github.com/repos/mozilla/pdf.js/releases/latest"

	// pdfjsZipURL is the dist asset of a given release. The "legacy" build
	// beside it targets older browsers and is not used.
	pdfjsZipURL = "https://github.com/mozilla/pdf.js/releases/download/v%s/pdfjs-%s-dist.zip"

	// maxPdfjsZip bounds the download. The dist zip is about 6MB; the cap is
	// there so a wrong URL or a hostile redirect cannot stream indefinitely
	// into memory.
	maxPdfjsZip = 32 << 20

	// maxPdfjsAsset bounds a single decompressed entry, which is the guard
	// against a zip bomb: the largest file actually taken is pdf.worker.mjs at
	// about 2.1MB.
	maxPdfjsAsset = 16 << 20

	pdfjsHTTPTimeout = 60 * time.Second
)

// pdfjsWanted is the subset of the dist zip that is kept.
//
// The full archive is 410 files and 19.8MB. Most of that is locale/ (114 files,
// 2.7MB) and cmaps/ (169 files, 1.1MB): the cmaps are character maps for CJK
// encodings no mail in this archive uses, and the locales are 113 translations
// of a viewer nobody here is reading in another language.
//
// Two of those locale files are kept regardless. The viewer fetches
// locale.json at startup no matter which language it ends up in, so dropping
// the directory wholesale bought 2.7MB and a 404 in the console on every PDF;
// keeping the index and the English strings costs 36KB and the rest fall back
// to what is compiled into viewer.mjs. This is the second time a file was cut
// for its directory's size rather than its own — web/images went the same way,
// 80KB of toolbar icons that viewer.css names one by one.
//
// standard_fonts/ is kept even though it is 779KB, because it is what renders a
// PDF that does not embed its fonts — which scanned invoices, the single most
// common PDF here, frequently do not. Dropping it would show blank or
// substituted glyphs on exactly the documents worth reading.
var pdfjsWanted = []string{
	"build/pdf.mjs",
	"build/pdf.worker.mjs",
	"web/viewer.mjs",
	"web/viewer.css",
	"web/viewer.html",
	// The viewer fetches this index at startup whatever locale it settles on,
	// and a 404 here is an error in the console on every PDF opened. It is
	// 2.5KB and maps each language tag to its .ftl file; only the English one
	// is actually stored, and the rest resolve to the strings already compiled
	// into viewer.mjs.
	"web/locale/locale.json",
	"web/locale/en-US/viewer.ftl",
}

// pdfjsWantedPrefixes are kept wholesale rather than named file by file, since
// their contents change between releases.
//
// web/images/ is only 80KB and is every icon in the toolbar. Leaving it out was
// a real bug rather than a saving: the viewer rendered, then filled the console
// with 404s for toolbarButton-pageUp.svg and its neighbours, because the
// stylesheet references them by name.
var pdfjsWantedPrefixes = []string{
	"web/standard_fonts/",
	"web/images/",
	// The JBIG2 and OpenJPEG decoders, 1.5MB. They are what decode the image
	// formats a scanner emits, and a scanned invoice is the most common PDF in
	// this archive, so leaving them out would fail on exactly the documents the
	// frame exists for.
	"web/wasm/",
}

// pdfjsWantedPrefix reports whether a path is inside one of them.
func pdfjsWantedPrefix(name string) bool {
	for _, p := range pdfjsWantedPrefixes {
		if strings.HasPrefix(name, p) {
			return true
		}
	}
	return false
}

// pdfjsAsset is one file of the viewer, as stored.
type pdfjsAsset struct {
	Path     string
	MimeType string
	Content  []byte
}

// pdfjsMime maps an asset to the type it must be served as.
//
// The .mjs case is the one that matters: an ES module served as anything but a
// JavaScript type is refused by the browser outright, and since the response
// also carries nosniff there is no guessing to fall back on. The rest are
// ordinary.
func pdfjsMime(p string) string {
	switch {
	case strings.HasSuffix(p, ".mjs"), strings.HasSuffix(p, ".js"):
		return "text/javascript; charset=utf-8"
	case strings.HasSuffix(p, ".css"):
		return "text/css; charset=utf-8"
	case strings.HasSuffix(p, ".html"):
		return "text/html; charset=utf-8"
	case strings.HasSuffix(p, ".pfb"):
		return "application/x-font-type1"
	case strings.HasSuffix(p, ".ttf"):
		return "font/ttf"
	case strings.HasSuffix(p, ".bcmap"):
		return "application/octet-stream"
	case strings.HasSuffix(p, ".svg"):
		return "image/svg+xml"
	case strings.HasSuffix(p, ".png"):
		return "image/png"
	case strings.HasSuffix(p, ".json"):
		return "application/json"
	default:
		return "application/octet-stream"
	}
}

// pdfjsHead reports the live generation and the release it came from.
//
// A database with no viewer yet answers ok=false rather than an error: that is
// the state of every mailweb before the first update runs, and it is normal
// rather than exceptional.
func pdfjsHead(db *sql.DB) (gen int64, version string, ok bool) {
	err := db.QueryRow(
		`SELECT generation, version FROM pdfjs_head WHERE id = 1`,
	).Scan(&gen, &version)
	if err == sql.ErrNoRows {
		return 0, "", false
	}
	if err != nil {
		log.Printf("pdfjs: read head: %v", err)
		return 0, "", false
	}
	return gen, version, true
}

// pdfjsLatestVersion asks GitHub which release is current, returning it without
// the leading "v".
func pdfjsLatestVersion(client *http.Client) (string, error) {
	req, err := http.NewRequest("GET", pdfjsReleaseAPI, nil)
	if err != nil {
		return "", err
	}
	// GitHub serves the v3 media type by default but asks that it be named.
	req.Header.Set("Accept", "application/vnd.github+json")
	resp, err := client.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return "", fmt.Errorf("release API: %s", resp.Status)
	}
	var rel struct {
		TagName string `json:"tag_name"`
	}
	if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&rel); err != nil {
		return "", fmt.Errorf("decode release: %w", err)
	}
	v := strings.TrimPrefix(strings.TrimSpace(rel.TagName), "v")
	if v == "" {
		return "", fmt.Errorf("release API returned no tag")
	}
	return v, nil
}

// pdfjsDownload fetches the dist zip for a version and returns the files worth
// keeping.
func pdfjsDownload(client *http.Client, version string) ([]pdfjsAsset, error) {
	url := fmt.Sprintf(pdfjsZipURL, version, version)
	resp, err := client.Get(url)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("download %s: %s", url, resp.Status)
	}

	// A zip is read by its central directory, at the end, so it cannot be
	// streamed: the whole archive is buffered, bounded by maxPdfjsZip.
	raw, err := io.ReadAll(io.LimitReader(resp.Body, maxPdfjsZip+1))
	if err != nil {
		return nil, fmt.Errorf("read zip: %w", err)
	}
	if len(raw) > maxPdfjsZip {
		return nil, fmt.Errorf("zip larger than %d bytes", maxPdfjsZip)
	}
	return pdfjsExtract(raw)
}

// pdfjsPathIsSuspicious reports whether a zip entry names a path outside the
// archive's own tree.
//
// An entry names its own path, the archive is fetched over the network, and
// nobody looks at it in between, so the name is checked rather than trusted.
// path.Clean resolves any "..", and a name that does not survive it unchanged,
// or that is absolute, is refused.
//
// A function rather than three conditions inline, because a guard that cannot
// be called from a test is a guard whose deletion no test notices — which was
// true of this one until it was pulled out here.
func pdfjsPathIsSuspicious(name string) bool {
	return name != path.Clean(name) ||
		strings.HasPrefix(name, "/") ||
		strings.HasPrefix(name, "../")
}

// pdfjsExtract picks the wanted files out of a dist zip.
//
// Split from the download so the awkward half — which entries are taken, and
// which are refused — can be tested without a network.
func pdfjsExtract(raw []byte) ([]pdfjsAsset, error) {
	zr, err := zip.NewReader(bytes.NewReader(raw), int64(len(raw)))
	if err != nil {
		return nil, fmt.Errorf("open zip: %w", err)
	}

	want := make(map[string]bool, len(pdfjsWanted))
	for _, p := range pdfjsWanted {
		want[p] = true
	}

	var out []pdfjsAsset
	for _, f := range zr.File {
		if f.FileInfo().IsDir() {
			continue
		}
		// An entry names its own path and the archive is not ours, so the name
		// is normalised and checked rather than trusted. path.Clean resolves
		// any "..", and a name that does not survive it unchanged, or that is
		// absolute, is refused: this is the zip-slip guard, and it matters
		// because these bytes are fetched over the network unattended.
		name := f.Name
		if pdfjsPathIsSuspicious(name) {
			log.Printf("pdfjs: refusing suspicious zip entry %q", name)
			continue
		}
		if !want[name] && !pdfjsWantedPrefix(name) {
			continue
		}
		if f.UncompressedSize64 > maxPdfjsAsset {
			return nil, fmt.Errorf("entry %q is %d bytes, over the cap", name, f.UncompressedSize64)
		}

		rc, err := f.Open()
		if err != nil {
			return nil, fmt.Errorf("open %q: %w", name, err)
		}
		content, err := io.ReadAll(io.LimitReader(rc, maxPdfjsAsset+1))
		rc.Close()
		if err != nil {
			return nil, fmt.Errorf("read %q: %w", name, err)
		}
		if len(content) > maxPdfjsAsset {
			return nil, fmt.Errorf("entry %q exceeded the cap while reading", name)
		}
		if name == "web/viewer.html" {
			content = pdfjsPatchViewerCSP(content)
			content = pdfjsInjectShim(content)
		}
		out = append(out, pdfjsAsset{Path: name, MimeType: pdfjsMime(name), Content: content})
	}

	// Every named file must be present. A release that reorganised the archive
	// would otherwise be ingested as a viewer missing its worker, which fails
	// at render time in the browser rather than here, where it can be reported.
	// The shims are not in the release; they are ours, and stored beside it so
	// that viewer.html can load them from its own directory.
	out = append(out, pdfjsShims()...)

	got := make(map[string]bool, len(out))
	for _, a := range out {
		got[a.Path] = true
	}
	for _, p := range pdfjsWanted {
		if !got[p] {
			return nil, fmt.Errorf("release is missing %q", p)
		}
	}
	return out, nil
}

// pdfjsCSPOrigin is the policy viewer.html is given in place of its own.
//
// Every 'self' in the shipped policy becomes the store path's origin — which is
// "null", because the frame withholds allow-same-origin — and a source
// expression can never match a null origin. The viewer therefore refuses to
// load its own stylesheet, its own module and, most visibly, its worker.
//
// The sources are named explicitly rather than opened up to '*'. What changes
// against upstream is 'self' becoming loopback — both spellings of it, because
// a source expression is matched against the host as written in the URL, and
// http://127.0.0.1:* does not match a page opened as http://localhost:8780.
// That is what happened the first time the viewer was opened by hand rather
// than by a test: every script, the stylesheet and the worker were refused, and
// the console named 127.0.0.1 as the only allowed source. ::1 would be the
// third spelling, and cannot be written: CSP's host grammar has no IPv6
// literals, and Chromium reports http://[::1]:* as an invalid source and
// ignores it. A viewer opened as http://[::1]:… is therefore refused.
// Loopback is what is stored; the host a viewer is actually requested at is
// added when it is served, since an application can also sit behind a proxy
// on a real name (see servedFrom).
// default-src 'none',
// base-uri 'none' and form-action 'none' are kept exactly as they are, so the
// document still cannot navigate itself anywhere or submit anything.
const loopback = `http://127.0.0.1:* http://localhost:*`

const pdfjsCSPOrigin = `default-src 'none'; ` +
	`script-src ` + loopback + ` blob: 'wasm-unsafe-eval'; ` +
	`worker-src ` + loopback + ` blob:; ` +
	`style-src ` + loopback + ` 'unsafe-inline'; ` +
	`img-src ` + loopback + ` blob: data:; ` +
	`media-src blob:; ` +
	`font-src ` + loopback + ` data:; ` +
	`connect-src * blob: data:; ` +
	`base-uri 'none'; form-action 'none';`

// pdfjsPatchViewerCSP replaces the policy in the shipped viewer.html.
//
// Patching a vendored file is worth being uneasy about, so it is done as
// narrowly as possible: one attribute of one meta tag, matched on the header it
// declares, with the rest of the document untouched. If a future release
// renames or restructures that tag the patch stops matching, which is reported
// rather than passed over, since a viewer left with 'self' in an opaque origin
// does not render at all.
func pdfjsPatchViewerCSP(html []byte) []byte {
	m := pdfjsCSPRe.FindSubmatchIndex(html)
	if m == nil {
		log.Printf("pdfjs: viewer.html has no recognisable CSP meta tag; leaving it as shipped")
		return html
	}
	// Group 1 is the policy itself, between the content=" and its closing quote.
	var out []byte
	out = append(out, html[:m[2]]...)
	out = append(out, []byte(pdfjsCSPOrigin)...)
	out = append(out, html[m[3]:]...)
	return out
}

// ============================================================================
// The storage shim
// ============================================================================
//
// The viewer frame is an opaque origin, and an opaque origin has no
// localStorage: reading the property throws a SecurityError. pdf.js reads it
// while constructing the viewer's preferences — as a field initialiser, before
// anything else runs — and the exception aborts initialisation. What is left is
// a viewer that fetches and parses the document (the console says "PDF … (PDF.js
// …)") and then draws nothing: a toolbar, "of 0" pages, an empty grey pane.
//
// That was how the frame looked from the day it was added to mailweb, in
// Chromium and Firefox alike, and nothing noticed: every request answered 200
// and the parse succeeded, which is what the checks at the time looked at. It
// was found when campusweb framed its first PDF and a page was actually
// expected to appear.
//
// The fix that is not available is allow-same-origin, which would give the
// frame a localStorage and also the application's origin; see FrameSandbox.
// The fix taken is to give the frame a localStorage of its own: an in-memory
// one, defined on window before pdf.js loads. pdf.js only keeps preferences,
// view history and saved signatures there, and losing those when the frame is
// closed is the right behaviour for a viewer that is not supposed to remember
// anything across documents anyway.
//
// It is a separate file rather than an inline script because the viewer's
// policy allows no inline script, and loosening that to admit one is a worse
// trade than one more asset.

const shimPath = "web/storage-shim.js"

// patchLevel is appended to the release version that is stored, and names
// what this package does to a release on the way in. Raising it makes Sync
// fetch and ingest the current release again even though its version has not
// changed, which is how a fix to the patches reaches a viewer that is already
// stored: without it, every database that had 6.4.299 would keep the
// unpatched copy until Mozilla published the next release.
//
//	+p1  the storage shim
//	+p2  localhost in the viewer's CSP, beside 127.0.0.1
//	+p3  without [::1], which is not a valid CSP source
//	+p4  the save shim
//	+p5  dark pages
//	+p6  the focus shim
//	+p7  the position shim
const patchLevel = "+p7"

const shimJS = `// Added by the pdfjs package, not part of pdf.js. See pdfjs.go, "The storage
// shim": the sandboxed frame has no localStorage, and pdf.js aborts without one.
(function () {
  try { window.localStorage; return; } catch (e) {}
  var m = new Map();
  var store = {
    getItem: function (k) { return m.has(String(k)) ? m.get(String(k)) : null; },
    setItem: function (k, v) { m.set(String(k), String(v)); },
    removeItem: function (k) { m.delete(String(k)); },
    clear: function () { m.clear(); },
    key: function (i) { return Array.from(m.keys())[i] ?? null; },
    get length() { return m.size; },
  };
  Object.defineProperty(window, "localStorage", { value: store, configurable: true });
})();
`

// ============================================================================
// The save shim
// ============================================================================
//
// pdf.js can annotate — highlight, draw, write, stamp — and its own Save
// button writes the result into a downloaded copy. An application that wants
// to keep the annotated copy itself names a URL to POST it to, in the viewer's
// save= parameter (ViewerURLSaving), and this script does the rest: some time
// after the person last touched the document it asks pdf.js for the annotated
// bytes, exactly what the Save button would download, and POSTs them there.
//
// Without save= it does nothing, which is how mailweb, which keeps no
// annotations, gets the same viewer unchanged.
//
// Two things about it are less obvious than they look.
//
// What triggers a save is the person's input — pointer, key, drop, change —
// anywhere in the viewer, debounced, and a slow poll behind it. pdf.js has no
// event for "the annotations changed": its storage reports the first change
// after a save (onSetModified) and nothing after that, and moving or recolouring
// an annotation that is already in it reports nothing at all. Whether there is
// anything to save is then decided by the storage's own hash of its serialised
// contents, which is what pdf.js computes for its save anyway; an unchanged hash
// sends nothing.
//
// The POST is a simple request — no Content-Type, so no preflight — from an
// opaque origin, and so is indistinguishable from one any web page could send
// to a loopback port. That is the application's problem to solve, with a token
// in the URL it hands out (campusweb(7)); this script only refuses a save URL
// that is not a path on the server that served it.
//
// pdf.js's "leave this page?" prompt asks whenever its annotation storage is
// not empty, which after a save it still is; the shim narrows that to
// "not empty and not what was last saved", so the prompt means unsaved notes.
//
// The save is the whole document each time, not the changes: pdf.js saves the
// document it loaded plus everything in its storage, so a copy that is opened
// again and annotated further is saved as the old copy plus the new notes.

const saveShimPath = "web/save-shim.js"

const saveShimJS = `// Added by the pdfjs package, not part of pdf.js. See pdfjs.go, "The save
// shim": with ?save=/path, keep POSTing the annotated document there.
(function () {
  "use strict";
  var url = new URLSearchParams(location.search).get("save");
  if (!url || url.charAt(0) !== "/" || url.charAt(1) === "/" || url.charAt(1) === "\\") return;

  var DEBOUNCE = 1500, POLL = 15000;
  var saved = "", timer = null, busy = false, again = false, status = null;

  function show(text, title) {
    if (!status) {
      var bar = document.getElementById("toolbarViewerRight");
      if (!bar) return;
      status = document.createElement("span");
      status.id = "campuswebSaveStatus";
      status.style.cssText = "align-self:center;margin:0 .5em;font-size:12px;white-space:nowrap;opacity:.8";
      bar.insertBefore(status, bar.firstChild);
    }
    status.textContent = text;
    status.title = title || "";
  }

  function app() { return window.PDFViewerApplication; }

  function schedule() {
    clearTimeout(timer);
    timer = setTimeout(save, DEBOUNCE);
  }

  async function save() {
    var doc = app() && app().pdfDocument;
    if (!doc) return;
    if (busy) { again = true; return; }
    var hash = doc.annotationStorage.serializable.hash;
    if (hash === saved) return;
    busy = true;
    show("saving\u2026");
    try {
      var data = await doc.saveDocument();
      var r = await fetch(url, { method: "POST", body: new Blob([data]), credentials: "omit" });
      if (!r.ok) throw new Error(r.status + " " + (await r.text()).trim());
      saved = hash;
      show("notes saved", "saved " + new Date().toLocaleTimeString());
    } catch (e) {
      console.error("save-shim:", e);
      show("NOT SAVED", String(e && e.message || e));
    } finally {
      busy = false;
      if (again) { again = false; schedule(); }
    }
  }

  ["pointerup", "keyup", "input", "change", "drop", "paste"].forEach(function (t) {
    window.addEventListener(t, schedule, true);
  });
  setInterval(save, POLL);

  // pdf.js asks before the page is left, and marks the title, whenever its
  // storage holds anything — saved or not, since it does not know about this
  // save. Ask only about what is not saved yet.
  var hook = setInterval(function () {
    var a = app();
    if (!a || typeof a._hasChanges !== "function") return;
    clearInterval(hook);
    var orig = a._hasChanges;
    a._hasChanges = function () {
      var doc = this.pdfDocument;
      if (doc && saved && doc.annotationStorage.serializable.hash === saved) return false;
      return orig.call(this);
    };
  }, 200);
})();
`

// ============================================================================
// Dark pages
// ============================================================================
//
// pdf.js darkens its own toolbar and sidebar when the system prefers dark, but
// draws the pages as the document has them: a white sheet in a dark window,
// which at night is the brightest thing on the screen.
//
// pdf.js has one recolouring of its own, forcePageColors, made for high
// contrast: it replaces the colour of every text run and path with one
// foreground on one background. It does nothing to images, and the documents
// read here are often images: a scanned book or a scanned invoice is one
// picture per page, with no text to recolour. It also flattens every colour
// in a diagram to the foreground.
//
// So the pages are inverted instead, as a picture: invert(), then
// hue-rotate(180deg) to turn the hues back, so that red stays roughly red and
// only lightness flips. White paper becomes near-black, black print becomes
// light, and a scan's yellowed paper and grey speckle become a dark
// background with faint speckle, which is the point. invert(.9) rather than 1
// keeps the page a dark grey and the print a soft white, not pure black and
// pure white. Photographs come out as negatives; that is the price, and why
// this follows the system preference rather than being always on.
//
// The filter is on the whole page, not just its canvas, so that the layers on
// top — highlights, ink, free text the reader is adding — are inverted with
// it and stay readable against it: black ink drawn on an inverted canvas but
// left uninverted would be invisible. What is saved is untouched, since the
// save shim sends what pdf.js serialises, not what is on screen. Thumbnails
// are inverted to match.
//
// It is a stylesheet of its own, linked after viewer.css so it wins, for the
// same reason the shims are files: no inline anything in the viewer.

const darkCSSPath = "web/dark-pages.css"

const darkCSS = `/* Added by the pdfjs package, not part of pdf.js. See pdfjs.go, "Dark
   pages": in dark mode, invert the pages, keeping hues. */
@media (prefers-color-scheme: dark) {
  .pdfViewer .page,
  .thumbnailImageContainer > img {
    filter: invert(0.9) hue-rotate(180deg);
  }
}
`

// pdfjsViewerCSSRe matches the viewer's own stylesheet link.
var pdfjsViewerCSSRe = regexp.MustCompile(
	`(?i)<link\s+rel="stylesheet"\s+href="viewer\.css"\s*/?>`)

// pdfjsInjectDarkCSS links dark-pages.css directly after viewer.css, unless it
// is linked already. A viewer.html without that link is left alone and
// reported; the viewer then simply has white pages.
func pdfjsInjectDarkCSS(html []byte) []byte {
	if bytes.Contains(html, []byte(`href="dark-pages.css"`)) {
		return html
	}
	m := pdfjsViewerCSSRe.FindIndex(html)
	if m == nil {
		log.Printf("pdfjs: viewer.html does not link viewer.css; leaving pages undarkened")
		return html
	}
	var out []byte
	out = append(out, html[:m[1]]...)
	out = append(out, []byte("\n<link rel=\"stylesheet\" href=\"dark-pages.css\" />")...)
	out = append(out, html[m[1]:]...)
	return out
}

// ============================================================================
// The focus shim
// ============================================================================
//
// A viewer that fills the window should take the keyboard: space, the arrows
// and PageDown should scroll the document, not the page the frame sits in. The
// embedding page cannot do this itself, being script-free; it can only put
// autofocus on the frame, which focuses the frame's document as a whole — its
// body, which does not scroll. pdf.js scrolls #viewerContainer, and only moves
// focus there itself once a key it handles is pressed, so the first presses of
// space or the arrow keys go nowhere.
//
// So the shim focuses #viewerContainer as soon as it exists, unless something
// inside the viewer already has focus. Focusing an element in a frame that
// does not have focus is meant to only decide what is focused once the frame
// gets it; whether every browser holds to that for a page that embeds a viewer
// without autofocus (mailweb) is not measured.

const focusShimPath = "web/focus-shim.js"

const focusShimJS = `// Added by the pdfjs package, not part of pdf.js. See pdfjs.go, "The focus
// shim": give the keyboard to the scrolling container, not to <body>.
document.addEventListener("DOMContentLoaded", function () {
  var c = document.getElementById("viewerContainer");
  var a = document.activeElement;
  if (c && (!a || a === document.body)) c.focus({ preventScroll: true });
});
`

// ============================================================================
// The position shim
// ============================================================================
//
// pdf.js remembers where in a document the reader was – its "view history" –
// in localStorage, and opens there next time. In the frame that is the storage
// shim's in-memory map, gone with the tab, so every document opened at its
// first page; and a position kept in one browser would not reach the reader's
// other devices anyway.
//
// So an application that wants it kept names a URL in the viewer's pos=
// parameter (Viewer.Position), and this script POSTs the position there a
// second after scrolling stops, and once more when the frame is hidden or
// left, with keepalive so that the request outlives the page. The body is
// Position's text form, "page=3&top=512"; a string body goes as text/plain,
// which keeps the request simple, without a preflight, like the save shim's.
//
// The position is pdf.js's own: the page at the top of the viewport and how
// far down that page, in PDF units, which do not change with the zoom or the
// width of the window. The application hands it back in the fragment of the
// next frame address (Viewer.At), where pdf.js reads it as it reads #page=.
//
// Nothing is sent before pdf.js has set the initial view, which is when it
// starts reporting where the reader is rather than where it is still
// scrolling to, nor when the position is the one last sent.

const positionShimPath = "web/position-shim.js"

const positionShimJS = `// Added by the pdfjs package, not part of pdf.js. See pdfjs.go, "The
// position shim": with ?pos=/path, POST where the reader is in the document.
(function () {
  "use strict";
  var url = new URLSearchParams(location.search).get("pos");
  if (!url || url.charAt(0) !== "/" || url.charAt(1) === "/" || url.charAt(1) === "\\") return;

  var DEBOUNCE = 1000;
  var sent = "", now = "", timer = null;

  function send(keepalive) {
    clearTimeout(timer);
    timer = null;
    if (!now || now === sent) return;
    var body = now;
    fetch(url, { method: "POST", body: body, credentials: "omit", keepalive: !!keepalive })
      .then(function (r) {
        if (r.ok) sent = body;
        else console.error("position-shim:", r.status);
      }, function (e) { console.error("position-shim:", e); });
  }

  var hook = setInterval(function () {
    var a = window.PDFViewerApplication;
    if (!a || !a.initializedPromise) return;
    clearInterval(hook);
    a.initializedPromise.then(function () {
      a.eventBus.on("updateviewarea", function (e) {
        var l = e && e.location;
        if (!a.isInitialViewSet || !l || !(l.pageNumber >= 1)) return;
        now = "page=" + l.pageNumber + "&top=" + Math.round(l.top || 0);
        if (now === sent) return;
        clearTimeout(timer);
        timer = setTimeout(send, DEBOUNCE);
      });
    });
  }, 200);

  window.addEventListener("pagehide", function () { send(true); });
  document.addEventListener("visibilitychange", function () {
    if (document.visibilityState === "hidden") send(true);
  });
})();
`

// Position is where in a document the viewer is: the page at the top of the
// viewport, from 1, and how far down that page, in PDF units from the page's
// bottom edge, as pdf.js counts it. The zero Position is the start.
type Position struct {
	Page int
	Top  int
}

// String is the text form the position shim sends: "page=3&top=512".
func (p Position) String() string {
	return fmt.Sprintf("page=%d&top=%d", p.Page, p.Top)
}

// ParsePosition reads what the position shim sends. Anything else is refused,
// so that what is stored, and later written into a frame's address, is two
// numbers and nothing more.
func ParsePosition(s string) (Position, error) {
	q, err := url.ParseQuery(strings.TrimSpace(s))
	if err != nil || len(q) != 2 || len(q["page"]) != 1 || len(q["top"]) != 1 {
		return Position{}, fmt.Errorf("want page=<n>&top=<n>")
	}
	page, err := strconv.Atoi(q.Get("page"))
	if err != nil || page < 1 || page > 1_000_000 {
		return Position{}, fmt.Errorf("page must be a number from 1")
	}
	// A page is at most 14400 units high (PDF's own limit is 200 inches);
	// the bound only keeps nonsense out.
	top, err := strconv.Atoi(q.Get("top"))
	if err != nil || top < -100_000 || top > 100_000 {
		return Position{}, fmt.Errorf("top must be a number")
	}
	return Position{Page: page, Top: top}, nil
}

// pdfjsInjectShim loads the shims before anything of pdf.js. A classic script
// in <head> runs before the module scripts after it, which are deferred.
// Inserted after the CSP meta tag so the policy applies to it too. A release
// whose viewer.html has no such tag is left alone and reported, like the CSP
// patch.
//
// The storage shim must run before pdf.js; the save shim only registers
// listeners and looks pdf.js up when they fire, so where it goes does not
// matter, and it goes after the storage shim. The dark-pages stylesheet is
// linked here too, though it goes elsewhere: after viewer.css.
func pdfjsInjectShim(html []byte) []byte {
	html = pdfjsInjectScript(html, "position-shim.js")
	html = pdfjsInjectScript(html, "focus-shim.js")
	html = pdfjsInjectScript(html, "save-shim.js")
	html = pdfjsInjectScript(html, "storage-shim.js")
	return pdfjsInjectDarkCSS(html)
}

// pdfjsInjectScript puts <script src=name> directly after the CSP meta tag,
// unless it is there already.
func pdfjsInjectScript(html []byte, name string) []byte {
	if bytes.Contains(html, []byte(`src="`+name+`"`)) {
		return html
	}
	m := pdfjsCSPTagRe.FindIndex(html)
	if m == nil {
		log.Printf("pdfjs: viewer.html has no CSP meta tag to put %s after; leaving it as shipped", name)
		return html
	}
	tag := []byte("\n<script src=\"" + name + "\"></script>")
	var out []byte
	out = append(out, html[:m[1]]...)
	out = append(out, tag...)
	out = append(out, html[m[1]:]...)
	return out
}

// pdfjsShims are the files this package adds to a release.
func pdfjsShims() []pdfjsAsset {
	return []pdfjsAsset{
		{Path: shimPath, MimeType: pdfjsMime(shimPath), Content: []byte(shimJS)},
		{Path: saveShimPath, MimeType: pdfjsMime(saveShimPath), Content: []byte(saveShimJS)},
		{Path: darkCSSPath, MimeType: pdfjsMime(darkCSSPath), Content: []byte(darkCSS)},
		{Path: focusShimPath, MimeType: pdfjsMime(focusShimPath), Content: []byte(focusShimJS)},
		{Path: positionShimPath, MimeType: pdfjsMime(positionShimPath), Content: []byte(positionShimJS)},
	}
}

// isShim reports whether a stored path is one of pdfjsShims, which a repatch
// replaces rather than carries over.
func isShim(p string) bool {
	for _, a := range pdfjsShims() {
		if a.Path == p {
			return true
		}
	}
	return false
}

// pdfjsCSPTagRe matches the whole CSP meta tag, to the end of the element.
var pdfjsCSPTagRe = regexp.MustCompile(
	`(?is)<meta\s+http-equiv="Content-Security-Policy"\s+content="[^"]*"\s*/?>`)

// pdfjsCSPRe matches the content attribute of the viewer's CSP meta tag. It is
// anchored on http-equiv naming the policy so that no other meta tag can match,
// and (?s) lets the attributes span lines, which in the shipped file they do.
var pdfjsCSPRe = regexp.MustCompile(
	`(?is)<meta\s+http-equiv="Content-Security-Policy"\s+content="([^"]*)"`)

// pdfjsIngest writes a new generation and makes it live.
//
// The order is the whole point, and it is source-forge's: write generation N+1
// in full, then flip pdfjs_head to it, in one transaction. A reader during the
// write still resolves every asset through the old generation, so no request
// ever sees a half-written viewer.
//
// The generation before the new one is kept and only older ones are dropped. A
// page loaded moments before an update is still fetching viewer.mjs and
// pdf.worker.mjs by the URL it was served, and deleting those immediately would
// break the frame it was about to draw.
func pdfjsIngest(db *sql.DB, version string, assets []pdfjsAsset) (int64, error) {
	tx, err := db.Begin()
	if err != nil {
		return 0, fmt.Errorf("begin: %w", err)
	}
	defer tx.Rollback()

	var maxGen sql.NullInt64
	if err := tx.QueryRow(`SELECT MAX(generation) FROM pdfjs_asset`).Scan(&maxGen); err != nil {
		return 0, fmt.Errorf("max generation: %w", err)
	}
	gen := maxGen.Int64 + 1

	for _, a := range assets {
		if _, err := tx.Exec(
			`INSERT INTO pdfjs_asset (generation, path, mime_type, size, content)
			 VALUES (?, ?, ?, ?, ?)`,
			gen, a.Path, a.MimeType, len(a.Content), a.Content,
		); err != nil {
			return 0, fmt.Errorf("insert %q: %w", a.Path, err)
		}
	}

	if _, err := tx.Exec(
		`INSERT INTO pdfjs_head (id, generation, version, ingested) VALUES (1, ?, ?, ?)
		 ON CONFLICT(id) DO UPDATE SET
		   generation = excluded.generation,
		   version    = excluded.version,
		   ingested   = excluded.ingested`,
		gen, version, time.Now().Unix(),
	); err != nil {
		return 0, fmt.Errorf("flip head: %w", err)
	}

	if _, err := tx.Exec(`DELETE FROM pdfjs_asset WHERE generation < ?`, gen-1); err != nil {
		return 0, fmt.Errorf("gc old generations: %w", err)
	}

	if err := tx.Commit(); err != nil {
		return 0, fmt.Errorf("commit: %w", err)
	}
	return gen, nil
}

// pdfjsSync brings the stored viewer up to the current release, if it is not
// already.
//
// Every failure here is logged and swallowed. Reading mail must not depend on
// GitHub being reachable: without a viewer the PDF frame is simply not drawn
// and the attachment list still links to the file, which is where this feature
// started.
func pdfjsSync(db *sql.DB) {
	client := &http.Client{Timeout: pdfjsHTTPTimeout}

	_, have, _ := pdfjsHead(db)

	// A stored release whose only difference is an older patch level is
	// repatched from what is stored, without the network: a fix to the
	// patches must not wait for GitHub to answer, and the first time this
	// mattered it was answering 504.
	if have != "" && strings.SplitN(have, "+", 2)[0]+patchLevel != have {
		if err := pdfjsRepatch(db, have); err != nil {
			log.Printf("pdfjs: repatching %s failed: %v", have, err)
		} else {
			_, have, _ = pdfjsHead(db)
			log.Printf("pdfjs: repatched the stored release as %s", have)
		}
	}

	latest, err := pdfjsLatestVersion(client)
	if err != nil {
		if have != "" {
			log.Printf("pdfjs: cannot check for updates (%v); keeping %s", err, have)
		} else {
			log.Printf("pdfjs: cannot check for updates (%v); no viewer stored, PDFs will be linked and not framed", err)
		}
		return
	}
	want := latest + patchLevel
	if want == have {
		log.Printf("pdfjs: %s is current", have)
		return
	}

	log.Printf("pdfjs: fetching %s (have %q)", want, have)
	assets, err := pdfjsDownload(client, latest)
	if err != nil {
		log.Printf("pdfjs: download %s failed: %v", latest, err)
		return
	}

	var total int
	for _, a := range assets {
		total += len(a.Content)
	}
	gen, err := pdfjsIngest(db, want, assets)
	if err != nil {
		log.Printf("pdfjs: ingest %s failed: %v", want, err)
		return
	}
	log.Printf("pdfjs: ingested %s as generation %d (%d files, %d bytes)",
		want, gen, len(assets), total)
}

// pdfjsRepatch writes the live generation again as a new one, with the
// current patches applied to it, under the current patch level.
//
// What is stored is the patched viewer.html, not the shipped one, so the patch
// is redone on a file that already carries an older version of it. Both
// patches are written for that: the CSP patch replaces the policy whatever it
// says, and the shim is only inserted when it is not there yet.
func pdfjsRepatch(db *sql.DB, have string) error {
	gen, _, ok := pdfjsHead(db)
	if !ok {
		return fmt.Errorf("no live generation")
	}
	rows, err := db.Query(`SELECT path, mime_type, content FROM pdfjs_asset WHERE generation = ?`, gen)
	if err != nil {
		return err
	}
	var assets []pdfjsAsset
	for rows.Next() {
		var a pdfjsAsset
		if err := rows.Scan(&a.Path, &a.MimeType, &a.Content); err != nil {
			rows.Close()
			return err
		}
		if a.Path == "web/viewer.html" {
			a.Content = pdfjsInjectShim(pdfjsPatchViewerCSP(a.Content))
		}
		if isShim(a.Path) {
			continue
		}
		assets = append(assets, a)
	}
	rows.Close()
	if err := rows.Err(); err != nil {
		return err
	}
	assets = append(assets, pdfjsShims()...)
	_, err = pdfjsIngest(db, strings.SplitN(have, "+", 2)[0]+patchLevel, assets)
	return err
}

// loadPdfjsAsset returns one file of the live viewer.
//
// The generation is returned alongside because it is what the ETag is built
// from: it is monotonic and a new one is written for every release, so it
// identifies the bytes exactly without hashing them on each request.
func loadPdfjsAsset(db *sql.DB, p string) (asset pdfjsAsset, gen int64, err error) {
	gen, _, ok := pdfjsHead(db)
	if !ok {
		return pdfjsAsset{}, 0, sql.ErrNoRows
	}
	err = db.QueryRow(
		`SELECT path, mime_type, content FROM pdfjs_asset
		  WHERE generation = ? AND path = ?`, gen, p,
	).Scan(&asset.Path, &asset.MimeType, &asset.Content)
	if err != nil {
		return pdfjsAsset{}, gen, err
	}
	return asset, gen, nil
}

// pdfjsAvailable reports whether a viewer is stored, which is what decides
// whether a view offers to frame a PDF at all.
func pdfjsAvailable(db *sql.DB) bool {
	_, _, ok := pdfjsHead(db)
	return ok
}

// etagMatch reports whether an ETag satisfies an If-None-Match header, which is
// either "*" or a comma-separated list of possibly-weak entity tags. The "W/"
// prefix is ignored for the comparison, which is what a conditional GET wants.
//
// The same function exists in source-forge, for the same reason and with the
// same semantics.
func etagMatch(ifNoneMatch, etag string) bool {
	strip := func(s string) string { return strings.TrimPrefix(strings.TrimSpace(s), "W/") }
	want := strip(etag)
	for _, part := range strings.Split(ifNoneMatch, ",") {
		got := strip(part)
		if got == "*" || got == want {
			return true
		}
	}
	return false
}

// ============================================================================
// The interface applications use
// ============================================================================

// Schema creates the two tables, for an application's migration list. It is
// mailweb's migration 12 verbatim, so a database made by mailweb before this
// package existed already has exactly these tables.
//
// Generations exist so an update is atomic. A new release is written in full
// under generation N+1 while readers still see N, and pdfjs_head is flipped in
// the same transaction that finishes the write. The previous generation is kept
// rather than deleted immediately: a page loaded seconds before an update is
// still fetching viewer.mjs and pdf.worker.mjs, and pulling those out from
// under it would fail the frame it was about to draw.
const Schema = `
CREATE TABLE pdfjs_asset (
  generation  INTEGER NOT NULL,
  path        TEXT    NOT NULL,   -- 'build/pdf.worker.mjs', as named in the zip
  mime_type   TEXT    NOT NULL,
  size        INTEGER NOT NULL,
  content     BLOB    NOT NULL,
  PRIMARY KEY (generation, path)
);

-- Exactly one row: which generation is live, and which upstream release it
-- came from. The CHECK is what makes "the live generation" a fact about the
-- database rather than a convention the code has to remember.
CREATE TABLE pdfjs_head (
  id          INTEGER PRIMARY KEY CHECK (id = 1),
  generation  INTEGER NOT NULL,
  version     TEXT    NOT NULL,   -- '6.3.289', the release tag without its 'v'
  ingested    INTEGER NOT NULL
);
`

// Available reports whether a viewer is stored, which is what decides whether
// a page offers to frame a PDF at all.
func Available(db *sql.DB) bool { return pdfjsAvailable(db) }

// Version is the stored release, "" when there is none.
func Version(db *sql.DB) string {
	_, v, _ := pdfjsHead(db)
	return v
}

// Sync brings the stored viewer up to the current release. Every failure is
// logged and swallowed: an application must keep working without GitHub, and
// without a viewer it simply links PDFs instead of framing them.
func Sync(db *sql.DB) { pdfjsSync(db) }

// Prefix is where Handler expects to be mounted.
const Prefix = "/static/pdfjs/"

// ViewerURL is the frame source for a PDF served at pdfURL.
//
// The document opens fitted to the frame's width (#zoom=page-width, which the
// viewer reads from the fragment on load) rather than at pdf.js's "auto",
// which shrinks a portrait page until the whole of it fits the frame's height
// and leaves it small in a wide frame.
func ViewerURL(pdfURL string) string {
	return Viewer{PDF: pdfURL}.URL()
}

// ViewerURLSaving is ViewerURL for a viewer that POSTs the annotated document
// to saveURL; see Viewer.Save.
func ViewerURLSaving(pdfURL, saveURL string) string {
	return Viewer{PDF: pdfURL, Save: saveURL}.URL()
}

// Viewer is a frame source with everything it can be told.
type Viewer struct {
	// PDF is where the document is served.
	PDF string
	// Save, if set, is a path on the same server the annotated document is
	// POSTed to whenever the person annotating it pauses; see "The save
	// shim". The POST comes from an opaque origin like any other web page's
	// would, so it must carry whatever proves it was handed out by the
	// application.
	Save string
	// Position, if set, is a path on the same server where the reader is in
	// the document is POSTed to, as Position's text form, a second after
	// scrolling stops; see "The position shim". Same caveat as Save.
	Position string
	// At is where the document opens; the zero Position is its start.
	At Position
}

// URL is the frame's src. The document is fitted to the frame's width either
// way: #zoom=FitH,top is page-width with the top of the viewport at top, on
// the page #page= names.
func (v Viewer) URL() string {
	s := Prefix + "web/viewer.html?file=" + url.QueryEscape(v.PDF)
	if v.Save != "" {
		s += "&save=" + url.QueryEscape(v.Save)
	}
	if v.Position != "" {
		s += "&pos=" + url.QueryEscape(v.Position)
	}
	if v.At.Page >= 1 {
		return s + fmt.Sprintf("#page=%d&zoom=FitH,%d", v.At.Page, v.At.Top)
	}
	return s + "#zoom=page-width"
}

// FrameSandbox is the sandbox attribute a viewer frame must carry.
//
// It withholds allow-same-origin deliberately, and this is the whole security
// argument for framing a PDF at all. A PDF viewer is script, so the frame
// cannot be denied script; what it is denied instead is the origin, so a bug
// in the viewer (pdf.js has had them: CVE-2024-4367 gave arbitrary script
// execution in the embedding origin) lands somewhere that cannot read the
// application's pages. Granting both was measured in mailweb: such a frame
// read the parent's title and fetched the application's own page from inside
// itself. The two must never be granted together.
//
// allow-downloads so the viewer's own save button works.
const FrameSandbox = "allow-scripts allow-downloads allow-popups allow-popups-to-escape-sandbox"

// Handler serves one file of the stored viewer at Prefix + path; mount it at
// "GET " + Prefix. 404 until a viewer has been stored.
//
// The assets live in SQLite rather than in the binary because they are fetched
// at runtime and updated without a rebuild.
//
// Caching follows source-forge's tarball route. The URL is mutable — an update
// changes what /static/pdfjs/build/pdf.mjs returns — so it must be revalidated
// rather than cached outright, and the generation makes that cheap: it is a
// monotonic stamp of the stored bytes, so a conditional GET is answered 304
// without reading the blob. A browser loading a page pays a handful of small
// conditional requests instead of 4.7MB.
//
// Assets are read whole rather than streamed. The SQLite driver has no
// incremental blob API, and the largest file here is about 2.1MB.
func Handler(db *sql.DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// The path is a key into a table, never a filesystem path: an entry
		// that is not stored is a 404, so "../" and friends have nothing to
		// reach. It is still cleaned, so that a request differing only in
		// encoding cannot miss a cache entry the equivalent request populated.
		p := strings.TrimPrefix(r.URL.Path, Prefix)
		if p == "" || p != path.Clean(p) {
			http.NotFound(w, r)
			return
		}
		asset, gen, err := loadPdfjsAsset(db, p)
		if err == sql.ErrNoRows {
			http.NotFound(w, r)
			return
		}
		if err != nil {
			http.Error(w, fmt.Sprintf("db error: %v", err), http.StatusInternalServerError)
			return
		}
		content := asset.Content
		tag := fmt.Sprintf("pdfjs-gen%d-%s", gen, p)
		if p == viewerHTMLPath {
			// The policy names the host the viewer is served from, which
			// only the request knows; see servedFrom.
			from := servedFrom(r.Host)
			content = bytes.ReplaceAll(content, []byte(loopback), []byte(from))
			tag += "-" + from
			w.Header().Set("Vary", "Host")
		}
		etag := fmt.Sprintf("%q", tag)
		w.Header().Set("ETag", etag)
		w.Header().Set("Content-Type", asset.MimeType)
		w.Header().Set("X-Content-Type-Options", "nosniff")
		// The viewer is framed with allow-scripts but not allow-same-origin,
		// so its document is an opaque origin and every asset it pulls — the
		// worker, the stylesheet, the toolbar icons, the standard fonts — is a
		// cross-origin request from "null". Without this they are blocked,
		// which shows up as a viewer that half-renders and a console full of
		// CORS errors.
		//
		// These assets are the release plus the shims, the same for
		// everybody and holding no data, so a wildcard here concedes nothing,
		// and it is what buys the frame its opaque origin instead of
		// allow-same-origin.
		w.Header().Set("Access-Control-Allow-Origin", "*")
		// Must revalidate: this URL carries no generation, so what it returns
		// changes when a new release is ingested.
		w.Header().Set("Cache-Control", "no-cache")
		if match := r.Header.Get("If-None-Match"); match != "" && etagMatch(match, etag) {
			w.WriteHeader(http.StatusNotModified)
			return
		}
		w.Write(content)
	}
}

const viewerHTMLPath = "web/viewer.html"

// servedFrom is what the viewer's policy allows in place of 'self': loopback,
// as stored, plus the host this request was addressed to, in both schemes.
//
// The stored policy names loopback only, because that is where mailweb and
// campusweb ran when this was written. campusweb then moved behind nginx at
// https://campusweb.profpatsch.de, and the viewer refused its own module and
// stylesheet there ("blocked … because it violates script-src
// http://127.0.0.1:* http://localhost:*") and drew nothing — which had been
// blamed on the missing secure context over plain-HTTP Tailscale before. The
// frame is an opaque origin, so 'self' cannot say it; the request's Host can,
// and doing it at serve time fixes viewers already stored without a re-fetch.
//
// Host is what the client sent, so it is admitted only if it is plainly a
// host[:port]; anything else gets loopback alone. Both schemes, because the
// application may be plain HTTP on a tailnet or HTTPS behind a proxy, and the
// handler cannot tell which.
func servedFrom(host string) string {
	if host == "" || len(host) > 255 {
		return loopback
	}
	for _, c := range host {
		if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '.' || c == '-' || c == ':') {
			return loopback
		}
	}
	h := strings.ToLower(host)
	if hn, _, err := net.SplitHostPort(h); err == nil {
		h = hn
	}
	if h == "127.0.0.1" || h == "localhost" {
		return loopback
	}
	return loopback + " http://" + host + " https://" + host
}

// LooksLikePDF reports whether bytes are a PDF, by the magic number every PDF
// begins with, after the whitespace and byte-order mark some producers put in
// front of it.
func LooksLikePDF(data []byte) bool {
	b := bytes.TrimLeft(data, "\x00 \t\r\n")
	b = bytes.TrimPrefix(b, []byte("\xef\xbb\xbf"))
	return bytes.HasPrefix(b, []byte("%PDF-"))
}

// SetPDFHeaders types a response as a PDF to be displayed, and opens it to the
// viewer frame. It does not check the bytes; callers check LooksLikePDF first,
// since the bytes, not whoever named the file, decide what is served as a PDF.
//
// The viewer fetches the document from a frame that has allow-scripts but not
// allow-same-origin, which makes it an opaque origin — and an opaque origin is
// "null" for CORS, so without Access-Control-Allow-Origin the viewer cannot
// read the document it was pointed at. The alternative is granting the frame
// allow-same-origin, which is what must not happen. A wildcard concedes the
// document to any page that can name its URL, so that URL must be no easier
// to come by than the document: behind the application's own access control
// (mailweb on loopback), or a capability nobody else can produce (campusweb's
// /frame/ routes, which are outside its gate).
//
// The sandbox policy keeps the document an opaque origin even when it is
// opened as a top-level page, in the browser's own viewer.
func SetPDFHeaders(w http.ResponseWriter, filename string) {
	w.Header().Set("Content-Type", "application/pdf")
	w.Header().Set("X-Content-Type-Options", "nosniff")
	w.Header().Set("Content-Security-Policy", "sandbox")
	w.Header().Set("Access-Control-Allow-Origin", "*")
	if filename != "" {
		w.Header().Set("Content-Disposition", mime.FormatMediaType("inline", map[string]string{"filename": filename}))
	}
}