@gerege-systems/eid-mongolia-sdk 0.20.0 → 0.21.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.
package/dist/validate.js CHANGED
@@ -3,337 +3,68 @@ import {
3
3
  InflateError,
4
4
  PRef,
5
5
  Reader,
6
+ StructureError,
6
7
  appearanceObjects,
8
+ checkStructure,
7
9
  inflateRaw,
8
10
  isBrowser,
9
11
  round100,
10
12
  visibleWidget
11
- } from "./chunk-ARITEQLS.js";
13
+ } from "./chunk-T3QLOY6J.js";
12
14
  import {
13
15
  EID_ISSUERS,
14
16
  INTERMEDIATES,
15
17
  NATIONAL_ROOT,
16
18
  OID,
19
+ SHA1_SIG,
17
20
  TAG,
21
+ ZERO_TIME,
22
+ addMs,
23
+ after,
24
+ before,
18
25
  children,
26
+ commonName,
19
27
  concat,
28
+ crlFor,
29
+ crlListed,
20
30
  digest,
21
31
  equal,
22
32
  expect,
33
+ formatTime,
34
+ freshAt,
23
35
  fromB64,
36
+ fromDate,
24
37
  fromLatin1,
38
+ fromPrecise,
39
+ hexSerial,
25
40
  intValue,
26
41
  isTSASigningCert,
42
+ isZero,
27
43
  latin1,
44
+ nameString,
45
+ ocspCertIDMatches,
46
+ ocspFreshAt,
28
47
  ocspRequest,
29
48
  oidString,
49
+ parseCRL,
30
50
  parseCertificate,
31
51
  parseOCSP,
32
52
  parseOCSPFrom,
33
53
  parseOne,
34
54
  parsePreciseTime,
55
+ pdfText,
35
56
  readNode,
36
57
  sameCertKey,
37
58
  sha256,
59
+ subjectNames,
60
+ subjectSerialNumber,
61
+ subtle,
38
62
  toHex,
39
63
  verifySignature
40
- } from "./chunk-HLSFSIWP.js";
64
+ } from "./chunk-ISTWNY6N.js";
41
65
  import {
42
66
  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
- }
67
+ } from "./chunk-ZB7LEWA5.js";
337
68
 
338
69
  // src/pades/validate/evaluate.ts
