@gerege-systems/eid-mongolia-sdk 0.31.0 → 0.33.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
@@ -23,6 +23,7 @@ import {
23
23
  NoSigningCertificateError,
24
24
  ON_BEHALF_ERROR_CODES,
25
25
  PDF_REGISTER_ERROR_CODES,
26
+ QrTokenInvalidError,
26
27
  RETRYABLE_ERROR_CODES,
27
28
  RequestInvalidError,
28
29
  ResponseTooLargeError,
@@ -30,7 +31,7 @@ import {
30
31
  ValidationError,
31
32
  maskPath,
32
33
  parseRetryAfter
33
- } from "./chunk-R73IR6OH.js";
34
+ } from "./chunk-TNXO4QLU.js";
34
35
 
35
36
  // src/http.ts
36
37
  var DEFAULT_TIMEOUT_MS = 15e3;
@@ -102,7 +103,7 @@ var Http = class {
102
103
  { headers, retryAfterMs }
103
104
  );
104
105
  }
105
- const Typed = code === "NO_SIGNING_CERTIFICATE" ? NoSigningCertificateError : code === "CERT_CHOICE_INVALID" ? CertChoiceInvalidError : code === "REQUEST_INVALID" ? RequestInvalidError : ApiError;
106
+ const Typed = code === "NO_SIGNING_CERTIFICATE" ? NoSigningCertificateError : code === "CERT_CHOICE_INVALID" ? CertChoiceInvalidError : code === "REQUEST_INVALID" ? RequestInvalidError : code === "QR_TOKEN_INVALID" ? QrTokenInvalidError : ApiError;
106
107
  throw new Typed(res.status, text, code, { headers, retryAfterMs });
107
108
  }
108
109
  };
@@ -168,12 +169,15 @@ var RP_ROUTES = {
168
169
  personActivity: { method: "GET", path: "/rp/activity/etsi/{personEtsi}" },
169
170
  personSummary: { method: "GET", path: "/person/summary/etsi/{personEtsi}" },
170
171
  personChildren: { method: "GET", path: "/person/children/etsi/{personEtsi}" },
172
+ personSignatureImage: { method: "GET", path: "/person/etsi/{personEtsi}/signature-image" },
171
173
  tokenCertificate: { method: "POST", path: "/token/certificate" },
172
174
  tokenCertificateResult: { method: "GET", path: "/token/certificate/{sessionID}" },
173
175
  pdfSignatures: { method: "POST", path: "/pdf/signatures" },
174
176
  tokenAuthChallenge: { method: "POST", path: "/token/auth/challenge" },
175
177
  tokenAuthVerify: { method: "POST", path: "/token/auth/verify" },
176
- share: { method: "POST", path: "/share" }
178
+ share: { method: "POST", path: "/share" },
179
+ /** «Миний QR» (CA гэрээ v1, 2026-10-23). */
180
+ authQr: { method: "POST", path: "/authentication/qr" }
177
181
  };
178
182
  var PDF_SIGNATURE_REGISTER_FIELDS = [
179
183
  "docID",
@@ -775,6 +779,7 @@ function parseSessionResult(raw) {
775
779
  onBehalfOf: parseOrg(r.onBehalfOf),
776
780
  person: parsePerson(r.person),
777
781
  tokenCertificate: parseTokenCert(r.tokenCertificate),
782
+ presentation: parsePresentation(r.presentation),
778
783
  raw
779
784
  };
780
785
  }
@@ -796,6 +801,11 @@ function parsePerson(raw) {
796
801
  if (typeof p.geID === "number" && p.geID !== 0) out.geID = p.geID;
797
802
  return Object.keys(out).length ? out : null;
798
803
  }
