@gerege-systems/eid-mongolia-sdk 0.19.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3462 @@
1
+ import {
2
+ Fetcher,
3
+ InflateError,
4
+ PRef,
5
+ Reader,
6
+ appearanceObjects,
7
+ inflateRaw,
8
+ isBrowser,
9
+ round100,
10
+ visibleWidget
11
+ } from "./chunk-ARITEQLS.js";
12
+ import {
13
+ EID_ISSUERS,
14
+ INTERMEDIATES,
15
+ NATIONAL_ROOT,
16
+ OID,
17
+ TAG,
18
+ children,
19
+ concat,
20
+ digest,
21
+ equal,
22
+ expect,
23
+ fromB64,
24
+ fromLatin1,
25
+ intValue,
26
+ isTSASigningCert,
27
+ latin1,
28
+ ocspRequest,
29
+ oidString,
30
+ parseCertificate,
31
+ parseOCSP,
32
+ parseOCSPFrom,
33
+ parseOne,
34
+ parsePreciseTime,
35
+ readNode,
36
+ sameCertKey,
37
+ sha256,
38
+ toHex,
39
+ verifySignature
40
+ } from "./chunk-HLSFSIWP.js";
41
+ import {
42
+ EidError
43
+ } from "./chunk-D5NPS7ET.js";
44
+
45
+ // src/pades/validate/gofmt.ts
46
+ var ZERO_TIME = { nanos: 0 };
47
+ function fromPrecise(t) {
48
+ return { sec: Math.floor(t.date.getTime() / 1e3), nanos: t.nanos };
49
+ }
50
+ function fromDate(d) {
51
+ const ms = d.getTime();
52
+ const sec = Math.floor(ms / 1e3);
53
+ return { sec, nanos: (ms - sec * 1e3) * 1e6 };
54
+ }
55
+ var isZero = (t) => t.sec === void 0;
56
+ function before(a, b) {
57
+ return cmp(a, b) < 0;
58
+ }
59
+ function after(a, b) {
60
+ return cmp(a, b) > 0;
61
+ }
62
+ function cmp(a, b) {
63
+ const as = a.sec ?? -62135596800;
64
+ const bs = b.sec ?? -62135596800;
65
+ if (as !== bs) return as < bs ? -1 : 1;
66
+ return a.nanos === b.nanos ? 0 : a.nanos < b.nanos ? -1 : 1;
67
+ }
68
+ function addMs(t, ms) {
69
+ const total = (t.sec ?? -62135596800) * 1e3 + Math.floor(t.nanos / 1e6) + ms;
70
+ const sec = Math.floor(total / 1e3);
71
+ return { sec, nanos: (total - sec * 1e3) * 1e6 + t.nanos % 1e6 };
72
+ }
73
+ function formatTime(t) {
74
+ if (t.sec === void 0) return "0001-01-01T00:00:00Z";
75
+ const d = new Date(t.sec * 1e3);
76
+ const p = (n, w = 2) => String(n).padStart(w, "0");
77
+ let s = `${p(d.getUTCFullYear(), 4)}-${p(d.getUTCMonth() + 1)}-${p(d.getUTCDate())}T${p(d.getUTCHours())}:${p(d.getUTCMinutes())}:${p(d.getUTCSeconds())}`;
78
+ if (t.nanos > 0) s += "." + String(t.nanos).padStart(9, "0").replace(/0+$/, "");
79
+ return s + "Z";
80
+ }
81
+ function hexSerial(intContent) {
82
+ let neg = intContent.length > 0 && (intContent[0] & 128) !== 0;
83
+ let v = 0n;
84
+ for (const b of intContent) v = v << 8n | BigInt(b);
85
+ if (neg) v -= 1n << BigInt(intContent.length * 8);
86
+ neg = v < 0n;
87
+ return (neg ? "-" : "") + (neg ? -v : v).toString(16).toUpperCase();
88
+ }
89
+ var NO_RUNE = -1;
90
+ var PDF_DOC = (() => {
91
+ const t = new Array(256).fill(NO_RUNE);
92
+ t[9] = 9;
93
+ t[10] = 10;
94
+ t[13] = 13;
95
+ [728, 711, 710, 729, 733, 731, 730, 732].forEach((r, i) => t[24 + i] = r);
96
+ for (let i = 32; i < 127; i++) t[i] = i;
97
+ [
98
+ 8226,
99
+ 8224,
100
+ 8225,
101
+ 8230,
102
+ 8212,
103
+ 8211,
104
+ 402,
105
+ 8260,
106
+ 8249,
107
+ 8250,
108
+ 8722,
109
+ 8240,
110
+ 8222,
111
+ 8220,
112
+ 8221,
113
+ 8216,
114
+ 8217,
115
+ 8218,
116
+ 8482,
117
+ 64257,
118
+ 64258,
119
+ 321,
120
+ 338,
121
+ 352,
122
+ 376,
123
+ 381,
124
+ 305,
125
+ 322,
126
+ 339,
127
+ 353,
128
+ 382,
129
+ NO_RUNE
130
+ ].forEach((r, i) => t[128 + i] = r);
131
+ t[160] = 8364;
132
+ for (let i = 161; i <= 255; i++) t[i] = i;
133
+ t[173] = NO_RUNE;
134
+ return t;
135
+ })();
136
+ function pdfText(b) {
137
+ const utf16 = b.length >= 2 && b[0] === 254 && b[1] === 255 && b.length % 2 === 0;
138
+ if (!utf16 && b.every((x) => PDF_DOC[x] !== NO_RUNE)) return String.fromCodePoint(...Array.from(b, (x) => PDF_DOC[x]));
139
+ if (utf16) {
140
+ const u = [];
141
+ for (let i = 2; i < b.length; i += 2) u.push(b[i] << 8 | b[i + 1]);
142
+ return fixSurrogates(String.fromCharCode(...u));
143
+ }
144
+ return goString(b);
145
+ }
146
+ function fixSurrogates(s) {
147
+ return s.replace(/[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/g, "\uFFFD");
148
+ }
149
+ function goString(b) {
150
+ let out = "";
151
+ for (let i = 0; i < b.length; ) {
152
+ const [r, n] = decodeRune(b, i);
153
+ out += String.fromCodePoint(r);
154
+ i += n;
155
+ }
156
+ return out;
157
+ }
158
+ function decodeRune(b, i) {
159
+ const c0 = b[i];
160
+ if (c0 < 128) return [c0, 1];
161
+ const bad = [65533, 1];
162
+ const cont = (k, lo = 128, hi = 191) => i + k < b.length && b[i + k] >= lo && b[i + k] <= hi;
163
+ if (c0 >= 194 && c0 <= 223) return cont(1) ? [(c0 & 31) << 6 | b[i + 1] & 63, 2] : bad;
164
+ if (c0 >= 224 && c0 <= 239) {
165
+ const lo = c0 === 224 ? 160 : 128;
166
+ const hi = c0 === 237 ? 159 : 191;
167
+ return cont(1, lo, hi) && cont(2) ? [(c0 & 15) << 12 | (b[i + 1] & 63) << 6 | b[i + 2] & 63, 3] : bad;
168
+ }
169
+ if (c0 >= 240 && c0 <= 244) {
170
+ const lo = c0 === 240 ? 144 : 128;
171
+ const hi = c0 === 244 ? 143 : 191;
172
+ return cont(1, lo, hi) && cont(2) && cont(3) ? [(c0 & 7) << 18 | (b[i + 1] & 63) << 12 | (b[i + 2] & 63) << 6 | b[i + 3] & 63, 4] : bad;
173
+ }
174
+ return bad;
175
+ }
176
+ var ATTR_NAMES = {
177
+ "2.5.4.6": "C",
178
+ "2.5.4.10": "O",
179
+ "2.5.4.11": "OU",
180
+ "2.5.4.3": "CN",
181
+ "2.5.4.5": "SERIALNUMBER",
182
+ "2.5.4.7": "L",
183
+ "2.5.4.8": "ST",
184
+ "2.5.4.9": "STREET",
185
+ "2.5.4.17": "POSTALCODE"
186
+ };
187
+ function asn1String(n) {
188
+ switch (n.tag) {
189
+ case TAG.PrintableString:
190
+ case TAG.IA5String:
191
+ case 18:
192
+ return goString(n.value);
193
+ case 20:
194
+ return goString(n.value);
195
+ case TAG.UTF8String:
196
+ return goString(n.value);
197
+ case 30: {
198
+ if (n.value.length % 2 !== 0) return void 0;
199
+ const u = [];
200
+ for (let i = 0; i < n.value.length; i += 2) u.push(n.value[i] << 8 | n.value[i + 1]);
201
+ if (u.length > 0 && u[u.length - 1] === 0) u.pop();
202
+ return fixSurrogates(String.fromCharCode(...u));
203
+ }
204
+ }
205
+ return void 0;
206
+ }
207
+ function rdns(name) {
208
+ return children(name).map(
209
+ (rdn) => children(rdn).map((atv) => {
210
+ const [t, v] = children(atv);
211
+ return { oid: oidString(t.value), str: asn1String(v), raw: v };
212
+ })
213
+ );
214
+ }
215
+ function marshalString(s) {
216
+ const bytes = new TextEncoder().encode(s);
217
+ const printable = [...s].every((ch) => {
218
+ const c = ch.codePointAt(0);
219
+ return c >= 97 && c <= 122 || c >= 65 && c <= 90 || c >= 48 && c <= 57 || " '()+,-./:=?".includes(ch);
220
+ });
221
+ const tag = printable ? TAG.PrintableString : TAG.UTF8String;
222
+ const len = bytes.length;
223
+ const hdr = len < 128 ? [tag, len] : len < 256 ? [tag, 129, len] : [tag, 130, len >> 8, len & 255];
224
+ const out = new Uint8Array(hdr.length + len);
225
+ out.set(hdr, 0);
226
+ out.set(bytes, hdr.length);
227
+ return out;
228
+ }
229
+ var toHex2 = (b) => Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
230
+ function nameString(rawName) {
231
+ const seq = rdns(readNode(rawName, 0));
232
+ const f = { C: [], ST: [], L: [], STREET: [], POSTALCODE: [], O: [], OU: [] };
233
+ let cn = "";
234
+ let sn = "";
235
+ const all = [];
236
+ for (const rdn of seq) {
237
+ for (const a of rdn) {
238
+ all.push(a);
239
+ if (a.str === void 0) continue;
240
+ switch (a.oid) {
241
+ case "2.5.4.3":
242
+ cn = a.str;
243
+ break;
244
+ case "2.5.4.5":
245
+ sn = a.str;
246
+ break;
247
+ case "2.5.4.6":
248
+ f.C.push(a.str);
249
+ break;
250
+ case "2.5.4.7":
251
+ f.L.push(a.str);
252
+ break;
253
+ case "2.5.4.8":
254
+ f.ST.push(a.str);
255
+ break;
256
+ case "2.5.4.9":
257
+ f.STREET.push(a.str);
258
+ break;
259
+ case "2.5.4.17":
260
+ f.POSTALCODE.push(a.str);
261
+ break;
262
+ case "2.5.4.10":
263
+ f.O.push(a.str);
264
+ break;
265
+ case "2.5.4.11":
266
+ f.OU.push(a.str);
267
+ break;
268
+ }
269
+ }
270
+ }
271
+ const out = [];
272
+ const skip = /* @__PURE__ */ new Set(["2.5.4.3", "2.5.4.5", "2.5.4.6", "2.5.4.7", "2.5.4.8", "2.5.4.9", "2.5.4.10", "2.5.4.11", "2.5.4.17"]);
273
+ for (const a of all) if (!skip.has(a.oid)) out.push([a]);
274
+ const add = (vals, oid) => {
275
+ if (vals.length > 0) out.push(vals.map((v) => ({ oid, str: v })));
276
+ };
277
+ add(f.C, "2.5.4.6");
278
+ add(f.ST, "2.5.4.8");
279
+ add(f.L, "2.5.4.7");
280
+ add(f.STREET, "2.5.4.9");
281
+ add(f.POSTALCODE, "2.5.4.17");
282
+ add(f.O, "2.5.4.10");
283
+ add(f.OU, "2.5.4.11");
284
+ if (cn) add([cn], "2.5.4.3");
285
+ if (sn) add([sn], "2.5.4.5");
286
+ let s = "";
287
+ for (let i = 0; i < out.length; i++) {
288
+ const rdn = out[out.length - 1 - i];
289
+ if (i > 0) s += ",";
290
+ rdn.forEach((tv, j) => {
291
+ if (j > 0) s += "+";
292
+ const typeName = ATTR_NAMES[tv.oid];
293
+ if (!typeName) {
294
+ const der = tv.str !== void 0 ? marshalString(tv.str) : tv.raw.raw;
295
+ s += `${tv.oid}=#${toHex2(der)}`;
296
+ return;
297
+ }
298
+ const v = tv.str ?? "";
299
+ const chars = [...v];
300
+ let byteIdx = 0;
301
+ const lastByte = new TextEncoder().encode(v).length - 1;
302
+ let esc = "";
303
+ for (const c of chars) {
304
+ let e = false;
305
+ if (',+"\\<>;'.includes(c)) e = true;
306
+ else if (c === " ") e = byteIdx === 0 || byteIdx === lastByte;
307
+ else if (c === "#") e = byteIdx === 0;
308
+ esc += e ? "\\" + c : c;
309
+ byteIdx += new TextEncoder().encode(c).length;
310
+ }
311
+ s += `${typeName}=${esc}`;
312
+ });
313
+ }
314
+ return s;
315
+ }
316
+ function commonName(rawName) {
317
+ let cn = "";
318
+ for (const rdn of rdns(readNode(rawName, 0))) for (const a of rdn) if (a.oid === "2.5.4.3" && a.str !== void 0) cn = a.str;
319
+ return cn;
320
+ }
321
+ function subjectNames(rawSubject) {
322
+ let given = "";
323
+ let surname = "";
324
+ for (const rdn of rdns(readNode(rawSubject, 0))) {
325
+ for (const a of rdn) {
326
+ if (a.oid === "2.5.4.42") given = a.str ?? "";
327
+ if (a.oid === "2.5.4.4") surname = a.str ?? "";
328
+ }
329
+ }
330
+ return { given, surname };
331
+ }
332
+ function subjectSerialNumber(rawSubject) {
333
+ let sn = "";
334
+ for (const rdn of rdns(readNode(rawSubject, 0))) for (const a of rdn) if (a.oid === "2.5.4.5" && a.str !== void 0) sn = a.str;
335
+ return sn;
336
+ }
337
+
338
+ // src/pades/validate/evaluate.ts
339
+ var PROBLEMS = {
340
+ integrity: "integrity_failed",
341
+ malformed: "malformed_signature",
342
+ weakAlgorithm: "weak_algorithm",
343
+ untrusted: "untrusted_chain",
344
+ keyUsage: "wrong_key_usage",
345
+ revoked: "revoked",
346
+ revokedAfter: "revoked_after_signing",
347
+ revocationUnknown: "revocation_unavailable",
348
+ expired: "expired",
349
+ notYetValid: "not_yet_valid",
350
+ modifiedAfter: "modified_after_signing",
351
+ timestampInvalid: "timestamp_invalid"
352
+ };
353
+ var SHA1_SIG = /* @__PURE__ */ new Set(["1.2.840.113549.1.1.5", "1.2.840.10045.4.1", "1.2.840.10040.4.3", "1.2.840.113549.1.1.4"]);
354
+ async function checkSigFrom(c, parent) {
355
+ if (parent.version === 3 && !parent.basicConstraintsValid || parent.basicConstraintsValid && !parent.isCA) return false;
356
+ if (parent.keyUsage !== 0 && !(parent.keyUsage & 1 << 5)) return false;
357
+ if (SHA1_SIG.has(oidString(children(c.sigAlg)[0].value))) return false;
358
+ try {
359
+ return await verifySignature(parent, c.sigAlg, c.tbs, c.signature);
360
+ } catch {
361
+ return false;
362
+ }
363
+ }
364
+ var HANDLED_CRITICAL = /* @__PURE__ */ new Set([
365
+ "2.5.29.15",
366
+ "2.5.29.37",
367
+ "2.5.29.19",
368
+ "2.5.29.17",
369
+ "2.5.29.30",
370
+ "2.5.29.32",
371
+ "2.5.29.31",
372
+ "2.5.29.35",
373
+ "2.5.29.14",
374
+ "2.5.29.36",
375
+ "2.5.29.54",
376
+ "2.5.29.33"
377
+ ]);
378
+ function extValue(c, oid) {
379
+ return c.extensions.find((e) => e.oid === oid)?.value;
380
+ }
381
+ function keyId(c, oid) {
382
+ const v = extValue(c, oid);
383
+ if (!v) return new Uint8Array();
384
+ try {
385
+ const n = parseOne(v);
386
+ if (oid === "2.5.29.14") return n.tag === TAG.OCTET_STRING ? n.value : new Uint8Array();
387
+ const k = children(n).find((x) => x.tag === 128);
388
+ return k ? k.value : new Uint8Array();
389
+ } catch {
390
+ return new Uint8Array();
391
+ }
392
+ }
393
+ function maxPathLen(c) {
394
+ const v = extValue(c, OID.basicConstraints);
395
+ if (!v) return -1;
396
+ try {
397
+ const p = children(parseOne(v)).find((x) => x.tag === TAG.INTEGER);
398
+ return p ? Number(intValue(p.value)) : -1;
399
+ } catch {
400
+ return -1;
401
+ }
402
+ }
403
+ var validAt = (c, at) => !before(at, fromDate(c.notBefore)) && !after(at, fromDate(c.notAfter));
404
+ var CertPool = class {
405
+ list = [];
406
+ add(c) {
407
+ if (!this.list.some((x) => equal(x.raw, c.raw))) this.list.push(c);
408
+ }
409
+ contains(c) {
410
+ return this.list.some((x) => equal(x.raw, c.raw));
411
+ }
412
+ /** Go findPotentialParents: AKID=SKID → нэг нь алга → зөрсөн. */
413
+ parents(c) {
414
+ const akid = keyId(c, "2.5.29.35");
415
+ const m = [];
416
+ const one = [];
417
+ const mis = [];
418
+ for (const p of this.list) {
419
+ if (!equal(p.rawSubject, c.rawIssuer)) continue;
420
+ const skid = keyId(p, "2.5.29.14");
421
+ if (equal(skid, akid)) m.push(p);
422
+ else if (skid.length === 0 && akid.length > 0 || skid.length > 0 && akid.length === 0) one.push(p);
423
+ else mis.push(p);
424
+ }
425
+ return [...m, ...one, ...mis];
426
+ }
427
+ };
428
+ var unhandledCritical = (c) => c.extensions.some((e) => e.critical && !HANDLED_CRITICAL.has(e.oid));
429
+ async function buildChains(chain, roots, inter, at, budget) {
430
+ const c = chain[chain.length - 1];
431
+ const out = [];
432
+ const consider = async (cand, root) => {
433
+ if (chain.some((x) => equal(x.rawSubject, cand.rawSubject) && equal(x.spki, cand.spki))) return;
434
+ if (++budget.n > 100) return;
435
+ if (!await checkSigFrom(c, cand)) return;
436
+ if (unhandledCritical(cand) || !validAt(cand, at)) return;
437
+ if (!root && (!cand.basicConstraintsValid || !cand.isCA)) return;
438
+ const mpl = maxPathLen(cand);
439
+ if (cand.basicConstraintsValid && mpl >= 0 && chain.length - 1 > mpl) return;
440
+ if (root) out.push([...chain, cand]);
441
+ else out.push(...await buildChains([...chain, cand], roots, inter, at, budget));
442
+ };
443
+ for (const r of roots.parents(c)) await consider(r, true);
444
+ for (const p of inter.parents(c)) await consider(p, false);
445
+ return out;
446
+ }
447
+ function chainAllows(chain, eku) {
448
+ for (let i = chain.length - 1; i >= 0; i--) {
449
+ const c = chain[i];
450
+ if (c.extKeyUsage.length === 0) continue;
451
+ if (c.extKeyUsage.includes(OID.kpAny)) continue;
452
+ if (!c.extKeyUsage.includes(eku)) return false;
453
+ }
454
+ return true;
455
+ }
456
+ var Evaluator = class {
457
+ constructor(cfg) {
458
+ this.cfg = cfg;
459
+ }
460
+ cfg;
461
+ pool(extra) {
462
+ const p = new CertPool();
463
+ for (const c of extra) p.add(c);
464
+ for (const c of this.cfg.intermediates) p.add(c);
465
+ return p;
466
+ }
467
+ /** verifyAt — leaf-ийг үндэсний Root CA хүртэл яг at цагт (eku "" — ExtKeyUsageAny). */
468
+ async verifyAt(leaf, extra, at, eku) {
469
+ if (this.cfg.roots.length === 0) return void 0;
470
+ if (unhandledCritical(leaf) || !validAt(leaf, at)) return void 0;
471
+ const roots = new CertPool();
472
+ for (const r of this.cfg.roots) roots.add(r);
473
+ if (roots.contains(leaf)) return [leaf];
474
+ const chains = await buildChains([leaf], roots, this.pool(extra), at, { n: 0 });
475
+ return eku === "" ? chains[0] : chains.find((ch) => chainAllows(ch, eku));
476
+ }
477
+ async verifyChain(leaf, extra, at) {
478
+ const ch = await this.verifyAt(leaf, extra, at, "");
479
+ if (ch) return ch;
480
+ const nb = fromDate(leaf.notBefore);
481
+ const na = fromDate(leaf.notAfter);
482
+ if (after(at, na) || before(at, nb)) {
483
+ const mid = addMs(nb, Math.trunc((leaf.notAfter.getTime() - leaf.notBefore.getTime()) / 2));
484
+ return this.verifyAt(leaf, extra, mid, "");
485
+ }
486
+ return void 0;
487
+ }
488
+ isIssuer(c) {
489
+ return this.cfg.issuers.some((is) => equal(c.rawSubject, is.rawSubject) && equal(c.spki, is.spki));
490
+ }
491
+ async certInfo(c, chain) {
492
+ const info = {
493
+ common_name: commonName(c.rawSubject),
494
+ subject: nameString(c.rawSubject),
495
+ issuer: nameString(c.rawIssuer),
496
+ serial: hexSerial(c.serial),
497
+ not_before: formatTime(fromDate(c.notBefore)),
498
+ not_after: formatTime(fromDate(c.notAfter)),
499
+ usage: usageOf(c),
500
+ issued_by_eid: false,
501
+ revocation: { status: "unknown" }
502
+ };
503
+ if (!chain || chain.length < 2 || !this.isIssuer(chain[1])) return info;
504
+ info.issued_by_eid = true;
505
+ if (!this.cfg.status) return info;
506
+ let st;
507
+ try {
508
+ st = await this.cfg.status.certStatus(intValue(c.serial));
509
+ } catch {
510
+ return info;
511
+ }
512
+ if (!st.issued) return info;
513
+ if (st.revoked) {
514
+ info.revocation = { status: "revoked", revoked_at: formatTime(st.revokedAt) };
515
+ this.lastRevokedAt = st.revokedAt;
516
+ } else info.revocation = { status: "good" };
517
+ return info;
518
+ }
519
+ async evaluateTimestamp(r) {
520
+ const info = { time: formatTime(r.time), serial: r.serial, tsa: "", trusted: false };
521
+ let tsa;
522
+ try {
523
+ tsa = parseCertificate(r.tsaCert ?? new Uint8Array());
524
+ } catch {
525
+ return { info, ok: false };
526
+ }
527
+ info.tsa = commonName(tsa.rawSubject);
528
+ if (!r.matches || r.weakDigest || isZero(r.time) || !isTSASigningCert(tsa)) return { info, ok: false };
529
+ const chain = await this.verifyAt(tsa, parseCerts(r.certs), r.time, OID.kpTimeStamping);
530
+ info.trusted = chain !== void 0;
531
+ return { info, chain, ok: info.trusted };
532
+ }
533
+ async evaluateSignature(r) {
534
+ const s = {
535
+ indication: "valid",
536
+ problems: [],
537
+ signer_name: "",
538
+ signer_name_source: "unverified",
539
+ covers_whole_document: r.coversWhole,
540
+ extended_by_signatures_only: false,
541
+ later_signatures: 0,
542
+ visible_later_signature: false,
543
+ visible: r.visible,
544
+ chain_trusted: false,
545
+ chain: [],
546
+ key_medium: "unknown"
547
+ };
548
+ if (r.signerName) s.claimed_name = r.signerName;
549
+ if (r.reason) s.reason = r.reason;
550
+ if (r.location) s.location = r.location;
551
+ if (r.claimedTime) s.claimed_time = formatTime(r.claimedTime);
552
+ if (r.claimedRoles.length > 0) s.claimed_roles = r.claimedRoles;
553
+ if (!r.coversWhole && r.laterSignaturesOnly) {
554
+ s.extended_by_signatures_only = true;
555
+ s.later_signatures = r.laterSignatures;
556
+ s.visible_later_signature = r.laterVisible;
557
+ }
558
+ const fail = (p) => {
559
+ s.problems.push(p);
560
+ s.indication = "invalid";
561
+ return s;
562
+ };
563
+ if (r.malformed) return fail(PROBLEMS.malformed);
564
+ let leaf;
565
+ try {
566
+ leaf = parseCertificate(r.leaf ?? new Uint8Array());
567
+ } catch {
568
+ return fail(PROBLEMS.malformed);
569
+ }
570
+ s.signer_name = displayName(leaf);
571
+ s.signer_name_source = "certificate";
572
+ const civil = civilID(leaf);
573
+ if (civil) s.civil_id = civil;
574
+ if (!r.integrity) return fail(PROBLEMS.integrity);
575
+ if (r.weakDigest) return fail(PROBLEMS.weakAlgorithm);
576
+ const cades = r.subFilter === "ETSI.CAdES.detached";
577
+ if (cades && r.signingCertV2 !== "match") return fail(PROBLEMS.malformed);
578
+ let at = this.cfg.now;
579
+ let signingTime;
580
+ let tsChain;
581
+ if (r.timestamp) {
582
+ const ts = await this.evaluateTimestamp(r.timestamp);
583
+ tsChain = ts.chain;
584
+ s.timestamp = ts.info;
585
+ if (ts.ok) {
586
+ signingTime = r.timestamp.time;
587
+ s.signing_time = formatTime(signingTime);
588
+ at = signingTime;
589
+ } else s.problems.push(PROBLEMS.timestampInvalid);
590
+ }
591
+ const chain = await this.verifyChain(leaf, parseCerts(r.certs), at);
592
+ const trusted = chain !== void 0;
593
+ s.chain_trusted = trusted;
594
+ s.chain = chain ? chain.map((c) => commonName(c.rawSubject)) : [commonName(leaf.rawSubject)];
595
+ this.lastRevokedAt = void 0;
596
+ const info = await this.certInfo(leaf, chain);
597
+ s.certificate = info;
598
+ if (!trusted) s.problems.push(PROBLEMS.untrusted);
599
+ if (!["sign", "seal", "document_signer"].includes(info.usage)) s.problems.push(PROBLEMS.keyUsage);
600
+ if (after(at, fromDate(leaf.notAfter))) s.problems.push(PROBLEMS.expired);
601
+ else if (before(at, fromDate(leaf.notBefore))) s.problems.push(PROBLEMS.notYetValid);
602
+ if (info.revocation.status === "revoked") {
603
+ const ra = this.lastRevokedAt;
604
+ if (signingTime && ra && after(ra, signingTime)) s.problems.push(PROBLEMS.revokedAfter);
605
+ else s.problems.push(PROBLEMS.revoked);
606
+ } else if (info.revocation.status === "unknown" && trusted) {
607
+ s.problems.push(PROBLEMS.revocationUnknown);
608
+ }
609
+ if (trusted && info.issued_by_eid && info.usage === "document_signer" && !s.problems.includes(PROBLEMS.revoked)) {
610
+ s.signer_name = r.signerName;
611
+ s.signer_name_source = "platform_attested";
612
+ }
613
+ if (cades && r.signingTimeAttr && info.issued_by_eid) s.problems.push(PROBLEMS.malformed);
614
+ if (!r.coversWhole && !r.laterSignaturesOnly) s.problems.push(PROBLEMS.modifiedAfter);
615
+ if (trusted) s.ltv = await ltvCoverage(r.dss, at, [chain, tsChain ?? []]);
616
+ if (cades) {
617
+ s.signature_level = signingTime && s.ltv?.complete ? "PAdES-BASELINE-LT" : signingTime ? "PAdES-BASELINE-T" : "PAdES-BASELINE-B";
618
+ }
619
+ s.indication = indication(s.problems);
620
+ return s;
621
+ }
622
+ /** certInfo-ийн сүүлийн revoked_at (GoTime — нарийвчлалтай харьцуулахад). */
623
+ lastRevokedAt;
624
+ };
625
+ function indication(problems) {
626
+ let out = "valid";
627
+ for (const p of problems) {
628
+ switch (p) {
629
+ case PROBLEMS.integrity:
630
+ case PROBLEMS.malformed:
631
+ case PROBLEMS.weakAlgorithm:
632
+ case PROBLEMS.untrusted:
633
+ case PROBLEMS.keyUsage:
634
+ case PROBLEMS.revoked:
635
+ case PROBLEMS.expired:
636
+ case PROBLEMS.notYetValid:
637
+ return "invalid";
638
+ case PROBLEMS.revokedAfter:
639
+ break;
640
+ default:
641
+ out = "indeterminate";
642
+ }
643
+ }
644
+ return out;
645
+ }
646
+ function parseCerts(ders2) {
647
+ const out = [];
648
+ for (const d of ders2) {
649
+ try {
650
+ out.push(parseCertificate(d));
651
+ } catch {
652
+ }
653
+ }
654
+ return out;
655
+ }
656
+ function displayName(c) {
657
+ const { given, surname } = subjectNames(c.rawSubject);
658
+ const n = `${given} ${surname}`.trim();
659
+ return n !== "" ? n : commonName(c.rawSubject);
660
+ }
661
+ function civilID(c) {
662
+ const sn = subjectSerialNumber(c.rawSubject);
663
+ return sn.startsWith("PNOMN-") ? sn.slice(6) : "";
664
+ }
665
+ var EKU_DOCUMENT_SIGNING = "1.3.6.1.5.5.7.3.36";
666
+ var GO_KNOWN_EKU = /* @__PURE__ */ new Set([
667
+ "2.5.29.37.0",
668
+ "1.3.6.1.5.5.7.3.1",
669
+ "1.3.6.1.5.5.7.3.2",
670
+ "1.3.6.1.5.5.7.3.3",
671
+ "1.3.6.1.5.5.7.3.4",
672
+ "1.3.6.1.5.5.7.3.5",
673
+ "1.3.6.1.5.5.7.3.6",
674
+ "1.3.6.1.5.5.7.3.7",
675
+ "1.3.6.1.5.5.7.3.8",
676
+ "1.3.6.1.5.5.7.3.9",
677
+ "1.3.6.1.4.1.311.10.3.3",
678
+ "2.16.840.1.113730.4.1",
679
+ "1.3.6.1.4.1.311.2.1.22",
680
+ "1.3.6.1.4.1.311.61.1.1"
681
+ ]);
682
+ function usageOf(c) {
683
+ const known = c.extKeyUsage.filter((e) => GO_KNOWN_EKU.has(e));
684
+ for (const e of known) {
685
+ if (e === OID.kpTimeStamping) return "timestamp";
686
+ if (e === OID.kpOCSPSigning) return "other";
687
+ }
688
+ if (c.isCA) return "other";
689
+ if (c.extKeyUsage.includes(EKU_DOCUMENT_SIGNING)) return "document_signer";
690
+ const cc = (c.keyUsage & 1 << 1) !== 0;
691
+ const ds = (c.keyUsage & 1) !== 0;
692
+ if (cc && !ds && known.length === 0) return "seal";
693
+ if (cc) return "sign";
694
+ if (ds && known.includes("1.3.6.1.5.5.7.3.2")) return "auth";
695
+ return "other";
696
+ }
697
+ var LTV_FRESHNESS_MS = 24 * 36e5;
698
+ var OID_OCSP_NOCHECK = "1.3.6.1.5.5.7.48.1.5";
699
+ async function ltvCoverage(dss, at, chains) {
700
+ const out = { complete: false, missing: [] };
701
+ const crls = [];
702
+ for (const der of dss?.crls ?? []) {
703
+ const c = parseCRL(der);
704
+ if (c) crls.push(c);
705
+ }
706
+ const seen = [];
707
+ for (const chain of chains) {
708
+ for (let i = 0; i + 1 < chain.length; i++) {
709
+ const cert = chain[i];
710
+ const issuer = chain[i + 1];
711
+ if (seen.some((x) => equal(x, cert.raw))) continue;
712
+ seen.push(cert.raw);
713
+ if (!await covered(cert, issuer, at, dss?.ocsps ?? [], crls)) out.missing.push(commonName(cert.rawSubject));
714
+ }
715
+ }
716
+ out.complete = out.missing.length === 0 && seen.length > 0;
717
+ return out;
718
+ }
719
+ async function covered(cert, issuer, at, ocsps, crls) {
720
+ for (const der of ocsps) {
721
+ let resp;
722
+ try {
723
+ resp = await parseOCSP(der, intValue(cert.serial), issuer);
724
+ } catch {
725
+ continue;
726
+ }
727
+ if (resp.status !== "good") continue;
728
+ if (resp.certificate && !equal(resp.certificate.raw, issuer.raw) && !resp.certificate.extensions.some((e) => e.oid === OID_OCSP_NOCHECK)) continue;
729
+ const tu = fromPrecise(resp.thisUpdate);
730
+ if (!before(tu, addMs(at, -LTV_FRESHNESS_MS))) return true;
731
+ if (resp.nextUpdate && !before(fromDate(resp.nextUpdate), at) && !after(tu, at)) return true;
732
+ }
733
+ for (const crl of crls) {
734
+ if (!equal(crl.rawIssuer, cert.rawIssuer) || !await crlSignedBy(crl, issuer)) continue;
735
+ if (crl.nextUpdate && before(crl.nextUpdate, at)) continue;
736
+ const serial = intValue(cert.serial);
737
+ if (crl.revoked.some((e) => e.serial === serial)) continue;
738
+ return true;
739
+ }
740
+ return false;
741
+ }
742
+ function parseCRL(der) {
743
+ try {
744
+ const top = children(expect(parseOne(der), TAG.SEQUENCE, "CertificateList"));
745
+ const tbs = expect(top[0], TAG.SEQUENCE, "TBSCertList");
746
+ const sigAlg = expect(top[1], TAG.SEQUENCE, "sigAlg");
747
+ const sigBits = expect(top[2], TAG.BIT_STRING, "sig");
748
+ const f = children(tbs);
749
+ let i = 0;
750
+ if (f[i]?.tag === TAG.INTEGER) i++;
751
+ expect(f[i++], TAG.SEQUENCE, "signature");
752
+ const issuer = expect(f[i++], TAG.SEQUENCE, "issuer");
753
+ const tu = f[i++];
754
+ if (!tu || tu.tag !== TAG.UTCTime && tu.tag !== TAG.GeneralizedTime) return void 0;
755
+ let nextUpdate;
756
+ if (f[i] && (f[i].tag === TAG.UTCTime || f[i].tag === TAG.GeneralizedTime)) nextUpdate = fromPrecise(parsePreciseTime(f[i++]));
757
+ const revoked = [];
758
+ if (f[i]?.tag === TAG.SEQUENCE) {
759
+ for (const e of children(f[i++])) {
760
+ const p = children(expect(e, TAG.SEQUENCE, "entry"));
761
+ revoked.push({ serial: intValue(expect(p[0], TAG.INTEGER, "serial").value), time: fromPrecise(parsePreciseTime(p[1])) });
762
+ }
763
+ }
764
+ return { rawIssuer: issuer.raw, tbs: tbs.raw, sigAlg, sig: sigBits.value.subarray(1), nextUpdate, revoked };
765
+ } catch {
766
+ return void 0;
767
+ }
768
+ }
769
+ async function crlSignedBy(crl, issuer) {
770
+ if (issuer.version === 3 && !issuer.basicConstraintsValid || issuer.basicConstraintsValid && !issuer.isCA) return false;
771
+ if (issuer.keyUsage !== 0 && !(issuer.keyUsage & 1 << 6)) return false;
772
+ if (SHA1_SIG.has(oidString(children(crl.sigAlg)[0].value))) return false;
773
+ try {
774
+ return await verifySignature(issuer, crl.sigAlg, crl.tbs, crl.sig);
775
+ } catch {
776
+ return false;
777
+ }
778
+ }
779
+ function responderOK(resp, issuer) {
780
+ if (!resp.certificate || equal(resp.certificate.raw, issuer.raw)) return true;
781
+ return resp.certificate.extKeyUsage.includes(OID.kpOCSPSigning);
782
+ }
783
+ var DSSStatus = class {
784
+ constructor(dss, issuers) {
785
+ this.dss = dss;
786
+ this.issuers = issuers;
787
+ }
788
+ dss;
789
+ issuers;
790
+ async certStatus(serial) {
791
+ for (const der of this.dss?.ocsps ?? []) {
792
+ for (const iss of this.issuers) {
793
+ let resp;
794
+ try {
795
+ resp = await parseOCSPFrom(der, void 0, iss);
796
+ } catch {
797
+ continue;
798
+ }
799
+ if (resp.serial !== serial || !responderOK(resp, iss)) continue;
800
+ if (resp.status === "good") return { issued: true, revoked: false };
801
+ if (resp.status === "revoked") return { issued: true, revoked: true, revokedAt: fromPrecise(resp.revokedAt) };
802
+ }
803
+ }
804
+ for (const der of this.dss?.crls ?? []) {
805
+ const crl = parseCRL(der);
806
+ if (!crl) continue;
807
+ for (const iss of this.issuers) {
808
+ if (!equal(crl.rawIssuer, iss.rawSubject) || !await crlSignedBy(crl, iss)) continue;
809
+ const e = crl.revoked.find((x) => x.serial === serial);
810
+ return e ? { issued: true, revoked: true, revokedAt: e.time } : { issued: true, revoked: false };
811
+ }
812
+ }
813
+ return { issued: false, revoked: false };
814
+ }
815
+ };
816
+ var ONLINE_OCSP_MAX = 16 << 10;
817
+ var CLOCK_SKEW_MS = 5 * 6e4;
818
+ var OnlineStatus = class _OnlineStatus {
819
+ constructor(f, fallback, now) {
820
+ this.f = f;
821
+ this.fallback = fallback;
822
+ this.now = now;
823
+ }
824
+ f;
825
+ fallback;
826
+ now;
827
+ leaves = /* @__PURE__ */ new Map();
828
+ cache = /* @__PURE__ */ new Map();
829
+ static async create(f, raws, issuers, fallback, now) {
830
+ const s = new _OnlineStatus(f, fallback, now);
831
+ for (const r of raws) {
832
+ let leaf;
833
+ try {
834
+ leaf = parseCertificate(r.leaf ?? new Uint8Array());
835
+ } catch {
836
+ continue;
837
+ }
838
+ const key = intValue(leaf.serial).toString(16);
839
+ const prev = s.leaves.get(key);
840
+ if (prev) {
841
+ if (!equal(prev.leaf.raw, leaf.raw)) prev.ambiguous = true;
842
+ continue;
843
+ }
844
+ let issuer;
845
+ for (const is of issuers) {
846
+ if (equal(leaf.rawIssuer, is.rawSubject) && await checkSigFrom(leaf, is)) {
847
+ issuer = is;
848
+ break;
849
+ }
850
+ }
851
+ if (issuer) s.leaves.set(key, { leaf, issuer, ambiguous: false });
852
+ }
853
+ return s;
854
+ }
855
+ async certStatus(serial) {
856
+ const key = serial.toString(16);
857
+ const hit = this.cache.get(key);
858
+ if (hit) return hit;
859
+ const li = this.leaves.get(key);
860
+ if (!li || li.ambiguous || !li.issuer) return { issued: false, revoked: false };
861
+ let st = await this.ocsp(li.leaf, li.issuer) ?? await this.crl(li.leaf, li.issuer);
862
+ if (!st) {
863
+ if (!this.fallback) return { issued: false, revoked: false };
864
+ st = await this.fallback.certStatus(serial);
865
+ }
866
+ this.cache.set(key, st);
867
+ return st;
868
+ }
869
+ async ocsp(leaf, issuer) {
870
+ let req;
871
+ try {
872
+ req = await ocspRequest(leaf, issuer);
873
+ } catch {
874
+ return void 0;
875
+ }
876
+ const now = this.now;
877
+ for (const u of leaf.ocspServers) {
878
+ let resp;
879
+ try {
880
+ const der = await this.f.do("POST", u, "application/ocsp-request", req);
881
+ if (der.length > ONLINE_OCSP_MAX) continue;
882
+ resp = await parseOCSPFrom(der, intValue(leaf.serial), issuer);
883
+ } catch {
884
+ continue;
885
+ }
886
+ if (resp.serial !== intValue(leaf.serial)) continue;
887
+ const rc = resp.certificate;
888
+ if (rc && !sameCertKey(rc, issuer) && (!responderOK(resp, issuer) || !validAt(rc, now))) continue;
889
+ if (after(fromPrecise(resp.thisUpdate), addMs(now, CLOCK_SKEW_MS))) continue;
890
+ if (resp.nextUpdate && before(fromDate(resp.nextUpdate), now)) continue;
891
+ if (resp.status === "good") return { issued: true, revoked: false };
892
+ if (resp.status === "revoked") return { issued: true, revoked: true, revokedAt: fromPrecise(resp.revokedAt) };
893
+ return { issued: false, revoked: false };
894
+ }
895
+ return void 0;
896
+ }
897
+ async crl(leaf, issuer) {
898
+ for (const u of leaf.crlDPs) {
899
+ let crl;
900
+ try {
901
+ crl = parseCRL(await this.f.do("GET", u, ""));
902
+ } catch {
903
+ continue;
904
+ }
905
+ if (!crl || !equal(crl.rawIssuer, issuer.rawSubject) || !await crlSignedBy(crl, issuer)) continue;
906
+ if (crl.nextUpdate && before(crl.nextUpdate, this.now)) continue;
907
+ const serial = intValue(leaf.serial);
908
+ const e = crl.revoked.find((x) => x.serial === serial);
909
+ return e ? { issued: true, revoked: true, revokedAt: e.time } : { issued: true, revoked: false };
910
+ }
911
+ return void 0;
912
+ }
913
+ };
914
+ var OID_QC_STATEMENTS = "1.3.6.1.5.5.7.1.3";
915
+ var OID_QC_COMPLIANCE = "0.4.0.1862.1.1";
916
+ var OID_QC_SSCD = "0.4.0.1862.1.4";
917
+ function signLevelOf(c) {
918
+ const e = c.extensions.find((x) => x.oid === OID_QC_STATEMENTS);
919
+ if (!e) return "ADVANCED";
920
+ try {
921
+ const seq = parseOne(e.value);
922
+ if (seq.tag !== TAG.SEQUENCE) return void 0;
923
+ let compliance = false;
924
+ let sscd = false;
925
+ for (const st of children(seq)) {
926
+ if (st.tag !== TAG.SEQUENCE) return void 0;
927
+ const id = readNode(st.value, 0);
928
+ if (id.tag !== TAG.OID) return void 0;
929
+ const o = oidString(id.value);
930
+ compliance ||= o === OID_QC_COMPLIANCE;
931
+ sscd ||= o === OID_QC_SSCD;
932
+ }
933
+ return !compliance ? "ADVANCED" : sscd ? "QSCD" : "QUALIFIED";
934
+ } catch {
935
+ return void 0;
936
+ }
937
+ }
938
+
939
+ // src/pades/validate/pdfobj.ts
940
+ var MAX_PDF_DEPTH = 64;
941
+ var MAX_PDF_NODES = 1e6;
942
+ var MAX_PDF_INFLATE = 64 << 20;
943
+ var MAX_XREF_SECTIONS = 128;
944
+ var MAX_OBJECT_NUMBER = 1 << 23;
945
+ var PdfObjError = class extends Error {
946
+ };
947
+ var errPDFSyntax = () => new PdfObjError("validate: PDF \u0431\u04AF\u0442\u044D\u0446 \u0442\u0430\u043D\u0438\u0433\u0434\u0441\u0430\u043D\u0433\u04AF\u0439");
948
+ var errPDFLimit = () => new PdfObjError("validate: PDF \u0448\u0438\u043D\u0436\u0438\u043B\u0433\u044D\u044D\u043D\u0438\u0439 \u0445\u044F\u0437\u0433\u0430\u0430\u0440 \u0445\u044D\u0442\u044D\u0440\u043B\u044D\u044D");
949
+ var PRef2 = class {
950
+ constructor(num, gen) {
951
+ this.num = num;
952
+ this.gen = gen;
953
+ }
954
+ num;
955
+ gen;
956
+ };
957
+ var PName = class {
958
+ constructor(v) {
959
+ this.v = v;
960
+ }
961
+ v;
962
+ };
963
+ var PStr = class {
964
+ constructor(v) {
965
+ this.v = v;
966
+ }
967
+ v;
968
+ };
969
+ var PReal = class {
970
+ constructor(v) {
971
+ this.v = v;
972
+ }
973
+ v;
974
+ };
975
+ var PStream = class {
976
+ constructor(dict, data) {
977
+ this.dict = dict;
978
+ this.data = data;
979
+ }
980
+ dict;
981
+ data;
982
+ };
983
+ var isDict = (v) => v instanceof Map;
984
+ var isArr = (v) => Array.isArray(v);
985
+ var isInt = (v) => typeof v === "bigint";
986
+ var isName = (v, s) => v instanceof PName && (s === void 0 || v.v === s);
987
+ var isStr = (v) => v instanceof PStr;
988
+ var isRef = (v) => v instanceof PRef2;
989
+ var dget = (d, k) => d ? d.get(k) ?? null : null;
990
+ var GoPanic = class extends Error {
991
+ };
992
+ function ifaceEq(a, b) {
993
+ if (a === null || b === null) return a === b;
994
+ const ta = kindOf(a);
995
+ if (ta !== kindOf(b)) return false;
996
+ switch (ta) {
997
+ case "bool":
998
+ case "int":
999
+ return a === b;
1000
+ case "real":
1001
+ return a.v === b.v;
1002
+ case "name":
1003
+ return a.v === b.v;
1004
+ case "str":
1005
+ return a.v === b.v;
1006
+ case "ref":
1007
+ return a.num === b.num && a.gen === b.gen;
1008
+ }
1009
+ throw new GoPanic("comparing uncomparable type");
1010
+ }
1011
+ function kindOf(v) {
1012
+ if (typeof v === "boolean") return "bool";
1013
+ if (typeof v === "bigint") return "int";
1014
+ if (v instanceof PReal) return "real";
1015
+ if (v instanceof PName) return "name";
1016
+ if (v instanceof PStr) return "str";
1017
+ if (v instanceof PRef2) return "ref";
1018
+ if (Array.isArray(v)) return "arr";
1019
+ if (v instanceof Map) return "dict";
1020
+ return "stream";
1021
+ }
1022
+ var PdfBudget = class {
1023
+ nodes = MAX_PDF_NODES;
1024
+ inflate = MAX_PDF_INFLATE;
1025
+ objs = /* @__PURE__ */ new Map();
1026
+ stms = /* @__PURE__ */ new Map();
1027
+ node() {
1028
+ if (--this.nodes < 0) throw errPDFLimit();
1029
+ }
1030
+ /** decode — xref/object stream-ийн агуулга: filter-гүй эсвэл ганц FlateDecode (+ PNG predictor). */
1031
+ decode(s) {
1032
+ const single = (v) => {
1033
+ if (!isArr(v)) return v;
1034
+ if (v.length === 0) return null;
1035
+ if (v.length === 1) return v[0];
1036
+ throw errPDFSyntax();
1037
+ };
1038
+ const filter = single(dget(s.dict, "Filter"));
1039
+ if (filter === null) return s.data;
1040
+ if (!ifaceEq(filter, new PName("FlateDecode"))) throw errPDFSyntax();
1041
+ const out = zlibStrict(s.data, this.inflate);
1042
+ this.inflate -= out.length;
1043
+ if (this.inflate < 0) throw errPDFLimit();
1044
+ const parms = single(dget(s.dict, "DecodeParms"));
1045
+ if (parms === null) return out;
1046
+ if (!isDict(parms)) throw errPDFSyntax();
1047
+ const intOr = (key, def) => {
1048
+ const v = dget(parms, key);
1049
+ if (v === null) return def;
1050
+ if (isInt(v)) return v;
1051
+ return -1n;
1052
+ };
1053
+ const pred = intOr("Predictor", 1n);
1054
+ const cols = intOr("Columns", 1n);
1055
+ if (pred === 1n) return out;
1056
+ if (pred < 10n || pred > 15n || cols < 1n || cols > 1n << 16n || intOr("Colors", 1n) !== 1n || intOr("BitsPerComponent", 8n) !== 8n) {
1057
+ throw errPDFSyntax();
1058
+ }
1059
+ return unPNG(out, Number(cols));
1060
+ }
1061
+ };
1062
+ var newPDFBudget = () => new PdfBudget();
1063
+ function zlibStrict(src, limit) {
1064
+ if (src.length < 2) throw errPDFSyntax();
1065
+ const cmf = src[0];
1066
+ const flg = src[1];
1067
+ if ((cmf & 15) !== 8 || cmf >> 4 > 7 || (cmf << 8 | flg) % 31 !== 0 || flg & 32) throw errPDFSyntax();
1068
+ const info = { end: 0, truncated: false };
1069
+ let out;
1070
+ try {
1071
+ out = inflateRaw(src.subarray(2), limit + 1, info);
1072
+ } catch (e) {
1073
+ if (e instanceof InflateError) {
1074
+ if (/хэмжээний хязгаар/.test(e.message)) throw errPDFLimit();
1075
+ throw errPDFSyntax();
1076
+ }
1077
+ throw e;
1078
+ }
1079
+ if (out.length > limit) return out;
1080
+ if (info.truncated) throw errPDFSyntax();
1081
+ const at = 2 + info.end;
1082
+ if (at + 4 > src.length) throw errPDFSyntax();
1083
+ const want = (src[at] << 24 | src[at + 1] << 16 | src[at + 2] << 8 | src[at + 3]) >>> 0;
1084
+ if (adler32(out) !== want) throw errPDFSyntax();
1085
+ return out;
1086
+ }
1087
+ function adler32(b) {
1088
+ let a = 1;
1089
+ let s = 0;
1090
+ for (let i = 0; i < b.length; ) {
1091
+ const n = Math.min(5552, b.length - i);
1092
+ for (let j = 0; j < n; j++, i++) {
1093
+ a += b[i];
1094
+ s += a;
1095
+ }
1096
+ a %= 65521;
1097
+ s %= 65521;
1098
+ }
1099
+ return (s << 16 | a) >>> 0;
1100
+ }
1101
+ function unPNG(input, cols) {
1102
+ if (input.length % (cols + 1) !== 0) throw errPDFSyntax();
1103
+ const rows = input.length / (cols + 1);
1104
+ const out = new Uint8Array(rows * cols);
1105
+ let prev = new Uint8Array(cols);
1106
+ for (let r = 0; r < rows; r++) {
1107
+ const base = r * (cols + 1);
1108
+ const ft = input[base];
1109
+ const cur = new Uint8Array(cols);
1110
+ for (let i = 0; i < cols; i++) {
1111
+ let x = input[base + 1 + i];
1112
+ let left = 0;
1113
+ let upLeft = 0;
1114
+ if (i > 0) {
1115
+ left = cur[i - 1];
1116
+ upLeft = prev[i - 1];
1117
+ }
1118
+ const up = prev[i];
1119
+ switch (ft) {
1120
+ case 0:
1121
+ break;
1122
+ case 1:
1123
+ x = x + left & 255;
1124
+ break;
1125
+ case 2:
1126
+ x = x + up & 255;
1127
+ break;
1128
+ case 3:
1129
+ x = x + ((left & up) + ((left ^ up) >> 1)) & 255;
1130
+ break;
1131
+ case 4: {
1132
+ const pa = Math.abs(up - upLeft);
1133
+ const pb = Math.abs(left - upLeft);
1134
+ const pc = Math.abs(left + up - 2 * upLeft);
1135
+ if (pa <= pb && pa <= pc) x = x + left & 255;
1136
+ else if (pb <= pc) x = x + up & 255;
1137
+ else x = x + upLeft & 255;
1138
+ break;
1139
+ }
1140
+ default:
1141
+ throw errPDFSyntax();
1142
+ }
1143
+ cur[i] = x;
1144
+ }
1145
+ out.set(cur, r * cols);
1146
+ prev = cur;
1147
+ }
1148
+ return out;
1149
+ }
1150
+ var isPDFSpace = (c) => c === 0 || c === 9 || c === 10 || c === 12 || c === 13 || c === 32;
1151
+ var DELIMS = new Set([..."()<>[]{}/%"].map((c) => c.charCodeAt(0)));
1152
+ var isPDFDelim = (c) => DELIMS.has(c);
1153
+ var isGapSpace = (c) => c === 9 || c === 10 || c === 12 || c === 13 || c === 32;
1154
+ function allGapSpace(b) {
1155
+ for (const c of b) if (!isGapSpace(c)) return false;
1156
+ return true;
1157
+ }
1158
+ var isDigit = (c) => c !== void 0 && c >= 48 && c <= 57;
1159
+ var HEX2 = /^[0-9a-fA-F]{2}$/;
1160
+ var INT_RE = /^[+-]?[0-9]+$/;
1161
+ var FLOAT_RE = /^[+-]?([0-9]+\.[0-9]*|\.[0-9]+)$/;
1162
+ var I64_MAX = (1n << 63n) - 1n;
1163
+ var I64_MIN = -(1n << 63n);
1164
+ function str(b, s, e) {
1165
+ let out = "";
1166
+ for (let i = s; i < e; i++) out += String.fromCharCode(b[i]);
1167
+ return out;
1168
+ }
1169
+ var PdfParser = class {
1170
+ constructor(b, pos, budget, strict = false) {
1171
+ this.b = b;
1172
+ this.pos = pos;
1173
+ this.budget = budget;
1174
+ this.strict = strict;
1175
+ }
1176
+ b;
1177
+ pos;
1178
+ budget;
1179
+ strict;
1180
+ skipGap() {
1181
+ while (this.pos < this.b.length && isGapSpace(this.b[this.pos])) this.pos++;
1182
+ }
1183
+ skipSpace() {
1184
+ if (this.strict) return this.skipGap();
1185
+ while (this.pos < this.b.length && isPDFSpace(this.b[this.pos])) this.pos++;
1186
+ }
1187
+ /** Зай ба тайлбар; хатуу горимд зөвхөн isGapSpace. */
1188
+ skip() {
1189
+ if (this.strict) return this.skipGap();
1190
+ while (this.pos < this.b.length) {
1191
+ const c = this.b[this.pos];
1192
+ if (isPDFSpace(c)) this.pos++;
1193
+ else if (c === 37) {
1194
+ while (this.pos < this.b.length && this.b[this.pos] !== 10 && this.b[this.pos] !== 13) this.pos++;
1195
+ } else return;
1196
+ }
1197
+ }
1198
+ keyword(k) {
1199
+ const e = this.pos + k.length;
1200
+ if (e > this.b.length) return false;
1201
+ for (let i = 0; i < k.length; i++) if (this.b[this.pos + i] !== k.charCodeAt(i)) return false;
1202
+ if (e < this.b.length && !isPDFSpace(this.b[e]) && !isPDFDelim(this.b[e])) return false;
1203
+ this.pos = e;
1204
+ return true;
1205
+ }
1206
+ /** Go uint(): ≤ 18 цифр. */
1207
+ uint() {
1208
+ const s = this.pos;
1209
+ while (this.pos < this.b.length && isDigit(this.b[this.pos])) this.pos++;
1210
+ if (this.pos === s || this.pos - s > 18) {
1211
+ this.pos = s;
1212
+ return void 0;
1213
+ }
1214
+ return Number(str(this.b, s, this.pos));
1215
+ }
1216
+ value(depth) {
1217
+ if (depth > MAX_PDF_DEPTH) throw errPDFSyntax();
1218
+ this.budget.node();
1219
+ this.skip();
1220
+ if (this.pos >= this.b.length) throw errPDFSyntax();
1221
+ const c = this.b[this.pos];
1222
+ if (c === 47) {
1223
+ this.pos++;
1224
+ return this.name();
1225
+ }
1226
+ if (c === 40) {
1227
+ this.pos++;
1228
+ return this.literal();
1229
+ }
1230
+ if (c === 91) {
1231
+ this.pos++;
1232
+ const arr = [];
1233
+ for (; ; ) {
1234
+ this.skip();
1235
+ if (this.pos < this.b.length && this.b[this.pos] === 93) {
1236
+ this.pos++;
1237
+ return arr;
1238
+ }
1239
+ arr.push(this.value(depth + 1));
1240
+ }
1241
+ }
1242
+ if (c === 60) {
1243
+ if (this.pos + 1 < this.b.length && this.b[this.pos + 1] === 60) {
1244
+ this.pos += 2;
1245
+ return this.dict(depth);
1246
+ }
1247
+ this.pos++;
1248
+ return this.hex();
1249
+ }
1250
+ if (isDigit(c) || c === 43 || c === 45 || c === 46) return this.number();
1251
+ if (this.keyword("true")) return true;
1252
+ if (this.keyword("false")) return false;
1253
+ if (this.keyword("null")) return null;
1254
+ throw errPDFSyntax();
1255
+ }
1256
+ dict(depth) {
1257
+ const d = /* @__PURE__ */ new Map();
1258
+ for (; ; ) {
1259
+ this.skip();
1260
+ if (this.pos + 1 < this.b.length && this.b[this.pos] === 62 && this.b[this.pos + 1] === 62) {
1261
+ this.pos += 2;
1262
+ for (const [k, v2] of [...d]) if (v2 === null) d.delete(k);
1263
+ return d;
1264
+ }
1265
+ if (this.pos >= this.b.length || this.b[this.pos] !== 47) throw errPDFSyntax();
1266
+ this.pos++;
1267
+ const key = this.name().v;
1268
+ const dup = d.has(key);
1269
+ const old = d.get(key) ?? null;
1270
+ const v = this.value(depth + 1);
1271
+ if (dup && !pdfEqual(old, v)) throw errPDFSyntax();
1272
+ d.set(key, v);
1273
+ }
1274
+ }
1275
+ name() {
1276
+ let out = "";
1277
+ while (this.pos < this.b.length && !isPDFSpace(this.b[this.pos]) && !isPDFDelim(this.b[this.pos])) {
1278
+ let c = this.b[this.pos];
1279
+ if (c === 35) {
1280
+ if (this.pos + 2 >= this.b.length) throw errPDFSyntax();
1281
+ const h = str(this.b, this.pos + 1, this.pos + 3);
1282
+ if (!HEX2.test(h)) throw errPDFSyntax();
1283
+ c = parseInt(h, 16);
1284
+ this.pos += 2;
1285
+ }
1286
+ out += String.fromCharCode(c);
1287
+ this.pos++;
1288
+ }
1289
+ return new PName(out);
1290
+ }
1291
+ literal() {
1292
+ let out = "";
1293
+ for (let depth = 1; ; this.pos++) {
1294
+ if (this.pos >= this.b.length) throw errPDFSyntax();
1295
+ let c = this.b[this.pos];
1296
+ if (c === 40) depth++;
1297
+ else if (c === 41) {
1298
+ if (--depth === 0) {
1299
+ this.pos++;
1300
+ return new PStr(out);
1301
+ }
1302
+ } else if (c === 13) {
1303
+ if (this.pos + 1 < this.b.length && this.b[this.pos + 1] === 10) this.pos++;
1304
+ c = 10;
1305
+ } else if (c === 92) {
1306
+ if (++this.pos >= this.b.length) throw errPDFSyntax();
1307
+ const e = this.b[this.pos];
1308
+ if (e === 110) c = 10;
1309
+ else if (e === 114) c = 13;
1310
+ else if (e === 116) c = 9;
1311
+ else if (e === 98) c = 8;
1312
+ else if (e === 102) c = 12;
1313
+ else if (e === 10) continue;
1314
+ else if (e === 13) {
1315
+ if (this.pos + 1 < this.b.length && this.b[this.pos + 1] === 10) this.pos++;
1316
+ continue;
1317
+ } else if (e >= 48 && e <= 55) {
1318
+ c = 0;
1319
+ for (let i = 0; i < 3 && this.pos < this.b.length && this.b[this.pos] >= 48 && this.b[this.pos] <= 55; i++) {
1320
+ c = (c << 3 | this.b[this.pos] - 48) & 255;
1321
+ this.pos++;
1322
+ }
1323
+ this.pos--;
1324
+ } else c = e;
1325
+ }
1326
+ out += String.fromCharCode(c);
1327
+ }
1328
+ }
1329
+ hex() {
1330
+ let digits = "";
1331
+ for (; ; this.pos++) {
1332
+ if (this.pos >= this.b.length) throw errPDFSyntax();
1333
+ const c = this.b[this.pos];
1334
+ if (c === 62) {
1335
+ this.pos++;
1336
+ break;
1337
+ }
1338
+ if (!isPDFSpace(c)) digits += String.fromCharCode(c);
1339
+ }
1340
+ if (digits.length % 2 === 1) digits += "0";
1341
+ let out = "";
1342
+ for (let i = 0; i < digits.length; i += 2) {
1343
+ const h = digits.slice(i, i + 2);
1344
+ if (!HEX2.test(h)) throw errPDFSyntax();
1345
+ out += String.fromCharCode(parseInt(h, 16));
1346
+ }
1347
+ return new PStr(out);
1348
+ }
1349
+ /** Бүхэл/бодит тоо, эсвэл «n g R» заалт. */
1350
+ number() {
1351
+ const s = this.pos;
1352
+ while (this.pos < this.b.length && "0123456789+-.".includes(String.fromCharCode(this.b[this.pos]))) this.pos++;
1353
+ const tok = str(this.b, s, this.pos);
1354
+ if (this.pos < this.b.length && !isPDFSpace(this.b[this.pos]) && !isPDFDelim(this.b[this.pos])) throw errPDFSyntax();
1355
+ if (tok.includes(".")) {
1356
+ if (!FLOAT_RE.test(tok)) throw errPDFSyntax();
1357
+ const f = Number(tok);
1358
+ if (!Number.isFinite(f)) throw errPDFSyntax();
1359
+ return new PReal(f);
1360
+ }
1361
+ if (!INT_RE.test(tok)) throw errPDFSyntax();
1362
+ const n = BigInt(tok);
1363
+ if (n > I64_MAX || n < I64_MIN) throw errPDFSyntax();
1364
+ if (n >= 0n && tok[0] !== "+") {
1365
+ const save = this.pos;
1366
+ this.skip();
1367
+ const g = this.uint();
1368
+ if (g !== void 0) {
1369
+ this.skip();
1370
+ if (this.keyword("R")) {
1371
+ if (n >= BigInt(MAX_OBJECT_NUMBER) || g > 65535) throw errPDFSyntax();
1372
+ return new PRef2(Number(n), g);
1373
+ }
1374
+ }
1375
+ this.pos = save;
1376
+ }
1377
+ return n;
1378
+ }
1379
+ /** «n g obj … endobj». length — шууд бус /Length-ийг тухайн харагдацад задална (undefined бол алдаа). */
1380
+ indirect(length) {
1381
+ this.skipSpace();
1382
+ const n = this.uint();
1383
+ this.skipSpace();
1384
+ const g = this.uint();
1385
+ this.skipSpace();
1386
+ if (n === void 0 || g === void 0 || n >= MAX_OBJECT_NUMBER || g > 65535 || !this.keyword("obj")) throw errPDFSyntax();
1387
+ const o = { num: n, gen: g, val: null };
1388
+ o.val = this.value(0);
1389
+ this.skip();
1390
+ if (isDict(o.val) && this.keyword("stream")) {
1391
+ const d = o.val;
1392
+ if (this.pos < this.b.length && this.b[this.pos] === 13) this.pos++;
1393
+ if (this.pos >= this.b.length || this.b[this.pos] !== 10) throw errPDFSyntax();
1394
+ this.pos++;
1395
+ let size;
1396
+ const l = dget(d, "Length");
1397
+ if (isInt(l)) size = l;
1398
+ else if (isRef(l)) {
1399
+ if (!length) throw errPDFSyntax();
1400
+ size = length(l);
1401
+ } else throw errPDFSyntax();
1402
+ if (size < 0n || size > BigInt(this.b.length - this.pos)) throw errPDFSyntax();
1403
+ const sz = Number(size);
1404
+ o.val = new PStream(d, this.b.subarray(this.pos, this.pos + sz));
1405
+ this.pos += sz;
1406
+ this.skipSpace();
1407
+ if (!this.keyword("endstream")) throw errPDFSyntax();
1408
+ this.skip();
1409
+ }
1410
+ if (!this.keyword("endobj")) throw errPDFSyntax();
1411
+ return o;
1412
+ }
1413
+ /** «startxref N %%EOF»; N. */
1414
+ startxref() {
1415
+ this.skipGap();
1416
+ if (!this.keyword("startxref")) return void 0;
1417
+ this.skipGap();
1418
+ const n = this.uint();
1419
+ this.skipGap();
1420
+ if (n === void 0 || n > this.b.length || str(this.b, this.pos, Math.min(this.b.length, this.pos + 5)) !== "%%EOF") return void 0;
1421
+ this.pos += 5;
1422
+ return n;
1423
+ }
1424
+ };
1425
+ function pdfEqual(a, b) {
1426
+ if (a === null) return b === null;
1427
+ if (isArr(a)) {
1428
+ if (!isArr(b) || a.length !== b.length) return false;
1429
+ for (let i = 0; i < a.length; i++) if (!pdfEqual(a[i], b[i])) return false;
1430
+ return true;
1431
+ }
1432
+ if (isDict(a)) {
1433
+ if (!isDict(b) || a.size !== b.size) return false;
1434
+ for (const [k, v] of a) {
1435
+ if (!b.has(k) || !pdfEqual(v, b.get(k))) return false;
1436
+ }
1437
+ return true;
1438
+ }
1439
+ if (a instanceof PStream) {
1440
+ if (!(b instanceof PStream) || a.data.length !== b.data.length) return false;
1441
+ for (let i = 0; i < a.data.length; i++) if (a.data[i] !== b.data[i]) return false;
1442
+ return pdfEqual(a.dict, b.dict);
1443
+ }
1444
+ if (b === null) return false;
1445
+ return ifaceEq(a, b);
1446
+ }
1447
+ function pdfRefs(v, f) {
1448
+ if (v instanceof PRef2) f(v);
1449
+ else if (isArr(v)) for (const e of v) pdfRefs(e, f);
1450
+ else if (isDict(v)) for (const e of v.values()) pdfRefs(e, f);
1451
+ else if (v instanceof PStream) pdfRefs(v.dict, f);
1452
+ }
1453
+ var ENT_FREE = 1;
1454
+ var ENT_USE = 2;
1455
+ var ENT_COMP = 3;
1456
+ var ZERO = Object.freeze({ kind: 0, off: 0, gen: 0, idx: 0 });
1457
+ var inUse = (e) => e.kind === ENT_USE || e.kind === ENT_COMP;
1458
+ var entEq = (a, b) => a.kind === b.kind && a.off === b.off && a.gen === b.gen && a.idx === b.idx;
1459
+ var ent = (m, n) => m.get(n) ?? ZERO;
1460
+ function useEnt(off, gen) {
1461
+ if (off === 0) return { kind: ENT_FREE, off: 0, gen: 0, idx: 0 };
1462
+ return { kind: ENT_USE, off, gen, idx: 0 };
1463
+ }
1464
+ var PdfView = class {
1465
+ constructor(b, budget) {
1466
+ this.b = b;
1467
+ this.budget = budget;
1468
+ }
1469
+ b;
1470
+ budget;
1471
+ sections = [];
1472
+ xref = /* @__PURE__ */ new Map();
1473
+ trailer = /* @__PURE__ */ new Map();
1474
+ objs = /* @__PURE__ */ new Map();
1475
+ inLength = false;
1476
+ usedLength = false;
1477
+ refs;
1478
+ parser(pos) {
1479
+ return new PdfParser(this.b, pos, this.budget);
1480
+ }
1481
+ section(off) {
1482
+ const p = this.parser(off);
1483
+ p.skipGap();
1484
+ const sec = { off, start: p.pos, end: 0, trailer: /* @__PURE__ */ new Map(), ents: /* @__PURE__ */ new Map() };
1485
+ const c0 = p.b[p.pos];
1486
+ if (p.pos >= p.b.length || c0 !== 120 && !isDigit(c0)) throw errPDFSyntax();
1487
+ const set = (num, e) => {
1488
+ if (num >= MAX_OBJECT_NUMBER) throw errPDFSyntax();
1489
+ if (sec.ents.has(num)) throw errPDFSyntax();
1490
+ sec.ents.set(num, e);
1491
+ this.budget.node();
1492
+ };
1493
+ if (p.keyword("xref")) {
1494
+ for (; ; ) {
1495
+ p.skipSpace();
1496
+ if (p.keyword("trailer")) break;
1497
+ const first = p.uint();
1498
+ p.skipSpace();
1499
+ const count = p.uint();
1500
+ if (first === void 0 || count === void 0 || first >= MAX_OBJECT_NUMBER || count > MAX_OBJECT_NUMBER) throw errPDFSyntax();
1501
+ p.skipGap();
1502
+ for (let i = 0; i < count; i++) {
1503
+ if (p.pos + 20 > p.b.length) throw errPDFSyntax();
1504
+ const row2 = str(p.b, p.pos, p.pos + 20);
1505
+ const os = row2.slice(0, 10);
1506
+ const gs = row2.slice(11, 16);
1507
+ const eol = row2.slice(18);
1508
+ if (!/^[0-9]+$/.test(os) || !/^[0-9]+$/.test(gs) || row2[10] !== " " || row2[16] !== " " || eol !== " \n" && eol !== " \r" && eol !== "\r\n") {
1509
+ throw errPDFSyntax();
1510
+ }
1511
+ const o2 = Number(os);
1512
+ const g = Number(gs);
1513
+ if (o2 > p.b.length || g > 65535) throw errPDFSyntax();
1514
+ let e;
1515
+ if (row2[17] === "n") e = useEnt(o2, g);
1516
+ else if (row2[17] === "f") e = { kind: ENT_FREE, off: 0, gen: 0, idx: 0 };
1517
+ else throw errPDFSyntax();
1518
+ p.pos += 20;
1519
+ set(first + i, e);
1520
+ }
1521
+ }
1522
+ const t = p.value(0);
1523
+ if (!isDict(t)) throw errPDFSyntax();
1524
+ sec.trailer = t;
1525
+ sec.end = p.pos;
1526
+ return sec;
1527
+ }
1528
+ const o = p.indirect(void 0);
1529
+ const st = o.val;
1530
+ if (!(st instanceof PStream) || !ifaceEq(dget(st.dict, "Type"), new PName("XRef"))) throw errPDFSyntax();
1531
+ const data = this.budget.decode(st);
1532
+ const w = dget(st.dict, "W");
1533
+ if (!isArr(w) || w.length !== 3) throw errPDFSyntax();
1534
+ const width = [];
1535
+ for (const x of w) {
1536
+ if (!isInt(x) || x < 0n || x > 7n) throw errPDFSyntax();
1537
+ width.push(Number(x));
1538
+ }
1539
+ const size = dget(st.dict, "Size");
1540
+ if (!isInt(size) || size < 0n) throw errPDFSyntax();
1541
+ let index = [0n, size];
1542
+ if (st.dict.has("Index")) {
1543
+ const ix = dget(st.dict, "Index");
1544
+ if (!isArr(ix) || ix.length % 2 !== 0) throw errPDFSyntax();
1545
+ index = ix;
1546
+ }
1547
+ const row = width[0] + width[1] + width[2];
1548
+ if (row === 0) throw errPDFSyntax();
1549
+ let cur = 0;
1550
+ const field = (n) => {
1551
+ let x = 0;
1552
+ for (let i = 0; i < n; i++) x = x * 256 + data[cur + i];
1553
+ cur += n;
1554
+ return x;
1555
+ };
1556
+ for (let i = 0; i < index.length; i += 2) {
1557
+ const first = index[i];
1558
+ const count = index[i + 1];
1559
+ if (!isInt(first) || !isInt(count) || first < 0n || first >= BigInt(MAX_OBJECT_NUMBER) || count < 0n || count > BigInt(Math.floor((data.length - cur) / row))) {
1560
+ throw errPDFSyntax();
1561
+ }
1562
+ const f0 = Number(first);
1563
+ for (let j = 0; j < Number(count); j++) {
1564
+ let kind = 1;
1565
+ if (width[0] > 0) kind = field(width[0]);
1566
+ const f2 = field(width[1]);
1567
+ const f3 = field(width[2]);
1568
+ let e;
1569
+ if (kind === 0) e = { kind: ENT_FREE, off: 0, gen: 0, idx: 0 };
1570
+ else if (kind === 1) e = useEnt(f2, f3);
1571
+ else if (kind === 2) e = { kind: ENT_COMP, off: f2, gen: 0, idx: f3 };
1572
+ else throw errPDFSyntax();
1573
+ set(f0 + j, e);
1574
+ }
1575
+ }
1576
+ if (cur !== data.length) throw errPDFSyntax();
1577
+ sec.trailer = st.dict;
1578
+ sec.end = p.pos;
1579
+ return sec;
1580
+ }
1581
+ /** Ашиглагдаж буй num объектыг задална (толгойн дугаар/үе xref-тэй таарах ёстой). */
1582
+ get(num) {
1583
+ if (this.objs.has(num)) return this.objs.get(num);
1584
+ let val;
1585
+ const e = ent(this.xref, num);
1586
+ if (e.kind === ENT_USE) {
1587
+ if (e.off >= this.b.length) throw errPDFSyntax();
1588
+ const key = `${e.off},-1`;
1589
+ let o = this.budget.objs.get(key);
1590
+ if (!o || o.end > this.b.length) {
1591
+ const p = this.parser(e.off);
1592
+ this.usedLength = false;
1593
+ const ind = p.indirect((r) => this.length(r));
1594
+ o = { ...ind, end: p.pos };
1595
+ if (!this.usedLength) this.budget.objs.set(key, o);
1596
+ }
1597
+ if (o.num !== num || o.gen !== e.gen) throw errPDFSyntax();
1598
+ val = o.val;
1599
+ } else if (e.kind === ENT_COMP) {
1600
+ const st = this.objStm(e.off);
1601
+ if (e.idx >= st.nums.length || st.nums[e.idx] !== num || st.first + st.offs[e.idx] > st.data.length) throw errPDFSyntax();
1602
+ const key = `${ent(this.xref, e.off).off},${e.idx}`;
1603
+ let o = this.budget.objs.get(key);
1604
+ if (!o) {
1605
+ const p = new PdfParser(st.data, st.first + st.offs[e.idx], this.budget);
1606
+ o = { num: 0, gen: 0, val: p.value(0), end: 0 };
1607
+ this.budget.objs.set(key, o);
1608
+ }
1609
+ val = o.val;
1610
+ } else throw errPDFSyntax();
1611
+ this.objs.set(num, val);
1612
+ return val;
1613
+ }
1614
+ /** ref-ийн заасан объект; ашиглагдаагүй дугаар бол null, үе таарахгүй бол алдаа. */
1615
+ deref(r) {
1616
+ const e = ent(this.xref, r.num);
1617
+ if (!inUse(e)) return null;
1618
+ if (e.kind === ENT_USE && e.gen !== r.gen || e.kind === ENT_COMP && r.gen !== 0) throw errPDFSyntax();
1619
+ return this.get(r.num);
1620
+ }
1621
+ resolve(x) {
1622
+ return x instanceof PRef2 ? this.deref(x) : x;
1623
+ }
1624
+ length(r) {
1625
+ if (this.inLength) throw errPDFSyntax();
1626
+ this.inLength = true;
1627
+ try {
1628
+ const o = this.deref(r);
1629
+ if (!isInt(o)) throw errPDFSyntax();
1630
+ this.usedLength = true;
1631
+ return o;
1632
+ } finally {
1633
+ this.inLength = false;
1634
+ }
1635
+ }
1636
+ objStm(num) {
1637
+ if (ent(this.xref, num).kind !== ENT_USE) throw errPDFSyntax();
1638
+ const o = this.get(num);
1639
+ const off = ent(this.xref, num).off;
1640
+ const cached = this.budget.stms.get(off);
1641
+ if (cached) return cached;
1642
+ if (!(o instanceof PStream)) throw errPDFSyntax();
1643
+ const n = dget(o.dict, "N");
1644
+ const first = dget(o.dict, "First");
1645
+ if (!isInt(n) || !isInt(first) || !isInt(dget(o.dict, "Length")) || !ifaceEq(dget(o.dict, "Type"), new PName("ObjStm")) || dget(o.dict, "Extends") !== null) {
1646
+ throw errPDFSyntax();
1647
+ }
1648
+ const data = this.budget.decode(o);
1649
+ if (n < 0n || n > BigInt(data.length) || first < 0n || first > BigInt(data.length)) throw errPDFSyntax();
1650
+ const st = { data, nums: [], offs: [], first: Number(first) };
1651
+ const p = new PdfParser(data.subarray(0, st.first), 0, this.budget);
1652
+ for (let i = 0; i < Number(n); i++) {
1653
+ p.skipSpace();
1654
+ const id = p.uint();
1655
+ p.skipSpace();
1656
+ const so = p.uint();
1657
+ if (id === void 0 || so === void 0 || id >= MAX_OBJECT_NUMBER || so > data.length) throw errPDFSyntax();
1658
+ this.budget.node();
1659
+ st.nums.push(id);
1660
+ st.offs.push(so);
1661
+ }
1662
+ this.budget.stms.set(off, st);
1663
+ return st;
1664
+ }
1665
+ /** Ашиглагдаж буй БҮХ объектыг задалж, объект бүрээс гарах ref-ийн дугааруудыг буцаана. */
1666
+ graph() {
1667
+ if (this.refs) return this.refs;
1668
+ const refs = /* @__PURE__ */ new Map();
1669
+ for (const [num, e] of this.xref) {
1670
+ if (!inUse(e)) continue;
1671
+ const o = this.get(num);
1672
+ const out = [];
1673
+ pdfRefs(o, (r) => out.push(r.num));
1674
+ refs.set(num, out);
1675
+ }
1676
+ this.refs = refs;
1677
+ return refs;
1678
+ }
1679
+ };
1680
+ function openView(b, budget) {
1681
+ const v = new PdfView(b, budget);
1682
+ const tail = Math.max(0, b.length - 1024);
1683
+ const i = lastIndex(b, tail, "startxref");
1684
+ if (i < 0) throw errPDFSyntax();
1685
+ const p = v.parser(i);
1686
+ let off = p.startxref();
1687
+ if (off === void 0 || !allGapSpace(b.subarray(p.pos))) throw errPDFSyntax();
1688
+ const seen = /* @__PURE__ */ new Set();
1689
+ for (; ; ) {
1690
+ if (v.sections.length === MAX_XREF_SECTIONS || seen.has(off) || off >= b.length) throw errPDFSyntax();
1691
+ seen.add(off);
1692
+ const sec = v.section(off);
1693
+ v.sections.push(sec);
1694
+ if (dget(sec.trailer, "Encrypt") !== null || dget(sec.trailer, "XRefStm") !== null) throw errPDFSyntax();
1695
+ if (!sec.trailer.has("Prev")) break;
1696
+ const prev = dget(sec.trailer, "Prev");
1697
+ if (!isInt(prev) || prev < 0n || prev >= BigInt(b.length)) throw errPDFSyntax();
1698
+ off = Number(prev);
1699
+ }
1700
+ for (const sec of v.sections) {
1701
+ for (const [num, e] of sec.ents) if (!v.xref.has(num)) v.xref.set(num, e);
1702
+ }
1703
+ v.trailer = v.sections[0].trailer;
1704
+ const size = dget(v.trailer, "Size");
1705
+ if (!isInt(size)) throw errPDFSyntax();
1706
+ for (const [num, e] of v.xref) {
1707
+ if (inUse(e) && (BigInt(num) >= size || num === 0)) throw errPDFSyntax();
1708
+ }
1709
+ return v;
1710
+ }
1711
+ function lastIndex(b, from, s) {
1712
+ outer: for (let i = b.length - s.length; i >= from; i--) {
1713
+ for (let j = 0; j < s.length; j++) if (b[i + j] !== s.charCodeAt(j)) continue outer;
1714
+ return i;
1715
+ }
1716
+ return -1;
1717
+ }
1718
+
1719
+ // src/pades/validate/appearance.ts
1720
+ var AP_VERIFY_PREFIX = "https://ca.eidmongolia.mn/verify/";
1721
+ var AP_URL_RE = /^\/EIDVerify <<\/URL \(https:\/\/ca\.eidmongolia\.mn\/verify\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\/([1-9][0-9]?)\)>> BDC\n/;
1722
+ function onlyKeys(d, ...keys) {
1723
+ for (const k of d.keys()) if (!keys.includes(k)) return false;
1724
+ return true;
1725
+ }
1726
+ function ownVisible(c, d, widget) {
1727
+ const fail = errNotSignatureOnly;
1728
+ if (!onlyKeys(d, "Type", "Subtype", "Rect", "P", "F", "FT", "T", "V", "AP")) throw fail();
1729
+ const pr = dget(d, "P");
1730
+ const sr = dget(d, "V");
1731
+ const ap = dget(d, "AP");
1732
+ const t = dget(d, "T");
1733
+ if (!(pr instanceof PRef2) || !(sr instanceof PRef2) || !isDict(ap) || !(t instanceof PStr) || !onlyKeys(ap, "N") || !c.pages.has(pr.num)) throw fail();
1734
+ const nr = dget(ap, "N");
1735
+ if (!(nr instanceof PRef2)) throw fail();
1736
+ const { box, rot } = pageGeometry(c, pr.num);
1737
+ const ra = dget(d, "Rect");
1738
+ if (!isArr(ra) || ra.length !== 4) throw fail();
1739
+ const rect = [];
1740
+ for (const x of ra) {
1741
+ const v = pdfNumber(x);
1742
+ if (v === void 0) throw fail();
1743
+ rect.push(round100(v));
1744
+ }
1745
+ if (rect[0] >= rect[2] || rect[1] >= rect[3] || rect[0] < box[0] || rect[1] < box[1] || rect[2] > box[2] || rect[3] > box[3]) throw fail();
1746
+ let w = rect[2] - rect[0];
1747
+ let h = rect[3] - rect[1];
1748
+ if (rot === 90 || rot === 270) [w, h] = [h, w];
1749
+ sameObject(c, widget, latin1(visibleWidget(t.v, rect, pr.num, pr.gen, sr.num, nr.num)));
1750
+ const sd = c.fin.deref(sr);
1751
+ const meta = c.sigs.get(sr.num);
1752
+ if (!isDict(sd) || !meta || !meta.roleOK) throw fail();
1753
+ const ns = dget(sd, "Name");
1754
+ const ms = dget(sd, "M");
1755
+ if (!(ns instanceof PStr) || !(ms instanceof PStr)) throw fail();
1756
+ const m = ms.v;
1757
+ if (!ownDate(m) || m.slice(16) !== "+08'00'") throw fail();
1758
+ const date = `${m.slice(2, 6)}-${m.slice(6, 8)}-${m.slice(8, 10)} ${m.slice(10, 12)}:${m.slice(12, 14)} (+08)`;
1759
+ const ids = apIDs(c, nr);
1760
+ const form = c.fin.get(ids[0]);
1761
+ if (!(form instanceof PStream)) throw fail();
1762
+ let head = "";
1763
+ for (let i = 0; i < Math.min(form.data.length, 200); i++) head += String.fromCharCode(form.data[i]);
1764
+ const sm = AP_URL_RE.exec(head);
1765
+ if (!sm || sm[2] !== String(meta.revIndex) || c.docID !== "" && sm[1] !== c.docID) throw fail();
1766
+ const url = AP_VERIFY_PREFIX + sm[1] + "/" + sm[2];
1767
+ const name = pdfTextString(ns);
1768
+ for (const lang of ["mn", "en"]) {
1769
+ let bodies;
1770
+ try {
1771
+ bodies = appearanceObjects({ w, h, rotate: rot, name, role: meta.role, lang, date, url }, ids);
1772
+ } catch {
1773
+ throw fail();
1774
+ }
1775
+ let match = true;
1776
+ for (let i = 0; i < bodies.length; i++) {
1777
+ const b = bodies[i];
1778
+ try {
1779
+ sameObject(c, ids[i], typeof b === "string" ? latin1(b) : b);
1780
+ } catch (e) {
1781
+ if (!(e instanceof PdfObjError)) throw e;
1782
+ match = false;
1783
+ break;
1784
+ }
1785
+ }
1786
+ if (match) return;
1787
+ }
1788
+ throw fail();
1789
+ }
1790
+ function apIDs(c, n) {
1791
+ const fail = errNotSignatureOnly;
1792
+ const refs = [n];
1793
+ const get = (r) => {
1794
+ const o = c.fin.deref(r);
1795
+ if (isDict(o)) return o;
1796
+ if (o instanceof PStream) return o.dict;
1797
+ throw fail();
1798
+ };
1799
+ const form = get(n);
1800
+ const res = dget(form, "Resources");
1801
+ const fonts = dget(isDict(res) ? res : null, "Font");
1802
+ for (const key of ["F1", "F2"]) {
1803
+ const t0 = dget(isDict(fonts) ? fonts : null, key);
1804
+ if (!(t0 instanceof PRef2)) throw fail();
1805
+ const td = get(t0);
1806
+ const desc = dget(td, "DescendantFonts");
1807
+ const tu = dget(td, "ToUnicode");
1808
+ if ((isArr(desc) ? desc.length : 0) !== 1 || !(tu instanceof PRef2)) throw fail();
1809
+ const cid = desc[0];
1810
+ if (!(cid instanceof PRef2)) throw fail();
1811
+ const cd = get(cid);
1812
+ const fd = dget(cd, "FontDescriptor");
1813
+ if (!(fd instanceof PRef2)) throw fail();
1814
+ const fdd = get(fd);
1815
+ const ff = dget(fdd, "FontFile2");
1816
+ if (!(ff instanceof PRef2)) throw fail();
1817
+ refs.push(t0, cid, fd, ff, tu);
1818
+ }
1819
+ const seen = /* @__PURE__ */ new Set();
1820
+ const ids = [];
1821
+ for (const r of refs) {
1822
+ if (r.gen !== 0 || !c.isNew.has(r.num) || seen.has(r.num)) throw fail();
1823
+ seen.add(r.num);
1824
+ ids.push(r.num);
1825
+ }
1826
+ return ids;
1827
+ }
1828
+ var isSpaceByte = (x) => x === 9 || x === 10 || x === 11 || x === 12 || x === 13 || x === 32;
1829
+ function sameObject(c, num, body) {
1830
+ let s = 0;
1831
+ let e = body.length;
1832
+ while (s < e && isSpaceByte(body[s])) s++;
1833
+ while (e > s && isSpaceByte(body[e - 1])) e--;
1834
+ const pre = latin1(`${num} 0 obj
1835
+ `);
1836
+ const post = latin1("\nendobj\n");
1837
+ const src = new Uint8Array(pre.length + (e - s) + post.length);
1838
+ src.set(pre, 0);
1839
+ src.set(body.subarray(s, e), pre.length);
1840
+ src.set(post, pre.length + (e - s));
1841
+ const p = new PdfParser(src, 0, c.fin.budget);
1842
+ const want = p.indirect(void 0);
1843
+ const got = c.fin.get(num);
1844
+ if (!pdfEqual(got, want.val)) throw errNotSignatureOnly();
1845
+ }
1846
+ function pageGeometry(c, num) {
1847
+ const fail = errNotSignatureOnly;
1848
+ const inh = (key) => {
1849
+ let cur = new PRef2(num, 0);
1850
+ for (let i = 0; i < 32; i++) {
1851
+ if (!(cur instanceof PRef2)) return null;
1852
+ const o = c.fin.get(cur.num);
1853
+ if (!isDict(o)) throw fail();
1854
+ if (o.has(key)) return c.fin.resolve(dget(o, key));
1855
+ cur = dget(o, "Parent");
1856
+ }
1857
+ throw fail();
1858
+ };
1859
+ let b = inh("CropBox");
1860
+ if (b === null) b = inh("MediaBox");
1861
+ if (!isArr(b) || b.length !== 4) throw fail();
1862
+ const f = [];
1863
+ for (const x of b) {
1864
+ const v = pdfNumber(x);
1865
+ if (v === void 0) throw fail();
1866
+ f.push(round100(v));
1867
+ }
1868
+ const box = [Math.min(f[0], f[2]), Math.min(f[1], f[3]), Math.max(f[0], f[2]), Math.max(f[1], f[3])];
1869
+ let rot = 0;
1870
+ const r = inh("Rotate");
1871
+ if (r !== null) {
1872
+ if (!isInt(r) || r % 90n !== 0n) throw fail();
1873
+ rot = Number((r % 360n + 360n) % 360n);
1874
+ }
1875
+ return { box, rot };
1876
+ }
1877
+ function pdfNumber(x) {
1878
+ let v;
1879
+ if (isInt(x)) v = Number(x);
1880
+ else if (x instanceof PReal) v = x.v;
1881
+ else return void 0;
1882
+ return !Number.isNaN(v) && Math.abs(v) <= 1e7 ? v : void 0;
1883
+ }
1884
+
1885
+ // src/pades/validate/revisions.ts
1886
+ var errNotSignatureOnly = () => new PdfObjError("validate: \u0433\u0430\u0440\u044B\u043D \u04AF\u0441\u0433\u0438\u0439\u043D \u0434\u0430\u0440\u0430\u0430\u0445 \u04E9\u04E9\u0440\u0447\u043B\u04E9\u043B\u0442 \u0437\u04E9\u0432\u0448\u04E9\u04E9\u0440\u04E9\u0433\u0434\u0441\u04E9\u043D \u0436\u0430\u0433\u0441\u0430\u0430\u043B\u0442\u0430\u0434 \u0431\u0430\u0433\u0442\u0441\u0430\u043D\u0433\u04AF\u0439");
1887
+ var SIG_FIELD_KEYS = ["Type", "Subtype", "FT", "T", "TU", "V", "Rect", "P", "F", "Ff", "M", "AP"];
1888
+ var SIG_DICT_KEYS = [
1889
+ "Type",
1890
+ "Filter",
1891
+ "SubFilter",
1892
+ "Contents",
1893
+ "ByteRange",
1894
+ "Cert",
1895
+ "M",
1896
+ "Name",
1897
+ "Location",
1898
+ "Reason",
1899
+ "ContactInfo",
1900
+ "Reference",
1901
+ "Prop_Build",
1902
+ "Prop_AuthTime",
1903
+ "Prop_AuthType",
1904
+ "Changes",
1905
+ "R",
1906
+ "V",
1907
+ "TransformMethod",
1908
+ "TransformParams"
1909
+ ];
1910
+ var OWN_FIELD_KEYS = ["Type", "Subtype", "Rect", "P", "F", "FT", "T", "V"];
1911
+ var OWN_SIG_DICT_KEYS = ["Type", "Filter", "SubFilter", "Prop_Build", "ByteRange", "Contents", "TransformMethod", "TransformParams", "Name", "Location", "Reason", "ContactInfo", "M"];
1912
+ var PADES_SIG_DICT_KEYS = ["Type", "Filter", "SubFilter", "ByteRange", "Contents", "M", "Name", "Reason"];
1913
+ var OWN_TEXT_LIMIT = 256;
1914
+ var OWN_TEXT_FORBIDDEN = [" obj", "endobj", "stream", "xref", "trailer", "startxref", "%%EOF"];
1915
+ function decodeUTF16(units) {
1916
+ let out = "";
1917
+ for (let i = 0; i < units.length; i++) {
1918
+ const u = units[i];
1919
+ if (u >= 55296 && u < 56320 && i + 1 < units.length && units[i + 1] >= 56320 && units[i + 1] < 57344) {
1920
+ out += String.fromCodePoint(65536 + (u - 55296 << 10) + (units[i + 1] - 56320));
1921
+ i++;
1922
+ } else if (u >= 55296 && u < 57344) out += "\uFFFD";
1923
+ else out += String.fromCharCode(u);
1924
+ }
1925
+ return out;
1926
+ }
1927
+ function goUTF8(raw) {
1928
+ let out = "";
1929
+ const b = (i) => raw.charCodeAt(i);
1930
+ for (let i = 0; i < raw.length; ) {
1931
+ const c = b(i);
1932
+ if (c < 128) {
1933
+ out += raw[i];
1934
+ i++;
1935
+ continue;
1936
+ }
1937
+ let n = 0;
1938
+ let cp = 0;
1939
+ let lo = 128;
1940
+ let hi = 191;
1941
+ if (c >= 194 && c <= 223) {
1942
+ n = 1;
1943
+ cp = c & 31;
1944
+ } else if (c >= 224 && c <= 239) {
1945
+ n = 2;
1946
+ cp = c & 15;
1947
+ if (c === 224) lo = 160;
1948
+ if (c === 237) hi = 159;
1949
+ } else if (c >= 240 && c <= 244) {
1950
+ n = 3;
1951
+ cp = c & 7;
1952
+ if (c === 240) lo = 144;
1953
+ if (c === 244) hi = 143;
1954
+ }
1955
+ let ok = n > 0 && i + n < raw.length;
1956
+ if (ok) {
1957
+ for (let k = 1; k <= n; k++) {
1958
+ const x = b(i + k);
1959
+ const l = k === 1 ? lo : 128;
1960
+ const h = k === 1 ? hi : 191;
1961
+ if (Number.isNaN(x) || x < l || x > h) {
1962
+ ok = false;
1963
+ break;
1964
+ }
1965
+ cp = cp << 6 | x & 63;
1966
+ }
1967
+ }
1968
+ if (!ok) {
1969
+ out += "\uFFFD";
1970
+ i++;
1971
+ continue;
1972
+ }
1973
+ out += String.fromCodePoint(cp);
1974
+ i += n + 1;
1975
+ }
1976
+ return out;
1977
+ }
1978
+ function pdfTextString(s) {
1979
+ const raw = s.v;
1980
+ if (!raw.startsWith("\xFE\xFF")) return goUTF8(raw);
1981
+ const units = [];
1982
+ for (let i = 2; i + 1 < raw.length; i += 2) units.push(raw.charCodeAt(i) << 8 | raw.charCodeAt(i + 1));
1983
+ return decodeUTF16(units);
1984
+ }
1985
+ function ownText(v, limit) {
1986
+ if (!isStr(v) || v.v.length > limit) return void 0;
1987
+ const raw = v.v;
1988
+ const utf16be = raw.startsWith("\xFE\xFF");
1989
+ if (utf16be && raw.length % 2 !== 0) return void 0;
1990
+ const text = pdfTextString(v);
1991
+ for (const ch of text) {
1992
+ const r = ch.codePointAt(0);
1993
+ if (r < 32 || r === 127 || !utf16be && r > 126) return void 0;
1994
+ }
1995
+ for (const bad of OWN_TEXT_FORBIDDEN) if (raw.includes(bad) || text.includes(bad)) return void 0;
1996
+ return text;
1997
+ }
1998
+ function ownFieldName(s) {
1999
+ if (!s.startsWith("Signature ")) return false;
2000
+ const n = s.slice("Signature ".length);
2001
+ return n.length >= 1 && n.length <= 4 && n[0] !== "0" && /^[0-9]*$/.test(n);
2002
+ }
2003
+ function ownDate(s) {
2004
+ if (s.length !== 23 || s.slice(0, 2) !== "D:" || s[16] !== "+" && s[16] !== "-" || s[19] !== "'" || s[22] !== "'") return false;
2005
+ return /^[0-9]*$/.test(s.slice(2, 16) + s.slice(17, 19) + s.slice(20, 22));
2006
+ }
2007
+ var MODE_NUM = { broad: 0, own: 1, dssOnly: 2 };
2008
+ var NOTHING = { signaturesOnly: false, signatures: 0, visible: false };
2009
+ var Revisions = class {
2010
+ constructor(doc, known, profile) {
2011
+ this.doc = doc;
2012
+ this.known = known;
2013
+ this.profile = profile;
2014
+ }
2015
+ doc;
2016
+ known;
2017
+ profile;
2018
+ budget = newPDFBudget();
2019
+ views = /* @__PURE__ */ new Map();
2020
+ steps = /* @__PURE__ */ new Map();
2021
+ sigs = /* @__PURE__ */ new Map();
2022
+ docID = "";
2023
+ view(n) {
2024
+ if (this.views.has(n)) return this.views.get(n);
2025
+ let v;
2026
+ try {
2027
+ v = openView(this.doc.subarray(0, n), this.budget);
2028
+ } catch {
2029
+ v = null;
2030
+ }
2031
+ this.views.set(n, v);
2032
+ return v;
2033
+ }
2034
+ /** end (ByteRange-ийн төгсгөл)-ээс хойшхи өөрчлөлтийг ангилна. Алдаа бүр «зөвшөөрөгдөөгүй». */
2035
+ async later(end) {
2036
+ try {
2037
+ return this.laterSync(end);
2038
+ } catch {
2039
+ return { ...NOTHING };
2040
+ }
2041
+ }
2042
+ laterSync(end) {
2043
+ const n = this.doc.length;
2044
+ if (end <= 0 || end >= n) return { ...NOTHING };
2045
+ const fin = this.view(n);
2046
+ const base = this.view(end);
2047
+ if (!fin || !base) return { ...NOTHING };
2048
+ const k = fin.sections.length - base.sections.length;
2049
+ if (k < 1) return { ...NOTHING };
2050
+ const ends = [end];
2051
+ for (let i = k - 1; i >= 0; i--) {
2052
+ const s = fin.sections[i];
2053
+ const p = fin.parser(s.end);
2054
+ const at = p.startxref();
2055
+ let e = p.pos;
2056
+ if (i === 0) e = n;
2057
+ if (at === void 0 || at !== s.off || e <= ends[ends.length - 1]) return { ...NOTHING };
2058
+ ends.push(e);
2059
+ }
2060
+ const out = { signaturesOnly: true, signatures: 0, visible: false };
2061
+ let sigSteps = 0;
2062
+ for (let i = 1; i < ends.length; i++) {
2063
+ const hasSig = this.hasSig(ends[i - 1], ends[i]);
2064
+ if (hasSig) sigSteps++;
2065
+ const st = this.classify(ends[i - 1], ends[i], true, this.stepMode(hasSig));
2066
+ if (!st) return { ...NOTHING };
2067
+ out.signatures += st.signatures;
2068
+ out.visible = out.visible || st.visible;
2069
+ }
2070
+ if (k > 1) {
2071
+ let mode = "broad";
2072
+ if (sigSteps === k) mode = this.stepMode(true);
2073
+ else if (sigSteps === 0) mode = this.stepMode(false);
2074
+ const cum = this.classify(ends[0], n, false, mode);
2075
+ if (!cum || cum.signatures !== out.signatures) return { ...NOTHING };
2076
+ out.visible = out.visible || cum.visible;
2077
+ }
2078
+ return out;
2079
+ }
2080
+ stepMode(hasSig) {
2081
+ if (!hasSig) return "dssOnly";
2082
+ if (this.profile === "own") return "own";
2083
+ return "broad";
2084
+ }
2085
+ hasSig(from, to) {
2086
+ const base = this.view(from);
2087
+ const fin = this.view(to);
2088
+ if (!base || !fin) return true;
2089
+ for (const num of this.known.keys()) {
2090
+ if (inUse(ent(fin.xref, num)) && !inUse(ent(base.xref, num))) return true;
2091
+ }
2092
+ return false;
2093
+ }
2094
+ classify(from, to, strict, mode) {
2095
+ const key = `${from},${to},${MODE_NUM[mode] * 2 + (strict ? 1 : 0)}`;
2096
+ if (this.steps.has(key)) return this.steps.get(key);
2097
+ let res = null;
2098
+ const base = this.view(from);
2099
+ const fin = this.view(to);
2100
+ if (base && fin) {
2101
+ const c = new Classifier(base, fin, strict, this.known);
2102
+ c.sigs = this.sigs;
2103
+ c.docID = this.docID;
2104
+ c.own = mode === "own";
2105
+ c.dssOnly = mode === "dssOnly";
2106
+ c.ownProfile = this.profile === "own";
2107
+ let ok = true;
2108
+ try {
2109
+ c.run();
2110
+ } catch (e) {
2111
+ if (!(e instanceof PdfObjError)) throw e;
2112
+ ok = false;
2113
+ }
2114
+ if (ok) res = { signaturesOnly: true, signatures: c.sigDicts.size, visible: c.visible };
2115
+ }
2116
+ this.steps.set(key, res);
2117
+ return res;
2118
+ }
2119
+ };
2120
+ var ek = (a, b) => `${a},${b}`;
2121
+ function sameExcept(a, b, ...keys) {
2122
+ for (const d of [a, b]) {
2123
+ if (!d) continue;
2124
+ for (const k of d.keys()) {
2125
+ if (!keys.includes(k) && !pdfEqual(dget(a, k), dget(b, k))) return false;
2126
+ }
2127
+ }
2128
+ return true;
2129
+ }
2130
+ function onlyKeys2(d, ...keys) {
2131
+ if (!d) return true;
2132
+ for (const k of d.keys()) if (!keys.includes(k)) return false;
2133
+ return true;
2134
+ }
2135
+ function sortedKeys(d) {
2136
+ return d ? [...d.keys()].sort((x, y) => x < y ? -1 : x > y ? 1 : 0) : [];
2137
+ }
2138
+ function pdfVersion(s) {
2139
+ if (s.length !== 3 || s[1] !== "." || s[0] !== "1" && s[0] !== "2" || s[2] < "0" || s[2] > "9") return void 0;
2140
+ return (s.charCodeAt(0) - 48) * 10 + (s.charCodeAt(2) - 48);
2141
+ }
2142
+ function trailerCompatible(base, later, infoOmitted) {
2143
+ if (!infoOmitted && !pdfEqual(dget(later, "Info"), dget(base, "Info"))) return false;
2144
+ const bid = dget(base, "ID");
2145
+ if (isArr(bid) && bid.length === 2 && later.has("ID")) {
2146
+ const a = dget(later, "ID");
2147
+ if (!isArr(a) || a.length !== 2 || !pdfEqual(a[0], bid[0])) return false;
2148
+ }
2149
+ const bsv = dget(base, "Size");
2150
+ const bs = isInt(bsv) ? bsv : 0n;
2151
+ const ls = dget(later, "Size");
2152
+ return isInt(ls) && ls >= bs;
2153
+ }
2154
+ var LTV_ROLES = ["catalog", "dss", "vri", "vrient", "ltvarr", "ltv", "info", "metadata"];
2155
+ var Classifier = class {
2156
+ constructor(base, fin, strict, known) {
2157
+ this.base = base;
2158
+ this.fin = fin;
2159
+ this.strict = strict;
2160
+ this.known = known;
2161
+ this.end = base.b.length;
2162
+ }
2163
+ base;
2164
+ fin;
2165
+ strict;
2166
+ known;
2167
+ end;
2168
+ own = false;
2169
+ dssOnly = false;
2170
+ ltvWork = false;
2171
+ infoWork = false;
2172
+ ownProfile = false;
2173
+ rewritten = /* @__PURE__ */ new Set();
2174
+ ownRewrite = /* @__PURE__ */ new Set();
2175
+ root = 0;
2176
+ changed = /* @__PURE__ */ new Set();
2177
+ isNew = /* @__PURE__ */ new Set();
2178
+ allowed = /* @__PURE__ */ new Set();
2179
+ exclusive = /* @__PURE__ */ new Set();
2180
+ infra = /* @__PURE__ */ new Set();
2181
+ xrefSelf = /* @__PURE__ */ new Set();
2182
+ edges = /* @__PURE__ */ new Map();
2183
+ sigDicts = /* @__PURE__ */ new Set();
2184
+ widgets = /* @__PURE__ */ new Set();
2185
+ role = /* @__PURE__ */ new Map();
2186
+ seen = /* @__PURE__ */ new Set();
2187
+ pages = /* @__PURE__ */ new Set();
2188
+ widgetP = /* @__PURE__ */ new Map();
2189
+ widgetPage = /* @__PURE__ */ new Map();
2190
+ annotsOf = /* @__PURE__ */ new Map();
2191
+ fieldNames = /* @__PURE__ */ new Set();
2192
+ visible = false;
2193
+ ownVis = /* @__PURE__ */ new Set();
2194
+ sigs = /* @__PURE__ */ new Map();
2195
+ docID = "";
2196
+ sigWork = false;
2197
+ edge(a, b) {
2198
+ const key = ek(a, b);
2199
+ this.edges.set(key, (this.edges.get(key) ?? 0) + 1);
2200
+ }
2201
+ claim(num, role) {
2202
+ const r = this.role.get(num);
2203
+ if (r !== void 0 && r !== role) throw errNotSignatureOnly();
2204
+ this.role.set(num, role);
2205
+ }
2206
+ run() {
2207
+ this.structure();
2208
+ this.diff();
2209
+ const refs = this.fin.graph();
2210
+ const reach = /* @__PURE__ */ new Set();
2211
+ const queue = [];
2212
+ pdfRefs(this.fin.trailer, (r) => queue.push(r.num));
2213
+ while (queue.length > 0) {
2214
+ const n = queue.pop();
2215
+ if (reach.has(n) || !inUse(ent(this.fin.xref, n))) continue;
2216
+ reach.add(n);
2217
+ queue.push(...refs.get(n) ?? []);
2218
+ }
2219
+ for (const n of this.isNew) if (this.strict || reach.has(n)) this.exclusive.add(n);
2220
+ let dangling = false;
2221
+ const markNew = (r) => {
2222
+ dangling = dangling || this.isNew.has(r.num);
2223
+ };
2224
+ pdfRefs(this.base.trailer, markNew);
2225
+ for (const [num, e] of this.fin.xref) {
2226
+ if (!inUse(e) || this.isNew.has(num)) continue;
2227
+ if (this.changed.has(num)) {
2228
+ pdfRefs(this.base.get(num), markNew);
2229
+ } else {
2230
+ for (const to of refs.get(num) ?? []) dangling = dangling || this.isNew.has(to);
2231
+ }
2232
+ }
2233
+ if (dangling) throw errNotSignatureOnly();
2234
+ this.catalog();
2235
+ for (const p of [...this.pages].sort((a, b) => a - b)) this.page(p);
2236
+ for (const n of this.ownRewrite) {
2237
+ const r = this.role.get(n);
2238
+ if (!this.changed.has(n) || !this.allowed.has(n) || r !== "page" && r !== "annots") throw errNotSignatureOnly();
2239
+ }
2240
+ for (const [w, p] of this.widgetP) {
2241
+ const placed = this.widgetPage.has(w);
2242
+ const at = this.widgetPage.get(w) ?? 0;
2243
+ if (p !== 0 && (!this.pages.has(p) || placed && at !== p) || this.ownVis.has(w) && (!placed || at !== p)) throw errNotSignatureOnly();
2244
+ }
2245
+ if (this.dssOnly) this.info();
2246
+ for (const n of this.changed) {
2247
+ if (!this.allowed.has(n) && !this.infra.has(n) && (this.strict || reach.has(n))) throw errNotSignatureOnly();
2248
+ const r = this.role.get(n);
2249
+ if (this.own && !this.isNew.has(n) && !(this.allowed.has(n) && (r === "page" || r === "annots"))) throw errNotSignatureOnly();
2250
+ }
2251
+ if (this.dssOnly) this.dssOnlyRules();
2252
+ if (this.own) {
2253
+ if (!this.isNew.has(this.root) || this.sigDicts.size !== this.widgets.size || this.sigDicts.size === 0 || this.strict && this.sigDicts.size !== 1 || this.visible && this.ownVis.size === 0) {
2254
+ throw errNotSignatureOnly();
2255
+ }
2256
+ for (const n of this.isNew) {
2257
+ const r = this.role.get(n) ?? "";
2258
+ if (this.strict && !this.xrefSelf.has(n) && r !== "sig" && r !== "field" && r !== "catalog" && (r !== "ap" || this.ownVis.size === 0)) {
2259
+ throw errNotSignatureOnly();
2260
+ }
2261
+ }
2262
+ }
2263
+ for (const [from, tos] of refs) {
2264
+ if (!this.strict && !reach.has(from) || this.infra.has(from)) continue;
2265
+ const count = /* @__PURE__ */ new Map();
2266
+ for (const to of tos) if (this.exclusive.has(to)) count.set(to, (count.get(to) ?? 0) + 1);
2267
+ for (const [to, n] of count) if ((this.edges.get(ek(from, to)) ?? 0) !== n) throw errNotSignatureOnly();
2268
+ }
2269
+ let bad = false;
2270
+ for (const [k, v] of this.fin.trailer) {
2271
+ if (k !== "Root") pdfRefs(v, (r) => bad = bad || this.exclusive.has(r.num));
2272
+ }
2273
+ if (bad || this.sigDicts.size === 0 && this.sigWork) throw errNotSignatureOnly();
2274
+ }
2275
+ /** xref гинж, trailer, мужийн дараах байтуудын бүрэн хамралт. */
2276
+ structure() {
2277
+ const fs = this.fin.sections;
2278
+ const bs = this.base.sections;
2279
+ const k = fs.length - bs.length;
2280
+ if (k < 1 || this.strict && k !== 1) throw errNotSignatureOnly();
2281
+ for (let i = 0; i < bs.length; i++) if (fs[k + i].off !== bs[i].off) throw errNotSignatureOnly();
2282
+ const lin = this.fin.parser(0);
2283
+ lin.skip();
2284
+ let linearized = false;
2285
+ try {
2286
+ const o = lin.indirect(void 0);
2287
+ linearized = isDict(o.val) && dget(o.val, "Linearized") !== null && ifaceEq(dget(o.val, "L"), BigInt(this.fin.b.length));
2288
+ } catch {
2289
+ }
2290
+ if (linearized) throw errNotSignatureOnly();
2291
+ const spans = [];
2292
+ for (const s of fs.slice(0, k)) {
2293
+ const infoOmitted = this.own && isName(dget(s.trailer, "Type"), "XRef") && dget(s.trailer, "Info") === null;
2294
+ if (s.off < this.end || !trailerCompatible(this.base.trailer, s.trailer, infoOmitted)) throw errNotSignatureOnly();
2295
+ const p = this.fin.parser(s.end);
2296
+ const at = p.startxref();
2297
+ if (at === void 0 || at !== s.off) throw errNotSignatureOnly();
2298
+ spans.push([s.start, p.pos]);
2299
+ const keys = ["Size", "Root", "Info", "ID", "Prev"];
2300
+ if (this.fin.b[s.start] === 120) {
2301
+ for (let i = s.start; i < s.end; i++) {
2302
+ const c = this.fin.b[i];
2303
+ if (c === 0 || c === 37) throw errNotSignatureOnly();
2304
+ }
2305
+ } else {
2306
+ keys.push("Type", "W", "Index", "Length", "Filter", "DecodeParms");
2307
+ const sp = this.fin.parser(s.start);
2308
+ sp.strict = true;
2309
+ sp.indirect(void 0);
2310
+ }
2311
+ if (!onlyKeys2(s.trailer, ...keys)) throw errNotSignatureOnly();
2312
+ const packed = /* @__PURE__ */ new Map();
2313
+ for (const [num, e] of s.ents) {
2314
+ if (this.own && e.kind !== ENT_USE) throw errNotSignatureOnly();
2315
+ if (this.own && inUse(ent(this.base.xref, num))) this.ownRewrite.add(num);
2316
+ if (this.dssOnly && this.ownProfile && inUse(e) && inUse(ent(this.base.xref, num))) this.rewritten.add(num);
2317
+ if (e.kind === ENT_USE) {
2318
+ const c = this.fin.b[e.off];
2319
+ if (e.off < this.end || e.off >= this.fin.b.length || c === void 0 || c < 48 || c > 57) throw errNotSignatureOnly();
2320
+ if (e.off === s.start) {
2321
+ this.infra.add(num);
2322
+ this.xrefSelf.add(num);
2323
+ continue;
2324
+ }
2325
+ const p2 = this.fin.parser(e.off);
2326
+ p2.strict = true;
2327
+ const o = p2.indirect((r) => this.fin.length(r));
2328
+ if (o.num !== num || o.gen !== e.gen) throw errNotSignatureOnly();
2329
+ spans.push([e.off, p2.pos]);
2330
+ } else if (e.kind === ENT_COMP) {
2331
+ const st = ent(this.fin.xref, e.off);
2332
+ if (st.kind !== ENT_USE || st.off < this.end) throw errNotSignatureOnly();
2333
+ if (this.own) throw errNotSignatureOnly();
2334
+ packed.set(e.off, (packed.get(e.off) ?? 0) + 1);
2335
+ }
2336
+ }
2337
+ for (const [stm, n] of packed) {
2338
+ if (!this.strict) continue;
2339
+ const st = this.fin.objStm(stm);
2340
+ if (!s.ents.has(stm) || st.nums.length !== n) throw errNotSignatureOnly();
2341
+ for (const off of st.offs) {
2342
+ const sp = new PdfParser(st.data, Math.min(st.first + off, st.data.length), this.fin.budget, true);
2343
+ sp.value(0);
2344
+ }
2345
+ this.infra.add(stm);
2346
+ }
2347
+ }
2348
+ spans.sort((a, b) => a[0] - b[0]);
2349
+ let cur = this.end;
2350
+ for (const sp of spans) {
2351
+ if (sp[0] < cur || !allGapSpace(this.fin.b.subarray(cur, sp[0]))) throw errNotSignatureOnly();
2352
+ cur = sp[1];
2353
+ }
2354
+ if (!allGapSpace(this.fin.b.subarray(cur))) throw errNotSignatureOnly();
2355
+ }
2356
+ /** Суурь ба эцсийн xref-ийг харьцуулж changed/isNew-г бөглөнө. */
2357
+ diff() {
2358
+ for (const [num, be] of this.base.xref) {
2359
+ if (!inUse(be)) continue;
2360
+ if (be.kind === ENT_USE && be.off >= this.end) throw errNotSignatureOnly();
2361
+ if (!inUse(ent(this.fin.xref, num))) throw errNotSignatureOnly();
2362
+ }
2363
+ for (const [num, fe] of this.fin.xref) {
2364
+ if (!inUse(fe)) continue;
2365
+ const be = ent(this.base.xref, num);
2366
+ if (!inUse(be)) {
2367
+ this.isNew.add(num);
2368
+ this.changed.add(num);
2369
+ continue;
2370
+ }
2371
+ if (entEq(be, fe) && (be.kind === ENT_USE || entEq(ent(this.base.xref, be.off), ent(this.fin.xref, fe.off)))) continue;
2372
+ const bo = this.base.get(num);
2373
+ const fo = this.fin.get(num);
2374
+ const unpack = be.kind === ENT_COMP && fe.kind === ENT_USE && fe.gen === 0 && (this.own || !this.strict && this.ownProfile && !this.dssOnly);
2375
+ if ((be.kind !== fe.kind || be.gen !== fe.gen) && !unpack) throw errNotSignatureOnly();
2376
+ if (unpack && pdfEqual(bo, fo)) throw errNotSignatureOnly();
2377
+ if (!pdfEqual(bo, fo)) this.changed.add(num);
2378
+ }
2379
+ }
2380
+ /** Эцсийн талын утга fv-г задална; ref бол заасан объект нь шинэ эсвэл суурьт ЯГ энэ байрлалд байсан. */
2381
+ container(bv, fv, owner, role) {
2382
+ if (!(fv instanceof PRef2)) return [fv, owner];
2383
+ if (!this.isNew.has(fv.num) && !ifaceEq(bv, fv)) throw errNotSignatureOnly();
2384
+ this.claim(fv.num, role);
2385
+ const val = this.fin.deref(fv);
2386
+ this.edge(owner, fv.num);
2387
+ if (this.changed.has(fv.num)) this.allowed.add(fv.num);
2388
+ return [val, fv.num];
2389
+ }
2390
+ baseDict(v) {
2391
+ const o = this.base.resolve(v);
2392
+ if (o === null) return null;
2393
+ if (!isDict(o)) throw errNotSignatureOnly();
2394
+ return o;
2395
+ }
2396
+ baseArr(v) {
2397
+ const o = this.base.resolve(v);
2398
+ if (o === null) return null;
2399
+ if (!isArr(o)) throw errNotSignatureOnly();
2400
+ return o;
2401
+ }
2402
+ catalog() {
2403
+ const fr = dget(this.fin.trailer, "Root");
2404
+ const br = dget(this.base.trailer, "Root");
2405
+ if (!isRef(fr) || !isRef(br) || fr.num !== br.num && !this.isNew.has(fr.num)) throw errNotSignatureOnly();
2406
+ const fc = this.fin.deref(fr);
2407
+ const bc = this.base.deref(br);
2408
+ const except = ["AcroForm", "DSS", "Perms", "Version"];
2409
+ if (this.dssOnly) except.push("Extensions", "Metadata");
2410
+ if (!isDict(fc) || !isDict(bc) || !sameExcept(bc, fc, ...except)) throw errNotSignatureOnly();
2411
+ if (this.own) {
2412
+ if (!sameExcept(bc, fc, "AcroForm", "Version") || !pdfEqual(dget(bc, "Version"), dget(fc, "Version")) && (dget(bc, "Version") !== null || !ifaceEq(dget(fc, "Version"), new PName("1.5")))) {
2413
+ throw errNotSignatureOnly();
2414
+ }
2415
+ }
2416
+ this.root = fr.num;
2417
+ this.allowed.add(fr.num);
2418
+ this.claim(fr.num, "catalog");
2419
+ this.pageTree(dget(fc, "Pages"));
2420
+ if (!pdfEqual(dget(bc, "Version"), dget(fc, "Version"))) {
2421
+ const fvn = dget(fc, "Version");
2422
+ const nv = pdfVersion(fvn instanceof PName ? fvn.v : "");
2423
+ const bb = this.base.b;
2424
+ let head = "";
2425
+ for (let i = Math.min(bb.length, 5); i < Math.min(bb.length, 8); i++) head += String.fromCharCode(bb[i]);
2426
+ let floor = pdfVersion(head);
2427
+ let ok2 = floor !== void 0;
2428
+ if (bc.has("Version")) {
2429
+ const bn = dget(bc, "Version");
2430
+ const bv = pdfVersion(bn instanceof PName ? bn.v : "");
2431
+ ok2 = ok2 && bv !== void 0;
2432
+ floor = Math.max(floor ?? 0, bv ?? 0);
2433
+ }
2434
+ let pfx = "";
2435
+ for (let i = 0; i < Math.min(5, bb.length); i++) pfx += String.fromCharCode(bb[i]);
2436
+ if (nv === void 0 || !ok2 || pfx !== "%PDF-" || nv < (floor ?? 0)) throw errNotSignatureOnly();
2437
+ if (this.dssOnly) this.infoWork = true;
2438
+ else this.sigWork = true;
2439
+ }
2440
+ if (this.dssOnly) {
2441
+ this.extensions(dget(bc, "Extensions"), dget(fc, "Extensions"));
2442
+ this.metadata(dget(bc, "Metadata"), dget(fc, "Metadata"));
2443
+ }
2444
+ this.acroForm(dget(bc, "AcroForm"), dget(fc, "AcroForm"));
2445
+ if (!pdfEqual(dget(bc, "Perms"), dget(fc, "Perms"))) {
2446
+ this.sigWork = true;
2447
+ const bpd = this.baseDict(dget(bc, "Perms"));
2448
+ const [pv, pn] = this.container(dget(bc, "Perms"), dget(fc, "Perms"), this.root, "perms");
2449
+ if (!isDict(pv) || !onlyKeys2(pv, "DocMDP", "UR", "UR3")) throw errNotSignatureOnly();
2450
+ for (const key of sortedKeys(pv)) {
2451
+ const r = dget(pv, key);
2452
+ if (!isRef(r) || !this.sigDicts.has(r.num) && (this.changed.has(r.num) || !ifaceEq(dget(bpd, key), r))) throw errNotSignatureOnly();
2453
+ this.edge(pn, r.num);
2454
+ }
2455
+ }
2456
+ this.dss(dget(bc, "DSS"), dget(fc, "DSS"));
2457
+ }
2458
+ pageTree(root) {
2459
+ const stack = [root];
2460
+ const visited = /* @__PURE__ */ new Set();
2461
+ while (stack.length > 0) {
2462
+ const r = stack.pop();
2463
+ if (!(r instanceof PRef2) || visited.has(r.num)) throw errNotSignatureOnly();
2464
+ visited.add(r.num);
2465
+ const o = this.fin.deref(r);
2466
+ const d = isDict(o) ? o : null;
2467
+ const t = dget(d, "Type");
2468
+ if (ifaceEq(t, new PName("Page"))) this.pages.add(r.num);
2469
+ else if (ifaceEq(t, new PName("Pages"))) {
2470
+ const kids = this.fin.resolve(dget(d, "Kids"));
2471
+ if (!isArr(kids)) throw errNotSignatureOnly();
2472
+ stack.push(...kids);
2473
+ } else throw errNotSignatureOnly();
2474
+ }
2475
+ }
2476
+ page(p) {
2477
+ const fo = this.fin.get(p);
2478
+ if (!isDict(fo) || this.isNew.has(p)) throw errNotSignatureOnly();
2479
+ const fd = fo;
2480
+ let bd = fd;
2481
+ if (this.changed.has(p)) {
2482
+ const bo = this.base.get(p);
2483
+ if (!isDict(bo) || !sameExcept(bo, fd, "Annots")) throw errNotSignatureOnly();
2484
+ bd = bo;
2485
+ this.claim(p, "page");
2486
+ this.sigWork = true;
2487
+ this.allowed.add(p);
2488
+ }
2489
+ const ar = dget(fd, "Annots");
2490
+ if (!this.changed.has(p) && !(ar instanceof PRef2 && this.changed.has(ar.num))) return;
2491
+ if (ar === null) {
2492
+ if (dget(bd, "Annots") !== null) throw errNotSignatureOnly();
2493
+ return;
2494
+ }
2495
+ const ba = this.baseArr(dget(bd, "Annots")) ?? [];
2496
+ const [v, anum] = this.container(dget(bd, "Annots"), ar, p, "annots");
2497
+ if (!isArr(v)) throw errNotSignatureOnly();
2498
+ const fa = v;
2499
+ if (anum !== p) {
2500
+ if (this.annotsOf.has(anum)) throw errNotSignatureOnly();
2501
+ this.annotsOf.set(anum, p);
2502
+ if (this.changed.has(anum)) {
2503
+ this.sigWork = true;
2504
+ this.exclusive.add(anum);
2505
+ }
2506
+ }
2507
+ if (fa.length < ba.length) throw errNotSignatureOnly();
2508
+ for (let i = 0; i < fa.length; i++) {
2509
+ const e = fa[i];
2510
+ if (i < ba.length) {
2511
+ if (!pdfEqual(ba[i], e)) throw errNotSignatureOnly();
2512
+ continue;
2513
+ }
2514
+ const num = e instanceof PRef2 ? e.num : 0;
2515
+ if (!(e instanceof PRef2) || !this.widgets.has(num) || this.widgetPage.has(num)) throw errNotSignatureOnly();
2516
+ this.widgetPage.set(num, p);
2517
+ this.edge(anum, num);
2518
+ }
2519
+ }
2520
+ acroForm(bv, fv) {
2521
+ if (fv === null) {
2522
+ if (bv !== null) throw errNotSignatureOnly();
2523
+ return;
2524
+ }
2525
+ const bd = this.baseDict(bv);
2526
+ const [v, num] = this.container(bv, fv, this.root, "acroform");
2527
+ if (!isDict(v) || !sameExcept(bd, v, "Fields", "SigFlags")) throw errNotSignatureOnly();
2528
+ const fd = v;
2529
+ if (!pdfEqual(dget(bd, "SigFlags"), dget(fd, "SigFlags"))) {
2530
+ const nf = dget(fd, "SigFlags");
2531
+ const ofv = dget(bd, "SigFlags");
2532
+ const was = isInt(ofv);
2533
+ const of = was ? ofv : 0n;
2534
+ if (!isInt(nf) || nf !== 1n && nf !== 3n || ofv !== null && !was || nf < of) throw errNotSignatureOnly();
2535
+ }
2536
+ if (!pdfEqual(dget(bd, "SigFlags"), dget(fd, "SigFlags")) || bd === null) this.sigWork = true;
2537
+ if (this.own) {
2538
+ if (!isDict(fv) || !isArr(dget(fd, "Fields")) || !ifaceEq(dget(fd, "SigFlags"), 3n)) throw errNotSignatureOnly();
2539
+ }
2540
+ const bf = this.baseArr(dget(bd, "Fields")) ?? [];
2541
+ if (this.own) {
2542
+ for (const e of bf) {
2543
+ const o = this.base.resolve(e);
2544
+ if (!isDict(o) || !(e instanceof PRef2)) throw errNotSignatureOnly();
2545
+ const t = dget(o, "T");
2546
+ if (t instanceof PStr) this.fieldNames.add(pdfTextString(t));
2547
+ }
2548
+ }
2549
+ const [fv2, fnum] = this.container(dget(bd, "Fields"), dget(fd, "Fields"), num, "fields");
2550
+ if (fv2 !== null && !isArr(fv2) || (isArr(fv2) ? fv2.length : 0) < bf.length) throw errNotSignatureOnly();
2551
+ const ff = isArr(fv2) ? fv2 : [];
2552
+ for (let i = 0; i < ff.length; i++) {
2553
+ const e = ff[i];
2554
+ if (i < bf.length) {
2555
+ if (!pdfEqual(bf[i], e)) throw errNotSignatureOnly();
2556
+ if (e instanceof PRef2 && this.changed.has(e.num)) {
2557
+ if (this.own) throw errNotSignatureOnly();
2558
+ this.filledField(e.num);
2559
+ }
2560
+ } else if (!(e instanceof PRef2)) throw errNotSignatureOnly();
2561
+ else this.newField(e, fnum);
2562
+ }
2563
+ }
2564
+ newField(r, owner) {
2565
+ if (!this.isNew.has(r.num) || this.widgets.has(r.num)) throw errNotSignatureOnly();
2566
+ const d = this.fin.deref(r);
2567
+ if (!isDict(d) || !onlyKeys2(d, ...SIG_FIELD_KEYS) || !ifaceEq(dget(d, "FT"), new PName("Sig"))) throw errNotSignatureOnly();
2568
+ if (d.has("Type") && !ifaceEq(dget(d, "Type"), new PName("Annot"))) throw errNotSignatureOnly();
2569
+ if (d.has("Subtype") && !ifaceEq(dget(d, "Subtype"), new PName("Widget"))) throw errNotSignatureOnly();
2570
+ for (const k of ["T", "TU", "M"]) if (d.has(k) && !isStr(dget(d, k))) throw errNotSignatureOnly();
2571
+ for (const k of ["F", "Ff"]) if (d.has(k) && !isInt(dget(d, k))) throw errNotSignatureOnly();
2572
+ if (this.own) {
2573
+ if (d.has("AP")) {
2574
+ ownVisible(this, d, r.num);
2575
+ this.ownVis.add(r.num);
2576
+ } else if (!onlyKeys2(d, ...OWN_FIELD_KEYS) || !ifaceEq(dget(d, "Type"), new PName("Annot")) || !ifaceEq(dget(d, "Subtype"), new PName("Widget")) || !pdfEqual(dget(d, "Rect"), [0n, 0n, 0n, 0n]) || !ifaceEq(dget(d, "F"), 132n)) {
2577
+ throw errNotSignatureOnly();
2578
+ }
2579
+ const name = ownText(dget(d, "T"), 32);
2580
+ if (name === void 0 || !ownFieldName(name) || !ifaceEq(dget(d, "T"), new PStr(name)) || this.fieldNames.has(name)) throw errNotSignatureOnly();
2581
+ this.fieldNames.add(name);
2582
+ }
2583
+ this.widgetP.set(r.num, 0);
2584
+ if (d.has("P")) {
2585
+ const pr = dget(d, "P");
2586
+ if (!(pr instanceof PRef2)) throw errNotSignatureOnly();
2587
+ this.widgetP.set(r.num, pr.num);
2588
+ }
2589
+ this.claim(r.num, "field");
2590
+ this.sigWork = true;
2591
+ this.widgets.add(r.num);
2592
+ this.allowed.add(r.num);
2593
+ this.edge(owner, r.num);
2594
+ this.sigValue(dget(d, "V"), r.num);
2595
+ this.appearance(null, d, r.num);
2596
+ }
2597
+ filledField(num) {
2598
+ const bd = this.base.get(num);
2599
+ const fd = this.fin.get(num);
2600
+ if (!isDict(bd) || !isDict(fd) || !ifaceEq(dget(bd, "FT"), new PName("Sig")) || dget(bd, "V") !== null || dget(bd, "Kids") !== null || !sameExcept(bd, fd, "V", "AP", "M")) {
2601
+ throw errNotSignatureOnly();
2602
+ }
2603
+ if (bd.has("Type") && !ifaceEq(dget(bd, "Type"), new PName("Annot"))) throw errNotSignatureOnly();
2604
+ if (bd.has("Subtype") && !ifaceEq(dget(bd, "Subtype"), new PName("Widget"))) throw errNotSignatureOnly();
2605
+ if (fd.has("M") && !isStr(dget(fd, "M"))) throw errNotSignatureOnly();
2606
+ this.claim(num, "field");
2607
+ this.sigWork = true;
2608
+ this.allowed.add(num);
2609
+ this.sigValue(dget(fd, "V"), num);
2610
+ this.appearance(bd, fd, num);
2611
+ }
2612
+ sigValue(v, owner) {
2613
+ if (!(v instanceof PRef2) || !this.isNew.has(v.num) || this.sigDicts.has(v.num)) throw errNotSignatureOnly();
2614
+ const r = v;
2615
+ this.claim(r.num, "sig");
2616
+ const d = this.fin.deref(r);
2617
+ if (!isDict(d) || !onlyKeys2(d, ...SIG_DICT_KEYS)) throw errNotSignatureOnly();
2618
+ if (this.own && (!onlyKeys2(d, ...OWN_SIG_DICT_KEYS) || !ifaceEq(dget(d, "Type"), new PName("Sig")))) throw errNotSignatureOnly();
2619
+ if (this.own) {
2620
+ if (ifaceEq(dget(d, "SubFilter"), new PName("ETSI.CAdES.detached")) && (!onlyKeys2(d, ...PADES_SIG_DICT_KEYS) || !ifaceEq(dget(d, "Filter"), new PName("Adobe.PPKLite")) || dget(d, "M") === null)) {
2621
+ throw errNotSignatureOnly();
2622
+ }
2623
+ for (const k of ["Name", "Location", "Reason", "ContactInfo", "M"]) {
2624
+ if (!d.has(k)) continue;
2625
+ const text = ownText(dget(d, k), OWN_TEXT_LIMIT);
2626
+ if (text === void 0 || k === "M" && !ownDate(text)) throw errNotSignatureOnly();
2627
+ }
2628
+ }
2629
+ if (d.has("Type") && !ifaceEq(dget(d, "Type"), new PName("Sig"))) throw errNotSignatureOnly();
2630
+ const br = dget(d, "ByteRange");
2631
+ if (!isArr(br) || !isStr(dget(d, "Contents")) || br.length !== 4) throw errNotSignatureOnly();
2632
+ const n = [];
2633
+ for (const x of br) {
2634
+ if (!isInt(x)) throw errNotSignatureOnly();
2635
+ n.push(x);
2636
+ }
2637
+ if (n[0] !== 0n || n[1] <= 0n || n[2] <= n[1] || n[3] < 0n || n[2] + n[3] <= BigInt(this.end)) throw errNotSignatureOnly();
2638
+ const kb = this.known.get(r.num);
2639
+ if (!kb || kb.length !== 4 || kb.some((x, i) => BigInt(x) !== n[i])) throw errNotSignatureOnly();
2640
+ let bad = false;
2641
+ for (const [k, val] of d) {
2642
+ if (k !== "Reference") {
2643
+ pdfRefs(val, () => bad = true);
2644
+ continue;
2645
+ }
2646
+ bad = bad || !isArr(val);
2647
+ for (const row of isArr(val) ? val : []) {
2648
+ if (!isDict(row) || !onlyKeys2(row, "Type", "TransformMethod", "TransformParams", "DigestMethod", "Data")) {
2649
+ bad = true;
2650
+ continue;
2651
+ }
2652
+ for (const [rk, rv] of row) {
2653
+ if (rk !== "Data") pdfRefs(rv, () => bad = true);
2654
+ else if (rv instanceof PRef2 && rv.num === this.root) this.edge(r.num, this.root);
2655
+ else if (rv instanceof PRef2 && ifaceEq(rv, dget(this.base.trailer, "Root"))) {
2656
+ } else bad = true;
2657
+ }
2658
+ }
2659
+ }
2660
+ if (bad) throw errNotSignatureOnly();
2661
+ this.sigDicts.add(r.num);
2662
+ this.allowed.add(r.num);
2663
+ this.edge(owner, r.num);
2664
+ }
2665
+ appearance(base, d, widget) {
2666
+ if (d.has("Rect")) {
2667
+ const a = dget(d, "Rect");
2668
+ if (!isArr(a) || a.length !== 4) throw errNotSignatureOnly();
2669
+ const f = [];
2670
+ for (const x of a) {
2671
+ if (isInt(x)) f.push(Number(x));
2672
+ else if (x instanceof PReal) f.push(x.v);
2673
+ else throw errNotSignatureOnly();
2674
+ }
2675
+ if (f[0] !== f[2] && f[1] !== f[3]) this.visible = true;
2676
+ }
2677
+ if (!d.has("AP")) return;
2678
+ const ap = dget(d, "AP");
2679
+ this.visible = true;
2680
+ if (pdfEqual(dget(base, "AP"), ap)) return;
2681
+ if (!isDict(ap) || !onlyKeys2(ap, "N", "R", "D")) throw errNotSignatureOnly();
2682
+ const queue = [];
2683
+ for (const key of sortedKeys(ap)) {
2684
+ const r = dget(ap, key);
2685
+ if (!(r instanceof PRef2) || !this.isNew.has(r.num)) throw errNotSignatureOnly();
2686
+ if (!(this.fin.deref(r) instanceof PStream)) throw errNotSignatureOnly();
2687
+ this.edge(widget, r.num);
2688
+ queue.push(r.num);
2689
+ }
2690
+ while (queue.length > 0) {
2691
+ const n = queue.pop();
2692
+ if (!this.changed.has(n)) continue;
2693
+ if (!this.isNew.has(n) || this.infra.has(n)) throw errNotSignatureOnly();
2694
+ this.claim(n, "ap");
2695
+ if (this.seen.has(n)) continue;
2696
+ this.seen.add(n);
2697
+ this.allowed.add(n);
2698
+ pdfRefs(this.fin.get(n), (t) => {
2699
+ this.edge(n, t.num);
2700
+ queue.push(t.num);
2701
+ });
2702
+ }
2703
+ }
2704
+ dssNode(bv, fv, owner, role) {
2705
+ const [v, num] = this.container(bv, fv, owner, role);
2706
+ if (num !== owner && this.changed.has(num)) {
2707
+ this.exclusive.add(num);
2708
+ this.ltvWork = true;
2709
+ }
2710
+ return [v, num];
2711
+ }
2712
+ baseLTVStreams(bd) {
2713
+ const out = /* @__PURE__ */ new Set();
2714
+ const add = (d, ...keys) => {
2715
+ for (const k of keys) {
2716
+ for (const e of this.baseArr(dget(d, k)) ?? []) if (e instanceof PRef2) out.add(e.num);
2717
+ }
2718
+ };
2719
+ add(bd, "Certs", "OCSPs", "CRLs");
2720
+ const vri = this.baseDict(dget(bd, "VRI"));
2721
+ for (const e of vri ? vri.values() : []) {
2722
+ const ed = this.baseDict(e);
2723
+ add(ed, "Cert", "OCSP", "CRL");
2724
+ const ts = dget(ed, "TS");
2725
+ if (ts instanceof PRef2) out.add(ts.num);
2726
+ }
2727
+ return out;
2728
+ }
2729
+ dss(bv, fv) {
2730
+ if (fv === null) {
2731
+ if (bv !== null) throw errNotSignatureOnly();
2732
+ return;
2733
+ }
2734
+ const bd = this.baseDict(bv);
2735
+ const old = this.baseLTVStreams(bd);
2736
+ const [v, num] = this.dssNode(bv, fv, this.root, "dss");
2737
+ if (!isDict(v) || !onlyKeys2(v, "Type", "VRI", "Certs", "OCSPs", "CRLs")) throw errNotSignatureOnly();
2738
+ const fd = v;
2739
+ for (const k of ["Certs", "OCSPs", "CRLs"]) this.ltvArray(dget(bd, k), dget(fd, k), num, old);
2740
+ if (dget(fd, "VRI") === null) return;
2741
+ const bvri = this.baseDict(dget(bd, "VRI"));
2742
+ const [vv, vnum] = this.dssNode(dget(bd, "VRI"), dget(fd, "VRI"), num, "vri");
2743
+ if (!isDict(vv)) throw errNotSignatureOnly();
2744
+ const fvri = vv;
2745
+ for (const key of sortedKeys(fvri)) {
2746
+ const bed = this.baseDict(dget(bvri, key));
2747
+ const [ev, enumv] = this.dssNode(dget(bvri, key), dget(fvri, key), vnum, "vrient");
2748
+ if (!isDict(ev) || !onlyKeys2(ev, "Type", "Cert", "OCSP", "CRL", "TU", "TS")) throw errNotSignatureOnly();
2749
+ const fed = ev;
2750
+ for (const k of ["Cert", "OCSP", "CRL"]) this.ltvArray(dget(bed, k), dget(fed, k), enumv, old);
2751
+ if (dget(fed, "TU") !== null && !isStr(dget(fed, "TU"))) throw errNotSignatureOnly();
2752
+ if (fed.has("TS")) this.ltvStream(dget(fed, "TS"), enumv, old);
2753
+ }
2754
+ }
2755
+ ltvArray(bv, fv, owner, old) {
2756
+ if (fv === null) return;
2757
+ const [v, num] = this.dssNode(bv, fv, owner, "ltvarr");
2758
+ if (!isArr(v)) throw errNotSignatureOnly();
2759
+ if (num !== owner) {
2760
+ if (this.seen.has(num)) return;
2761
+ this.seen.add(num);
2762
+ }
2763
+ for (const e of v) this.ltvStream(e, num, old);
2764
+ }
2765
+ ltvStream(v, owner, old) {
2766
+ if (!(v instanceof PRef2)) throw errNotSignatureOnly();
2767
+ const r = v;
2768
+ this.claim(r.num, "ltv");
2769
+ this.edge(owner, r.num);
2770
+ if (!this.isNew.has(r.num)) {
2771
+ if (this.changed.has(r.num) || !old.has(r.num)) throw errNotSignatureOnly();
2772
+ return;
2773
+ }
2774
+ const s = this.fin.deref(r);
2775
+ if (!(s instanceof PStream) || !onlyKeys2(s.dict, "Length", "Filter", "DecodeParms")) throw errNotSignatureOnly();
2776
+ let ok = true;
2777
+ pdfRefs(s.dict, () => ok = false);
2778
+ if (!ok) throw errNotSignatureOnly();
2779
+ this.allowed.add(r.num);
2780
+ this.ltvWork = true;
2781
+ }
2782
+ dssOnlyRules() {
2783
+ if (this.sigDicts.size > 0 || this.widgets.size > 0 || this.sigWork || this.visible || (this.infoWork || this.ownProfile) && !this.ltvWork) {
2784
+ throw errNotSignatureOnly();
2785
+ }
2786
+ for (const n of this.changed) {
2787
+ if (this.infra.has(n) || !this.strict && !this.allowed.has(n)) continue;
2788
+ if (!LTV_ROLES.includes(this.role.get(n) ?? "")) throw errNotSignatureOnly();
2789
+ }
2790
+ for (const n of this.rewritten) {
2791
+ if (!this.changed.has(n) || !this.allowed.has(n) || !LTV_ROLES.includes(this.role.get(n) ?? "")) throw errNotSignatureOnly();
2792
+ }
2793
+ }
2794
+ extensions(bv, fv) {
2795
+ if (pdfEqual(bv, fv)) return;
2796
+ if (!isDict(fv)) throw errNotSignatureOnly();
2797
+ const dev = (x) => {
2798
+ if (!isDict(x) || !onlyKeys2(x, "Type", "BaseVersion", "ExtensionLevel", "ExtensionRevision", "URL")) return false;
2799
+ if (!(dget(x, "BaseVersion") instanceof PName)) return false;
2800
+ if (!isInt(dget(x, "ExtensionLevel"))) return false;
2801
+ for (const k of ["ExtensionRevision", "URL"]) if (x.has(k) && !isStr(dget(x, k))) return false;
2802
+ if (x.has("Type") && !ifaceEq(dget(x, "Type"), new PName("DeveloperExtensions"))) return false;
2803
+ return true;
2804
+ };
2805
+ for (const [k, v] of fv) {
2806
+ if (k === "Type") {
2807
+ if (!ifaceEq(v, new PName("Extensions"))) throw errNotSignatureOnly();
2808
+ continue;
2809
+ }
2810
+ if (isArr(v)) {
2811
+ for (const e of v) if (!dev(e)) throw errNotSignatureOnly();
2812
+ } else if (!dev(v)) throw errNotSignatureOnly();
2813
+ }
2814
+ this.infoWork = true;
2815
+ }
2816
+ metadata(bv, fv) {
2817
+ if (pdfEqual(bv, fv) && (!(fv instanceof PRef2) || !this.changed.has(fv.num))) return;
2818
+ if (!(fv instanceof PRef2)) throw errNotSignatureOnly();
2819
+ const [v, num] = this.container(bv, fv, this.root, "metadata");
2820
+ if (!(v instanceof PStream) || !onlyKeys2(v.dict, "Type", "Subtype", "Length", "Filter", "DecodeParms") || !ifaceEq(dget(v.dict, "Type"), new PName("Metadata")) || !ifaceEq(dget(v.dict, "Subtype"), new PName("XML"))) {
2821
+ throw errNotSignatureOnly();
2822
+ }
2823
+ let bad = false;
2824
+ pdfRefs(v.dict, () => bad = true);
2825
+ if (bad) throw errNotSignatureOnly();
2826
+ if (this.isNew.has(num)) this.exclusive.add(num);
2827
+ this.infoWork = true;
2828
+ }
2829
+ info() {
2830
+ const r = dget(this.fin.trailer, "Info");
2831
+ if (!(r instanceof PRef2) || !this.changed.has(r.num) || this.isNew.has(r.num)) return;
2832
+ const d = this.fin.get(r.num);
2833
+ if (!isDict(d)) throw errNotSignatureOnly();
2834
+ for (const v of d.values()) if (!(v instanceof PStr) && !(v instanceof PName)) throw errNotSignatureOnly();
2835
+ this.claim(r.num, "info");
2836
+ this.allowed.add(r.num);
2837
+ this.infoWork = true;
2838
+ }
2839
+ };
2840
+
2841
+ // src/pades/validate/extract.ts
2842
+ var MAX_PDF_BYTES = 10 << 20;
2843
+ var MAX_SIGNATURES = 16;
2844
+ var ExtractError = class extends Error {
2845
+ constructor(code) {
2846
+ super(code === "not_pdf" ? "PDF \u0444\u0430\u0439\u043B \u0437\u0430\u0434\u0430\u0440\u0441\u0430\u043D\u0433\u04AF\u0439" : code === "no_signature" ? "\u0431\u0430\u0440\u0438\u043C\u0442\u0430\u0434 \u0446\u0430\u0445\u0438\u043C \u0433\u0430\u0440\u044B\u043D \u04AF\u0441\u044D\u0433 \u0430\u043B\u0433\u0430" : "\u0431\u0430\u0440\u0438\u043C\u0442\u0430\u0434 \u0445\u044D\u0442 \u043E\u043B\u043E\u043D \u0433\u0430\u0440\u044B\u043D \u04AF\u0441\u044D\u0433 \u0431\u0430\u0439\u043D\u0430");
2847
+ this.code = code;
2848
+ }
2849
+ code;
2850
+ };
2851
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
2852
+ var AP_VERIFY_PREFIX2 = "https://ca.eidmongolia.mn/verify/";
2853
+ async function extract(doc, profile = "own") {
2854
+ let rdr;
2855
+ try {
2856
+ rdr = new Reader(doc);
2857
+ if (!rdr.trailerValue().key("Encrypt").isNull()) throw new Error("encrypted");
2858
+ } catch {
2859
+ throw new ExtractError("not_pdf");
2860
+ }
2861
+ const sigs = [];
2862
+ const visible = /* @__PURE__ */ new Map();
2863
+ let docID = "";
2864
+ let dss;
2865
+ try {
2866
+ for (const x of rdr.xref) {
2867
+ const obj = rdr.resolve(x.ptr, new PRef(x.ptr.id, x.ptr.gen));
2868
+ if (obj.kind() !== "dict") continue;
2869
+ if (obj.key("FT").name() === "Sig" && obj.key("V").kind() === "dict") {
2870
+ const vp = obj.key("V").ptr;
2871
+ if (vp.id !== x.ptr.id) visible.set(vp.id, (visible.get(vp.id) ?? false) || widgetVisible(obj));
2872
+ }
2873
+ if (docID === "" && obj.key("Subtype").name() === "Link") {
2874
+ const u = fromLatin1(obj.key("A").key("URI").rawString());
2875
+ if (u.startsWith(AP_VERIFY_PREFIX2) && UUID_RE.test(u.slice(AP_VERIFY_PREFIX2.length))) docID = u.slice(AP_VERIFY_PREFIX2.length);
2876
+ }
2877
+ if (obj.key("Contents").isNull() || obj.key("ByteRange").isNull()) continue;
2878
+ const t = obj.key("Type").name();
2879
+ if (t !== "" && t !== "Sig") continue;
2880
+ if (sigs.length === MAX_SIGNATURES) throw new ExtractError("too_many");
2881
+ const s = await extractSignature(doc, obj);
2882
+ s.objNum = x.ptr.id;
2883
+ sigs.push(s);
2884
+ }
2885
+ if (sigs.length === 0) throw new ExtractError("no_signature");
2886
+ for (const s of sigs) s.visible = visible.get(s.objNum) ?? false;
2887
+ dss = extractDSS(rdr.trailerValue().key("Root").key("DSS"));
2888
+ } catch (e) {
2889
+ if (e instanceof ExtractError) throw e;
2890
+ throw new ExtractError("not_pdf");
2891
+ }
2892
+ if (dss) for (const s of sigs) s.dss = dss;
2893
+ const known = /* @__PURE__ */ new Map();
2894
+ const metas = /* @__PURE__ */ new Map();
2895
+ for (const s of sigs) {
2896
+ if (!s.malformed) {
2897
+ known.set(s.objNum, s.byteRange);
2898
+ metas.set(s.objNum, { revIndex: 1, role: "", roleOK: s.claimedRoles.length <= 1 });
2899
+ }
2900
+ }
2901
+ for (const [num, m] of metas) {
2902
+ const br = known.get(num);
2903
+ for (const s of sigs) {
2904
+ if (!s.malformed && s.signedEnd < br[2] + br[3]) m.revIndex++;
2905
+ if (s.objNum === num && s.claimedRoles.length === 1) m.role = s.claimedRoles[0];
2906
+ }
2907
+ }
2908
+ let revs;
2909
+ for (const s of sigs) {
2910
+ if (s.malformed || s.coversWhole) continue;
2911
+ if (!revs) {
2912
+ revs = new Revisions(doc, known, profile);
2913
+ revs.sigs = metas;
2914
+ revs.docID = docID;
2915
+ }
2916
+ const later = await revs.later(s.signedEnd);
2917
+ s.laterSignaturesOnly = later.signaturesOnly;
2918
+ s.laterSignatures = later.signatures;
2919
+ s.laterVisible = later.visible;
2920
+ }
2921
+ return { sigs, metas, docID };
2922
+ }
2923
+ function widgetVisible(w) {
2924
+ if (!w.key("AP").isNull()) return true;
2925
+ const r = w.key("Rect");
2926
+ if (r.kind() !== "array" || r.len() !== 4) return false;
2927
+ return r.index(0).float64() !== r.index(2).float64() && r.index(1).float64() !== r.index(3).float64();
2928
+ }
2929
+ function emptySig(obj) {
2930
+ return {
2931
+ signerName: valueText(obj.key("Name")),
2932
+ reason: valueText(obj.key("Reason")),
2933
+ location: valueText(obj.key("Location")),
2934
+ malformed: false,
2935
+ integrity: false,
2936
+ weakDigest: false,
2937
+ coversWhole: false,
2938
+ laterSignaturesOnly: false,
2939
+ laterSignatures: 0,
2940
+ laterVisible: false,
2941
+ visible: false,
2942
+ signedEnd: 0,
2943
+ objNum: 0,
2944
+ certs: [],
2945
+ subFilter: "",
2946
+ signingCertV2: "",
2947
+ signingTimeAttr: false,
2948
+ claimedRoles: [],
2949
+ cmsSha256: "",
2950
+ messageDigest: ""
2951
+ };
2952
+ }
2953
+ function valueText(v) {
2954
+ return v.kind() === "string" ? pdfText(v.rawString()) : "";
2955
+ }
2956
+ async function extractSignature(doc, obj) {
2957
+ const s = emptySig(obj);
2958
+ const m = obj.key("M");
2959
+ if (!m.isNull()) {
2960
+ const t = parsePDFDate(valueText(m));
2961
+ if (t) s.claimedTime = t;
2962
+ }
2963
+ const contents = obj.key("Contents").rawString();
2964
+ const br = byteRange(obj.key("ByteRange"));
2965
+ const sb = signedBytes(doc, br, contents);
2966
+ if (!sb) {
2967
+ s.malformed = true;
2968
+ return s;
2969
+ }
2970
+ s.coversWhole = sb.whole;
2971
+ s.signedEnd = br[2] + br[3];
2972
+ s.byteRange = br;
2973
+ s.subFilter = obj.key("SubFilter").name();
2974
+ const p7 = parsePKCS7(contents);
2975
+ if (!p7 || p7.signers.length !== 1) {
2976
+ s.malformed = true;
2977
+ return s;
2978
+ }
2979
+ const si = p7.signers[0];
2980
+ const leaf = onlySigner(p7);
2981
+ if (!leaf) {
2982
+ s.malformed = true;
2983
+ return s;
2984
+ }
2985
+ s.leaf = leaf.raw;
2986
+ const der = cmsDER(contents);
2987
+ if (der) s.cmsSha256 = toHex(await sha256(der));
2988
+ const chk = await signedAttrChecks(si.authAttrs, leaf);
2989
+ s.signingCertV2 = chk.certV2;
2990
+ s.signingTimeAttr = chk.signingTime;
2991
+ s.claimedRoles = claimedRoles(si.authAttrs);
2992
+ for (const a of si.authAttrs) {
2993
+ if (a.type === O.messageDigest) {
2994
+ const md = firstOctet(a.values);
2995
+ if (md) s.messageDigest = toHex(md);
2996
+ }
2997
+ }
2998
+ for (const c of p7.certs) if (!equal(c.raw, leaf.raw)) s.certs.push(c.raw);
2999
+ s.weakDigest = !STRONG.has(si.digestAlg);
3000
+ s.integrity = await verifyPKCS7(p7, sb.signed);
3001
+ s.timestamp = await extractTimestamp(si);
3002
+ return s;
3003
+ }
3004
+ var O = {
3005
+ signedData: "1.2.840.113549.1.7.2",
3006
+ messageDigest: "1.2.840.113549.1.9.4",
3007
+ signingTime: "1.2.840.113549.1.9.5",
3008
+ signingCertV2: "1.2.840.113549.1.9.16.2.47",
3009
+ timeStampToken: "1.2.840.113549.1.9.16.2.14",
3010
+ signerAttrV2: "0.4.0.19122.1.1",
3011
+ role: "2.5.4.72"
3012
+ };
3013
+ var STRONG = /* @__PURE__ */ new Set([OID.sha256, OID.sha384, OID.sha512]);
3014
+ function parsePKCS7(data) {
3015
+ try {
3016
+ if (data.length === 0) return void 0;
3017
+ const ci = children(expect(readNode(data, 0), TAG.SEQUENCE, "ContentInfo"));
3018
+ if (oidString(expect(ci[0], TAG.OID, "contentType").value) !== O.signedData) return void 0;
3019
+ const sd = children(expect(children(expect(ci[1], 160, "[0]"))[0], TAG.SEQUENCE, "SignedData"));
3020
+ let i = 0;
3021
+ expect(sd[i++], TAG.INTEGER, "version");
3022
+ expect(sd[i++], TAG.SET, "digestAlgorithms");
3023
+ const eci = children(expect(sd[i++], TAG.SEQUENCE, "EncapsulatedContentInfo"));
3024
+ let content = new Uint8Array();
3025
+ if (eci[1]) {
3026
+ const inner = children(expect(eci[1], 160, "eContent"))[0];
3027
+ if (inner?.tag === TAG.OCTET_STRING) content = inner.value;
3028
+ else if (inner?.tag === 36) content = concat(children(inner).map((x) => x.value));
3029
+ }
3030
+ const certs = [];
3031
+ if (sd[i]?.tag === 160) {
3032
+ for (const c of children(sd[i])) certs.push(parseCertificate(c.raw));
3033
+ i++;
3034
+ }
3035
+ if (sd[i]?.tag === 161) i++;
3036
+ const signers = children(expect(sd[i], TAG.SET, "signerInfos")).map(parseSignerInfo);
3037
+ return { content, certs, signers };
3038
+ } catch {
3039
+ return void 0;
3040
+ }
3041
+ }
3042
+ function parseAttrs(n) {
3043
+ return children(n).map((a) => {
3044
+ const [t, v] = children(expect(a, TAG.SEQUENCE, "Attribute"));
3045
+ return { type: oidString(expect(t, TAG.OID, "attr type").value), values: expect(v, TAG.SET, "attr values").value };
3046
+ });
3047
+ }
3048
+ function parseSignerInfo(n) {
3049
+ const f = children(expect(n, TAG.SEQUENCE, "SignerInfo"));
3050
+ let i = 0;
3051
+ expect(f[i++], TAG.INTEGER, "version");
3052
+ const ias = children(expect(f[i++], TAG.SEQUENCE, "IssuerAndSerialNumber"));
3053
+ const issuer = expect(ias[0], TAG.SEQUENCE, "issuer").raw;
3054
+ const serial = intValue(expect(ias[1], TAG.INTEGER, "serial").value);
3055
+ const digestAlg = oidString(expect(children(expect(f[i++], TAG.SEQUENCE, "digestAlg"))[0], TAG.OID, "alg").value);
3056
+ let authAttrs = [];
3057
+ let authRaw;
3058
+ if (f[i]?.tag === 160) {
3059
+ authAttrs = parseAttrs(f[i]);
3060
+ authRaw = concat([Uint8Array.of(49), f[i].raw.subarray(1)]);
3061
+ i++;
3062
+ }
3063
+ const encAlg = oidString(expect(children(expect(f[i++], TAG.SEQUENCE, "encAlg"))[0], TAG.OID, "alg").value);
3064
+ const sig = expect(f[i++], TAG.OCTET_STRING, "signature").value;
3065
+ let unauthAttrs = [];
3066
+ if (f[i]?.tag === 161) unauthAttrs = parseAttrs(f[i++]);
3067
+ return { issuer, serial, digestAlg, authAttrs, authRaw, encAlg, sig, unauthAttrs };
3068
+ }
3069
+ function onlySigner(p7) {
3070
+ if (p7.signers.length !== 1) return void 0;
3071
+ const si = p7.signers[0];
3072
+ return p7.certs.find((c) => equal(c.rawIssuer, si.issuer) && intValue(c.serial) === si.serial);
3073
+ }
3074
+ var HASH_FOR_OID = {
3075
+ [OID.sha1]: "SHA-1",
3076
+ "1.2.840.10045.4.1": "SHA-1",
3077
+ "1.2.840.10040.4.1": "SHA-1",
3078
+ "1.2.840.10040.4.3": "SHA-1",
3079
+ [OID.rsaEncryption]: "SHA-1",
3080
+ [OID.sha256]: "SHA-256",
3081
+ [OID.ecdsaSHA256]: "SHA-256",
3082
+ [OID.sha384]: "SHA-384",
3083
+ [OID.ecdsaSHA384]: "SHA-384",
3084
+ [OID.sha512]: "SHA-512",
3085
+ [OID.ecdsaSHA512]: "SHA-512"
3086
+ };
3087
+ var RSA_ENC = /* @__PURE__ */ new Set([OID.rsaEncryption, "1.2.840.113549.1.1.5", OID.sha256WithRSA, OID.sha384WithRSA, OID.sha512WithRSA]);
3088
+ var ECDSA_CURVE_ENC = /* @__PURE__ */ new Set([OID.p256, OID.p384, OID.p521]);
3089
+ function sigAlgOID(encAlg, digestAlg) {
3090
+ switch (encAlg) {
3091
+ case "1.2.840.10045.4.1":
3092
+ return "1.2.840.10045.4.1";
3093
+ case OID.ecdsaSHA256:
3094
+ case OID.ecdsaSHA384:
3095
+ case OID.ecdsaSHA512:
3096
+ return encAlg;
3097
+ }
3098
+ if (RSA_ENC.has(encAlg)) {
3099
+ return { [OID.sha1]: "1.2.840.113549.1.1.5", [OID.sha256]: OID.sha256WithRSA, [OID.sha384]: OID.sha384WithRSA, [OID.sha512]: OID.sha512WithRSA }[digestAlg];
3100
+ }
3101
+ if (ECDSA_CURVE_ENC.has(encAlg)) {
3102
+ return { [OID.sha1]: "1.2.840.10045.4.1", [OID.sha256]: OID.ecdsaSHA256, [OID.sha384]: OID.ecdsaSHA384, [OID.sha512]: OID.ecdsaSHA512 }[digestAlg];
3103
+ }
3104
+ return void 0;
3105
+ }
3106
+ function algNode(oid) {
3107
+ const o = oidBytes(oid);
3108
+ return parseOne(Uint8Array.from([48, o.length, ...o]));
3109
+ }
3110
+ function oidBytes(s) {
3111
+ const parts = s.split(".").map((x) => BigInt(x));
3112
+ const body = [];
3113
+ const enc = (v) => {
3114
+ const tmp = [Number(v & 0x7fn)];
3115
+ for (v >>= 7n; v > 0n; v >>= 7n) tmp.unshift(Number(v & 0x7fn) | 128);
3116
+ body.push(...tmp);
3117
+ };
3118
+ enc(parts[0] * 40n + parts[1]);
3119
+ for (const p of parts.slice(2)) enc(p);
3120
+ return [6, body.length, ...body];
3121
+ }
3122
+ async function verifyPKCS7(p7, content) {
3123
+ if (p7.signers.length === 0) return false;
3124
+ for (const si of p7.signers) {
3125
+ const ee = p7.certs.find((c) => equal(c.rawIssuer, si.issuer) && intValue(c.serial) === si.serial);
3126
+ if (!ee) return false;
3127
+ let signed = content;
3128
+ if (si.authAttrs.length > 0) {
3129
+ const mdAttr = si.authAttrs.find((a) => a.type === O.messageDigest);
3130
+ const md = mdAttr ? firstOctet(mdAttr.values) : void 0;
3131
+ if (!md) return false;
3132
+ const hash = HASH_FOR_OID[si.digestAlg];
3133
+ if (!hash) return false;
3134
+ if (!equal(md, await digest(hash, content))) return false;
3135
+ signed = si.authRaw;
3136
+ const st = si.authAttrs.find((a) => a.type === O.signingTime);
3137
+ if (st) {
3138
+ const t = attrTime(st.values);
3139
+ if (t && (t.getTime() > ee.notAfter.getTime() || t.getTime() < ee.notBefore.getTime())) return false;
3140
+ }
3141
+ }
3142
+ const alg = sigAlgOID(si.encAlg, si.digestAlg);
3143
+ if (!alg) return false;
3144
+ let ok = false;
3145
+ try {
3146
+ ok = await verifySignature(ee, algNode(alg), signed, si.sig);
3147
+ } catch {
3148
+ ok = false;
3149
+ }
3150
+ if (!ok) return false;
3151
+ }
3152
+ return true;
3153
+ }
3154
+ function firstOctet(values) {
3155
+ try {
3156
+ const n = readNode(values, 0);
3157
+ return n.tag === TAG.OCTET_STRING ? n.value : void 0;
3158
+ } catch {
3159
+ return void 0;
3160
+ }
3161
+ }
3162
+ function attrTime(values) {
3163
+ try {
3164
+ const n = readNode(values, 0);
3165
+ if (n.tag !== TAG.UTCTime && n.tag !== TAG.GeneralizedTime) return void 0;
3166
+ return parsePreciseTime(n).date;
3167
+ } catch {
3168
+ return void 0;
3169
+ }
3170
+ }
3171
+ function cmsDER(contents) {
3172
+ try {
3173
+ const n = readNode(contents, 0);
3174
+ return n.tag === TAG.SEQUENCE ? n.raw : void 0;
3175
+ } catch {
3176
+ return void 0;
3177
+ }
3178
+ }
3179
+ async function signedAttrChecks(attrs, leaf) {
3180
+ let certV2 = "";
3181
+ let signingTime = false;
3182
+ for (const a of attrs) {
3183
+ if (a.type === O.signingTime) {
3184
+ signingTime = true;
3185
+ continue;
3186
+ }
3187
+ if (a.type !== O.signingCertV2) continue;
3188
+ if (certV2 !== "") {
3189
+ certV2 = "mismatch";
3190
+ continue;
3191
+ }
3192
+ certV2 = "mismatch";
3193
+ try {
3194
+ const top = readNode(a.values, 0);
3195
+ if (top.raw.length !== a.values.length || top.tag !== TAG.SEQUENCE) continue;
3196
+ const scf = children(top);
3197
+ if (scf.length !== 1 || scf[0].tag !== TAG.SEQUENCE) continue;
3198
+ const ids = children(scf[0]);
3199
+ if (ids.length === 0) continue;
3200
+ const id = children(expect(ids[0], TAG.SEQUENCE, "ESSCertIDv2"));
3201
+ let k = 0;
3202
+ let hash = "SHA-256";
3203
+ if (id[k]?.tag === TAG.SEQUENCE) {
3204
+ const alg = oidString(expect(children(id[k])[0], TAG.OID, "alg").value);
3205
+ hash = alg === OID.sha256 ? "SHA-256" : alg === OID.sha384 ? "SHA-384" : alg === OID.sha512 ? "SHA-512" : void 0;
3206
+ k++;
3207
+ }
3208
+ const certHash = expect(id[k++], TAG.OCTET_STRING, "certHash").value;
3209
+ let serial;
3210
+ if (id[k]) {
3211
+ const is = children(expect(id[k], TAG.SEQUENCE, "IssuerSerial"));
3212
+ serial = intValue(expect(is[1], TAG.INTEGER, "serial").value);
3213
+ k++;
3214
+ }
3215
+ if (k !== id.length || !hash) continue;
3216
+ if (!equal(await digest(hash, leaf.raw), certHash)) continue;
3217
+ if (serial !== void 0 && serial !== intValue(leaf.serial)) continue;
3218
+ certV2 = "match";
3219
+ } catch {
3220
+ }
3221
+ }
3222
+ return { certV2, signingTime };
3223
+ }
3224
+ var MAX_CLAIMED_ROLES = 4;
3225
+ var MAX_CLAIMED_ROLE_RUNES = 900;
3226
+ function claimedRoles(attrs) {
3227
+ const out = [];
3228
+ for (const a of attrs) {
3229
+ if (a.type !== O.signerAttrV2) continue;
3230
+ try {
3231
+ const seq = readNode(a.values, 0);
3232
+ if (seq.tag !== TAG.SEQUENCE) continue;
3233
+ const first = seq.value.length > 0 ? readNode(seq.value, 0) : void 0;
3234
+ if (!first || first.tag !== 160) continue;
3235
+ const list = readNode(first.value, 0);
3236
+ if (list.tag !== TAG.SEQUENCE) continue;
3237
+ let p = 0;
3238
+ while (p < list.value.length && out.length < MAX_CLAIMED_ROLES) {
3239
+ let at;
3240
+ try {
3241
+ at = readNode(list.value, p);
3242
+ } catch {
3243
+ break;
3244
+ }
3245
+ p += at.raw.length;
3246
+ if (at.tag !== TAG.SEQUENCE) break;
3247
+ const parts = children(at);
3248
+ if (parts[0]?.tag !== TAG.OID || parts[1]?.tag !== TAG.SET) break;
3249
+ if (oidString(parts[0].value) !== O.role) continue;
3250
+ let q = 0;
3251
+ const vals = parts[1].value;
3252
+ while (q < vals.length && out.length < MAX_CLAIMED_ROLES) {
3253
+ let v;
3254
+ try {
3255
+ v = readNode(vals, q);
3256
+ } catch {
3257
+ break;
3258
+ }
3259
+ q += v.raw.length;
3260
+ if (v.tag !== TAG.UTF8String && v.tag !== TAG.PrintableString) continue;
3261
+ const r = validClaimedRole(v.value);
3262
+ if (r !== void 0) out.push(r);
3263
+ }
3264
+ }
3265
+ } catch {
3266
+ }
3267
+ }
3268
+ return out;
3269
+ }
3270
+ function validClaimedRole(b) {
3271
+ let s;
3272
+ try {
3273
+ s = new TextDecoder("utf-8", { fatal: true }).decode(b);
3274
+ } catch {
3275
+ return void 0;
3276
+ }
3277
+ if (s === "" || [...s].length > MAX_CLAIMED_ROLE_RUNES) return void 0;
3278
+ if (/[\p{Cc}\p{Cf}]/u.test(s)) return void 0;
3279
+ return s;
3280
+ }
3281
+ var TS_HASH = {
3282
+ [OID.sha1]: "SHA-1",
3283
+ [OID.sha256]: "SHA-256",
3284
+ [OID.sha384]: "SHA-384",
3285
+ [OID.sha512]: "SHA-512"
3286
+ };
3287
+ async function extractTimestamp(si) {
3288
+ for (const a of si.unauthAttrs) {
3289
+ if (a.type !== O.timeStampToken) continue;
3290
+ const out = { time: ZERO_TIME, serial: "", matches: false, weakDigest: false, certs: [] };
3291
+ const tok = parsePKCS7(a.values);
3292
+ if (!tok) return out;
3293
+ if (tok.certs.length > 0 && !await verifyPKCS7(tok, tok.content)) return out;
3294
+ let info;
3295
+ let hashAlg;
3296
+ let hashed;
3297
+ let time;
3298
+ let serial;
3299
+ try {
3300
+ info = children(expect(parseOne(tok.content), TAG.SEQUENCE, "TSTInfo"));
3301
+ const mi = children(expect(info[2], TAG.SEQUENCE, "messageImprint"));
3302
+ hashAlg = oidString(expect(children(expect(mi[0], TAG.SEQUENCE, "alg"))[0], TAG.OID, "alg").value);
3303
+ hashed = expect(mi[1], TAG.OCTET_STRING, "hashedMessage").value;
3304
+ if (hashed.length === 0) return out;
3305
+ serial = hexSerial(expect(info[3], TAG.INTEGER, "serial").value);
3306
+ time = fromPrecise(parsePreciseTime(expect(info[4], TAG.GeneralizedTime, "genTime")));
3307
+ } catch {
3308
+ return out;
3309
+ }
3310
+ out.time = time;
3311
+ out.serial = serial;
3312
+ if (tok.signers.length !== 1) return out;
3313
+ const tsa = onlySigner(tok);
3314
+ if (!tsa) return out;
3315
+ out.tsaCert = tsa.raw;
3316
+ for (const c of tok.certs) if (!equal(c.raw, tsa.raw)) out.certs.push(c.raw);
3317
+ const h = TS_HASH[hashAlg];
3318
+ out.weakDigest = !STRONG.has(tok.signers[0].digestAlg) || !(h && h !== "SHA-1");
3319
+ if (!h) return out;
3320
+ out.matches = equal(await digest(h, si.sig), hashed);
3321
+ return out;
3322
+ }
3323
+ return void 0;
3324
+ }
3325
+ function signedBytes(doc, br, contents) {
3326
+ if (!br || br.length !== 4) return void 0;
3327
+ const n = doc.length;
3328
+ const [a0, l0, a1, l1] = br;
3329
+ if (a0 !== 0 || l0 <= 0 || l1 < 0 || a1 <= l0 || a1 > n || l1 > n - a1) return void 0;
3330
+ const gap = doc.subarray(l0, a1);
3331
+ if (gap.length < 2 || gap[0] !== 60 || gap[gap.length - 1] !== 62) return void 0;
3332
+ const hex = fromLatin1(gap, 1, gap.length - 1);
3333
+ if (hex.length % 2 !== 0 || /[^0-9a-fA-F]/.test(hex)) return void 0;
3334
+ if (hex.length / 2 !== contents.length) return void 0;
3335
+ for (let i = 0; i < contents.length; i++) if (parseInt(hex.substr(i * 2, 2), 16) !== contents[i]) return void 0;
3336
+ return { signed: concat([doc.subarray(0, l0), doc.subarray(a1, a1 + l1)]), whole: a1 + l1 === n };
3337
+ }
3338
+ function byteRange(v) {
3339
+ if (v.kind() !== "array" || v.len() !== 4) return void 0;
3340
+ const out = [];
3341
+ for (let i = 0; i < 4; i++) {
3342
+ const e = v.index(i);
3343
+ if (e.kind() !== "int") return void 0;
3344
+ out.push(e.int64());
3345
+ }
3346
+ return out;
3347
+ }
3348
+ function parsePDFDate(raw) {
3349
+ const s = (raw.startsWith("D:") ? raw.slice(2) : raw).replaceAll("'", "");
3350
+ const m = /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(Z|[+-]\d{4})?$/.exec(s);
3351
+ if (!m) return void 0;
3352
+ const [y, mo, d, h, mi, se] = m.slice(1, 7).map(Number);
3353
+ if (mo < 1 || mo > 12 || d < 1 || h > 23 || mi > 59 || se > 59) return void 0;
3354
+ const dim = new Date(Date.UTC(2e3, mo, 0)).getUTCDate();
3355
+ const leap = y % 4 === 0 && y % 100 !== 0 || y % 400 === 0;
3356
+ if (d > (mo === 2 ? leap ? 29 : 28 : dim)) return void 0;
3357
+ let off = 0;
3358
+ const z = m[7];
3359
+ if (z && z !== "Z") {
3360
+ const oh = Number(z.slice(1, 3));
3361
+ const om = Number(z.slice(3, 5));
3362
+ if (oh > 24 || om > 59) return void 0;
3363
+ off = (oh * 60 + om) * 60 * (z[0] === "+" ? 1 : -1);
3364
+ }
3365
+ const dt = /* @__PURE__ */ new Date(0);
3366
+ dt.setUTCFullYear(y, mo - 1, d);
3367
+ dt.setUTCHours(h, mi, se, 0);
3368
+ return { sec: Math.floor(dt.getTime() / 1e3) - off, nanos: 0 };
3369
+ }
3370
+ var MAX_DSS_ITEMS = 64;
3371
+ var MAX_DSS_STREAM = 1 << 20;
3372
+ function extractDSS(dss) {
3373
+ if (dss.kind() !== "dict") return void 0;
3374
+ const read = (key) => {
3375
+ const arr = dss.key(key);
3376
+ const out = [];
3377
+ for (let i = 0; i < arr.len() && i < MAX_DSS_ITEMS; i++) {
3378
+ const e = arr.index(i);
3379
+ if (e.kind() !== "stream") continue;
3380
+ let b;
3381
+ try {
3382
+ b = e.streamData();
3383
+ } catch {
3384
+ continue;
3385
+ }
3386
+ if (b.length > MAX_DSS_STREAM) continue;
3387
+ out.push(b);
3388
+ }
3389
+ return out;
3390
+ };
3391
+ return { certs: read("Certs"), ocsps: read("OCSPs"), crls: read("CRLs") };
3392
+ }
3393
+
3394
+ // src/validate.ts
3395
+ var ValidatePdfError = class extends EidError {
3396
+ constructor(code, message) {
3397
+ super(message);
3398
+ this.code = code;
3399
+ this.name = "ValidatePdfError";
3400
+ }
3401
+ code;
3402
+ };
3403
+ function ders(list, what) {
3404
+ try {
3405
+ return (list ?? []).map((d) => parseCertificate(d));
3406
+ } catch (e) {
3407
+ throw new ValidatePdfError("REQUEST_INVALID", `${what}: ${e instanceof Error ? e.message : String(e)}`);
3408
+ }
3409
+ }
3410
+ var embedded = (b64) => b64.map((x) => parseCertificate(fromB64(x)));
3411
+ async function validatePdf(pdf, opts = {}) {
3412
+ const doc = pdf instanceof Uint8Array ? pdf : new Uint8Array(pdf);
3413
+ if (doc.length > MAX_PDF_BYTES) throw new ValidatePdfError("PDF_TOO_LARGE", "PDF 10 MiB-\u0430\u0430\u0441 \u0438\u0445");
3414
+ const roots = opts.roots && opts.roots.length > 0 ? ders(opts.roots, "roots") : embedded(NATIONAL_ROOT);
3415
+ const extraInter = ders(opts.intermediates, "intermediates");
3416
+ const issuers = [...embedded(EID_ISSUERS), ...ders(opts.issuers, "issuers")];
3417
+ let ex;
3418
+ try {
3419
+ ex = await extract(doc);
3420
+ } catch (e) {
3421
+ if (e instanceof ExtractError) {
3422
+ if (e.code === "no_signature") throw new ValidatePdfError("PDF_NO_SIGNATURE", e.message);
3423
+ if (e.code === "too_many") throw new ValidatePdfError("PDF_TOO_MANY_SIGNATURES", e.message);
3424
+ }
3425
+ throw new ValidatePdfError("PDF_INVALID", "PDF \u0437\u0430\u0434\u0430\u0440\u0441\u0430\u043D\u0433\u04AF\u0439");
3426
+ }
3427
+ const now = fromDate(opts.time ?? /* @__PURE__ */ new Date());
3428
+ const dss = ex.sigs.find((s) => s.dss)?.dss;
3429
+ let status = new DSSStatus(dss, issuers);
3430
+ if (!opts.offline) {
3431
+ const fetchFn = opts.fetch ?? globalThis.fetch;
3432
+ status = await OnlineStatus.create(new Fetcher(fetchFn, isBrowser(), opts.signal), ex.sigs, issuers, status, now);
3433
+ }
3434
+ const ev = new Evaluator({ roots, intermediates: [...embedded(INTERMEDIATES), ...extraInter], issuers, status, now });
3435
+ const rep = { indication: "valid", signatures: [] };
3436
+ for (const r of ex.sigs) {
3437
+ const s = await ev.evaluateSignature(r);
3438
+ if (s.chain_trusted && r.leaf) {
3439
+ const lvl = signLevelOf(parseCertificate(r.leaf));
3440
+ if (lvl) s.certificate_level = lvl;
3441
+ }
3442
+ s.key_medium = keyMedium(s);
3443
+ rep.signatures.push(s);
3444
+ }
3445
+ for (const s of rep.signatures) {
3446
+ if (s.indication === "invalid") {
3447
+ rep.indication = "invalid";
3448
+ break;
3449
+ }
3450
+ if (s.indication === "indeterminate") rep.indication = "indeterminate";
3451
+ }
3452
+ return rep;
3453
+ }
3454
+ function keyMedium(s) {
3455
+ const c = s.certificate;
3456
+ if (c?.issued_by_eid && c.usage === "sign" && (s.certificate_level === "QUALIFIED" || s.certificate_level === "QSCD")) return "phone";
3457
+ return "unknown";
3458
+ }
3459
+ export {
3460
+ ValidatePdfError,
3461
+ validatePdf
3462
+ };