@gerege-systems/eid-mongolia-sdk 0.32.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
  };
@@ -174,7 +175,9 @@ var RP_ROUTES = {
174
175
  pdfSignatures: { method: "POST", path: "/pdf/signatures" },
175
176
  tokenAuthChallenge: { method: "POST", path: "/token/auth/challenge" },
176
177
  tokenAuthVerify: { method: "POST", path: "/token/auth/verify" },
177
- 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" }
178
181
  };
179
182
  var PDF_SIGNATURE_REGISTER_FIELDS = [
180
183
  "docID",
@@ -776,6 +779,7 @@ function parseSessionResult(raw) {
776
779
  onBehalfOf: parseOrg(r.onBehalfOf),
777
780
  person: parsePerson(r.person),
778
781
  tokenCertificate: parseTokenCert(r.tokenCertificate),
782
+ presentation: parsePresentation(r.presentation),
779
783
  raw
780
784
  };
781
785
  }
@@ -797,6 +801,11 @@ function parsePerson(raw) {
797
801
  if (typeof p.geID === "number" && p.geID !== 0) out.geID = p.geID;
798
802
  return Object.keys(out).length ? out : null;
799
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
+ }
800
809
  function parseTokenCert(raw) {
801
810
  const t = asRecord(raw);
802
811
  const status = str(t.status);
@@ -1391,9 +1400,9 @@ var ResponseValidator = class {
1391
1400
  ...this.intermediates.map((c) => [c, false])
1392
1401
  ]) {
1393
1402
  if (cas.includes(cand) || !signedBy(cur, cand)) continue;
1394
- const bad = caReason(cand, cas.length, now, usage);
1395
- if (bad) {
1396
- reason ??= bad;
1403
+ const bad2 = caReason(cand, cas.length, now, usage);
1404
+ if (bad2) {
1405
+ reason ??= bad2;
1397
1406
  continue;
1398
1407
  }
1399
1408
  if (isAnchor || extend(cand, [...cas, cand])) return true;
@@ -2030,6 +2039,318 @@ function tokenLimitOf(err) {
2030
2039
  return void 0;
2031
2040
  }
2032
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
+
2033
2354
  // src/share.ts
2034
2355
  var DEFAULT_SHARE_TIMEOUT_MS = 15e4;
2035
2356
  var SHARE_ERROR_CODES = [
@@ -2162,6 +2483,8 @@ var EidClient = class {
2162
2483
  organization;
2163
2484
  person;
2164
2485
  token;
2486
+ /** «Миний QR» (биечлэн шалгах): parse → start → result. */
2487
+ qr;
2165
2488
  session;
2166
2489
  validator;
2167
2490
  /** `credentials.rpName` — иргэний утсанд харагдах RP нэр. */
@@ -2186,6 +2509,15 @@ var EidClient = class {
2186
2509
  this.validator = new ResponseValidator(cfg.trust ?? {});
2187
2510
  this.token = new TokenApi(http, cfg.credentials, this.validator);
2188
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
+ });
2189
2521
  this.rpName = cfg.credentials.rpName;
2190
2522
  this.http = http;
2191
2523
  }
@@ -2290,7 +2622,7 @@ function ocspRevocationChecker(opts = {}) {
2290
2622
  import { createHmac } from "crypto";
2291
2623
  var TYPES = ["QR", "Web2App", "App2App"];
2292
2624
  var PROTOCOL = { auth: "ACSP_V2", sign: "RAW_DIGEST_SIGNATURE", cert: "" };
2293
- var TOKEN_RE = /^[A-Za-z0-9_-]+$/;
2625
+ var TOKEN_RE2 = /^[A-Za-z0-9_-]+$/;
2294
2626
  var LANG_RE = /^[a-z]{3}$/;
2295
2627
  var STD_B64_RE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
2296
2628
  var b642 = (s) => Buffer.from(s, "utf8").toString("base64");
@@ -2310,7 +2642,7 @@ function buildDeviceLink(p) {
2310
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");
2311
2643
  if (!TYPES.includes(p.deviceLinkType)) fail(`deviceLinkType ${String(p.deviceLinkType)} (QR | Web2App | App2App)`);
2312
2644
  if (!(p.sessionType in PROTOCOL)) fail(`sessionType ${String(p.sessionType)} (auth | sign | cert)`);
2313
- 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");
2314
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)");
2315
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");
2316
2648
  let challenge = "";
@@ -2484,7 +2816,7 @@ function forwardedClientIp(headers, trustProxy) {
2484
2816
  }
2485
2817
  var ID_RE = /^(\p{L}{2}[0-9]{8}|[0-9]{8,14}|PNOMN-[0-9]{8,14})$/u;
2486
2818
  var UUID_RE2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
2487
- var B64URL_RE = /^[A-Za-z0-9_-]{43}$/;
2819
+ var B64URL_RE2 = /^[A-Za-z0-9_-]{43}$/;
2488
2820
  var IOS_BROWSERS = [
2489
2821
  [/CriOS/i, "googlechromes"],
2490
2822
  [/EdgiOS/i, "microsoft-edge-https"],
@@ -2689,7 +3021,7 @@ function createEidLogin(opts) {
2689
3021
  const dot = raw.indexOf(".");
2690
3022
  const sid = raw.slice(0, dot);
2691
3023
  const binding = raw.slice(dot + 1);
2692
- 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;
2693
3025
  const tx = await store.get(sid);
2694
3026
  if (!tx || !safeEqualHex(tx.bindingHash, sha256hex(binding))) return void 0;
2695
3027
  if (tx.expiresAt <= Date.now()) {
@@ -2985,6 +3317,10 @@ export {
2985
3317
  DEFAULT_BASE_URL,
2986
3318
  DEFAULT_MAX_WAIT_MS,
2987
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,
2988
3324
  DEFAULT_SHARE_TIMEOUT_MS,
2989
3325
  DEFAULT_SIGN_SESSION_TTL_MS,
2990
3326
  DeviceLinkError,
@@ -3005,6 +3341,13 @@ export {
3005
3341
  PDF_REGISTER_ERROR_CODES,
3006
3342
  PDF_SIGNATURE_REGISTER_FIELDS,
3007
3343
  PersonApi,
3344
+ QR_ATTRIBUTES,
3345
+ QR_CLOCK_SKEW_MS,
3346
+ QR_ERROR_CODES,
3347
+ QR_PREFIX,
3348
+ QrApi,
3349
+ QrError,
3350
+ QrTokenInvalidError,
3008
3351
  RETRYABLE_ERROR_CODES,
3009
3352
  RequestInvalidError,
3010
3353
  ResponseTooLargeError,
@@ -3035,6 +3378,7 @@ export {
3035
3378
  memoryLoginStore,
3036
3379
  ocspRevocationChecker,
3037
3380
  parseExpiresAt,
3381
+ parseQr,
3038
3382
  parseRetryAfter,
3039
3383
  parseSessionResult,
3040
3384
  parseSubject,
@@ -3051,6 +3395,7 @@ export {
3051
3395
  userChallengeOf,
3052
3396
  verifyPayloadSignature,
3053
3397
  verifyPrehashedSignature,
3398
+ verifyQrPresentation,
3054
3399
  verifyTokenCertificates,
3055
3400
  withReturnHint
3056
3401
  };
package/dist/pades.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { E as EidError } from './errors-3JEfE-FW.cjs';
2
- import { P as PdfImage } from './types-ByGHVzuP.cjs';
1
+ import { E as EidError } from './errors-mcDbKiz_.cjs';
2
+ import { P as PdfImage } from './types-Cf3GT4wh.cjs';
3
3
  import { F as FetchFn } from './fetch-BjfH46q9.cjs';
4
4
 
5
5
  /** Олгогчийн гарын үсэгтэй «revoked» хариу (OCSP эсвэл CRL) — complete-д дахин оролдохгүй хатуу алдаа (Go ErrCertificateRevoked). */
package/dist/pades.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { E as EidError } from './errors-3JEfE-FW.js';
2
- import { P as PdfImage } from './types-ByGHVzuP.js';
1
+ import { E as EidError } from './errors-mcDbKiz_.js';
2
+ import { P as PdfImage } from './types-Cf3GT4wh.js';
3
3
  import { F as FetchFn } from './fetch-BjfH46q9.js';
4
4
 
5
5
  /** Олгогчийн гарын үсэгтэй «revoked» хариу (OCSP эсвэл CRL) — complete-д дахин оролдохгүй хатуу алдаа (Go ErrCertificateRevoked). */
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);
@@ -188,9 +188,19 @@ interface SessionResult {
188
188
  person?: PersonBlock | null;
189
189
  /** USB токены гэрчилгээ олголтын session-ий `tokenCertificate` блок (`token.issueCertificate`); бусад урсгалд null. */
190
190
  tokenCertificate?: TokenCertSessionBlock | null;
191
+ /**
192
+ * «Миний QR» session-ий CA-ийн presentation (`qr.result` шалгана): `jws` (ES256) ба `claims` (payload-ийн хуулбар —
193
+ * ШАЛГААГҮЙ; итгэхдээ `qr.result` / `verifyQrPresentation`-ийн үр дүнг л хэрэглэ). Бусад урсгалд null.
194
+ */
195
+ presentation?: SessionPresentation | null;
191
196
  /** Серверийн хариуны түүхий JSON (`parseSessionResult`-ийн оролт) — SDK задлаагүй талбарт. */
192
197
  raw?: unknown;
193
198
  }
199
+ /** QR session-ий `presentation` блок. */
200
+ interface SessionPresentation {
201
+ jws: string;
202
+ claims?: Record<string, unknown>;
203
+ }
194
204
  /**
195
205
  * Session-ий `person` блок (CA `dto.PersonBlock`). Нэршил core.gerege.mn-тэй нэг мөр — гурван нэр ӨӨР ойлголт:
196
206
  * `firstName` = нэр, `lastName` = ЭЦГИЙН нэр (гэрчилгээнд ордог), `familyName` = УРГИЙН овог (гэрчилгээнд ОРОХГҮЙ).
@@ -342,4 +352,4 @@ interface RpCredentials {
342
352
  apiSecret: string;
343
353
  }
344
354
 
345
- export { type AcspContext as A, type CertificateLevel as C, type DeviceLinkSession as D, type EidImage as E, type FlowType as F, type HashAlgorithm as H, type Interaction as I, type NotificationSession as N, type OrgResult as O, type PdfImage as P, type RpCredentials as R, type SignatureAlgorithm as S, type TokenCertSessionBlock as T, type SessionResult as a, type PersonBlock as b, type RepresentationsResponse as c, DEFAULT_SIGN_SESSION_TTL_MS as d, type EndResult as e, type Representation as f, type SessionState as g, type SignContext as h, type SignatureAlgorithmParameters as i, type SignatureProtocol as j, type TokenCertStatus as k, startExpiry as l, parseExpiresAt as p, sessionExpiry as s };
355
+ export { type AcspContext as A, type CertificateLevel as C, type DeviceLinkSession as D, type EidImage as E, type FlowType as F, type HashAlgorithm as H, type Interaction as I, type NotificationSession as N, type OrgResult as O, type PdfImage as P, type RpCredentials as R, type SignatureAlgorithm as S, type TokenCertSessionBlock as T, type SessionResult as a, type PersonBlock as b, type RepresentationsResponse as c, DEFAULT_SIGN_SESSION_TTL_MS as d, type EndResult as e, type Representation as f, type SessionPresentation as g, type SessionState as h, type SignContext as i, type SignatureAlgorithmParameters as j, type SignatureProtocol as k, type TokenCertStatus as l, startExpiry as m, parseExpiresAt as p, sessionExpiry as s };
@@ -188,9 +188,19 @@ interface SessionResult {
188
188
  person?: PersonBlock | null;
189
189
  /** USB токены гэрчилгээ олголтын session-ий `tokenCertificate` блок (`token.issueCertificate`); бусад урсгалд null. */
190
190
  tokenCertificate?: TokenCertSessionBlock | null;
191
+ /**
192
+ * «Миний QR» session-ий CA-ийн presentation (`qr.result` шалгана): `jws` (ES256) ба `claims` (payload-ийн хуулбар —
193
+ * ШАЛГААГҮЙ; итгэхдээ `qr.result` / `verifyQrPresentation`-ийн үр дүнг л хэрэглэ). Бусад урсгалд null.
194
+ */
195
+ presentation?: SessionPresentation | null;
191
196
  /** Серверийн хариуны түүхий JSON (`parseSessionResult`-ийн оролт) — SDK задлаагүй талбарт. */
192
197
  raw?: unknown;
193
198
  }
199
+ /** QR session-ий `presentation` блок. */
200
+ interface SessionPresentation {
201
+ jws: string;
202
+ claims?: Record<string, unknown>;
203
+ }
194
204
  /**
195
205
  * Session-ий `person` блок (CA `dto.PersonBlock`). Нэршил core.gerege.mn-тэй нэг мөр — гурван нэр ӨӨР ойлголт:
196
206
  * `firstName` = нэр, `lastName` = ЭЦГИЙН нэр (гэрчилгээнд ордог), `familyName` = УРГИЙН овог (гэрчилгээнд ОРОХГҮЙ).
@@ -342,4 +352,4 @@ interface RpCredentials {
342
352
  apiSecret: string;
343
353
  }
344
354
 
345
- export { type AcspContext as A, type CertificateLevel as C, type DeviceLinkSession as D, type EidImage as E, type FlowType as F, type HashAlgorithm as H, type Interaction as I, type NotificationSession as N, type OrgResult as O, type PdfImage as P, type RpCredentials as R, type SignatureAlgorithm as S, type TokenCertSessionBlock as T, type SessionResult as a, type PersonBlock as b, type RepresentationsResponse as c, DEFAULT_SIGN_SESSION_TTL_MS as d, type EndResult as e, type Representation as f, type SessionState as g, type SignContext as h, type SignatureAlgorithmParameters as i, type SignatureProtocol as j, type TokenCertStatus as k, startExpiry as l, parseExpiresAt as p, sessionExpiry as s };
355
+ export { type AcspContext as A, type CertificateLevel as C, type DeviceLinkSession as D, type EidImage as E, type FlowType as F, type HashAlgorithm as H, type Interaction as I, type NotificationSession as N, type OrgResult as O, type PdfImage as P, type RpCredentials as R, type SignatureAlgorithm as S, type TokenCertSessionBlock as T, type SessionResult as a, type PersonBlock as b, type RepresentationsResponse as c, DEFAULT_SIGN_SESSION_TTL_MS as d, type EndResult as e, type Representation as f, type SessionPresentation as g, type SessionState as h, type SignContext as i, type SignatureAlgorithmParameters as j, type SignatureProtocol as k, type TokenCertStatus as l, startExpiry as m, parseExpiresAt as p, sessionExpiry as s };
@@ -1,4 +1,4 @@
1
- import { E as EidError } from './errors-3JEfE-FW.cjs';
1
+ import { E as EidError } from './errors-mcDbKiz_.cjs';
2
2
  import { F as FetchFn } from './fetch-BjfH46q9.cjs';
3
3
 
4
4
  type Indication = "valid" | "invalid" | "indeterminate";
@@ -1,4 +1,4 @@
1
- import { E as EidError } from './errors-3JEfE-FW.js';
1
+ import { E as EidError } from './errors-mcDbKiz_.js';
2
2
  import { F as FetchFn } from './fetch-BjfH46q9.js';
3
3
 
4
4
  type Indication = "valid" | "invalid" | "indeterminate";
package/dist/validate.js CHANGED
@@ -66,7 +66,7 @@ import {
66
66
  } from "./chunk-ISTWNY6N.js";
67
67
  import {
68
68
  EidError
69
- } from "./chunk-R73IR6OH.js";
69
+ } from "./chunk-TNXO4QLU.js";
70
70
 
71
71
  // src/pades/validate/evaluate.ts
72
72
  var PROBLEMS = {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gerege-systems/eid-mongolia-sdk",
3
- "version": "0.32.0",
3
+ "version": "0.33.0",
4
4
  "description": "e-ID Mongolia Relying Party SDK — иргэнээр утсаар нь нэвтрэлт ба хууль ёсны цахим гарын үсэг (RP-API v3, Smart-ID нийцтэй).",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -49,7 +49,7 @@
49
49
  },
50
50
  "scripts": {
51
51
  "build": "tsup src/index.ts src/browser.ts src/pades.ts src/validate.ts --format esm,cjs --dts --clean && tsup src/button.ts --format esm,cjs --dts --tsconfig tsconfig.button.json && tsup src/convert.ts --format esm --dts --tsconfig tsconfig.button.json",
52
- "test": "npm run build && node --test --experimental-strip-types test/sdk.test.ts test/portal-gaps.test.ts test/chain.test.ts test/qr.test.ts test/login.test.ts test/button.test.ts test/sign-gaps.test.ts test/session-start.test.ts test/pades-session.test.ts test/pades-golden.test.ts test/pades-placement.test.ts test/pades-unit.test.ts test/convert.test.ts test/share.test.ts test/validate-golden.test.ts test/validate-revisions.test.ts test/validate-env.test.ts test/pades-revocation.test.ts test/pades-encrypt.test.ts test/pades-objstm.test.ts test/validate-fuzz.test.ts test/pades-lexer-loop.test.ts",
52
+ "test": "npm run build && node --test --experimental-strip-types test/sdk.test.ts test/portal-gaps.test.ts test/chain.test.ts test/qr.test.ts test/myqr.test.ts test/login.test.ts test/button.test.ts test/sign-gaps.test.ts test/session-start.test.ts test/pades-session.test.ts test/pades-golden.test.ts test/pades-placement.test.ts test/pades-unit.test.ts test/convert.test.ts test/share.test.ts test/validate-golden.test.ts test/validate-revisions.test.ts test/validate-env.test.ts test/pades-revocation.test.ts test/pades-encrypt.test.ts test/pades-objstm.test.ts test/validate-fuzz.test.ts test/pades-lexer-loop.test.ts",
53
53
  "test:contract": "npm run build && node --experimental-strip-types test/contract.test.ts",
54
54
  "lint": "tsc --noEmit && tsc --noEmit -p tsconfig.button.json",
55
55
  "golden:check": "node scripts/sync-pades-golden.mjs --check",