339
70
  var PROBLEMS = {
@@ -350,7 +81,6 @@ var PROBLEMS = {
350
81
  modifiedAfter: "modified_after_signing",
351
82
  timestampInvalid: "timestamp_invalid"
352
83
  };
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
84
  async function checkSigFrom(c, parent) {
355
85
  if (parent.version === 3 && !parent.basicConstraintsValid || parent.basicConstraintsValid && !parent.isCA) return false;
356
86
  if (parent.keyUsage !== 0 && !(parent.keyUsage & 1 << 5)) return false;
@@ -488,7 +218,7 @@ var Evaluator = class {
488
218
  isIssuer(c) {
489
219
  return this.cfg.issuers.some((is) => equal(c.rawSubject, is.rawSubject) && equal(c.spki, is.spki));
490
220
  }
491
- async certInfo(c, chain) {
221
+ async certInfo(c, chain, at) {
492
222
  const info = {
493
223
  common_name: commonName(c.rawSubject),
494
224
  subject: nameString(c.rawSubject),
@@ -505,7 +235,7 @@ var Evaluator = class {
505
235
  if (!this.cfg.status) return info;
506
236
  let st;
507
237
  try {
508
- st = await this.cfg.status.certStatus(intValue(c.serial));
238
+ st = await this.cfg.status.certStatus(c, chain[1], at);
509
239
  } catch {
510
240
  return info;
511
241
  }
@@ -593,7 +323,7 @@ var Evaluator = class {
593
323
  s.chain_trusted = trusted;
594
324
  s.chain = chain ? chain.map((c) => commonName(c.rawSubject)) : [commonName(leaf.rawSubject)];
595
325
  this.lastRevokedAt = void 0;
596
- const info = await this.certInfo(leaf, chain);
326
+ const info = await this.certInfo(leaf, chain, at);
597
327
  s.certificate = info;
598
328
  if (!trusted) s.problems.push(PROBLEMS.untrusted);
599
329
  if (!["sign", "seal", "document_signer"].includes(info.usage)) s.problems.push(PROBLEMS.keyUsage);
@@ -612,7 +342,7 @@ var Evaluator = class {
612
342
  }
613
343
  if (cades && r.signingTimeAttr && info.issued_by_eid) s.problems.push(PROBLEMS.malformed);
614
344
  if (!r.coversWhole && !r.laterSignaturesOnly) s.problems.push(PROBLEMS.modifiedAfter);
615
- if (trusted) s.ltv = await ltvCoverage(r.dss, at, [chain, tsChain ?? []]);
345
+ if (trusted) s.ltv = await ltvCoverage(r.dss, at, this.cfg.now, [chain, tsChain ?? []]);
616
346
  if (cades) {
617
347
  s.signature_level = signingTime && s.ltv?.complete ? "PAdES-BASELINE-LT" : signingTime ? "PAdES-BASELINE-T" : "PAdES-BASELINE-B";
618
348
  }
@@ -694,9 +424,8 @@ function usageOf(c) {
694
424
  if (ds && known.includes("1.3.6.1.5.5.7.3.2")) return "auth";
695
425
  return "other";
696
426
  }
697
- var LTV_FRESHNESS_MS = 24 * 36e5;
698
427
  var OID_OCSP_NOCHECK = "1.3.6.1.5.5.7.48.1.5";
699
- async function ltvCoverage(dss, at, chains) {
428
+ async function ltvCoverage(dss, at, now, chains) {
700
429
  const out = { complete: false, missing: [] };
701
430
  const crls = [];
702
431
  for (const der of dss?.crls ?? []) {
@@ -710,13 +439,13 @@ async function ltvCoverage(dss, at, chains) {
710
439
  const issuer = chain[i + 1];
711
440
  if (seen.some((x) => equal(x, cert.raw))) continue;
712
441
  seen.push(cert.raw);
713
- if (!await covered(cert, issuer, at, dss?.ocsps ?? [], crls)) out.missing.push(commonName(cert.rawSubject));
442
+ if (!await covered(cert, issuer, at, now, dss?.ocsps ?? [], crls)) out.missing.push(commonName(cert.rawSubject));
714
443
  }
715
444
  }
716
445
  out.complete = out.missing.length === 0 && seen.length > 0;
717
446
  return out;
718
447
  }
719
- async function covered(cert, issuer, at, ocsps, crls) {
448
+ async function covered(cert, issuer, at, now, ocsps, crls) {
720
449
  for (const der of ocsps) {
721
450
  let resp;
722
451
  try {
@@ -724,98 +453,64 @@ async function covered(cert, issuer, at, ocsps, crls) {
724
453
  } catch {
725
454
  continue;
726
455
  }
727
- if (resp.status !== "good") continue;
456
+ if (resp.status !== "good" || !await ocspCertIDMatches(der, cert, issuer)) continue;
728
457
  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;
458
+ if (ocspFreshAt(resp, at, now)) return true;
732
459
  }
733
460
  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;
461
+ if (!await crlFor(crl, cert, issuer) || !freshAt(crl.thisUpdate, crl.nextUpdate, at, now)) continue;
462
+ if (crlListed(crl, cert)) continue;
738
463
  return true;
739
464
  }
740
465
  return false;
741
466
  }
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
- }
467
+ function responderOK(resp, issuer) {
468
+ if (!resp.certificate || equal(resp.certificate.raw, issuer.raw)) return true;
469
+ return resp.certificate.extKeyUsage.includes(OID.kpOCSPSigning);
768
470
  }
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;
471
+ async function ocspFor(der, cert, issuer) {
472
+ let resp;
773
473
  try {
774
- return await verifySignature(issuer, crl.sigAlg, crl.tbs, crl.sig);
474
+ resp = await parseOCSPFrom(der, intValue(cert.serial), issuer);
775
475
  } catch {
776
- return false;
476
+ return void 0;
777
477
  }
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);
478
+ if (resp.serial !== intValue(cert.serial) || !await ocspCertIDMatches(der, cert, issuer) || !responderOK(resp, issuer)) return void 0;
479
+ return resp;
782
480
  }
783
481
  var DSSStatus = class {
784
- constructor(dss, issuers) {
482
+ constructor(dss, now) {
785
483
  this.dss = dss;
786
- this.issuers = issuers;
484
+ this.now = now;
787
485
  }
788
486
  dss;
789
- issuers;
790
- async certStatus(serial) {
487
+ now;
488
+ async certStatus(cert, issuer, at) {
489
+ let revoked;
490
+ const markRevoked = (t) => {
491
+ if (!revoked || before(t, revoked)) revoked = t;
492
+ };
493
+ let good = false;
791
494
  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
- }
495
+ const resp = await ocspFor(der, cert, issuer);
496
+ if (!resp) continue;
497
+ if (resp.status === "revoked") markRevoked(fromPrecise(resp.revokedAt));
498
+ else if (resp.status === "good") good ||= ocspFreshAt(resp, at, this.now);
803
499
  }
804
500
  for (const der of this.dss?.crls ?? []) {
805
501
  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
- }
502
+ if (!crl || !await crlFor(crl, cert, issuer)) continue;
503
+ const t = crlListed(crl, cert);
504
+ if (t) markRevoked(t);
505
+ else good ||= freshAt(crl.thisUpdate, crl.nextUpdate, at, this.now);
812
506
  }
507
+ if (revoked) return { issued: true, revoked: true, revokedAt: revoked };
508
+ if (good) return { issued: true, revoked: false };
813
509
  return { issued: false, revoked: false };
814
510
  }
815
511
  };
816
512
  var ONLINE_OCSP_MAX = 16 << 10;
817
- var CLOCK_SKEW_MS = 5 * 6e4;
818
- var OnlineStatus = class _OnlineStatus {
513
+ var OnlineStatus = class {
819
514
  constructor(f, fallback, now) {
820
515
  this.f = f;
821
516
  this.fallback = fallback;
@@ -824,89 +519,59 @@ var OnlineStatus = class _OnlineStatus {
824
519
  f;
825
520
  fallback;
826
521
  now;
827
- leaves = /* @__PURE__ */ new Map();
828
522
  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);
523
+ async certStatus(cert, issuer, at) {
524
+ const key = toHex(cert.raw) + ":" + toHex(issuer.raw);
857
525
  const hit = this.cache.get(key);
858
526
  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);
527
+ let st = await this.ocsp(cert, issuer) ?? await this.crl(cert, issuer);
528
+ if (this.fallback && (!st || !st.revoked)) {
529
+ const fst = await this.fallback.certStatus(cert, issuer, at);
530
+ if (!st || fst.revoked) st = fst;
865
531
  }
532
+ st ??= { issued: false, revoked: false };
866
533
  this.cache.set(key, st);
867
534
  return st;
868
535
  }
869
- async ocsp(leaf, issuer) {
536
+ async ocsp(cert, issuer) {
870
537
  let req;
871
538
  try {
872
- req = await ocspRequest(leaf, issuer);
539
+ req = await ocspRequest(cert, issuer);
873
540
  } catch {
874
541
  return void 0;
875
542
  }
876
543
  const now = this.now;
877
- for (const u of leaf.ocspServers) {
878
- let resp;
544
+ for (const u of cert.ocspServers) {
545
+ let der;
879
546
  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);
547
+ der = await this.f.do("POST", u, "application/ocsp-request", req);
883
548
  } catch {
884
549
  continue;
885
550
  }
886
- if (resp.serial !== intValue(leaf.serial)) continue;
551
+ if (der.length > ONLINE_OCSP_MAX) continue;
552
+ const resp = await ocspFor(der, cert, issuer);
553
+ if (!resp) continue;
887
554
  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 };
555
+ if (rc && !sameCertKey(rc, issuer) && !validAt(rc, now)) continue;
892
556
  if (resp.status === "revoked") return { issued: true, revoked: true, revokedAt: fromPrecise(resp.revokedAt) };
557
+ if (!ocspFreshAt(resp, now, now)) continue;
558
+ if (resp.status === "good") return { issued: true, revoked: false };
893
559
  return { issued: false, revoked: false };
894
560
  }
895
561
  return void 0;
896
562
  }
897
- async crl(leaf, issuer) {
898
- for (const u of leaf.crlDPs) {
563
+ async crl(cert, issuer) {
564
+ for (const u of cert.crlDPs) {
899
565
  let crl;
900
566
  try {
901
567
  crl = parseCRL(await this.f.do("GET", u, ""));
902
568
  } catch {
903
569
  continue;
904
570
  }
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 };
571
+ if (!crl || !await crlFor(crl, cert, issuer)) continue;
572
+ const t = crlListed(crl, cert);
573
+ if (t) return { issued: true, revoked: true, revokedAt: t };
574
+ if (freshAt(crl.thisUpdate, crl.nextUpdate, this.now, this.now)) return { issued: true, revoked: false };
910
575
  }
911
576
  return void 0;
912
577
  }
@@ -2841,23 +2506,37 @@ var Classifier = class {
2841
2506
  // src/pades/validate/extract.ts
2842
2507
  var MAX_PDF_BYTES = 10 << 20;
2843
2508
  var MAX_SIGNATURES = 16;
2509
+ var MESSAGES = {
2510
+ not_pdf: "PDF \u0444\u0430\u0439\u043B \u0437\u0430\u0434\u0430\u0440\u0441\u0430\u043D\u0433\u04AF\u0439",
2511
+ encrypted: "\u0448\u0438\u0444\u0440\u043B\u044D\u0433\u0434\u0441\u044D\u043D PDF-\u0438\u0439\u0433 \u0448\u0430\u043B\u0433\u0430\u0445 \u0431\u043E\u043B\u043E\u043C\u0436\u0433\u04AF\u0439 \u2014 \u043D\u0443\u0443\u0446\u043B\u0430\u043B\u044B\u0433 \u0430\u0440\u0438\u043B\u0433\u0430\u0430\u0434 \u0434\u0430\u0445\u0438\u043D \u043E\u0440\u043E\u043B\u0434\u043E\u043D\u043E \u0443\u0443",
2512
+ 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",
2513
+ too_many: "\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",
2514
+ structure: "PDF-\u0438\u0439\u043D \u0431\u04AF\u0442\u044D\u0446 \u0445\u044D\u0442 \u0433\u04AF\u043D \u0434\u0430\u0432\u0445\u0430\u0440\u043B\u0430\u0441\u0430\u043D \u044D\u0441\u0432\u044D\u043B \u0445\u044D\u0442 \u0442\u04E9\u0432\u04E9\u0433\u0442\u044D\u0439"
2515
+ };
2844
2516
  var ExtractError = class extends Error {
2845
2517
  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");
2518
+ super(MESSAGES[code]);
2847
2519
  this.code = code;
2848
2520
  }
2849
2521
  code;
2850
2522
  };
2523
+ var ENCRYPT_REF = /\/Encrypt(?:\s+\d+\s+\d+\s+R|\s*<<)/;
2851
2524
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
2852
2525
  var AP_VERIFY_PREFIX2 = "https://ca.eidmongolia.mn/verify/";
2853
2526
  async function extract(doc, profile = "own") {
2527
+ try {
2528
+ checkStructure(doc);
2529
+ } catch (e) {
2530
+ if (e instanceof StructureError) throw new ExtractError("structure");
2531
+ throw e;
2532
+ }
2854
2533
  let rdr;
2855
2534
  try {
2856
2535
  rdr = new Reader(doc);
2857
- if (!rdr.trailerValue().key("Encrypt").isNull()) throw new Error("encrypted");
2858
2536
  } catch {
2859
- throw new ExtractError("not_pdf");
2537
+ throw new ExtractError(ENCRYPT_REF.test(fromLatin1(doc)) ? "encrypted" : "not_pdf");
2860
2538
  }
2539
+ if (rdr.trailerValue().keys().includes("Encrypt")) throw new ExtractError("encrypted");
2861
2540
  const sigs = [];
2862
2541
  const visible = /* @__PURE__ */ new Map();
2863
2542
  let docID = "";
@@ -3411,6 +3090,11 @@ var embedded = (b64) => b64.map((x) => parseCertificate(fromB64(x)));
3411
3090
  async function validatePdf(pdf, opts = {}) {
3412
3091
  const doc = pdf instanceof Uint8Array ? pdf : new Uint8Array(pdf);
3413
3092
  if (doc.length > MAX_PDF_BYTES) throw new ValidatePdfError("PDF_TOO_LARGE", "PDF 10 MiB-\u0430\u0430\u0441 \u0438\u0445");
3093
+ try {
3094
+ await subtle();
3095
+ } catch {
3096
+ throw new ValidatePdfError("UNSUPPORTED_ENVIRONMENT", "Web Crypto (crypto.subtle) \u0430\u043B\u0433\u0430 \u2014 https \u0445\u0443\u0443\u0434\u0430\u0441 \u044D\u0441\u0432\u044D\u043B \u0448\u0438\u043D\u044D \u0445\u04E9\u0442\u04E9\u0447 \u0448\u0430\u0430\u0440\u0434\u043B\u0430\u0433\u0430\u0442\u0430\u0439");
3097
+ }
3414
3098
  const roots = opts.roots && opts.roots.length > 0 ? ders(opts.roots, "roots") : embedded(NATIONAL_ROOT);
3415
3099
  const extraInter = ders(opts.intermediates, "intermediates");
3416
3100
  const issuers = [...embedded(EID_ISSUERS), ...ders(opts.issuers, "issuers")];
@@ -3421,15 +3105,16 @@ async function validatePdf(pdf, opts = {}) {
3421
3105
  if (e instanceof ExtractError) {
3422
3106
  if (e.code === "no_signature") throw new ValidatePdfError("PDF_NO_SIGNATURE", e.message);
3423
3107
  if (e.code === "too_many") throw new ValidatePdfError("PDF_TOO_MANY_SIGNATURES", e.message);
3108
+ if (e.code === "encrypted") throw new ValidatePdfError("PDF_ENCRYPTED", e.message);
3424
3109
  }
3425
3110
  throw new ValidatePdfError("PDF_INVALID", "PDF \u0437\u0430\u0434\u0430\u0440\u0441\u0430\u043D\u0433\u04AF\u0439");
3426
3111
  }
3427
3112
  const now = fromDate(opts.time ?? /* @__PURE__ */ new Date());
3428
3113
  const dss = ex.sigs.find((s) => s.dss)?.dss;
3429
- let status = new DSSStatus(dss, issuers);
3114
+ let status = new DSSStatus(dss, now);
3430
3115
  if (!opts.offline) {
3431
3116
  const fetchFn = opts.fetch ?? globalThis.fetch;
3432
- status = await OnlineStatus.create(new Fetcher(fetchFn, isBrowser(), opts.signal), ex.sigs, issuers, status, now);
3117
+ status = new OnlineStatus(new Fetcher(fetchFn, isBrowser(), opts.signal), status, now);
3433
3118
  }
3434
3119
  const ev = new Evaluator({ roots, intermediates: [...embedded(INTERMEDIATES), ...extraInter], issuers, status, now });
3435
3120
  const rep = { indication: "valid", signatures: [] };