@gerege-systems/eid-mongolia-sdk 0.36.0 → 0.38.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/index.js CHANGED
@@ -175,7 +175,7 @@ var RP_ROUTES = {
175
175
  tokenAuthChallenge: { method: "POST", path: "/token/auth/challenge" },
176
176
  tokenAuthVerify: { method: "POST", path: "/token/auth/verify" },
177
177
  share: { method: "POST", path: "/share" },
178
- /** «Миний QR» (CA гэрээ v1, 2026-10-23). */
178
+ /** «Миний QR» (CA гэрээ myqr-2026-10-26): `{qr, relyingPartyUUID, relyingPartyName, nonce}` → `{sessionID}`. */
179
179
  authQr: { method: "POST", path: "/authentication/qr" }
180
180
  };
181
181
  var PDF_SIGNATURE_REGISTER_FIELDS = [
@@ -367,15 +367,15 @@ var AuthApi = class {
367
367
 
368
368
  // src/sign.ts
369
369
  function registrationFromCompleted(done, extra) {
370
- const fail2 = (m) => {
370
+ const fail3 = (m) => {
371
371
  throw new ValidationError(`registrationFromCompleted: ${m}`);
372
372
  };
373
373
  const sessionID = extra.sessionID?.trim() ?? "";
374
374
  const medium = extra.medium || (sessionID ? "phone" : "token");
375
- if (medium !== "phone" && medium !== "token") fail2("medium: phone | token");
376
- if (medium === "phone" && !sessionID) fail2("medium phone-\u0434 sessionID \u0437\u0430\u0430\u0432\u0430\u043B");
377
- if (medium === "token" && sessionID) fail2("medium token-\u0434 sessionID \u0438\u043B\u0433\u044D\u044D\u0445\u0433\u04AF\u0439");
378
- if (done.claimedRole && !extra.onBehalfOf?.trim()) fail2("claimedRole-\u0442\u043E\u0439 \u0433\u0430\u0440\u044B\u043D \u04AF\u0441\u044D\u0433\u0442 onBehalfOf (NTRMN-\u2026) \u0437\u0430\u0430\u0432\u0430\u043B");
375
+ if (medium !== "phone" && medium !== "token") fail3("medium: phone | token");
376
+ if (medium === "phone" && !sessionID) fail3("medium phone-\u0434 sessionID \u0437\u0430\u0430\u0432\u0430\u043B");
377
+ if (medium === "token" && sessionID) fail3("medium token-\u0434 sessionID \u0438\u043B\u0433\u044D\u044D\u0445\u0433\u04AF\u0439");
378
+ if (done.claimedRole && !extra.onBehalfOf?.trim()) fail3("claimedRole-\u0442\u043E\u0439 \u0433\u0430\u0440\u044B\u043D \u04AF\u0441\u044D\u0433\u0442 onBehalfOf (NTRMN-\u2026) \u0437\u0430\u0430\u0432\u0430\u043B");
379
379
  const out = {
380
380
  docID: done.docId,
381
381
  revIndex: done.revIndex,
@@ -417,38 +417,38 @@ function priorSplits(n) {
417
417
  var HEX64 = /^[0-9a-f]{64}$/;
418
418
  var MAX_CMS_BYTES = 28672;
419
419
  function buildRegisterBody(input) {
420
- const fail2 = (m) => {
420
+ const fail3 = (m) => {
421
421
  throw new ValidationError(`registerSignature: ${m}`);
422
422
  };
423
- if (!UUID_RE.test(input.docID ?? "")) fail2("docID UUID \u0431\u0438\u0448");
424
- if (!Number.isInteger(input.revIndex) || input.revIndex < 1 || input.revIndex > 16) fail2("revIndex 1\u201316");
423
+ if (!UUID_RE.test(input.docID ?? "")) fail3("docID UUID \u0431\u0438\u0448");
424
+ if (!Number.isInteger(input.revIndex) || input.revIndex < 1 || input.revIndex > 16) fail3("revIndex 1\u201316");
425
425
  const hex = (name, v) => {
426
426
  const x = v?.trim().toLowerCase() ?? "";
427
- if (!HEX64.test(x)) fail2(`${name} SHA-256 hex (64) \u0431\u0438\u0448`);
427
+ if (!HEX64.test(x)) fail3(`${name} SHA-256 hex (64) \u0431\u0438\u0448`);
428
428
  return x;
429
429
  };
430
430
  let cmsB64;
431
431
  if (typeof input.cms === "string") {
432
432
  const raw = Buffer.from(input.cms, "base64");
433
- if (raw.length === 0 || raw.toString("base64") !== input.cms) fail2("cms \u0441\u0442\u0430\u043D\u0434\u0430\u0440\u0442 base64 \u0431\u0438\u0448");
433
+ if (raw.length === 0 || raw.toString("base64") !== input.cms) fail3("cms \u0441\u0442\u0430\u043D\u0434\u0430\u0440\u0442 base64 \u0431\u0438\u0448");
434
434
  cmsB64 = input.cms;
435
- if (raw.length > MAX_CMS_BYTES) fail2(`cms > ${MAX_CMS_BYTES} \u0431\u0430\u0439\u0442`);
435
+ if (raw.length > MAX_CMS_BYTES) fail3(`cms > ${MAX_CMS_BYTES} \u0431\u0430\u0439\u0442`);
436
436
  } else {
437
- if (!input.cms?.length) fail2("cms \u0445\u043E\u043E\u0441\u043E\u043D");
438
- if (input.cms.length > MAX_CMS_BYTES) fail2(`cms > ${MAX_CMS_BYTES} \u0431\u0430\u0439\u0442`);
437
+ if (!input.cms?.length) fail3("cms \u0445\u043E\u043E\u0441\u043E\u043D");
438
+ if (input.cms.length > MAX_CMS_BYTES) fail3(`cms > ${MAX_CMS_BYTES} \u0431\u0430\u0439\u0442`);
439
439
  cmsB64 = Buffer.from(input.cms).toString("base64");
440
440
  }
441
441
  const fileName = input.fileName?.trim() ?? "";
442
- if (!fileName || Array.from(fileName).length > PDF_MAX_FILE_NAME) fail2(`fileName \u0437\u0430\u0430\u0432\u0430\u043B, \u2264 ${PDF_MAX_FILE_NAME} \u0442\u044D\u043C\u0434\u044D\u0433\u0442`);
442
+ if (!fileName || Array.from(fileName).length > PDF_MAX_FILE_NAME) fail3(`fileName \u0437\u0430\u0430\u0432\u0430\u043B, \u2264 ${PDF_MAX_FILE_NAME} \u0442\u044D\u043C\u0434\u044D\u0433\u0442`);
443
443
  const sessionID = input.sessionID?.trim() ?? "";
444
444
  const medium = input.medium ?? (sessionID ? "phone" : "token");
445
- if (medium !== "phone" && medium !== "token") fail2("medium: phone | token");
446
- if (medium === "phone" && !sessionID) fail2("phone-\u0434 sessionID \u0437\u0430\u0430\u0432\u0430\u043B");
447
- if (medium === "token" && sessionID) fail2("token-\u0434 sessionID \u0438\u043B\u0433\u044D\u044D\u0445\u0433\u04AF\u0439");
445
+ if (medium !== "phone" && medium !== "token") fail3("medium: phone | token");
446
+ if (medium === "phone" && !sessionID) fail3("phone-\u0434 sessionID \u0437\u0430\u0430\u0432\u0430\u043B");
447
+ if (medium === "token" && sessionID) fail3("token-\u0434 sessionID \u0438\u043B\u0433\u044D\u044D\u0445\u0433\u04AF\u0439");
448
448
  const priorCms = (input.priorCmsSha256 ?? []).map((h, i) => hex(`priorCmsSha256[${i}]`, h));
449
449
  const priorRev = (input.priorRevisionSha256 ?? []).map((h, i) => hex(`priorRevisionSha256[${i}]`, h));
450
- if (priorCms.length + priorRev.length !== input.revIndex - 1) fail2("priorCmsSha256 + priorRevisionSha256-\u0438\u0439\u043D \u0442\u043E\u043E = revIndex \u2212 1");
451
- if (input.revIndex === 1 && !input.pageSha256) fail2("revIndex 1-\u0434 pageSha256 \u0437\u0430\u0430\u0432\u0430\u043B");
450
+ if (priorCms.length + priorRev.length !== input.revIndex - 1) fail3("priorCmsSha256 + priorRevisionSha256-\u0438\u0439\u043D \u0442\u043E\u043E = revIndex \u2212 1");
451
+ if (input.revIndex === 1 && !input.pageSha256) fail3("revIndex 1-\u0434 pageSha256 \u0437\u0430\u0430\u0432\u0430\u043B");
452
452
  const body = { docID: input.docID, revIndex: input.revIndex, medium };
453
453
  if (sessionID) body.sessionID = sessionID;
454
454
  body.cms = cmsB64;
@@ -461,7 +461,7 @@ function buildRegisterBody(input) {
461
461
  if (priorRev.length) body.priorRevisionSha256 = priorRev;
462
462
  if (input.onBehalfOf?.trim()) body.onBehalfOf = input.onBehalfOf.trim();
463
463
  if (input.signerEtsi?.trim()) body.signerEtsi = input.signerEtsi.trim();
464
- for (const k of Object.keys(body)) if (!PDF_SIGNATURE_REGISTER_FIELDS.includes(k)) fail2(`\u0434\u043E\u0442\u043E\u043E\u0434: \u04AF\u043B \u043C\u044D\u0434\u044D\u0433\u0434\u044D\u0445 \u0442\u0430\u043B\u0431\u0430\u0440 ${k}`);
464
+ for (const k of Object.keys(body)) if (!PDF_SIGNATURE_REGISTER_FIELDS.includes(k)) fail3(`\u0434\u043E\u0442\u043E\u043E\u0434: \u04AF\u043B \u043C\u044D\u0434\u044D\u0433\u0434\u044D\u0445 \u0442\u0430\u043B\u0431\u0430\u0440 ${k}`);
465
465
  return body;
466
466
  }
467
467
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
@@ -795,7 +795,7 @@ function parsePerson(raw) {
795
795
  function parsePresentation(raw) {
796
796
  const p = asRecord(raw);
797
797
  if (typeof p.jws !== "string" || !p.jws) return null;
798
- return { jws: p.jws, ...p.claims && typeof p.claims === "object" ? { claims: p.claims } : {} };
798
+ return { jws: p.jws };
799
799
  }
800
800
  function parseTokenCert(raw) {
801
801
  const t = asRecord(raw);
@@ -1305,6 +1305,22 @@ var ResponseValidator = class {
1305
1305
  this.checkValidity(leaf);
1306
1306
  this.verifyCertificate(leaf, "ACSP_V2");
1307
1307
  }
1308
+ /**
1309
+ * «Миний QR» (`verifyQrPresentation`)-ийн гарын үсэгтний гэрчилгээ, цаг `nowMs` ± `skewMs`: CA биш, хугацаа,
1310
+ * зориулалт (sign — contentCommitment, `checkKeyUsage`-ээс үл хамааран), trust anchor хүртэлх гинж (anchor ЗААВАЛ),
1311
+ * issuer allowlist, түвшин (qcStatements, `requiredLevel`). Шууд issuer-ийг (revocation-д) буцаана.
1312
+ * @internal
1313
+ */
1314
+ verifyQrSigner(leaf, nowMs, skewMs) {
1315
+ if (isCa(leaf)) throw new ValidationError("\u0413\u0430\u0440\u044B\u043D \u04AF\u0441\u044D\u0433\u0442\u043D\u0438\u0439 \u0433\u044D\u0440\u0447\u0438\u043B\u0433\u044D\u044D CA \u0431\u0430\u0439\u043D\u0430");
1316
+ if (this.anchors.length === 0) throw new ValidationError("Trust anchor \u0442\u043E\u0445\u0438\u0440\u0443\u0443\u043B\u0430\u0430\u0433\u04AF\u0439");
1317
+ this.checkValidity(leaf, nowMs, skewMs);
1318
+ if (!(keyUsageBits(leaf) & 64)) throw new ValidationError("\u0413\u0430\u0440\u044B\u043D \u04AF\u0441\u0433\u0438\u0439\u043D \u0433\u044D\u0440\u0447\u0438\u043B\u0433\u044D\u044D\u043D\u0434 KeyUsage nonRepudiation (contentCommitment) \u0430\u043B\u0433\u0430");
1319
+ this.verifyChain(leaf, EKU_EMAIL_PROTECTION, nowMs);
1320
+ this.checkIssuer(leaf);
1321
+ this.checkLevel(certificateLevelOf(leaf, "RAW_DIGEST_SIGNATURE"));
1322
+ return this.findIssuer(leaf);
1323
+ }
1308
1324
  /** Зориулалт (protocol), гинж, issuer — хугацаа/түвшнийг дуудагч шалгасан. */
1309
1325
  verifyCertificate(leaf, protocol) {
1310
1326
  this.checkPurpose(leaf, protocol);
@@ -1345,12 +1361,11 @@ var ResponseValidator = class {
1345
1361
  throw new ValidationError("\u0413\u044D\u0440\u0447\u0438\u043B\u0433\u044D\u044D\u0433 \u0433\u0430\u0440\u0433\u0430\u0441\u0430\u043D CA \u0437\u04E9\u0432\u0448\u04E9\u04E9\u0440\u04E9\u0433\u0434\u0441\u04E9\u043D \u0438\u0440\u0433\u044D\u043D\u0438\u0439 issuer \u0431\u0438\u0448 (allowedIssuerSkis)");
1346
1362
  }
1347
1363
  }
1348
- checkValidity(cert) {
1349
- const now = Date.now();
1364
+ checkValidity(cert, now = Date.now(), skew = this.skew) {
1350
1365
  const from = Date.parse(cert.validFrom);
1351
1366
  const to = Date.parse(cert.validTo);
1352
- if (!Number.isNaN(from) && now + this.skew < from) throw new ValidationError("\u0413\u044D\u0440\u0447\u0438\u043B\u0433\u044D\u044D \u0445\u04AF\u0447\u0438\u043D\u0442\u044D\u0439 \u0431\u043E\u043B\u043E\u043E\u0433\u04AF\u0439 \u0431\u0430\u0439\u043D\u0430");
1353
- if (!Number.isNaN(to) && now - this.skew > to) throw new ValidationError("\u0413\u044D\u0440\u0447\u0438\u043B\u0433\u044D\u044D\u043D\u0438\u0439 \u0445\u0443\u0433\u0430\u0446\u0430\u0430 \u0434\u0443\u0443\u0441\u0441\u0430\u043D");
1367
+ if (!Number.isNaN(from) && now + skew < from) throw new ValidationError("\u0413\u044D\u0440\u0447\u0438\u043B\u0433\u044D\u044D \u0445\u04AF\u0447\u0438\u043D\u0442\u044D\u0439 \u0431\u043E\u043B\u043E\u043E\u0433\u04AF\u0439 \u0431\u0430\u0439\u043D\u0430");
1368
+ if (!Number.isNaN(to) && now - skew > to) throw new ValidationError("\u0413\u044D\u0440\u0447\u0438\u043B\u0433\u044D\u044D\u043D\u0438\u0439 \u0445\u0443\u0433\u0430\u0446\u0430\u0430 \u0434\u0443\u0443\u0441\u0441\u0430\u043D");
1354
1369
  }
1355
1370
  checkLevel(level) {
1356
1371
  const got = LEVEL_RANK[level] ?? 0;
@@ -1366,8 +1381,8 @@ var ResponseValidator = class {
1366
1381
  * fail-closed (CA-ийн бодит гинж 01–04-т алга). Цаг = now, leaf-ийн хүчинтэй хугацаанд хавчсан (`clockSkewMs`-ийн
1367
1382
  * хүрээнд; leaf-ийн хугацааг checkValidity шалгасан). certificatePolicies шалгахгүй (Go-той ижил).
1368
1383
  */
1369
- verifyChain(leaf, usage) {
1370
- const now = Math.min(Math.max(Date.now(), Date.parse(leaf.validFrom)), Date.parse(leaf.validTo));
1384
+ verifyChain(leaf, usage, at = Date.now()) {
1385
+ const now = Math.min(Math.max(at, Date.parse(leaf.validFrom)), Date.parse(leaf.validTo));
1371
1386
  const leafReason = criticalReason(leaf) ?? ekuReason(leaf, usage);
1372
1387
  if (leafReason) throw new ValidationError(`\u0413\u044D\u0440\u0447\u0438\u043B\u0433\u044D\u044D\u043D\u0438\u0439 \u0433\u0438\u043D\u0436 \u0445\u04AF\u0447\u0438\u043D\u0433\u04AF\u0439: ${leafReason}`);
1373
1388
  let reason;
@@ -1378,9 +1393,9 @@ var ResponseValidator = class {
1378
1393
  ...this.intermediates.map((c) => [c, false])
1379
1394
  ]) {
1380
1395
  if (cas.includes(cand) || !signedBy(cur, cand)) continue;
1381
- const bad2 = caReason(cand, cas.length, now, usage);
1382
- if (bad2) {
1383
- reason ??= bad2;
1396
+ const bad = caReason(cand, cas.length, now, usage);
1397
+ if (bad) {
1398
+ reason ??= bad;
1384
1399
  continue;
1385
1400
  }
1386
1401
  if (isAnchor || extend(cand, [...cas, cand])) return true;
@@ -2018,23 +2033,105 @@ function tokenLimitOf(err) {
2018
2033
  }
2019
2034
 
2020
2035
  // src/myqr.ts
2021
- import { createPublicKey as createPublicKey2, verify as cryptoVerify } from "crypto";
2022
- var QR_ATTRIBUTES = ["age_over_18", "age_over_21", "full_name", "phone", "birth_date", "civil_id"];
2036
+ import { X509Certificate as X509Certificate4, constants as constants2, createHash as createHash5, randomBytes as randomBytes2, verify as cryptoVerify } from "crypto";
2037
+
2038
+ // src/ocsp.ts
2039
+ import { createHash as createHash4 } from "crypto";
2040
+ var CACHE_TTL_MS = 5 * 6e4;
2041
+ var CACHE_MAX = 1024;
2042
+ var MAX_BYTES = 16 << 10;
2043
+ var CLOCK_SKEW_MS = 5 * 6e4;
2044
+ var MAX_AGE_MS = 48 * 36e5;
2045
+ function ocspRevocationChecker(opts = {}) {
2046
+ const doFetch = opts.fetchImpl ?? globalThis.fetch;
2047
+ const timeoutMs = opts.timeoutMs ?? 2e3;
2048
+ const totalMs = Math.max(timeoutMs, 3e3);
2049
+ const now = opts.now ?? Date.now;
2050
+ const cache = /* @__PURE__ */ new Map();
2051
+ async function ask(leaf, issuer) {
2052
+ const body = await ocspRequest(leaf, issuer);
2053
+ const deadline = Date.now() + totalMs;
2054
+ for (const raw of leaf.ocspServers) {
2055
+ const left = deadline - Date.now();
2056
+ if (left <= 0) break;
2057
+ try {
2058
+ const u = new URL(raw);
2059
+ if (u.protocol !== "http:" && u.protocol !== "https:") continue;
2060
+ const res = await doFetch(u.toString(), {
2061
+ method: "POST",
2062
+ headers: { "Content-Type": "application/ocsp-request", Accept: "application/ocsp-response" },
2063
+ body,
2064
+ redirect: "manual",
2065
+ signal: AbortSignal.timeout(Math.min(timeoutMs, left))
2066
+ });
2067
+ if (res.status !== 200) continue;
2068
+ const der = new Uint8Array(await res.arrayBuffer());
2069
+ if (der.length > MAX_BYTES) continue;
2070
+ const resp = await parseOCSPFrom(der, intValue(leaf.serial), issuer);
2071
+ const t = now();
2072
+ const rc = resp.certificate;
2073
+ if (rc && !sameCertKey(rc, issuer)) {
2074
+ if (!rc.extKeyUsage.includes(OID.kpOCSPSigning)) continue;
2075
+ if (t < rc.notBefore.getTime() || t > rc.notAfter.getTime()) continue;
2076
+ }
2077
+ const tu = resp.thisUpdate.date.getTime();
2078
+ if (tu > t + CLOCK_SKEW_MS || tu < t - MAX_AGE_MS) continue;
2079
+ if (resp.nextUpdate && resp.nextUpdate.getTime() < t) continue;
2080
+ return { status: resp.status === "good" ? "good" : "revoked", nextUpdate: resp.nextUpdate?.getTime() };
2081
+ } catch {
2082
+ }
2083
+ }
2084
+ return void 0;
2085
+ }
2086
+ return async (cert, issuer) => {
2087
+ if (!issuer) return "unknown";
2088
+ let leaf, iss;
2089
+ try {
2090
+ leaf = parseCertificate(new Uint8Array(cert.raw));
2091
+ iss = parseCertificate(new Uint8Array(issuer.raw));
2092
+ } catch {
2093
+ return "unknown";
2094
+ }
2095
+ const key = createHash4("sha256").update(issuer.raw).digest("hex").slice(0, 16) + ":" + cert.serialNumber;
2096
+ const exp = cache.get(key);
2097
+ if (exp !== void 0 && now() < exp) return "good";
2098
+ const r = await ask(leaf, iss);
2099
+ if (!r) return "unknown";
2100
+ if (r.status === "good") {
2101
+ const t = now();
2102
+ const until = Math.min(t + CACHE_TTL_MS, r.nextUpdate ?? Infinity);
2103
+ if (until > t) {
2104
+ if (cache.size >= CACHE_MAX) cache.clear();
2105
+ cache.set(key, until);
2106
+ }
2107
+ }
2108
+ return r.status;
2109
+ };
2110
+ }
2111
+
2112
+ // src/myqr.ts
2023
2113
  var QR_PREFIX = "EIDMN-QR1:";
2024
2114
  var DEFAULT_QR_ISSUER = "https://ca.eidmongolia.mn";
2025
- var DEFAULT_QR_JWKS_URL = "https://ca.eidmongolia.mn/.well-known/eid-jwks.json";
2026
- var DEFAULT_QR_JWKS_CACHE_TTL_MS = 36e5;
2027
- var DEFAULT_QR_MAX_AGE_MS = 6e5;
2028
- var QR_CLOCK_SKEW_MS = 6e4;
2029
- var JWKS_MIN_REFRESH_MS = 3e4;
2030
- var MAX_JWS = 16 << 10;
2031
- var MAX_JWKS = 64 << 10;
2115
+ var QR_CLOCK_SKEW_SECONDS = 60;
2116
+ var QR_MAX_AGE_SECONDS = 300;
2117
+ var QR_LIMITS = Object.freeze({ maxFields: 128, maxKeyChars: 64, maxValueBytes: 2048, maxPhotoBytes: 153600 });
2118
+ var MAX_JWS_BYTES = 524288;
2032
2119
  var QR_ERROR_CODES = [
2033
2120
  "QR_FORMAT_INVALID",
2034
- "QR_TOKEN_INVALID",
2035
- "QR_ATTRIBUTES_INVALID",
2036
- "QR_PRESENTATION_INVALID",
2037
- "QR_JWKS_UNAVAILABLE",
2121
+ "QR_JWS_MALFORMED",
2122
+ "QR_HEADER_INVALID",
2123
+ "QR_CHAIN_INVALID",
2124
+ "QR_CERT_REVOKED",
2125
+ "QR_REVOCATION_UNKNOWN",
2126
+ "QR_SIGNATURE_INVALID",
2127
+ "QR_CLAIMS_INVALID",
2128
+ "QR_AUDIENCE_MISMATCH",
2129
+ "QR_SESSION_MISMATCH",
2130
+ "QR_NONCE_MISMATCH",
2131
+ "QR_NOT_YET_VALID",
2132
+ "QR_EXPIRED",
2133
+ "QR_DATA_INVALID",
2134
+ "QR_PRESENTATION_GONE",
2038
2135
  "QR_PENDING"
2039
2136
  ];
2040
2137
  var QrError = class extends EidError {
@@ -2046,303 +2143,260 @@ var QrError = class extends EidError {
2046
2143
  code;
2047
2144
  reason;
2048
2145
  };
2049
- var bad = (reason) => new QrError("QR_PRESENTATION_INVALID", reason);
2050
2146
  var TOKEN_RE = /^[A-Za-z0-9_-]{43}$/;
2147
+ var SEGMENT_RE = /^[A-Za-z0-9_-]+$/;
2148
+ var STD_B64_RE = /^[A-Za-z0-9+/]*={0,2}$/;
2149
+ var SOURCE_RE = /^[a-z0-9_-]{1,32}$/;
2150
+ var KEY_FORBIDDEN_RE = /[\u0000-\u001f\u007f-\u009f]/;
2151
+ var LONE_SURROGATE_RE = /\p{Cs}/u;
2152
+ var utf8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
2153
+ var fail = (code, reason) => new QrError(code, reason);
2051
2154
  function parseQr(scanned) {
2052
- let s = String(scanned ?? "").trim();
2053
- if (s.startsWith(QR_PREFIX)) s = s.slice(QR_PREFIX.length);
2054
- if (!TOKEN_RE.test(s)) throw new QrError("QR_FORMAT_INVALID", "eID \xAB\u041C\u0438\u043D\u0438\u0439 QR\xBB \u0431\u0438\u0448");
2055
- return s;
2155
+ const s = String(scanned ?? "").replace(/^[\t\n\v\f\r ]+|[\t\n\v\f\r ]+$/g, "");
2156
+ const token = s.slice(QR_PREFIX.length);
2157
+ if (!s.startsWith(QR_PREFIX) || !TOKEN_RE.test(token)) throw fail("QR_FORMAT_INVALID", "eID \xAB\u041C\u0438\u043D\u0438\u0439 QR\xBB \u0431\u0438\u0448");
2158
+ return { token, qr: QR_PREFIX + token };
2056
2159
  }
2057
- function checkAttributes(attrs) {
2058
- if (!attrs?.length) throw new QrError("QR_ATTRIBUTES_INVALID", "\u0430\u0442\u0442\u0440\u0438\u0431\u0443\u0442 \u0441\u043E\u043D\u0433\u043E\u043E\u0433\u04AF\u0439");
2059
- const seen = /* @__PURE__ */ new Set();
2060
- for (const a of attrs) {
2061
- if (!QR_ATTRIBUTES.includes(a)) throw new QrError("QR_ATTRIBUTES_INVALID", `\u043A\u0430\u0442\u0430\u043B\u043E\u0433\u0438\u0434 \u0430\u043B\u0433\u0430: ${a}`);
2062
- if (seen.has(a)) throw new QrError("QR_ATTRIBUTES_INVALID", `\u0434\u0430\u0432\u0445\u0430\u0440\u0434\u0441\u0430\u043D: ${a}`);
2063
- seen.add(a);
2064
- }
2065
- return [...attrs];
2160
+ function qrStatement(rpName) {
2161
+ return `\u0422\u0430 ${rpName}-\u0434 \xAB\u041C\u0438\u043D\u0438\u0439 \u043C\u044D\u0434\u044D\u044D\u043B\u044D\u043B\xBB \u0445\u044D\u0441\u0433\u0438\u0439\u043D \u0431\u04AF\u0445 \u043C\u044D\u0434\u044D\u044D\u043B\u043B\u0438\u0439\u0433 \u0445\u0443\u0432\u0430\u0430\u043B\u0446\u0430\u0445 \u0433\u044D\u0436 \u0431\u0430\u0439\u043D\u0430`;
2066
2162
  }
2067
- var UnknownKid = class extends Error {
2068
- };
2069
- var B64URL_RE = /^[A-Za-z0-9_-]*$/;
2070
- function b64url(s) {
2071
- if (!B64URL_RE.test(s) || s.length % 4 === 1) throw bad("base64url \u0431\u0443\u0440\u0443\u0443");
2072
- return Buffer.from(s, "base64url");
2163
+ function isObj(v) {
2164
+ return !!v && typeof v === "object" && !Array.isArray(v);
2073
2165
  }
2074
- function keyFor(jwks, kid) {
2075
- const j = jwks?.keys?.find((k) => k?.kid === kid);
2076
- if (!j) throw new UnknownKid();
2077
- if (j.kty !== "EC" || j.crv !== "P-256" || j.alg && j.alg !== "ES256" || j.use && j.use !== "sig") {
2078
- throw bad(`kid ${kid} \u043D\u044C ES256 P-256 \u0442\u04AF\u043B\u0445\u04AF\u04AF\u0440 \u0431\u0438\u0448`);
2079
- }
2166
+ function jsonSegment(seg) {
2080
2167
  try {
2081
- if (b64url(j.x ?? "").length !== 32 || b64url(j.y ?? "").length !== 32) throw new Error("x/y");
2082
- return createPublicKey2({ key: { kty: "EC", crv: "P-256", x: j.x, y: j.y }, format: "jwk" });
2168
+ const b = Buffer.from(seg, "base64url");
2169
+ if (b.toString("base64url") !== seg) return void 0;
2170
+ return JSON.parse(utf8.decode(b));
2083
2171
  } catch {
2084
- throw bad(`kid ${kid}: \u0442\u04AF\u043B\u0445\u04AF\u04AF\u0440 \u0431\u0443\u0440\u0443\u0443`);
2172
+ return void 0;
2085
2173
  }
2086
2174
  }
2087
- function isObj(v) {
2088
- return !!v && typeof v === "object" && !Array.isArray(v);
2175
+ function stdBase64(s) {
2176
+ if (!s || s.length % 4 !== 0 || !STD_B64_RE.test(s)) return void 0;
2177
+ const b = Buffer.from(s, "base64");
2178
+ return b.toString("base64") === s ? b : void 0;
2089
2179
  }
2090
- var PHONE_RE = /^\+[1-9][0-9]{6,14}$/;
2091
- var DATE_RE = /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/;
2092
- function validDate(s) {
2093
- const m = DATE_RE.exec(s);
2094
- if (!m) return false;
2095
- const [y, mo, d] = [Number(m[1]), Number(m[2]), Number(m[3])];
2096
- const t = new Date(Date.UTC(y, mo - 1, d));
2097
- return t.getUTCFullYear() === y && t.getUTCMonth() === mo - 1 && t.getUTCDate() === d;
2098
- }
2099
- function setAttr(out, name, v) {
2100
- const wrong = () => bad(`${name}-\u0438\u0439\u043D \u0442\u04E9\u0440\u04E9\u043B \u0431\u0443\u0440\u0443\u0443`);
2101
- switch (name) {
2102
- case "age_over_18":
2103
- case "age_over_21":
2104
- if (typeof v !== "boolean") throw wrong();
2105
- out[name] = v;
2106
- return;
2107
- case "full_name":
2108
- if (!isObj(v) || typeof v.surname !== "string" || typeof v.givenName !== "string" || !v.givenName) throw wrong();
2109
- out.full_name = { surname: v.surname, givenName: v.givenName };
2110
- return;
2111
- case "phone":
2112
- if (typeof v !== "string" || !PHONE_RE.test(v)) throw wrong();
2113
- out.phone = v;
2114
- return;
2115
- case "birth_date":
2116
- if (typeof v !== "string" || !validDate(v)) throw wrong();
2117
- out.birth_date = v;
2118
- return;
2119
- case "civil_id":
2120
- if (typeof v !== "string" || !v) throw wrong();
2121
- out.civil_id = v;
2122
- return;
2180
+ var derToPem = (der) => `-----BEGIN CERTIFICATE-----
2181
+ ${der.toString("base64").match(/.{1,64}/g).join("\n")}
2182
+ -----END CERTIFICATE-----
2183
+ `;
2184
+ var defaultChecker;
2185
+ function revocationOf(trust) {
2186
+ return trust.revocation ?? (defaultChecker ??= ocspRevocationChecker());
2187
+ }
2188
+ function checkData(d) {
2189
+ const bad = (why) => fail("QR_DATA_INVALID", why);
2190
+ if (!isObj(d)) throw bad("data \u043E\u0431\u044A\u0435\u043A\u0442 \u0431\u0438\u0448");
2191
+ for (const k of Object.keys(d)) if (k !== "source" && k !== "fields" && k !== "photo") throw bad("data-\u0434 \u0438\u043B\u04AF\u04AF \u0433\u0438\u0448\u04AF\u04AF\u043D");
2192
+ if (typeof d.source !== "string" || !SOURCE_RE.test(d.source)) throw bad("source \u0431\u0443\u0440\u0443\u0443");
2193
+ if (!isObj(d.fields)) throw bad("fields \u043E\u0431\u044A\u0435\u043A\u0442 \u0431\u0438\u0448");
2194
+ const keys = Object.keys(d.fields);
2195
+ if (keys.length > QR_LIMITS.maxFields) throw bad(`fields > ${QR_LIMITS.maxFields}`);
2196
+ for (const k of keys) {
2197
+ const n = [...k].length;
2198
+ if (n < 1 || n > QR_LIMITS.maxKeyChars || KEY_FORBIDDEN_RE.test(k) || LONE_SURROGATE_RE.test(k)) throw bad("\u0442\u04AF\u043B\u0445\u04AF\u04AF\u0440 \u0431\u0443\u0440\u0443\u0443");
2199
+ const v = d.fields[k];
2200
+ if (typeof v !== "string") throw bad("\u0443\u0442\u0433\u0430 string \u0431\u0438\u0448");
2201
+ if (Buffer.byteLength(v, "utf8") > QR_LIMITS.maxValueBytes || v.includes("\0") || LONE_SURROGATE_RE.test(v)) {
2202
+ throw bad(`\u0443\u0442\u0433\u0430 > ${QR_LIMITS.maxValueBytes} \u0431\u0430\u0439\u0442 \u044D\u0441\u0432\u044D\u043B \u0431\u0443\u0440\u0443\u0443 \u0442\u044D\u043C\u0434\u044D\u0433\u0442`);
2203
+ }
2204
+ }
2205
+ let photo;
2206
+ if ("photo" in d) {
2207
+ if (typeof d.photo !== "string") throw bad("photo string \u0431\u0438\u0448");
2208
+ const b = stdBase64(d.photo);
2209
+ if (!b) throw bad("photo base64 \u0431\u0438\u0448");
2210
+ if (b.length > QR_LIMITS.maxPhotoBytes) throw bad(`photo > ${QR_LIMITS.maxPhotoBytes} \u0431\u0430\u0439\u0442`);
2211
+ if (b.length < 3 || b[0] !== 255 || b[1] !== 216 || b[2] !== 255) throw bad("photo JPEG \u0431\u0438\u0448");
2212
+ photo = d.photo;
2213
+ }
2214
+ if (keys.length === 0 && photo === void 0) throw bad("fields \u0445\u043E\u043E\u0441\u043E\u043D, photo \u0430\u043B\u0433\u0430");
2215
+ return { source: d.source, fields: d.fields, ...photo !== void 0 ? { photo } : {} };
2216
+ }
2217
+ async function verifyQrPresentation(jws, expect, trust) {
2218
+ if (typeof jws !== "string" || Buffer.byteLength(jws, "utf8") > MAX_JWS_BYTES) throw fail("QR_JWS_MALFORMED", "JWS \u0445\u044D\u0442 \u0443\u0440\u0442 \u044D\u0441\u0432\u044D\u043B string \u0431\u0438\u0448");
2219
+ const seg = jws.split(".");
2220
+ if (seg.length !== 3 || !seg.every((s) => SEGMENT_RE.test(s))) throw fail("QR_JWS_MALFORMED", "compact JWS \u0431\u0438\u0448");
2221
+ const [h64, p64, s64] = seg;
2222
+ const badHeader = (why) => fail("QR_HEADER_INVALID", why);
2223
+ const hdr = jsonSegment(h64);
2224
+ if (!isObj(hdr)) throw badHeader("header JSON \u043E\u0431\u044A\u0435\u043A\u0442 \u0431\u0438\u0448");
2225
+ const hk = Object.keys(hdr);
2226
+ if (hk.length !== 3 || !hk.includes("alg") || !hk.includes("typ") || !hk.includes("x5c")) throw badHeader("header \u0437\u04E9\u0432\u0445\u04E9\u043D alg, typ, x5c");
2227
+ if (hdr.alg !== "PS256") throw badHeader("alg PS256 \u0431\u0438\u0448");
2228
+ if (hdr.typ !== "eidmn-myqr+jwt") throw badHeader("typ eidmn-myqr+jwt \u0431\u0438\u0448");
2229
+ const x5c = hdr.x5c;
2230
+ if (!Array.isArray(x5c) || x5c.length !== 2 || !x5c.every((c2) => typeof c2 === "string" && c2.length > 0)) {
2231
+ throw badHeader("x5c 2 \u0433\u044D\u0440\u0447\u0438\u043B\u0433\u044D\u044D \u0431\u0438\u0448");
2232
+ }
2233
+ const certs = x5c.map((c2) => {
2234
+ const der = stdBase64(c2);
2235
+ if (!der) throw badHeader("x5c base64 \u0431\u0438\u0448");
2236
+ try {
2237
+ const cert = new X509Certificate4(der);
2238
+ if (!cert.raw.equals(der)) throw new Error("trailing");
2239
+ return cert;
2240
+ } catch {
2241
+ throw badHeader("x5c \u0433\u044D\u0440\u0447\u0438\u043B\u0433\u044D\u044D \u0431\u0438\u0448");
2242
+ }
2243
+ });
2244
+ const leaf = certs[0];
2245
+ const nowMs = (expect.now ?? /* @__PURE__ */ new Date()).getTime();
2246
+ const validator = new ResponseValidator({
2247
+ ...trust,
2248
+ trustAnchorsPem: trust.trustAnchorsPem?.length ? trust.trustAnchorsPem : [NATIONAL_ROOT_CA_PEM],
2249
+ intermediatesPem: [...trust.intermediatesPem ?? CITIZEN_INTERMEDIATES_PEM, derToPem(certs[1].raw)],
2250
+ requiredLevel: trust.requiredLevel === "QSCD" ? "QSCD" : "QUALIFIED",
2251
+ allowUntrusted: false
2252
+ });
2253
+ let issuer;
2254
+ try {
2255
+ issuer = validator.verifyQrSigner(leaf, nowMs, QR_CLOCK_SKEW_SECONDS * 1e3);
2256
+ } catch (e) {
2257
+ throw fail("QR_CHAIN_INVALID", e instanceof Error ? e.message : "\u0433\u0438\u043D\u0436 \u0445\u04AF\u0447\u0438\u043D\u0433\u04AF\u0439");
2123
2258
  }
2124
- throw wrong();
2125
- }
2126
- function numericDate(v) {
2127
- return typeof v === "number" && Number.isFinite(v) && v > 0 && v < 1e11 ? v * 1e3 : void 0;
2128
- }
2129
- function verifyInner(jws, jwks, exp) {
2130
- if (typeof jws !== "string" || !jws || jws.length > MAX_JWS) throw bad("JWS \u0445\u043E\u043E\u0441\u043E\u043D \u044D\u0441\u0432\u044D\u043B \u0445\u044D\u0442 \u0443\u0440\u0442");
2131
- const parts = jws.split(".");
2132
- if (parts.length !== 3) throw bad("compact JWS \u0431\u0438\u0448");
2133
- const [h64, p64, s64] = parts;
2134
- const hb = b64url(h64);
2135
- const pb = b64url(p64);
2136
- const sig = b64url(s64);
2137
- let hdr;
2259
+ const kt = leaf.publicKey.asymmetricKeyType;
2260
+ if (kt !== "rsa" && kt !== "rsa-pss" || (leaf.publicKey.asymmetricKeyDetails?.modulusLength ?? 0) < 2048) {
2261
+ throw fail("QR_CHAIN_INVALID", "\u0433\u0430\u0440\u044B\u043D \u04AF\u0441\u044D\u0433\u0442\u043D\u0438\u0439 \u0442\u04AF\u043B\u0445\u04AF\u04AF\u0440 RSA \u2265 2048 \u0431\u0438\u0448");
2262
+ }
2263
+ let status;
2138
2264
  try {
2139
- hdr = JSON.parse(hb.toString("utf8"));
2265
+ status = await revocationOf(trust)(leaf, issuer);
2140
2266
  } catch {
2141
- throw bad("header JSON \u0431\u0438\u0448");
2142
- }
2143
- if (!isObj(hdr) || hdr.alg !== "ES256") throw bad("alg ES256 \u0431\u0438\u0448");
2144
- if ("crit" in hdr) throw bad("crit \u0434\u044D\u043C\u0436\u0438\u0445\u0433\u04AF\u0439");
2145
- if (typeof hdr.kid !== "string" || !hdr.kid) throw bad("kid \u0430\u043B\u0433\u0430");
2146
- const key = keyFor(jwks, hdr.kid);
2147
- if (sig.length !== 64) throw bad("ES256 \u0433\u0430\u0440\u044B\u043D \u04AF\u0441\u044D\u0433 64 \u0431\u0430\u0439\u0442 \u0431\u0438\u0448");
2148
- const ok = cryptoVerify("sha256", Buffer.from(`${h64}.${p64}`, "ascii"), { key, dsaEncoding: "ieee-p1363" }, sig);
2149
- if (!ok) throw bad("\u0433\u0430\u0440\u044B\u043D \u04AF\u0441\u044D\u0433 \u0442\u0430\u0430\u0440\u0441\u0430\u043D\u0433\u04AF\u0439");
2150
- let c;
2267
+ status = "unknown";
2268
+ }
2269
+ if (status === "revoked") throw fail("QR_CERT_REVOKED", "\u0433\u044D\u0440\u0447\u0438\u043B\u0433\u044D\u044D \u0446\u0443\u0446\u043B\u0430\u0433\u0434\u0441\u0430\u043D");
2270
+ if (status !== "good" && (trust.revocationMode ?? "hard-fail") === "hard-fail") {
2271
+ throw fail("QR_REVOCATION_UNKNOWN", "\u0433\u044D\u0440\u0447\u0438\u043B\u0433\u044D\u044D\u043D\u0438\u0439 \u0446\u0443\u0446\u043B\u0430\u043B\u0442\u044B\u043D \u0442\u04E9\u043B\u04E9\u0432 \u0442\u043E\u0433\u0442\u043E\u043E\u0433\u0434\u0441\u043E\u043D\u0433\u04AF\u0439");
2272
+ }
2273
+ const signingInput = Buffer.from(`${h64}.${p64}`, "ascii");
2274
+ let sigOk = false;
2151
2275
  try {
2152
- c = JSON.parse(pb.toString("utf8"));
2276
+ const sig = Buffer.from(s64, "base64url");
2277
+ sigOk = sig.toString("base64url") === s64 && cryptoVerify("sha256", signingInput, { key: leaf.publicKey, padding: constants2.RSA_PKCS1_PSS_PADDING, saltLength: 32 }, sig);
2153
2278
  } catch {
2154
- throw bad("payload JSON \u0431\u0438\u0448");
2155
- }
2156
- if (!isObj(c)) throw bad("payload JSON \u043E\u0431\u044A\u0435\u043A\u0442 \u0431\u0438\u0448");
2157
- if (c.iss !== (exp.issuer || DEFAULT_QR_ISSUER)) throw bad("iss \u0442\u0430\u0430\u0440\u0441\u0430\u043D\u0433\u04AF\u0439");
2158
- if (!exp.audience || typeof c.aud !== "string" || c.aud.toLowerCase() !== exp.audience.toLowerCase()) throw bad("aud (RP UUID) \u0442\u0430\u0430\u0440\u0441\u0430\u043D\u0433\u04AF\u0439");
2159
- if (!exp.sessionId || c.sid !== exp.sessionId) throw bad("sid \u0442\u0430\u0430\u0440\u0441\u0430\u043D\u0433\u04AF\u0439");
2160
- if (!exp.nonce || c.nonce !== exp.nonce) throw bad("nonce \u0442\u0430\u0430\u0440\u0441\u0430\u043D\u0433\u04AF\u0439");
2161
- if (typeof c.sub !== "string" || !c.sub) throw bad("sub \u0430\u043B\u0433\u0430");
2162
- const now = exp.now ?? Date.now();
2163
- const iat = numericDate(c.iat);
2164
- if (iat === void 0) throw bad("iat \u0430\u043B\u0433\u0430");
2165
- if (iat > now + QR_CLOCK_SKEW_MS) throw bad("iat \u0438\u0440\u044D\u044D\u0434\u04AF\u0439\u0434");
2166
- if (now - iat > (exp.maxAgeMs && exp.maxAgeMs > 0 ? exp.maxAgeMs : DEFAULT_QR_MAX_AGE_MS)) throw bad("presentation \u0445\u0443\u0443\u0447\u0438\u0440\u0441\u0430\u043D");
2167
- if ("exp" in c) {
2168
- const e = numericDate(c.exp);
2169
- if (e === void 0 || now >= e + QR_CLOCK_SKEW_MS) throw bad("exp \u0434\u0443\u0443\u0441\u0441\u0430\u043D");
2170
- }
2171
- const want = new Set(exp.attributes);
2172
- const got = /* @__PURE__ */ new Set();
2173
- let attrs = {};
2174
- if ("attrs" in c) {
2175
- if (!isObj(c.attrs)) throw bad("attrs \u043E\u0431\u044A\u0435\u043A\u0442 \u0431\u0438\u0448");
2176
- attrs = c.attrs;
2177
- }
2178
- const out = { sub: c.sub, attrs: {}, unavailable: [], sessionId: exp.sessionId, issuedAt: iat, jws };
2179
- for (const [name, v] of Object.entries(attrs)) {
2180
- if (!want.has(name)) throw bad(`\u0445\u04AF\u0441\u044D\u044D\u0433\u04AF\u0439 \u0430\u0442\u0442\u0440\u0438\u0431\u0443\u0442: ${name}`);
2181
- setAttr(out.attrs, name, v);
2182
- got.add(name);
2183
- }
2184
- if ("unavailable" in c) {
2185
- if (!Array.isArray(c.unavailable)) throw bad("unavailable \u043C\u0430\u0441\u0441\u0438\u0432 \u0431\u0438\u0448");
2186
- for (const x of c.unavailable) {
2187
- if (typeof x !== "string" || !want.has(x) || got.has(x)) throw bad(`unavailable \u0431\u0443\u0440\u0443\u0443: ${String(x)}`);
2188
- got.add(x);
2189
- out.unavailable.push(x);
2190
- }
2191
- }
2192
- if (got.size !== want.size) throw bad("\u0445\u04AF\u0441\u0441\u044D\u043D \u0430\u0442\u0442\u0440\u0438\u0431\u0443\u0442\u044B\u043D \u0445\u0430\u0440\u0438\u0443 \u0434\u0443\u0442\u0443\u0443");
2193
- return out;
2194
- }
2195
- function verifyQrPresentation(jws, jwks, expect) {
2196
- try {
2197
- return verifyInner(jws, jwks, expect);
2198
- } catch (e) {
2199
- if (e instanceof UnknownKid) throw bad("JWKS-\u0434 kid \u0430\u043B\u0433\u0430");
2200
- throw e;
2201
- }
2279
+ sigOk = false;
2280
+ }
2281
+ if (!sigOk) throw fail("QR_SIGNATURE_INVALID", "\u0433\u0430\u0440\u044B\u043D \u04AF\u0441\u044D\u0433 \u0442\u0430\u0430\u0440\u0441\u0430\u043D\u0433\u04AF\u0439");
2282
+ const c = jsonSegment(p64);
2283
+ if (!isObj(c)) throw fail("QR_JWS_MALFORMED", "payload JSON \u043E\u0431\u044A\u0435\u043A\u0442 \u0431\u0438\u0448");
2284
+ const badClaims = (why) => fail("QR_CLAIMS_INVALID", why);
2285
+ if (c.iss !== (expect.issuer || DEFAULT_QR_ISSUER)) throw badClaims("iss \u0442\u0430\u0430\u0440\u0441\u0430\u043D\u0433\u04AF\u0439");
2286
+ const subj = parseSubject(leaf);
2287
+ if (typeof c.sub !== "string" || !subj.serialNumber || c.sub !== subj.serialNumber) throw badClaims("sub \u2260 \u0433\u044D\u0440\u0447\u0438\u043B\u0433\u044D\u044D\u043D\u0438\u0439 serialNumber");
2288
+ for (const k of ["rp_name", "statement", "nonce", "sid", "aud"]) if (typeof c[k] !== "string") throw badClaims(`${k} string \u0431\u0438\u0448`);
2289
+ if (!Number.isSafeInteger(c.iat) || !Number.isSafeInteger(c.exp)) throw badClaims("iat/exp \u0431\u04AF\u0445\u044D\u043B \u0442\u043E\u043E \u0431\u0438\u0448");
2290
+ if (c.statement !== qrStatement(c.rp_name)) throw badClaims("statement \u0442\u0430\u0430\u0440\u0441\u0430\u043D\u0433\u04AF\u0439");
2291
+ const iat = c.iat;
2292
+ const exp = c.exp;
2293
+ if (!expect.rpUUID || c.aud.toLowerCase() !== expect.rpUUID.toLowerCase()) throw fail("QR_AUDIENCE_MISMATCH", "aud (RP UUID) \u0442\u0430\u0430\u0440\u0441\u0430\u043D\u0433\u04AF\u0439");
2294
+ if (!expect.sessionId || c.sid !== expect.sessionId) throw fail("QR_SESSION_MISMATCH", "sid \u0442\u0430\u0430\u0440\u0441\u0430\u043D\u0433\u04AF\u0439");
2295
+ if (!expect.nonce || c.nonce !== expect.nonce) throw fail("QR_NONCE_MISMATCH", "nonce \u0442\u0430\u0430\u0440\u0441\u0430\u043D\u0433\u04AF\u0439");
2296
+ const now = nowMs / 1e3;
2297
+ if (exp - iat <= 0 || exp - iat > QR_MAX_AGE_SECONDS) throw badClaims(`exp \u2212 iat \u2209 (0, ${QR_MAX_AGE_SECONDS}]`);
2298
+ if (iat > now + QR_CLOCK_SKEW_SECONDS) throw fail("QR_NOT_YET_VALID", "iat \u0438\u0440\u044D\u044D\u0434\u04AF\u0439\u0434");
2299
+ if (now >= exp + QR_CLOCK_SKEW_SECONDS) throw fail("QR_EXPIRED", "presentation-\u0438\u0439\u043D \u0445\u0443\u0433\u0430\u0446\u0430\u0430 \u0434\u0443\u0443\u0441\u0441\u0430\u043D");
2300
+ const data = checkData(c.data);
2301
+ const claims = {
2302
+ iss: c.iss,
2303
+ sub: c.sub,
2304
+ aud: c.aud,
2305
+ rp_name: c.rp_name,
2306
+ sid: c.sid,
2307
+ nonce: c.nonce,
2308
+ iat,
2309
+ exp,
2310
+ statement: c.statement,
2311
+ data
2312
+ };
2313
+ return {
2314
+ jws,
2315
+ claims,
2316
+ data: Object.fromEntries(Object.entries(data.fields)),
2317
+ source: data.source,
2318
+ ...data.photo !== void 0 ? { photo: new Uint8Array(Buffer.from(data.photo, "base64")) } : {},
2319
+ signer: {
2320
+ certificate: leaf,
2321
+ etsi: c.sub,
2322
+ ...subj.givenName ? { givenName: subj.givenName } : {},
2323
+ ...subj.surname ? { surname: subj.surname } : {},
2324
+ ...subj.commonName ? { commonName: subj.commonName } : {}
2325
+ },
2326
+ signedAt: new Date(iat * 1e3),
2327
+ sha256: createHash5("sha256").update(signingInput).digest("hex")
2328
+ };
2202
2329
  }
2203
2330
  var QrApi = class {
2204
2331
  constructor(d) {
2205
2332
  this.d = d;
2206
2333
  }
2207
2334
  d;
2208
- jwks = null;
2209
- fetchedAt = 0;
2210
- lastAttempt = 0;
2211
- inflight = null;
2212
2335
  /** {@link parseQr}. */
2213
2336
  parse(scanned) {
2214
2337
  return parseQr(scanned);
2215
2338
  }
2216
2339
  /**
2217
- * `POST /authentication/qr` — QR-ийн токеныг (нэг удаагийн) CA-д өгч иргэний утас руу хүсэлт илгээнэ; `vc`-г кассын
2218
- * дэлгэцэнд харуул. Алдаа: {@link QrError} (FORMAT / ATTRIBUTES — CA руу явахгүй), 404 {@link QrTokenInvalidError}
2219
- * (шинэ QR гаргуул), 403 ForbiddenError (QR_PRESENT / QR_ATTR:* эрх алга).
2340
+ * `POST /authentication/qr` — QR-ийн токеныг (нэг удаагийн) CA-д өгч иргэний утас руу хүсэлт илгээнэ (VC алга). Буруу
2341
+ * мөр → {@link QrError} `QR_FORMAT_INVALID` (CA руу явахгүй). CA-ийн алдаа: 404 `QrTokenInvalidError` (шинэ QR), 409
2342
+ * `NoSigningCertificateError`, 403 `ForbiddenError` (`PERMISSION_DENIED` — `QR_PRESENT` алга, `RP_REQUIRED`), 400
2343
+ * `RequestInvalidError` (nonce буруу г.м.), 429 `RATE_LIMITED`.
2220
2344
  */
2221
2345
  async start(input) {
2222
- const token = parseQr(input.qr);
2223
- const attributes = checkAttributes(input.attributes);
2224
- const rpChallenge = randomChallenge(32);
2225
- const nonce = input.nonce?.trim() || void 0;
2346
+ const p = parseQr(input.qr);
2347
+ const nonce = input.nonce ?? randomBytes2(16).toString("base64url");
2226
2348
  const body = {
2227
- qr: QR_PREFIX + token,
2228
- attributes,
2349
+ qr: p.qr,
2229
2350
  relyingPartyUUID: this.d.credentials.rpUUID,
2230
- relyingPartyName: this.d.credentials.rpName,
2231
- signatureProtocol: "ACSP_V2",
2232
- signatureProtocolParameters: { rpChallenge },
2233
- ...nonce ? { nonce } : {}
2351
+ relyingPartyName: input.relyingPartyName ?? this.d.credentials.rpName,
2352
+ nonce
2234
2353
  };
2235
2354
  const r = await this.d.http.post(routePath(RP_ROUTES.authQr), body);
2236
- const sessionId = typeof r.sessionID === "string" ? r.sessionID : "";
2355
+ const sessionId = typeof r?.sessionID === "string" ? r.sessionID : "";
2237
2356
  if (!sessionId) throw new EidError("POST /authentication/qr: sessionID \u0430\u043B\u0433\u0430");
2238
- const vcRaw = r.vc;
2239
- const vc = typeof vcRaw === "string" ? vcRaw : isObj(vcRaw) && vcRaw.value != null ? String(vcRaw.value) : "";
2240
- const expiresAt = parseExpiresAt(r.expiresAt);
2241
- return { sessionId, vc, nonce: nonce ?? rpChallenge, attributes, ...expiresAt !== void 0 ? { expiresAt } : {} };
2357
+ return { sessionId, nonce };
2242
2358
  }
2243
2359
  /**
2244
- * Session дуустал long-poll хийж presentation-ийг CA-ийн JWKS-ээр шалгана. Татгалзсан / хугацаа дууссан бол
2245
- * SessionFailedError (`USER_REFUSED`, `TIMEOUT` г.м.); шалгалт унавал {@link QrError} `QR_PRESENTATION_INVALID`;
2246
- * JWKS татагдахгүй бол `QR_JWKS_UNAVAILABLE` (дахин оролдож болно).
2360
+ * Session дуустал long-poll хийж presentation-ийг {@link verifyQrPresentation}-аар шалгана. Татгалзсан / хугацаа
2361
+ * дууссан → SessionFailedError (`endResult`); `maxWaitMs` дуусахад иргэн хариулаагүй → `QR_PENDING`; 410 →
2362
+ * `QR_PRESENTATION_GONE` (CA presentation-ийг нэг л удаа өгнө — шинэ QR уншуулна).
2247
2363
  */
2248
2364
  async result(session, opts) {
2249
2365
  if (!session?.sessionId) throw new EidError("qr.result: QrSession \u0448\u0430\u0430\u0440\u0434\u043B\u0430\u0433\u0430\u0442\u0430\u0439");
2250
- const r = await this.d.session.waitForResult(session.sessionId, { expiresAt: session.expiresAt, ...opts });
2251
- if (r.state !== "COMPLETE") throw new QrError("QR_PENDING", "\u0438\u0440\u0433\u044D\u043D \u0445\u0430\u0440\u0430\u0430\u0445\u0430\u043D \u0445\u0430\u0440\u0438\u0443\u043B\u0430\u0430\u0433\u04AF\u0439");
2366
+ const r = await gone(this.d.session.waitForResult(session.sessionId, opts));
2367
+ if (r.state !== "COMPLETE") throw fail("QR_PENDING", "\u0438\u0440\u0433\u044D\u043D \u0445\u0430\u0440\u0430\u0430\u0445\u0430\u043D \u0445\u0430\u0440\u0438\u0443\u043B\u0430\u0430\u0433\u04AF\u0439");
2252
2368
  return this.finish(r, session);
2253
2369
  }
2254
- /**
2255
- * Нэг удаагийн шалгалт (polling UI-д): `GET /session/{id}` (`serverPollMs` хүртэл, анхдагч 1000 мс) — иргэн хараахан
2256
- * хариулаагүй бол `{ state: "RUNNING" }`, зөвшөөрсөн бол JWS/JWKS-ээр шалгасан `{ state: "COMPLETE", presentation }`.
2257
- * Татгалзсан / CA-ийн хугацаа дууссан бол SessionFailedError; бусад алдаа {@link result}-тэй ижил.
2258
- */
2370
+ /** Нэг удаагийн шалгалт (polling UI): `GET /session/{id}` (`serverPollMs` хүртэл, анхдагч 1000 мс). Алдаа {@link result}-тэй ижил. */
2259
2371
  async check(session, opts) {
2260
2372
  if (!session?.sessionId) throw new EidError("qr.check: QrSession \u0448\u0430\u0430\u0440\u0434\u043B\u0430\u0433\u0430\u0442\u0430\u0439");
2261
- const r = await this.d.session.poll(session.sessionId, opts?.serverPollMs ?? 1e3);
2262
- if (r.state !== "COMPLETE") return { state: "RUNNING" };
2263
- return { state: "COMPLETE", presentation: await this.finish(r, session) };
2373
+ const r = await gone(this.d.session.poll(session.sessionId, opts?.serverPollMs ?? 1e3));
2374
+ if (r.state !== "COMPLETE") return { complete: false };
2375
+ return { complete: true, result: await this.finish(r, session) };
2376
+ }
2377
+ /** Presentation JWS-ийг шалгана; `rpUUID` анхдагч `credentials.rpUUID`, `issuer` — клиентийн тохиргоо. */
2378
+ verify(jws, expect) {
2379
+ return verifyQrPresentation(
2380
+ jws,
2381
+ { ...expect, rpUUID: expect.rpUUID ?? this.d.credentials.rpUUID, issuer: expect.issuer ?? this.d.issuer },
2382
+ this.d.trust ?? {}
2383
+ );
2264
2384
  }
2265
2385
  finish(r, session) {
2266
2386
  if (r.endResult !== "OK") throw new SessionFailedError(r.endResult ?? "UNKNOWN");
2267
2387
  const jws = r.presentation?.jws;
2268
- if (!jws) throw bad("\u0445\u0430\u0440\u0438\u0443\u043D\u0434 presentation \u0430\u043B\u0433\u0430");
2269
- return this.verify(jws, session);
2270
- }
2271
- /** Хадгалсан presentation JWS-ийг QrSession-тэй тулгаж шалгана (JWKS кэш; танихгүй kid → нэг удаа дахин татна). */
2272
- async verify(jws, session) {
2273
- const cfg = this.d.config ?? {};
2274
- const exp = {
2275
- issuer: cfg.issuer,
2276
- audience: this.d.credentials.rpUUID,
2277
- sessionId: session.sessionId,
2278
- nonce: session.nonce,
2279
- attributes: session.attributes,
2280
- maxAgeMs: cfg.maxAgeMs
2281
- };
2282
- try {
2283
- return verifyInner(jws, await this.keys(false), exp);
2284
- } catch (e) {
2285
- if (!(e instanceof UnknownKid)) throw e;
2286
- }
2287
- return verifyQrPresentation(jws, await this.keys(true), exp);
2288
- }
2289
- async keys(force) {
2290
- const ttl = this.d.config?.jwksCacheTtlMs && this.d.config.jwksCacheTtlMs > 0 ? this.d.config.jwksCacheTtlMs : DEFAULT_QR_JWKS_CACHE_TTL_MS;
2291
- const now = Date.now();
2292
- const fresh = this.jwks && now - this.fetchedAt < ttl;
2293
- if (fresh && (!force || now - this.lastAttempt < JWKS_MIN_REFRESH_MS)) return this.jwks;
2294
- if (!this.inflight) {
2295
- this.lastAttempt = now;
2296
- this.inflight = this.fetchJwks().then((k) => {
2297
- this.jwks = k;
2298
- this.fetchedAt = Date.now();
2299
- return k;
2300
- }).finally(() => {
2301
- this.inflight = null;
2302
- });
2303
- }
2304
- return this.inflight;
2305
- }
2306
- async fetchJwks() {
2307
- const url = this.d.config?.jwksUrl || DEFAULT_QR_JWKS_URL;
2308
- const fail2 = (why) => new QrError("QR_JWKS_UNAVAILABLE", why);
2309
- let u;
2310
- try {
2311
- u = new URL(url);
2312
- } catch {
2313
- throw fail2("jwksUrl \u0431\u0443\u0440\u0443\u0443");
2314
- }
2315
- if (u.protocol !== "https:" && !(u.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(u.hostname))) {
2316
- throw fail2("jwksUrl https \u0431\u0430\u0439\u0445 \u0451\u0441\u0442\u043E\u0439");
2317
- }
2318
- const init = {
2319
- method: "GET",
2320
- headers: { Accept: "application/json" },
2321
- signal: AbortSignal.timeout(this.d.timeoutMs ?? 15e3)
2322
- };
2323
- if (this.d.dispatcher) init.dispatcher = this.d.dispatcher;
2324
- let res;
2325
- try {
2326
- res = await (this.d.fetchImpl ?? fetch)(url, init);
2327
- } catch (e) {
2328
- throw fail2(`\u0442\u0430\u0442\u0430\u0433\u0434\u0441\u0430\u043D\u0433\u04AF\u0439: ${e.message}`);
2329
- }
2330
- if (res.status !== 200) {
2331
- await res.body?.cancel().catch(() => void 0);
2332
- throw fail2(`HTTP ${res.status}`);
2333
- }
2334
- const text = await res.text();
2335
- if (text.length > MAX_JWKS) throw fail2("JWKS \u0445\u044D\u0442 \u0442\u043E\u043C");
2336
- let k;
2337
- try {
2338
- k = JSON.parse(text);
2339
- } catch {
2340
- throw fail2("JWKS JSON \u0431\u0438\u0448");
2341
- }
2342
- if (!isObj(k) || !Array.isArray(k.keys) || k.keys.length === 0) throw fail2("JWKS \u0445\u043E\u043E\u0441\u043E\u043D");
2343
- return k;
2388
+ if (!jws) throw fail("QR_JWS_MALFORMED", "\u0445\u0430\u0440\u0438\u0443\u043D\u0434 presentation \u0430\u043B\u0433\u0430");
2389
+ return this.verify(jws, { sessionId: session.sessionId, nonce: session.nonce });
2344
2390
  }
2345
2391
  };
2392
+ async function gone(p) {
2393
+ try {
2394
+ return await p;
2395
+ } catch (e) {
2396
+ if (e instanceof ApiError && e.status === 410) throw fail("QR_PRESENTATION_GONE", "presentation \u0430\u043B\u044C \u0445\u044D\u0434\u0438\u0439\u043D \u0443\u043D\u0448\u0438\u0433\u0434\u0441\u0430\u043D \u044D\u0441\u0432\u044D\u043B \u0445\u0443\u0433\u0430\u0446\u0430\u0430 \u0434\u0443\u0443\u0441\u0441\u0430\u043D");
2397
+ throw e;
2398
+ }
2399
+ }
2346
2400
 
2347
2401
  // src/share.ts
2348
2402
  var DEFAULT_SHARE_TIMEOUT_MS = 15e4;
@@ -2476,7 +2530,7 @@ var EidClient = class {
2476
2530
  organization;
2477
2531
  person;
2478
2532
  token;
2479
- /** «Миний QR» (биечлэн шалгах): parse → start → result. */
2533
+ /** «Миний QR» (биечлэн шалгах): parse → start → result / check. */
2480
2534
  qr;
2481
2535
  session;
2482
2536
  validator;
@@ -2506,10 +2560,8 @@ var EidClient = class {
2506
2560
  http,
2507
2561
  session: this.session,
2508
2562
  credentials: cfg.credentials,
2509
- config: cfg.qr,
2510
- fetchImpl: cfg.fetchImpl,
2511
- dispatcher: cfg.dispatcher,
2512
- timeoutMs: cfg.timeoutMs
2563
+ trust: cfg.trust,
2564
+ issuer: cfg.qr?.issuer
2513
2565
  });
2514
2566
  this.rpName = cfg.credentials.rpName;
2515
2567
  this.http = http;
@@ -2537,125 +2589,51 @@ var EidClient = class {
2537
2589
  }
2538
2590
  };
2539
2591
 
2540
- // src/ocsp.ts
2541
- import { createHash as createHash4 } from "crypto";
2542
- var CACHE_TTL_MS = 5 * 6e4;
2543
- var CACHE_MAX = 1024;
2544
- var MAX_BYTES = 16 << 10;
2545
- var CLOCK_SKEW_MS = 5 * 6e4;
2546
- var MAX_AGE_MS = 48 * 36e5;
2547
- function ocspRevocationChecker(opts = {}) {
2548
- const doFetch = opts.fetchImpl ?? globalThis.fetch;
2549
- const timeoutMs = opts.timeoutMs ?? 2e3;
2550
- const totalMs = Math.max(timeoutMs, 3e3);
2551
- const now = opts.now ?? Date.now;
2552
- const cache = /* @__PURE__ */ new Map();
2553
- async function ask(leaf, issuer) {
2554
- const body = await ocspRequest(leaf, issuer);
2555
- const deadline = Date.now() + totalMs;
2556
- for (const raw of leaf.ocspServers) {
2557
- const left = deadline - Date.now();
2558
- if (left <= 0) break;
2559
- try {
2560
- const u = new URL(raw);
2561
- if (u.protocol !== "http:" && u.protocol !== "https:") continue;
2562
- const res = await doFetch(u.toString(), {
2563
- method: "POST",
2564
- headers: { "Content-Type": "application/ocsp-request", Accept: "application/ocsp-response" },
2565
- body,
2566
- redirect: "manual",
2567
- signal: AbortSignal.timeout(Math.min(timeoutMs, left))
2568
- });
2569
- if (res.status !== 200) continue;
2570
- const der = new Uint8Array(await res.arrayBuffer());
2571
- if (der.length > MAX_BYTES) continue;
2572
- const resp = await parseOCSPFrom(der, intValue(leaf.serial), issuer);
2573
- const t = now();
2574
- const rc = resp.certificate;
2575
- if (rc && !sameCertKey(rc, issuer)) {
2576
- if (!rc.extKeyUsage.includes(OID.kpOCSPSigning)) continue;
2577
- if (t < rc.notBefore.getTime() || t > rc.notAfter.getTime()) continue;
2578
- }
2579
- const tu = resp.thisUpdate.date.getTime();
2580
- if (tu > t + CLOCK_SKEW_MS || tu < t - MAX_AGE_MS) continue;
2581
- if (resp.nextUpdate && resp.nextUpdate.getTime() < t) continue;
2582
- return { status: resp.status === "good" ? "good" : "revoked", nextUpdate: resp.nextUpdate?.getTime() };
2583
- } catch {
2584
- }
2585
- }
2586
- return void 0;
2587
- }
2588
- return async (cert, issuer) => {
2589
- if (!issuer) return "unknown";
2590
- let leaf, iss;
2591
- try {
2592
- leaf = parseCertificate(new Uint8Array(cert.raw));
2593
- iss = parseCertificate(new Uint8Array(issuer.raw));
2594
- } catch {
2595
- return "unknown";
2596
- }
2597
- const key = createHash4("sha256").update(issuer.raw).digest("hex").slice(0, 16) + ":" + cert.serialNumber;
2598
- const exp = cache.get(key);
2599
- if (exp !== void 0 && now() < exp) return "good";
2600
- const r = await ask(leaf, iss);
2601
- if (!r) return "unknown";
2602
- if (r.status === "good") {
2603
- const t = now();
2604
- const until = Math.min(t + CACHE_TTL_MS, r.nextUpdate ?? Infinity);
2605
- if (until > t) {
2606
- if (cache.size >= CACHE_MAX) cache.clear();
2607
- cache.set(key, until);
2608
- }
2609
- }
2610
- return r.status;
2611
- };
2612
- }
2613
-
2614
2592
  // src/devicelinkv3.ts
2615
2593
  import { createHmac } from "crypto";
2616
2594
  var TYPES = ["QR", "Web2App", "App2App"];
2617
2595
  var PROTOCOL = { auth: "ACSP_V2", sign: "RAW_DIGEST_SIGNATURE", cert: "" };
2618
2596
  var TOKEN_RE2 = /^[A-Za-z0-9_-]+$/;
2619
2597
  var LANG_RE = /^[a-z]{3}$/;
2620
- var STD_B64_RE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
2598
+ var STD_B64_RE2 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
2621
2599
  var b642 = (s) => Buffer.from(s, "utf8").toString("base64");
2622
2600
  var ms = (t) => t instanceof Date ? t.getTime() : t;
2623
- function fail(msg) {
2601
+ function fail2(msg) {
2624
2602
  throw new DeviceLinkError(`buildDeviceLink: ${msg}`);
2625
2603
  }
2626
2604
  function buildDeviceLink(p) {
2627
2605
  const base = p.deviceLinkBase?.trim();
2628
- if (!base) fail("deviceLinkBase \u0445\u043E\u043E\u0441\u043E\u043D \u2014 device-link session-\u0438\u0439 \u0445\u0430\u0440\u0438\u0443\u0433 \u0448\u0430\u043B\u0433\u0430");
2606
+ if (!base) fail2("deviceLinkBase \u0445\u043E\u043E\u0441\u043E\u043D \u2014 device-link session-\u0438\u0439 \u0445\u0430\u0440\u0438\u0443\u0433 \u0448\u0430\u043B\u0433\u0430");
2629
2607
  let u;
2630
2608
  try {
2631
2609
  u = new URL(base);
2632
2610
  } catch {
2633
- fail(`deviceLinkBase \u0431\u0443\u0440\u0443\u0443 URL: ${base}`);
2634
- }
2635
- if (u.protocol !== "https:" || /[?#]/.test(base)) fail("deviceLinkBase \u043D\u044C query/fragment-\u0433\u04AF\u0439 https URL \u0431\u0430\u0439\u0445 \u0451\u0441\u0442\u043E\u0439");
2636
- if (!TYPES.includes(p.deviceLinkType)) fail(`deviceLinkType ${String(p.deviceLinkType)} (QR | Web2App | App2App)`);
2637
- if (!(p.sessionType in PROTOCOL)) fail(`sessionType ${String(p.sessionType)} (auth | sign | cert)`);
2638
- if (!p.sessionToken || !TOKEN_RE2.test(p.sessionToken)) fail("sessionToken \u0445\u044D\u043B\u0431\u044D\u0440 \u0431\u0443\u0440\u0443\u0443");
2639
- if (!LANG_RE.test(p.lang ?? "")) fail("lang \u043D\u044C ISO 639-2 \u0433\u0443\u0440\u0432\u0430\u043D \u0436\u0438\u0436\u0438\u0433 \u04AF\u0441\u044D\u0433 (mon, eng)");
2640
- if (!p.sessionSecret || !STD_B64_RE.test(p.sessionSecret)) fail("sessionSecret \u0441\u0442\u0430\u043D\u0434\u0430\u0440\u0442 Base64 (padding-\u0442\u044D\u0439) \u0431\u0438\u0448");
2611
+ fail2(`deviceLinkBase \u0431\u0443\u0440\u0443\u0443 URL: ${base}`);
2612
+ }
2613
+ if (u.protocol !== "https:" || /[?#]/.test(base)) fail2("deviceLinkBase \u043D\u044C query/fragment-\u0433\u04AF\u0439 https URL \u0431\u0430\u0439\u0445 \u0451\u0441\u0442\u043E\u0439");
2614
+ if (!TYPES.includes(p.deviceLinkType)) fail2(`deviceLinkType ${String(p.deviceLinkType)} (QR | Web2App | App2App)`);
2615
+ if (!(p.sessionType in PROTOCOL)) fail2(`sessionType ${String(p.sessionType)} (auth | sign | cert)`);
2616
+ if (!p.sessionToken || !TOKEN_RE2.test(p.sessionToken)) fail2("sessionToken \u0445\u044D\u043B\u0431\u044D\u0440 \u0431\u0443\u0440\u0443\u0443");
2617
+ if (!LANG_RE.test(p.lang ?? "")) fail2("lang \u043D\u044C ISO 639-2 \u0433\u0443\u0440\u0432\u0430\u043D \u0436\u0438\u0436\u0438\u0433 \u04AF\u0441\u044D\u0433 (mon, eng)");
2618
+ if (!p.sessionSecret || !STD_B64_RE2.test(p.sessionSecret)) fail2("sessionSecret \u0441\u0442\u0430\u043D\u0434\u0430\u0440\u0442 Base64 (padding-\u0442\u044D\u0439) \u0431\u0438\u0448");
2641
2619
  let challenge = "";
2642
2620
  if (p.sessionType === "auth") {
2643
- if (!p.rpChallenge) fail("auth session-\u0434 rpChallenge \u0437\u0430\u0430\u0432\u0430\u043B");
2621
+ if (!p.rpChallenge) fail2("auth session-\u0434 rpChallenge \u0437\u0430\u0430\u0432\u0430\u043B");
2644
2622
  challenge = p.rpChallenge;
2645
2623
  } else if (p.sessionType === "sign") {
2646
- if (!p.digest) fail("sign session-\u0434 digest \u0437\u0430\u0430\u0432\u0430\u043B");
2624
+ if (!p.digest) fail2("sign session-\u0434 digest \u0437\u0430\u0430\u0432\u0430\u043B");
2647
2625
  challenge = p.digest;
2648
2626
  } else if (p.rpChallenge || p.digest) {
2649
- fail("cert session-\u0434 rpChallenge/digest \u0431\u0430\u0439\u0445\u0433\u04AF\u0439");
2627
+ fail2("cert session-\u0434 rpChallenge/digest \u0431\u0430\u0439\u0445\u0433\u04AF\u0439");
2650
2628
  }
2651
2629
  const qr = p.deviceLinkType === "QR";
2652
2630
  const callback = qr ? "" : p.initialCallbackUrl ?? "";
2653
- if (!qr && !callback) fail(`${p.deviceLinkType} \u0445\u043E\u043B\u0431\u043E\u043E\u0441 initialCallbackUrl-\u0442\u0430\u0439 session-\u0434 \u043B \u0445\u04AF\u0447\u0438\u043D\u0442\u044D\u0439`);
2631
+ if (!qr && !callback) fail2(`${p.deviceLinkType} \u0445\u043E\u043B\u0431\u043E\u043E\u0441 initialCallbackUrl-\u0442\u0430\u0439 session-\u0434 \u043B \u0445\u04AF\u0447\u0438\u043D\u0442\u044D\u0439`);
2654
2632
  let elapsed = "";
2655
2633
  if (qr) {
2656
- if (p.receivedAt == null) fail("QR \u0445\u043E\u043B\u0431\u043E\u043E\u0441\u043E\u043D\u0434 receivedAt \u0437\u0430\u0430\u0432\u0430\u043B");
2634
+ if (p.receivedAt == null) fail2("QR \u0445\u043E\u043B\u0431\u043E\u043E\u0441\u043E\u043D\u0434 receivedAt \u0437\u0430\u0430\u0432\u0430\u043B");
2657
2635
  const e = Math.max(0, Math.floor((ms(p.now ?? Date.now()) - ms(p.receivedAt)) / 1e3));
2658
- if (!Number.isSafeInteger(e)) fail("receivedAt/now \u0431\u0443\u0440\u0443\u0443");
2636
+ if (!Number.isSafeInteger(e)) fail2("receivedAt/now \u0431\u0443\u0440\u0443\u0443");
2659
2637
  elapsed = `&elapsedSeconds=${e}`;
2660
2638
  }
2661
2639
  const unprotected = `${base}?deviceLinkType=${p.deviceLinkType}${elapsed}&sessionToken=${p.sessionToken}&sessionType=${p.sessionType}&version=1.0&lang=${p.lang}`;
@@ -2713,7 +2691,7 @@ function qrDeviceLinkTicker(input, onLink, opts) {
2713
2691
  }
2714
2692
 
2715
2693
  // src/login.ts
2716
- import { createHash as createHash5, createHmac as createHmac2, randomBytes as randomBytes2, randomInt, randomUUID, timingSafeEqual as timingSafeEqual2 } from "crypto";
2694
+ import { createHash as createHash6, createHmac as createHmac2, randomBytes as randomBytes3, randomInt, randomUUID, timingSafeEqual as timingSafeEqual2 } from "crypto";
2717
2695
  var MEMORY_LOGIN_STORE_MAX = 1e4;
2718
2696
  var LoginStoreFullError = class extends Error {
2719
2697
  constructor() {
@@ -2809,7 +2787,7 @@ function forwardedClientIp(headers, trustProxy) {
2809
2787
  }
2810
2788
  var ID_RE = /^(\p{L}{2}[0-9]{8}|[0-9]{8,14}|PNOMN-[0-9]{8,14})$/u;
2811
2789
  var UUID_RE2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
2812
- var B64URL_RE2 = /^[A-Za-z0-9_-]{43}$/;
2790
+ var B64URL_RE = /^[A-Za-z0-9_-]{43}$/;
2813
2791
  var IOS_BROWSERS = [
2814
2792
  [/CriOS/i, "googlechromes"],
2815
2793
  [/EdgiOS/i, "microsoft-edge-https"],
@@ -2852,7 +2830,7 @@ function readCookie(h, name) {
2852
2830
  }
2853
2831
  return "";
2854
2832
  }
2855
- var sha256hex = (s) => createHash5("sha256").update(s).digest("hex");
2833
+ var sha256hex = (s) => createHash6("sha256").update(s).digest("hex");
2856
2834
  function safeEqualHex(a, b) {
2857
2835
  const x = Buffer.from(a, "hex");
2858
2836
  const y = Buffer.from(b, "hex");
@@ -2931,7 +2909,7 @@ function createEidLogin(opts) {
2931
2909
  const pushFloorMs = opts.pushFloorMs ?? 1e3;
2932
2910
  const revocation = opts.revocation === false ? void 0 : opts.revocation ?? ocspRevocationChecker();
2933
2911
  const revocationMode = opts.revocationMode ?? "soft-fail";
2934
- const auditKey = opts.auditKey ?? randomBytes2(32);
2912
+ const auditKey = opts.auditKey ?? randomBytes3(32);
2935
2913
  let caTtl = 0;
2936
2914
  let caTtlNext = 0;
2937
2915
  let caTtlInflight;
@@ -3014,7 +2992,7 @@ function createEidLogin(opts) {
3014
2992
  const dot = raw.indexOf(".");
3015
2993
  const sid = raw.slice(0, dot);
3016
2994
  const binding = raw.slice(dot + 1);
3017
- if (dot < 0 || !UUID_RE2.test(sid) || !B64URL_RE2.test(binding)) return void 0;
2995
+ if (dot < 0 || !UUID_RE2.test(sid) || !B64URL_RE.test(binding)) return void 0;
3018
2996
  const tx = await store.get(sid);
3019
2997
  if (!tx || !safeEqualHex(tx.bindingHash, sha256hex(binding))) return void 0;
3020
2998
  if (tx.expiresAt <= Date.now()) {
@@ -3078,7 +3056,7 @@ function createEidLogin(opts) {
3078
3056
  return { ...await save(tx, ttlMs), appLink };
3079
3057
  }
3080
3058
  async function save(tx, ttlMs) {
3081
- const binding = randomBytes2(32).toString("base64url");
3059
+ const binding = randomBytes3(32).toString("base64url");
3082
3060
  const full = { ...tx, bindingHash: sha256hex(binding), expiresAt: Date.now() + ttlMs };
3083
3061
  await store.set(full.sessionId, full, ttlMs);
3084
3062
  const expiresIn = Math.ceil(ttlMs / 1e3);
@@ -3231,37 +3209,37 @@ function createEidLogin(opts) {
3231
3209
  const q = new URL(req.url, "http://x").searchParams;
3232
3210
  const sid = q.get("sessionId") ?? "";
3233
3211
  const verifier = q.get("userChallengeVerifier") ?? "";
3234
- const fail2 = (code) => redirect(failTo(code), { "Set-Cookie": clearCookie });
3212
+ const fail3 = (code) => redirect(failTo(code), { "Set-Cookie": clearCookie });
3235
3213
  const tx = await loadTx(req);
3236
- if (!tx) return fail2("expired");
3214
+ if (!tx) return fail3("expired");
3237
3215
  const ctx = { request: req, mode: tx.mode };
3238
3216
  if (tx.sessionId !== sid || tx.mode !== "web2app" || !verifier) {
3239
3217
  await emit("flow_refused", tx.sessionId, { mode: tx.mode, reason: "unbound" }, ctx);
3240
- return fail2("unbound");
3218
+ return fail3("unbound");
3241
3219
  }
3242
3220
  let r;
3243
3221
  try {
3244
3222
  r = await client.session.poll(tx.sessionId, 1e4);
3245
3223
  } catch (e) {
3246
3224
  onError(e, ctx);
3247
- return fail2("eid_unavailable");
3225
+ return fail3("eid_unavailable");
3248
3226
  }
3249
- if (r.state !== "COMPLETE") return fail2("not_complete");
3227
+ if (r.state !== "COMPLETE") return fail3("not_complete");
3250
3228
  if (r.endResult !== "OK") {
3251
3229
  await store.delete(tx.sessionId);
3252
3230
  await endEvent(tx, r.endResult, ctx);
3253
- return fail2(r.endResult ?? "UNKNOWN");
3231
+ return fail3(r.endResult ?? "UNKNOWN");
3254
3232
  }
3255
3233
  try {
3256
3234
  const out = await finish(req, tx, r, "Web2App", verifier);
3257
- if (!out) return fail2("expired");
3235
+ if (!out) return fail3("expired");
3258
3236
  return redirect(out.redirect ?? successRedirect, mergeHeaders({ "Set-Cookie": clearCookie }, out.headers));
3259
3237
  } catch (e) {
3260
3238
  onError(e, ctx);
3261
- if (!(e instanceof ValidationError || e instanceof SessionFailedError)) return fail2("internal");
3239
+ if (!(e instanceof ValidationError || e instanceof SessionFailedError)) return fail3("internal");
3262
3240
  await store.delete(tx.sessionId);
3263
3241
  await unverified(tx, e, ctx);
3264
- return fail2("VALIDATION");
3242
+ return fail3("VALIDATION");
3265
3243
  }
3266
3244
  }
3267
3245
  async function handleRequest(req) {
@@ -3311,9 +3289,6 @@ export {
3311
3289
  DEFAULT_MAX_WAIT_MS,
3312
3290
  DEFAULT_PDF_TIMEOUT_MS,
3313
3291
  DEFAULT_QR_ISSUER,
3314
- DEFAULT_QR_JWKS_CACHE_TTL_MS,
3315
- DEFAULT_QR_JWKS_URL,
3316
- DEFAULT_QR_MAX_AGE_MS,
3317
3292
  DEFAULT_SHARE_TIMEOUT_MS,
3318
3293
  DEFAULT_SIGN_SESSION_TTL_MS,
3319
3294
  DeviceLinkError,
@@ -3334,9 +3309,10 @@ export {
3334
3309
  PDF_REGISTER_ERROR_CODES,
3335
3310
  PDF_SIGNATURE_REGISTER_FIELDS,
3336
3311
  PersonApi,
3337
- QR_ATTRIBUTES,
3338
- QR_CLOCK_SKEW_MS,
3312
+ QR_CLOCK_SKEW_SECONDS,
3339
3313
  QR_ERROR_CODES,
3314
+ QR_LIMITS,
3315
+ QR_MAX_AGE_SECONDS,
3340
3316
  QR_PREFIX,
3341
3317
  QrApi,
3342
3318
  QrError,
@@ -3377,6 +3353,7 @@ export {
3377
3353
  parseSubject,
3378
3354
  personMatchesCertificate,
3379
3355
  qrDeviceLinkTicker,
3356
+ qrStatement,
3380
3357
  randomChallenge,
3381
3358
  registrationFromCompleted,
3382
3359
  resolveBaseUrl,