804
+ function parsePresentation(raw) {
805
+ const p = asRecord(raw);
806
+ if (typeof p.jws !== "string" || !p.jws) return null;
807
+ return { jws: p.jws, ...p.claims && typeof p.claims === "object" ? { claims: p.claims } : {} };
808
+ }
799
809
  function parseTokenCert(raw) {
800
810
  const t = asRecord(raw);
801
811
  const status = str(t.status);
@@ -939,6 +949,19 @@ var PersonApi = class {
939
949
  children(personEtsi) {
940
950
  return this.get(routePath(RP_ROUTES.personChildren, personEtsi));
941
951
  }
952
+ /**
953
+ * GET /person/etsi/{personEtsi}/signature-image — иргэний гарын үсгийн зураг (харагдах гарын үсэгт:
954
+ * `appearance.signatureImage = img.pdfImage`). PKI_READ биш, **SIGN** эрх; иргэн сүүлийн 24 цагт танай RP-ээр
955
+ * нэвтэрсэн байх ёстой (эс бөгөөс `ForbiddenError`). Иргэн зураг хадгалаагүй (404) бол `null`.
956
+ */
957
+ async signatureImage(personEtsi) {
958
+ try {
959
+ return rec3(await this.http.get(routePath(RP_ROUTES.personSignatureImage, personEtsi)));
960
+ } catch (e) {
961
+ if (e instanceof ApiError && e.status === 404) return null;
962
+ throw e;
963
+ }
964
+ }
942
965
  };
943
966
 
944
967
  // src/token.ts
@@ -1377,9 +1400,9 @@ var ResponseValidator = class {
1377
1400
  ...this.intermediates.map((c) => [c, false])
1378
1401
  ]) {
1379
1402
  if (cas.includes(cand) || !signedBy(cur, cand)) continue;
1380
- const bad = caReason(cand, cas.length, now, usage);
1381
- if (bad) {
1382
- reason ??= bad;
1403
+ const bad2 = caReason(cand, cas.length, now, usage);
1404
+ if (bad2) {
1405
+ reason ??= bad2;
1383
1406
  continue;
1384
1407
  }
1385
1408
  if (isAnchor || extend(cand, [...cas, cand])) return true;
@@ -2016,6 +2039,318 @@ function tokenLimitOf(err) {
2016
2039
  return void 0;
2017
2040
  }
2018
2041
 
2042
+ // src/myqr.ts
2043
+ import { createPublicKey as createPublicKey2, verify as cryptoVerify } from "crypto";
2044
+ var QR_ATTRIBUTES = ["age_over_18", "age_over_21", "full_name", "phone", "birth_date", "civil_id"];
2045
+ var QR_PREFIX = "EIDMN-QR1:";
2046
+ var DEFAULT_QR_ISSUER = "https://ca.eidmongolia.mn";
2047
+ var DEFAULT_QR_JWKS_URL = "https://ca.eidmongolia.mn/.well-known/eid-jwks.json";
2048
+ var DEFAULT_QR_JWKS_CACHE_TTL_MS = 36e5;
2049
+ var DEFAULT_QR_MAX_AGE_MS = 6e5;
2050
+ var QR_CLOCK_SKEW_MS = 6e4;
2051
+ var JWKS_MIN_REFRESH_MS = 3e4;
2052
+ var MAX_JWS = 16 << 10;
2053
+ var MAX_JWKS = 64 << 10;
2054
+ var QR_ERROR_CODES = [
2055
+ "QR_FORMAT_INVALID",
2056
+ "QR_TOKEN_INVALID",
2057
+ "QR_ATTRIBUTES_INVALID",
2058
+ "QR_PRESENTATION_INVALID",
2059
+ "QR_JWKS_UNAVAILABLE"
2060
+ ];
2061
+ var QrError = class extends EidError {
2062
+ constructor(code, reason) {
2063
+ super(`${code}: ${reason}`);
2064
+ this.code = code;
2065
+ this.reason = reason;
2066
+ }
2067
+ code;
2068
+ reason;
2069
+ };
2070
+ var bad = (reason) => new QrError("QR_PRESENTATION_INVALID", reason);
2071
+ var TOKEN_RE = /^[A-Za-z0-9_-]{43}$/;
2072
+ function parseQr(scanned) {
2073
+ let s = String(scanned ?? "").trim();
2074
+ if (s.startsWith(QR_PREFIX)) s = s.slice(QR_PREFIX.length);
2075
+ if (!TOKEN_RE.test(s)) throw new QrError("QR_FORMAT_INVALID", "eID \xAB\u041C\u0438\u043D\u0438\u0439 QR\xBB \u0431\u0438\u0448");
2076
+ return s;
2077
+ }
2078
+ function checkAttributes(attrs) {
2079
+ 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");
2080
+ const seen = /* @__PURE__ */ new Set();
2081
+ for (const a of attrs) {
2082
+ 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}`);
2083
+ if (seen.has(a)) throw new QrError("QR_ATTRIBUTES_INVALID", `\u0434\u0430\u0432\u0445\u0430\u0440\u0434\u0441\u0430\u043D: ${a}`);
2084
+ seen.add(a);
2085
+ }
2086
+ return [...attrs];
2087
+ }
2088
+ var UnknownKid = class extends Error {
2089
+ };
2090
+ var B64URL_RE = /^[A-Za-z0-9_-]*$/;
2091
+ function b64url(s) {
2092
+ if (!B64URL_RE.test(s) || s.length % 4 === 1) throw bad("base64url \u0431\u0443\u0440\u0443\u0443");
2093
+ return Buffer.from(s, "base64url");
2094
+ }
2095
+ function keyFor(jwks, kid) {
2096
+ const j = jwks?.keys?.find((k) => k?.kid === kid);
2097
+ if (!j) throw new UnknownKid();
2098
+ if (j.kty !== "EC" || j.crv !== "P-256" || j.alg && j.alg !== "ES256" || j.use && j.use !== "sig") {
2099
+ throw bad(`kid ${kid} \u043D\u044C ES256 P-256 \u0442\u04AF\u043B\u0445\u04AF\u04AF\u0440 \u0431\u0438\u0448`);
2100
+ }
2101
+ try {
2102
+ if (b64url(j.x ?? "").length !== 32 || b64url(j.y ?? "").length !== 32) throw new Error("x/y");
2103
+ return createPublicKey2({ key: { kty: "EC", crv: "P-256", x: j.x, y: j.y }, format: "jwk" });
2104
+ } catch {
2105
+ throw bad(`kid ${kid}: \u0442\u04AF\u043B\u0445\u04AF\u04AF\u0440 \u0431\u0443\u0440\u0443\u0443`);
2106
+ }
2107
+ }
2108
+ function isObj(v) {
2109
+ return !!v && typeof v === "object" && !Array.isArray(v);
2110
+ }
2111
+ var PHONE_RE = /^\+[1-9][0-9]{6,14}$/;
2112
+ var DATE_RE = /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/;
2113
+ function validDate(s) {
2114
+ const m = DATE_RE.exec(s);
2115
+ if (!m) return false;
2116
+ const [y, mo, d] = [Number(m[1]), Number(m[2]), Number(m[3])];
2117
+ const t = new Date(Date.UTC(y, mo - 1, d));
2118
+ return t.getUTCFullYear() === y && t.getUTCMonth() === mo - 1 && t.getUTCDate() === d;
2119
+ }
2120
+ function setAttr(out, name, v) {
2121
+ const wrong = () => bad(`${name}-\u0438\u0439\u043D \u0442\u04E9\u0440\u04E9\u043B \u0431\u0443\u0440\u0443\u0443`);
2122
+ switch (name) {
2123
+ case "age_over_18":
2124
+ case "age_over_21":
2125
+ if (typeof v !== "boolean") throw wrong();
2126
+ out[name] = v;
2127
+ return;
2128
+ case "full_name":
2129
+ if (!isObj(v) || typeof v.surname !== "string" || typeof v.givenName !== "string" || !v.givenName) throw wrong();
2130
+ out.full_name = { surname: v.surname, givenName: v.givenName };
2131
+ return;
2132
+ case "phone":
2133
+ if (typeof v !== "string" || !PHONE_RE.test(v)) throw wrong();
2134
+ out.phone = v;
2135
+ return;
2136
+ case "birth_date":
2137
+ if (typeof v !== "string" || !validDate(v)) throw wrong();
2138
+ out.birth_date = v;
2139
+ return;
2140
+ case "civil_id":
2141
+ if (typeof v !== "string" || !v) throw wrong();
2142
+ out.civil_id = v;
2143
+ return;
2144
+ }
2145
+ throw wrong();
2146
+ }
2147
+ function numericDate(v) {
2148
+ return typeof v === "number" && Number.isFinite(v) && v > 0 && v < 1e11 ? v * 1e3 : void 0;
2149
+ }
2150
+ function verifyInner(jws, jwks, exp) {
2151
+ 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");
2152
+ const parts = jws.split(".");
2153
+ if (parts.length !== 3) throw bad("compact JWS \u0431\u0438\u0448");
2154
+ const [h64, p64, s64] = parts;
2155
+ const hb = b64url(h64);
2156
+ const pb = b64url(p64);
2157
+ const sig = b64url(s64);
2158
+ let hdr;
2159
+ try {
2160
+ hdr = JSON.parse(hb.toString("utf8"));
2161
+ } catch {
2162
+ throw bad("header JSON \u0431\u0438\u0448");
2163
+ }
2164
+ if (!isObj(hdr) || hdr.alg !== "ES256") throw bad("alg ES256 \u0431\u0438\u0448");
2165
+ if ("crit" in hdr) throw bad("crit \u0434\u044D\u043C\u0436\u0438\u0445\u0433\u04AF\u0439");
2166
+ if (typeof hdr.kid !== "string" || !hdr.kid) throw bad("kid \u0430\u043B\u0433\u0430");
2167
+ const key = keyFor(jwks, hdr.kid);
2168
+ if (sig.length !== 64) throw bad("ES256 \u0433\u0430\u0440\u044B\u043D \u04AF\u0441\u044D\u0433 64 \u0431\u0430\u0439\u0442 \u0431\u0438\u0448");
2169
+ const ok = cryptoVerify("sha256", Buffer.from(`${h64}.${p64}`, "ascii"), { key, dsaEncoding: "ieee-p1363" }, sig);
2170
+ if (!ok) throw bad("\u0433\u0430\u0440\u044B\u043D \u04AF\u0441\u044D\u0433 \u0442\u0430\u0430\u0440\u0441\u0430\u043D\u0433\u04AF\u0439");
2171
+ let c;
2172
+ try {
2173
+ c = JSON.parse(pb.toString("utf8"));
2174
+ } catch {
2175
+ throw bad("payload JSON \u0431\u0438\u0448");
2176
+ }
2177
+ if (!isObj(c)) throw bad("payload JSON \u043E\u0431\u044A\u0435\u043A\u0442 \u0431\u0438\u0448");
2178
+ if (c.iss !== (exp.issuer || DEFAULT_QR_ISSUER)) throw bad("iss \u0442\u0430\u0430\u0440\u0441\u0430\u043D\u0433\u04AF\u0439");
2179
+ 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");
2180
+ if (!exp.sessionId || c.sid !== exp.sessionId) throw bad("sid \u0442\u0430\u0430\u0440\u0441\u0430\u043D\u0433\u04AF\u0439");
2181
+ if (!exp.nonce || c.nonce !== exp.nonce) throw bad("nonce \u0442\u0430\u0430\u0440\u0441\u0430\u043D\u0433\u04AF\u0439");
2182
+ if (typeof c.sub !== "string" || !c.sub) throw bad("sub \u0430\u043B\u0433\u0430");
2183
+ const now = exp.now ?? Date.now();
2184
+ const iat = numericDate(c.iat);
2185
+ if (iat === void 0) throw bad("iat \u0430\u043B\u0433\u0430");
2186
+ if (iat > now + QR_CLOCK_SKEW_MS) throw bad("iat \u0438\u0440\u044D\u044D\u0434\u04AF\u0439\u0434");
2187
+ 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");
2188
+ if ("exp" in c) {
2189
+ const e = numericDate(c.exp);
2190
+ if (e === void 0 || now >= e + QR_CLOCK_SKEW_MS) throw bad("exp \u0434\u0443\u0443\u0441\u0441\u0430\u043D");
2191
+ }
2192
+ const want = new Set(exp.attributes);
2193
+ const got = /* @__PURE__ */ new Set();
2194
+ let attrs = {};
2195
+ if ("attrs" in c) {
2196
+ if (!isObj(c.attrs)) throw bad("attrs \u043E\u0431\u044A\u0435\u043A\u0442 \u0431\u0438\u0448");
2197
+ attrs = c.attrs;
2198
+ }
2199
+ const out = { sub: c.sub, attrs: {}, unavailable: [], sessionId: exp.sessionId, issuedAt: iat, jws };
2200
+ for (const [name, v] of Object.entries(attrs)) {
2201
+ if (!want.has(name)) throw bad(`\u0445\u04AF\u0441\u044D\u044D\u0433\u04AF\u0439 \u0430\u0442\u0442\u0440\u0438\u0431\u0443\u0442: ${name}`);
2202
+ setAttr(out.attrs, name, v);
2203
+ got.add(name);
2204
+ }
2205
+ if ("unavailable" in c) {
2206
+ if (!Array.isArray(c.unavailable)) throw bad("unavailable \u043C\u0430\u0441\u0441\u0438\u0432 \u0431\u0438\u0448");
2207
+ for (const x of c.unavailable) {
2208
+ if (typeof x !== "string" || !want.has(x) || got.has(x)) throw bad(`unavailable \u0431\u0443\u0440\u0443\u0443: ${String(x)}`);
2209
+ got.add(x);
2210
+ out.unavailable.push(x);
2211
+ }
2212
+ }
2213
+ 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");
2214
+ return out;
2215
+ }
2216
+ function verifyQrPresentation(jws, jwks, expect) {
2217
+ try {
2218
+ return verifyInner(jws, jwks, expect);
2219
+ } catch (e) {
2220
+ if (e instanceof UnknownKid) throw bad("JWKS-\u0434 kid \u0430\u043B\u0433\u0430");
2221
+ throw e;
2222
+ }
2223
+ }
2224
+ var QrApi = class {
2225
+ constructor(d) {
2226
+ this.d = d;
2227
+ }
2228
+ d;
2229
+ jwks = null;
2230
+ fetchedAt = 0;
2231
+ lastAttempt = 0;
2232
+ inflight = null;
2233
+ /** {@link parseQr}. */
2234
+ parse(scanned) {
2235
+ return parseQr(scanned);
2236
+ }
2237
+ /**
2238
+ * `POST /authentication/qr` — QR-ийн токеныг (нэг удаагийн) CA-д өгч иргэний утас руу хүсэлт илгээнэ; `vc`-г кассын
2239
+ * дэлгэцэнд харуул. Алдаа: {@link QrError} (FORMAT / ATTRIBUTES — CA руу явахгүй), 404 {@link QrTokenInvalidError}
2240
+ * (шинэ QR гаргуул), 403 ForbiddenError (QR_PRESENT / QR_ATTR:* эрх алга).
2241
+ */
2242
+ async start(input) {
2243
+ const token = parseQr(input.qr);
2244
+ const attributes = checkAttributes(input.attributes);
2245
+ const rpChallenge = randomChallenge(32);
2246
+ const nonce = input.nonce?.trim() || void 0;
2247
+ const body = {
2248
+ qr: QR_PREFIX + token,
2249
+ attributes,
2250
+ relyingPartyUUID: this.d.credentials.rpUUID,
2251
+ relyingPartyName: this.d.credentials.rpName,
2252
+ signatureProtocol: "ACSP_V2",
2253
+ signatureProtocolParameters: { rpChallenge },
2254
+ ...nonce ? { nonce } : {}
2255
+ };
2256
+ const r = await this.d.http.post(routePath(RP_ROUTES.authQr), body);
2257
+ const sessionId = typeof r.sessionID === "string" ? r.sessionID : "";
2258
+ if (!sessionId) throw new EidError("POST /authentication/qr: sessionID \u0430\u043B\u0433\u0430");
2259
+ const vcRaw = r.vc;
2260
+ const vc = typeof vcRaw === "string" ? vcRaw : isObj(vcRaw) && vcRaw.value != null ? String(vcRaw.value) : "";
2261
+ const expiresAt = parseExpiresAt(r.expiresAt);
2262
+ return { sessionId, vc, nonce: nonce ?? rpChallenge, attributes, ...expiresAt !== void 0 ? { expiresAt } : {} };
2263
+ }
2264
+ /**
2265
+ * Session дуустал long-poll хийж presentation-ийг CA-ийн JWKS-ээр шалгана. Татгалзсан / хугацаа дууссан бол
2266
+ * SessionFailedError (`USER_REFUSED`, `TIMEOUT` г.м.); шалгалт унавал {@link QrError} `QR_PRESENTATION_INVALID`;
2267
+ * JWKS татагдахгүй бол `QR_JWKS_UNAVAILABLE` (дахин оролдож болно).
2268
+ */
2269
+ async result(session, opts) {
2270
+ if (!session?.sessionId) throw new EidError("qr.result: QrSession \u0448\u0430\u0430\u0440\u0434\u043B\u0430\u0433\u0430\u0442\u0430\u0439");
2271
+ const r = await this.d.session.waitForResult(session.sessionId, { expiresAt: session.expiresAt, ...opts });
2272
+ if (r.state !== "COMPLETE") throw new SessionFailedError("TIMEOUT");
2273
+ if (r.endResult !== "OK") throw new SessionFailedError(r.endResult ?? "UNKNOWN");
2274
+ const jws = r.presentation?.jws;
2275
+ if (!jws) throw bad("\u0445\u0430\u0440\u0438\u0443\u043D\u0434 presentation \u0430\u043B\u0433\u0430");
2276
+ return this.verify(jws, session);
2277
+ }
2278
+ /** Хадгалсан presentation JWS-ийг QrSession-тэй тулгаж шалгана (JWKS кэш; танихгүй kid → нэг удаа дахин татна). */
2279
+ async verify(jws, session) {
2280
+ const cfg = this.d.config ?? {};
2281
+ const exp = {
2282
+ issuer: cfg.issuer,
2283
+ audience: this.d.credentials.rpUUID,
2284
+ sessionId: session.sessionId,
2285
+ nonce: session.nonce,
2286
+ attributes: session.attributes,
2287
+ maxAgeMs: cfg.maxAgeMs
2288
+ };
2289
+ try {
2290
+ return verifyInner(jws, await this.keys(false), exp);
2291
+ } catch (e) {
2292
+ if (!(e instanceof UnknownKid)) throw e;
2293
+ }
2294
+ return verifyQrPresentation(jws, await this.keys(true), exp);
2295
+ }
2296
+ async keys(force) {
2297
+ const ttl = this.d.config?.jwksCacheTtlMs && this.d.config.jwksCacheTtlMs > 0 ? this.d.config.jwksCacheTtlMs : DEFAULT_QR_JWKS_CACHE_TTL_MS;
2298
+ const now = Date.now();
2299
+ const fresh = this.jwks && now - this.fetchedAt < ttl;
2300
+ if (fresh && (!force || now - this.lastAttempt < JWKS_MIN_REFRESH_MS)) return this.jwks;
2301
+ if (!this.inflight) {
2302
+ this.lastAttempt = now;
2303
+ this.inflight = this.fetchJwks().then((k) => {
2304
+ this.jwks = k;
2305
+ this.fetchedAt = Date.now();
2306
+ return k;
2307
+ }).finally(() => {
2308
+ this.inflight = null;
2309
+ });
2310
+ }
2311
+ return this.inflight;
2312
+ }
2313
+ async fetchJwks() {
2314
+ const url = this.d.config?.jwksUrl || DEFAULT_QR_JWKS_URL;
2315
+ const fail2 = (why) => new QrError("QR_JWKS_UNAVAILABLE", why);
2316
+ let u;
2317
+ try {
2318
+ u = new URL(url);
2319
+ } catch {
2320
+ throw fail2("jwksUrl \u0431\u0443\u0440\u0443\u0443");
2321
+ }
2322
+ if (u.protocol !== "https:" && !(u.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(u.hostname))) {
2323
+ throw fail2("jwksUrl https \u0431\u0430\u0439\u0445 \u0451\u0441\u0442\u043E\u0439");
2324
+ }
2325
+ const init = {
2326
+ method: "GET",
2327
+ headers: { Accept: "application/json" },
2328
+ signal: AbortSignal.timeout(this.d.timeoutMs ?? 15e3)
2329
+ };
2330
+ if (this.d.dispatcher) init.dispatcher = this.d.dispatcher;
2331
+ let res;
2332
+ try {
2333
+ res = await (this.d.fetchImpl ?? fetch)(url, init);
2334
+ } catch (e) {
2335
+ throw fail2(`\u0442\u0430\u0442\u0430\u0433\u0434\u0441\u0430\u043D\u0433\u04AF\u0439: ${e.message}`);
2336
+ }
2337
+ if (res.status !== 200) {
2338
+ await res.body?.cancel().catch(() => void 0);
2339
+ throw fail2(`HTTP ${res.status}`);
2340
+ }
2341
+ const text = await res.text();
2342
+ if (text.length > MAX_JWKS) throw fail2("JWKS \u0445\u044D\u0442 \u0442\u043E\u043C");
2343
+ let k;
2344
+ try {
2345
+ k = JSON.parse(text);
2346
+ } catch {
2347
+ throw fail2("JWKS JSON \u0431\u0438\u0448");
2348
+ }
2349
+ if (!isObj(k) || !Array.isArray(k.keys) || k.keys.length === 0) throw fail2("JWKS \u0445\u043E\u043E\u0441\u043E\u043D");
2350
+ return k;
2351
+ }
2352
+ };
2353
+
2019
2354
  // src/share.ts
2020
2355
  var DEFAULT_SHARE_TIMEOUT_MS = 15e4;
2021
2356
  var SHARE_ERROR_CODES = [
@@ -2148,6 +2483,8 @@ var EidClient = class {
2148
2483
  organization;
2149
2484
  person;
2150
2485
  token;
2486
+ /** «Миний QR» (биечлэн шалгах): parse → start → result. */
2487
+ qr;
2151
2488
  session;
2152
2489
  validator;
2153
2490
  /** `credentials.rpName` — иргэний утсанд харагдах RP нэр. */
@@ -2172,6 +2509,15 @@ var EidClient = class {
2172
2509
  this.validator = new ResponseValidator(cfg.trust ?? {});
2173
2510
  this.token = new TokenApi(http, cfg.credentials, this.validator);
2174
2511
  this.session = new SessionApi(http);
2512
+ this.qr = new QrApi({
2513
+ http,
2514
+ session: this.session,
2515
+ credentials: cfg.credentials,
2516
+ config: cfg.qr,
2517
+ fetchImpl: cfg.fetchImpl,
2518
+ dispatcher: cfg.dispatcher,
2519
+ timeoutMs: cfg.timeoutMs
2520
+ });
2175
2521
  this.rpName = cfg.credentials.rpName;
2176
2522
  this.http = http;
2177
2523
  }
@@ -2276,7 +2622,7 @@ function ocspRevocationChecker(opts = {}) {
2276
2622
  import { createHmac } from "crypto";
2277
2623
  var TYPES = ["QR", "Web2App", "App2App"];
2278
2624
  var PROTOCOL = { auth: "ACSP_V2", sign: "RAW_DIGEST_SIGNATURE", cert: "" };
2279
- var TOKEN_RE = /^[A-Za-z0-9_-]+$/;
2625
+ var TOKEN_RE2 = /^[A-Za-z0-9_-]+$/;
2280
2626
  var LANG_RE = /^[a-z]{3}$/;
2281
2627
  var STD_B64_RE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
2282
2628
  var b642 = (s) => Buffer.from(s, "utf8").toString("base64");
@@ -2296,7 +2642,7 @@ function buildDeviceLink(p) {
2296
2642
  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");
2297
2643
  if (!TYPES.includes(p.deviceLinkType)) fail(`deviceLinkType ${String(p.deviceLinkType)} (QR | Web2App | App2App)`);
2298
2644
  if (!(p.sessionType in PROTOCOL)) fail(`sessionType ${String(p.sessionType)} (auth | sign | cert)`);
2299
- if (!p.sessionToken || !TOKEN_RE.test(p.sessionToken)) fail("sessionToken \u0445\u044D\u043B\u0431\u044D\u0440 \u0431\u0443\u0440\u0443\u0443");
2645
+ if (!p.sessionToken || !TOKEN_RE2.test(p.sessionToken)) fail("sessionToken \u0445\u044D\u043B\u0431\u044D\u0440 \u0431\u0443\u0440\u0443\u0443");
2300
2646
  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)");
2301
2647
  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");
2302
2648
  let challenge = "";
@@ -2470,7 +2816,7 @@ function forwardedClientIp(headers, trustProxy) {
2470
2816
  }
2471
2817
  var ID_RE = /^(\p{L}{2}[0-9]{8}|[0-9]{8,14}|PNOMN-[0-9]{8,14})$/u;
2472
2818
  var UUID_RE2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
2473
- var B64URL_RE = /^[A-Za-z0-9_-]{43}$/;
2819
+ var B64URL_RE2 = /^[A-Za-z0-9_-]{43}$/;
2474
2820
  var IOS_BROWSERS = [
2475
2821
  [/CriOS/i, "googlechromes"],
2476
2822
  [/EdgiOS/i, "microsoft-edge-https"],
@@ -2675,7 +3021,7 @@ function createEidLogin(opts) {
2675
3021
  const dot = raw.indexOf(".");
2676
3022
  const sid = raw.slice(0, dot);
2677
3023
  const binding = raw.slice(dot + 1);
2678
- if (dot < 0 || !UUID_RE2.test(sid) || !B64URL_RE.test(binding)) return void 0;
3024
+ if (dot < 0 || !UUID_RE2.test(sid) || !B64URL_RE2.test(binding)) return void 0;
2679
3025
  const tx = await store.get(sid);
2680
3026
  if (!tx || !safeEqualHex(tx.bindingHash, sha256hex(binding))) return void 0;
2681
3027
  if (tx.expiresAt <= Date.now()) {
@@ -2971,6 +3317,10 @@ export {
2971
3317
  DEFAULT_BASE_URL,
2972
3318
  DEFAULT_MAX_WAIT_MS,
2973
3319
  DEFAULT_PDF_TIMEOUT_MS,
3320
+ DEFAULT_QR_ISSUER,
3321
+ DEFAULT_QR_JWKS_CACHE_TTL_MS,
3322
+ DEFAULT_QR_JWKS_URL,
3323
+ DEFAULT_QR_MAX_AGE_MS,
2974
3324
  DEFAULT_SHARE_TIMEOUT_MS,
2975
3325
  DEFAULT_SIGN_SESSION_TTL_MS,
2976
3326
  DeviceLinkError,
@@ -2991,6 +3341,13 @@ export {
2991
3341
  PDF_REGISTER_ERROR_CODES,
2992
3342
  PDF_SIGNATURE_REGISTER_FIELDS,
2993
3343
  PersonApi,
3344
+ QR_ATTRIBUTES,
3345
+ QR_CLOCK_SKEW_MS,
3346
+ QR_ERROR_CODES,
3347
+ QR_PREFIX,
3348
+ QrApi,
3349
+ QrError,
3350
+ QrTokenInvalidError,
2994
3351
  RETRYABLE_ERROR_CODES,
2995
3352
  RequestInvalidError,
2996
3353
  ResponseTooLargeError,
@@ -3021,6 +3378,7 @@ export {
3021
3378
  memoryLoginStore,
3022
3379
  ocspRevocationChecker,
3023
3380
  parseExpiresAt,
3381
+ parseQr,
3024
3382
  parseRetryAfter,
3025
3383
  parseSessionResult,
3026
3384
  parseSubject,
@@ -3037,6 +3395,7 @@ export {
3037
3395
  userChallengeOf,
3038
3396
  verifyPayloadSignature,
3039
3397
  verifyPrehashedSignature,
3398
+ verifyQrPresentation,
3040
3399
  verifyTokenCertificates,
3041
3400
  withReturnHint
3042
3401
  };
package/dist/pades.d.cts CHANGED
@@ -1,4 +1,5 @@
1
- import { E as EidError } from './errors-3JEfE-FW.cjs';
1
+ import { E as EidError } from './errors-mcDbKiz_.cjs';
2
+ import { P as PdfImage } from './types-Cf3GT4wh.cjs';
2
3
  import { F as FetchFn } from './fetch-BjfH46q9.cjs';
3
4
 
4
5
  /** Олгогчийн гарын үсэгтэй «revoked» хариу (OCSP эсвэл CRL) — complete-д дахин оролдохгүй хатуу алдаа (Go ErrCertificateRevoked). */
@@ -103,29 +104,7 @@ interface PadesAppearance {
103
104
  */
104
105
  stampImage?: PdfImage;
105
106
  }
106
- /**
107
- * A "PDF image" as the CA serves it (Go `pades.PDFImage`, APPEARANCE_SPEC.md §6.1): one ink colour + an 8-bit alpha
108
- * channel. The SDK writes `alpha` into the PDF verbatim (/SMask, /FlateDecode) — nothing is compressed at runtime, so
109
- * every SDK writes the same bytes. Not a PNG.
110
- */
111
- interface PdfImage {
112
- /** px, 1…1600. */
113
- width: number;
114
- /** px, 1…1600. */
115
- height: number;
116
- /** Ink colour `[r, g, b]`, 0…255. */
117
- color: [number, number, number];
118
- /**
119
- * Standard base64 of a zlib stream (RFC 1950, no preset dictionary, nothing after the Adler-32) inflating to exactly
120
- * `width·height` bytes, rows top-down, no PNG filter bytes; ≤ 300 KiB decoded.
121
- */
122
- alpha: string;
123
- /**
124
- * Lowercase hex SHA-256 of the PNG the CA stores; not written into the PDF — carried to the registration
125
- * ({@link PadesCompleted.images} → `registrationFromCompleted` → `images`).
126
- */
127
- sha256: string;
128
- }
107
+
129
108
  /** One image drawn in a signature's stamp, as registered with the CA (`POST /pdf/signatures` `images`, APPEARANCE_SPEC §6.6). */
130
109
  interface PadesImageRef {
131
110
  kind: "signature" | "stamp";
@@ -309,4 +288,4 @@ declare function suggestPlacement(pdf: Uint8Array, appearance: PadesAppearance):
309
288
  */
310
289
  declare function complete(state: Uint8Array | ArrayBuffer, signature: Uint8Array | string, opts?: PadesCompleteOptions): Promise<PadesCompleted>;
311
290
 
312
- export { CertificateRevokedError, DEFAULT_ORG_STAMP_SIZE, DEFAULT_SIGNATURE_STAMP_SIZE, DEFAULT_STAMP_SIZE, PADES_ERROR_CODES, PROFILE_VERSION, type PadesAppearance, type PadesCompleteOptions, type PadesCompleted, PadesError, type PadesErrorCode, type PadesImageRef, type PadesPlacement, type PadesPlacementStatus, type PadesPrepareOptions, type PadesPrepared, type PdfImage, type PlacementSuggestion, complete, prepare, profileVersion, suggestPlacement };
291
+ export { CertificateRevokedError, DEFAULT_ORG_STAMP_SIZE, DEFAULT_SIGNATURE_STAMP_SIZE, DEFAULT_STAMP_SIZE, PADES_ERROR_CODES, PROFILE_VERSION, type PadesAppearance, type PadesCompleteOptions, type PadesCompleted, PadesError, type PadesErrorCode, type PadesImageRef, type PadesPlacement, type PadesPlacementStatus, type PadesPrepareOptions, type PadesPrepared, PdfImage, type PlacementSuggestion, complete, prepare, profileVersion, suggestPlacement };
package/dist/pades.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- import { E as EidError } from './errors-3JEfE-FW.js';
1
+ import { E as EidError } from './errors-mcDbKiz_.js';
2
+ import { P as PdfImage } from './types-Cf3GT4wh.js';
2
3
  import { F as FetchFn } from './fetch-BjfH46q9.js';
3
4
 
4
5
  /** Олгогчийн гарын үсэгтэй «revoked» хариу (OCSP эсвэл CRL) — complete-д дахин оролдохгүй хатуу алдаа (Go ErrCertificateRevoked). */
@@ -103,29 +104,7 @@ interface PadesAppearance {
103
104
  */
104
105
  stampImage?: PdfImage;
105
106
  }
106
- /**
107
- * A "PDF image" as the CA serves it (Go `pades.PDFImage`, APPEARANCE_SPEC.md §6.1): one ink colour + an 8-bit alpha
108
- * channel. The SDK writes `alpha` into the PDF verbatim (/SMask, /FlateDecode) — nothing is compressed at runtime, so
109
- * every SDK writes the same bytes. Not a PNG.
110
- */
111
- interface PdfImage {
112
- /** px, 1…1600. */
113
- width: number;
114
- /** px, 1…1600. */
115
- height: number;
116
- /** Ink colour `[r, g, b]`, 0…255. */
117
- color: [number, number, number];
118
- /**
119
- * Standard base64 of a zlib stream (RFC 1950, no preset dictionary, nothing after the Adler-32) inflating to exactly
120
- * `width·height` bytes, rows top-down, no PNG filter bytes; ≤ 300 KiB decoded.
121
- */
122
- alpha: string;
123
- /**
124
- * Lowercase hex SHA-256 of the PNG the CA stores; not written into the PDF — carried to the registration
125
- * ({@link PadesCompleted.images} → `registrationFromCompleted` → `images`).
126
- */
127
- sha256: string;
128
- }
107
+
129
108
  /** One image drawn in a signature's stamp, as registered with the CA (`POST /pdf/signatures` `images`, APPEARANCE_SPEC §6.6). */
130
109
  interface PadesImageRef {
131
110
  kind: "signature" | "stamp";
@@ -309,4 +288,4 @@ declare function suggestPlacement(pdf: Uint8Array, appearance: PadesAppearance):
309
288
  */
310
289
  declare function complete(state: Uint8Array | ArrayBuffer, signature: Uint8Array | string, opts?: PadesCompleteOptions): Promise<PadesCompleted>;
311
290
 
312
- export { CertificateRevokedError, DEFAULT_ORG_STAMP_SIZE, DEFAULT_SIGNATURE_STAMP_SIZE, DEFAULT_STAMP_SIZE, PADES_ERROR_CODES, PROFILE_VERSION, type PadesAppearance, type PadesCompleteOptions, type PadesCompleted, PadesError, type PadesErrorCode, type PadesImageRef, type PadesPlacement, type PadesPlacementStatus, type PadesPrepareOptions, type PadesPrepared, type PdfImage, type PlacementSuggestion, complete, prepare, profileVersion, suggestPlacement };
291
+ export { CertificateRevokedError, DEFAULT_ORG_STAMP_SIZE, DEFAULT_SIGNATURE_STAMP_SIZE, DEFAULT_STAMP_SIZE, PADES_ERROR_CODES, PROFILE_VERSION, type PadesAppearance, type PadesCompleteOptions, type PadesCompleted, PadesError, type PadesErrorCode, type PadesImageRef, type PadesPlacement, type PadesPlacementStatus, type PadesPrepareOptions, type PadesPrepared, PdfImage, type PlacementSuggestion, complete, prepare, profileVersion, suggestPlacement };
package/dist/pades.js CHANGED
@@ -61,7 +61,7 @@ import {
61
61
  } from "./chunk-ISTWNY6N.js";
62
62
  import {
63
63
  EidError
64
- } from "./chunk-R73IR6OH.js";
64
+ } from "./chunk-TNXO4QLU.js";
65
65
 
66
66
  // src/pades/limits.ts
67
67
  var MAX_INPUT_BYTES = (10 << 20) - (256 << 10);