@gerege-systems/eid-mongolia-sdk 0.30.0 → 0.31.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/README.md CHANGED
@@ -674,6 +674,21 @@ const p = await prepare(pdfBytes, { signerCert, verifyPage: true, fileName: "Г
674
674
  appearance: { page, x, y, width: s.width, height: s.height, exact: true } });
675
675
  ```
676
676
 
677
+ **Гарын үсэг ба байгууллагын тамганы зураг (0.31.0+).** `appearance.signatureImage` (иргэний гарын үсгийн зураг) ба
678
+ `appearance.stampImage` (байгууллагын тамга — зөвхөн `claimedRole`/onBehalfOf-той, эс бөгөөс `REQUEST_INVALID`) —
679
+ `PdfImage { width, height, color: [r, g, b], alpha: "<base64 zlib>", sha256 }`, CA-ийн өгөх «PDF зураг» (PNG биш; SDK
680
+ `alpha`-г байтаар нь /SMask болгон бичнэ, шахалт хийхгүй — бүх SDK байт-ижил). Зураг дүрслэлийн ДОТОР (дээд зурвас; тамга
681
+ баруун дээд буланд хайрцгийг давж) зурагдана — тусдаа annotation биш тул өмнөх гарын үсэг «өөрчлөгдөөгүй» хэвээр.
682
+ `width`, `height` хоёулаа 0 бол анхдагч хэмжээ: 220×64 / гарын үсэгтэй 220×110 / тамгатай 240×147.5 (`suggestPlacement`-д ч —
683
+ ижил `appearance`-ийг өг). Зургийн оролт буруу (хэмжээ 1…1600 px, өнгө 0…255, alpha ≤ 300 KiB, нэг zlib stream яг
684
+ `width·height` байт, `sha256` жижиг hex) бол `REQUEST_INVALID`. Зургийн sha256 `complete().images` →
685
+ `registrationFromCompleted` → `images` болж CA-д очно. Дүрэм: `APPEARANCE_SPEC.md` §6, `PLACEMENT_SPEC.md` §6c.
686
+
687
+ ```ts
688
+ const p = await prepare(pdfBytes, { signerCert, claimedRole, verifyPage: true, fileName: "Гэрээ №12.pdf",
689
+ appearance: { x: 340, y: 36, width: 0, height: 0, signatureImage, stampImage } }); // 240 × 147.5
690
+ ```
691
+
677
692
  **Баталгаажуулах хуудсыг эхэнд (0.30.0+).** `verifyPagePosition: "first"` — QR хуудас баримтын 1-р хуудас болно (анхдагч
678
693
  `"last"` — төгсгөлд, өмнөхтэй байт-ижил; бусад утга `REQUEST_INVALID`). Хуудас нэмэгдэх үед л (гарын үсэггүй баримт,
679
694
  `verifyPage: true`) нөлөөтэй. `appearance.page`, `suggestPlacement`, `placement.page` үргэлж **оролтын** PDF-ийн хуудсаар
@@ -1089,8 +1104,8 @@ npm run test:convert-e2e # /convert жинхэнэ LibreOffice Chromium-д (BR
1089
1104
 
1090
1105
  `/pades`-ийн conformance fixture (golden: оролт, тестийн PKI-ийн гэрчилгээ, TSA/OCSP/CRL-ийн тогтмол хариу, хүлээгдэх
1091
1106
  sha256) ба фонт/гинжийн asset-ийг Go reference-ээс `node scripts/sync-pades-golden.mjs` хуулна (`GO_SDK_COMMIT` —
1092
- tag `pades-golden-vN`, одоо v7 — `placement/` scanner vectors-той, page 0 verify хуудас алгасна, `exact` +
1093
- `expect.suggestion`); CI `--check`-ээр бэхэлсэн commit-тэй тулгана. Профайл:
1107
+ Go `pades-golden-v10` — зургийн кейсүүд `img-*`; v7-оос `placement/` scanner vectors-той, page 0 verify хуудас алгасна,
1108
+ `exact` + `expect.suggestion`); CI `--check`-ээр бэхэлсэн commit-тэй тулгана. Профайл:
1094
1109
  Go репогийн `pades/PROFILE.md`, `PAGE_SPEC.md`, `PRECHECKS.md`, `WIRE.md`, `APPEARANCE_SPEC.md`, `PLACEMENT_SPEC.md`.
1095
1110
 
1096
1111
  ### Гэрээний шалгалт
@@ -1,4 +1,4 @@
1
- import './errors-CxAr-WIA.cjs';
1
+ import './errors-3JEfE-FW.cjs';
2
2
 
3
3
  /** isMobileUserAgent-ийн уншдаг navigator-ийн хэсэг (тестэд орлуулна). */
4
4
  interface NavigatorLike {
@@ -1,4 +1,4 @@
1
- import './errors-CxAr-WIA.js';
1
+ import './errors-3JEfE-FW.js';
2
2
 
3
3
  /** isMobileUserAgent-ийн уншдаг navigator-ийн хэсэг (тестэд орлуулна). */
4
4
  interface NavigatorLike {
@@ -1,2 +1,2 @@
1
- export { D as DeviceLinkSession, d as NavigatorLike, k as isMobileUserAgent } from './browser-CYpvoCRr.cjs';
2
- export { D as DeviceLinkError, E as EidError } from './errors-CxAr-WIA.cjs';
1
+ export { D as DeviceLinkSession, d as NavigatorLike, k as isMobileUserAgent } from './browser-B3cWNpRM.cjs';
2
+ export { D as DeviceLinkError, E as EidError } from './errors-3JEfE-FW.cjs';
package/dist/browser.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export { D as DeviceLinkSession, d as NavigatorLike, k as isMobileUserAgent } from './browser-DturMWIL.js';
2
- export { D as DeviceLinkError, E as EidError } from './errors-CxAr-WIA.js';
1
+ export { D as DeviceLinkSession, d as NavigatorLike, k as isMobileUserAgent } from './browser-X_HjiWxc.js';
2
+ export { D as DeviceLinkError, E as EidError } from './errors-3JEfE-FW.js';
package/dist/browser.js CHANGED
@@ -4,7 +4,7 @@ import {
4
4
  import {
5
5
  DeviceLinkError,
6
6
  EidError
7
- } from "./chunk-H7JOACAZ.js";
7
+ } from "./chunk-R73IR6OH.js";
8
8
  export {
9
9
  DeviceLinkError,
10
10
  EidError,
@@ -151,7 +151,7 @@ function zlibInflate(src, limit = 64 << 20, initial) {
151
151
  function inflateRaw(src, limit = 64 << 20, info, initial) {
152
152
  return inflate(src, limit, info, initial, false);
153
153
  }
154
- function zlibInflateStrict(src, limit) {
154
+ function zlibInflateStrict(src, limit, exact = false) {
155
155
  if (src.length < 2) throw new InflateError("zlib: header \u0430\u043B\u0433\u0430");
156
156
  const cmf = src[0];
157
157
  const flg = src[1];
@@ -169,6 +169,7 @@ function zlibInflateStrict(src, limit) {
169
169
  if (at + 4 > src.length) throw new InflateError("zlib: adler32 \u0430\u043B\u0433\u0430");
170
170
  const want = (src[at] << 24 | src[at + 1] << 16 | src[at + 2] << 8 | src[at + 3]) >>> 0;
171
171
  if (adler32(out) !== want) throw new InflateError("zlib: adler32 \u0442\u0430\u0430\u0440\u0430\u0445\u0433\u04AF\u0439");
172
+ if (exact && at + 4 !== src.length) throw new InflateError("zlib: stream-\u0438\u0439\u043D \u0430\u0440\u0434 \u0438\u043B\u04AF\u04AF \u0431\u0430\u0439\u0442");
172
173
  return out;
173
174
  }
174
175
  function adler32(b) {
@@ -476,10 +477,12 @@ var Lexer = class {
476
477
  const out = [];
477
478
  for (; ; ) {
478
479
  let c = this.readByte();
479
- while (isSpace(c)) c = this.readByte();
480
+ while (isSpace(c) && !this.eof) c = this.readByte();
481
+ if (this.eof) throw new PdfError("unterminated hex string");
480
482
  if (c === 62) break;
481
483
  let c2 = this.readByte();
482
- while (isSpace(c2)) c2 = this.readByte();
484
+ while (isSpace(c2) && !this.eof) c2 = this.readByte();
485
+ if (this.eof) throw new PdfError("unterminated hex string");
483
486
  const x = unhex(c) << 4 | unhex(c2);
484
487
  if (unhex(c) < 0 || unhex(c2) < 0 || x < 0) throw new PdfError("malformed hex string");
485
488
  out.push(x);
@@ -491,6 +494,7 @@ var Lexer = class {
491
494
  let depth = 1;
492
495
  for (; ; ) {
493
496
  let c = this.readByte();
497
+ if (this.eof) throw new PdfError("unterminated literal string");
494
498
  if (c === 40) {
495
499
  depth++;
496
500
  out.push(c);
@@ -635,6 +639,7 @@ var Lexer = class {
635
639
  const tok = this.readToken();
636
640
  if (isKw(tok, "]")) break;
637
641
  if (tok === EOF_TOKEN) throw new PdfError("unterminated array");
642
+ if (isKw(tok, "endobj")) throw new PdfError("unterminated array");
638
643
  this.unreadToken(tok);
639
644
  x.push(asObj(this.readObject()));
640
645
  }
@@ -993,6 +998,7 @@ var Reader = class {
993
998
  for (let i = 0; i < n; i++) {
994
999
  const id = b.readToken();
995
1000
  const off = b.readToken();
1001
+ if (id === EOF_TOKEN || off === EOF_TOKEN) break;
996
1002
  const idn = id instanceof PInt ? Number(BigInt.asUintN(32, id.v)) : 0;
997
1003
  if (idn === ptr.id) {
998
1004
  const o = off instanceof PInt ? Number(off.v) : 0;
@@ -2079,6 +2085,61 @@ function toUnicode(f) {
2079
2085
  // src/pades/page/appearance.ts
2080
2086
  var AppearanceError = class extends PdfError {
2081
2087
  };
2088
+ var MAX_IMAGE_SIDE = 1600;
2089
+ var MAX_IMAGE_ALPHA_BYTES = 300 << 10;
2090
+ var isIntIn = (v, lo, hi) => Number.isInteger(v) && v >= lo && v <= hi;
2091
+ function checkPdfImage(im) {
2092
+ const bad = (msg) => new AppearanceError(`\u0437\u0443\u0440\u0430\u0433: ${msg}`);
2093
+ if (!isIntIn(im.w, 1, MAX_IMAGE_SIDE) || !isIntIn(im.h, 1, MAX_IMAGE_SIDE)) throw bad("\u0445\u044D\u043C\u0436\u044D\u044D 1\u20261600 px");
2094
+ if (!Array.isArray(im.color) || im.color.length !== 3) throw bad("\u04E9\u043D\u0433\u04E9 0\u2026255");
2095
+ for (const c of im.color) if (!isIntIn(c, 0, 255)) throw bad("\u04E9\u043D\u0433\u04E9 0\u2026255");
2096
+ if (!(im.alpha instanceof Uint8Array) || im.alpha.length === 0 || im.alpha.length > MAX_IMAGE_ALPHA_BYTES) throw bad("alpha 1 B\u2026300 KiB");
2097
+ if (im.alpha.length >= 2 && im.alpha[1] & 32) throw bad("alpha preset dictionary (FDICT)");
2098
+ let n;
2099
+ try {
2100
+ n = zlibInflateStrict(im.alpha, im.w * im.h, true).length;
2101
+ } catch (e) {
2102
+ if (!(e instanceof InflateError)) throw e;
2103
+ n = -1;
2104
+ }
2105
+ if (n !== im.w * im.h) throw bad("alpha \u043D\u044C \u044F\u0433 \u04E9\u0440\u0433\u04E9\u043D\xD7\u04E9\u043D\u0434\u04E9\u0440 \u0431\u0430\u0439\u0442 \u0431\u0438\u0448 (\u044D\u0441\u0432\u044D\u043B \u044D\u0432\u0434\u044D\u0440\u0441\u044D\u043D)");
2106
+ }
2107
+ var idiv = (a, b) => Math.trunc(a / b);
2108
+ function apFit(iw, ih, bw, bh) {
2109
+ if (iw * bh >= ih * bw) return [bw, Math.max(1, idiv(bw * ih, iw))];
2110
+ return [Math.max(1, idiv(bh * iw, ih)), bh];
2111
+ }
2112
+ function apLayoutImages(p) {
2113
+ const l = { boxH: p.h, rowH: p.h, sig: [0, 0, 0, 0], stamp: [0, 0, 0, 0] };
2114
+ if (!p.sig && !p.stamp) return l;
2115
+ const small = () => new AppearanceError("\u0445\u044D\u0442 \u0436\u0438\u0436\u0438\u0433 (\u0437\u0443\u0440\u0430\u0433\u0442\u0430\u0439 \u0434\u04AF\u0440\u0441\u043B\u044D\u043B)");
2116
+ if (p.stamp) l.boxH = idiv(p.h * 4, 5);
2117
+ const band = idiv(l.boxH * 9, 22);
2118
+ l.rowH = l.boxH - band;
2119
+ const sh = idiv(band * 14, 15);
2120
+ const sy = l.rowH - idiv(band * 2, 15);
2121
+ let sw = idiv(p.w * 15, 22);
2122
+ let sx = idiv(p.w - sw, 2);
2123
+ if (p.stamp) {
2124
+ const d = idiv(l.boxH * 2, 3);
2125
+ const qx = Math.min(idiv(p.w * 41, 60) - idiv(d, 2), p.w - d);
2126
+ if (qx < 0 || d <= 0) throw small();
2127
+ const [dw, dh] = apFit(p.stamp.w, p.stamp.h, d, d);
2128
+ l.stamp = [qx + idiv(d - dw, 2), p.h - d + idiv(d - dh, 2), dw, dh];
2129
+ sx = idiv(p.w, 30);
2130
+ sw = qx + idiv(d, 2) - sx;
2131
+ }
2132
+ if (p.sig) {
2133
+ if (sw <= 0 || sh <= 0) throw small();
2134
+ const [dw, dh] = apFit(p.sig.w, p.sig.h, sw, sh);
2135
+ const dx = p.stamp ? sx : sx + idiv(sw - dw, 2);
2136
+ l.sig = [dx, sy + idiv(sh - dh, 2), dw, dh];
2137
+ }
2138
+ return l;
2139
+ }
2140
+ function apDrawImage(w, name, r) {
2141
+ w.op(`q ${num100(r[2])} 0 0 ${num100(r[3])} ${num100(r[0])} ${num100(r[1])} cm /${name} Do Q`);
2142
+ }
2082
2143
  var AP_PAD = 400;
2083
2144
  var AP_GAP = 400;
2084
2145
  var AP_MIN_MODULE = 100;
@@ -2124,6 +2185,10 @@ function appearanceContent(p) {
2124
2185
  if (label === void 0) throw new AppearanceError(`\u0445\u044D\u043B ${p.lang}`);
2125
2186
  if (!asciiURL(p.url)) throw new AppearanceError("URL ASCII \u0431\u0438\u0448");
2126
2187
  if (p.w <= 0 || p.h <= 0 || p.w > MAX_APPEARANCE_SIDE || p.h > MAX_APPEARANCE_SIDE) throw new AppearanceError("\u0445\u044D\u043C\u0436\u044D\u044D");
2188
+ if (p.stamp && p.role === "") throw new AppearanceError("\u0442\u0430\u043C\u0433\u044B\u043D \u0437\u0443\u0440\u0430\u0433 \u0437\u04E9\u0432\u0445\u04E9\u043D \u0431\u0430\u0439\u0433\u0443\u0443\u043B\u043B\u0430\u0433\u044B\u043D \u043D\u044D\u0440\u0438\u0439\u043D \u04E9\u043C\u043D\u04E9\u04E9\u0441 (claimedRole)");
2189
+ for (const im of [p.sig, p.stamp]) if (im) checkPdfImage(im);
2190
+ const il = apLayoutImages(p);
2191
+ const rowH = il.rowH;
2127
2192
  let m;
2128
2193
  try {
2129
2194
  m = qrEncode(latin1(p.url));
@@ -2131,14 +2196,14 @@ function appearanceContent(p) {
2131
2196
  throw new AppearanceError(String(e));
2132
2197
  }
2133
2198
  const n = m.length;
2134
- const mod = Math.trunc((p.h - 2 * AP_PAD) / n);
2199
+ const mod = Math.trunc((rowH - 2 * AP_PAD) / n);
2135
2200
  if (mod < AP_MIN_MODULE) throw new AppearanceError(`\u0445\u044D\u0442 \u0436\u0438\u0436\u0438\u0433 (\u04E9\u043D\u0434\u04E9\u0440 \u2265 ${num100(2 * AP_PAD + n * AP_MIN_MODULE)} pt)`);
2136
2201
  const tx = AP_PAD + mod * n + AP_GAP;
2137
2202
  const tw = p.w - tx - AP_PAD;
2138
2203
  const [reg, bld] = loadFonts();
2139
2204
  const w = new PageWriter(reg, bld);
2140
2205
  let lines;
2141
- for (let f = AP_MAX_SIZE; f >= AP_MIN_SIZE && lines === void 0 && tw > 0; f--) lines = apLayout(w, p, label, f, tw);
2206
+ for (let f = AP_MAX_SIZE; f >= AP_MIN_SIZE && lines === void 0 && tw > 0; f--) lines = apLayout(w, p, label, f, tw, rowH);
2142
2207
  if (lines === void 0) throw new AppearanceError("\u0445\u044D\u0442 \u0436\u0438\u0436\u0438\u0433 (\u0431\u0438\u0447\u0432\u044D\u0440 \u0431\u0430\u0433\u0442\u0430\u0445\u0433\u04AF\u0439)");
2143
2208
  let total = 0;
2144
2209
  for (const l of lines) total += l.size * AP_LEADING;
@@ -2150,8 +2215,13 @@ function appearanceContent(p) {
2150
2215
  }
2151
2216
  w.op(`${C_OK} RG`);
2152
2217
  w.op("1 w");
2153
- w.op(`0.5 0.5 ${num100(p.w - 100)} ${num100(p.h - 100)} re S`);
2154
- w.op(`q ${num100(mod)} 0 0 ${num100(mod)} ${num100(AP_PAD)} ${num100(Math.trunc((p.h - mod * n) / 2))} cm`);
2218
+ w.op(`0.5 0.5 ${num100(p.w - 100)} ${num100(il.boxH - 100)} re S`);
2219
+ if (p.sig || p.stamp) {
2220
+ w.op("0.5 w");
2221
+ w.op(`0 ${num100(rowH)} m ${num100(p.w)} ${num100(rowH)} l S`);
2222
+ }
2223
+ if (p.sig) apDrawImage(w, "Sig", il.sig);
2224
+ w.op(`q ${num100(mod)} 0 0 ${num100(mod)} ${num100(AP_PAD)} ${num100(Math.trunc((rowH - mod * n) / 2))} cm`);
2155
2225
  w.op("0 0 0 rg");
2156
2226
  for (let r = 0; r < n; r++) {
2157
2227
  for (let c = 0; c < n; ) {
@@ -2166,17 +2236,18 @@ function appearanceContent(p) {
2166
2236
  }
2167
2237
  w.op("f");
2168
2238
  w.op("Q");
2169
- let cursor = p.h - AP_PAD - Math.trunc((p.h - 2 * AP_PAD - total) / 2);
2239
+ let cursor = rowH - AP_PAD - Math.trunc((rowH - 2 * AP_PAD - total) / 2);
2170
2240
  for (const l of lines) {
2171
2241
  cursor -= l.size * AP_LEADING;
2172
2242
  w.op(`${l.color} rg`);
2173
2243
  w.op(`BT /F${l.font} ${l.size} Tf ${num100(tx)} ${num100(cursor + l.size * AP_DESCENT)} Td ${w.glyphHex(l.font, l.text)} Tj ET`);
2174
2244
  }
2245
+ if (p.stamp) apDrawImage(w, "Stamp", il.stamp);
2175
2246
  if (cm !== "") w.op("Q");
2176
2247
  w.op("EMC");
2177
2248
  return w.ops;
2178
2249
  }
2179
- function apLayout(w, p, label, f, tw) {
2250
+ function apLayout(w, p, label, f, tw, rowH) {
2180
2251
  const b = f - AP_BODY_DELTA;
2181
2252
  const limit = tw * 10;
2182
2253
  const lines = [];
@@ -2190,20 +2261,40 @@ function apLayout(w, p, label, f, tw) {
2190
2261
  if (l.text === "" || w.width1000(l.font, l.size, l.text) > limit) return void 0;
2191
2262
  total += l.size * AP_LEADING;
2192
2263
  }
2193
- if (total > p.h - 2 * AP_PAD) return void 0;
2264
+ if (total > rowH - 2 * AP_PAD) return void 0;
2194
2265
  return lines;
2195
2266
  }
2267
+ function appearanceObjectCount(p) {
2268
+ return 11 + (p.sig ? 2 : 0) + (p.stamp ? 2 : 0);
2269
+ }
2196
2270
  function appearanceObjects(p, ids) {
2271
+ if (ids.length !== appearanceObjectCount(p)) throw new AppearanceError("\u043E\u0431\u044A\u0435\u043A\u0442\u044B\u043D \u0442\u043E\u043E");
2197
2272
  const [reg, bld] = loadFonts();
2198
2273
  const { bw, bh } = apRotation(p.rotate, p.w, p.h);
2199
2274
  const content = appearanceContent(p);
2275
+ let res = `/Font << /F1 ${ids[1]} 0 R /F2 ${ids[6]} 0 R >>`;
2276
+ const imgs = [];
2277
+ let next = 11;
2278
+ if (p.sig || p.stamp) {
2279
+ res += " /XObject <<";
2280
+ for (const [name, im] of [["Sig", p.sig], ["Stamp", p.stamp]]) {
2281
+ if (!im) continue;
2282
+ const base = ids[next];
2283
+ const mask = ids[next + 1];
2284
+ next += 2;
2285
+ res += ` /${name} ${base} 0 R`;
2286
+ imgs.push(
2287
+ streamObj(` /Type /XObject /Subtype /Image /Width 1 /Height 1 /ColorSpace /DeviceRGB /BitsPerComponent 8 /SMask ${mask} 0 R`, Uint8Array.from(im.color)),
2288
+ streamObj(` /Type /XObject /Subtype /Image /Width ${im.w} /Height ${im.h} /ColorSpace /DeviceGray /BitsPerComponent 8 /Filter /FlateDecode`, im.alpha)
2289
+ );
2290
+ }
2291
+ res += " >>";
2292
+ }
2200
2293
  return [
2201
- streamObj(
2202
- ` /Type /XObject /Subtype /Form /BBox [0 0 ${num100(bw)} ${num100(bh)}] /Resources << /Font << /F1 ${ids[1]} 0 R /F2 ${ids[6]} 0 R >> >>`,
2203
- latin1(content)
2204
- ),
2294
+ streamObj(` /Type /XObject /Subtype /Form /BBox [0 0 ${num100(bw)} ${num100(bh)}] /Resources << ${res} >>`, latin1(content)),
2205
2295
  ...fontBodies(ids.slice(1, 6), reg),
2206
- ...fontBodies(ids.slice(6, 11), bld)
2296
+ ...fontBodies(ids.slice(6, 11), bld),
2297
+ ...imgs
2207
2298
  ];
2208
2299
  }
2209
2300
  function visibleWidget(fieldName, rect, pageID, pageGen, sigID, formID) {
@@ -2360,7 +2451,10 @@ export {
2360
2451
  Incremental,
2361
2452
  appendVerifyPage,
2362
2453
  AppearanceError,
2454
+ MAX_IMAGE_SIDE,
2455
+ checkPdfImage,
2363
2456
  round100,
2457
+ appearanceObjectCount,
2364
2458
  appearanceObjects,
2365
2459
  visibleWidget,
2366
2460
  visibleRect,
@@ -109,6 +109,7 @@ var PDF_REGISTER_ERROR_CODES = [
109
109
  "REGISTRY_CONFLICT",
110
110
  "DOC_NOT_FOUND",
111
111
  "PRIOR_MISMATCH",
112
+ "IMAGE_MISMATCH",
112
113
  "RATE_LIMITED",
113
114
  "STATE_UNAVAILABLE"
114
115
  ];
package/dist/convert.js CHANGED
@@ -423,10 +423,12 @@ var Lexer = class {
423
423
  const out = [];
424
424
  for (; ; ) {
425
425
  let c = this.readByte();
426
- while (isSpace(c)) c = this.readByte();
426
+ while (isSpace(c) && !this.eof) c = this.readByte();
427
+ if (this.eof) throw new PdfError("unterminated hex string");
427
428
  if (c === 62) break;
428
429
  let c2 = this.readByte();
429
- while (isSpace(c2)) c2 = this.readByte();
430
+ while (isSpace(c2) && !this.eof) c2 = this.readByte();
431
+ if (this.eof) throw new PdfError("unterminated hex string");
430
432
  const x = unhex(c) << 4 | unhex(c2);
431
433
  if (unhex(c) < 0 || unhex(c2) < 0 || x < 0) throw new PdfError("malformed hex string");
432
434
  out.push(x);
@@ -438,6 +440,7 @@ var Lexer = class {
438
440
  let depth = 1;
439
441
  for (; ; ) {
440
442
  let c = this.readByte();
443
+ if (this.eof) throw new PdfError("unterminated literal string");
441
444
  if (c === 40) {
442
445
  depth++;
443
446
  out.push(c);
@@ -582,6 +585,7 @@ var Lexer = class {
582
585
  const tok = this.readToken();
583
586
  if (isKw(tok, "]")) break;
584
587
  if (tok === EOF_TOKEN) throw new PdfError("unterminated array");
588
+ if (isKw(tok, "endobj")) throw new PdfError("unterminated array");
585
589
  this.unreadToken(tok);
586
590
  x.push(asObj(this.readObject()));
587
591
  }
@@ -940,6 +944,7 @@ var Reader = class {
940
944
  for (let i = 0; i < n; i++) {
941
945
  const id = b.readToken();
942
946
  const off = b.readToken();
947
+ if (id === EOF_TOKEN || off === EOF_TOKEN) break;
943
948
  const idn = id instanceof PInt ? Number(BigInt.asUintN(32, id.v)) : 0;
944
949
  if (idn === ptr.id) {
945
950
  const o = off instanceof PInt ? Number(off.v) : 0;
@@ -106,10 +106,10 @@ declare const ON_BEHALF_ERROR_CODES: readonly OnBehalfErrorCode[];
106
106
  * `pades_register.go`, `handlers_pdf.go`). 400: REQUEST_INVALID, CMS_INVALID, SIGNATURE_INVALID, TIMESTAMP_INVALID;
107
107
  * 403: TOKEN_ORG_MISMATCH, REPRESENTATION_REVOKED; 404: DOC_NOT_FOUND; 409: SIGNER_MISMATCH, SIGNER_CERT_INVALID,
108
108
  * TOKEN_CERT_INVALID, SESSION_MISMATCH, SESSION_NOT_COMPLETE, SESSION_FAILED, CLAIMED_ROLE_MISMATCH, DOC_ID_CONFLICT,
109
- * REGISTRY_CONFLICT, PRIOR_MISMATCH; 413: REQUEST_TOO_LARGE; 429: RATE_LIMITED; 503: STATE_UNAVAILABLE (сүүлийн хоёр
109
+ * REGISTRY_CONFLICT, PRIOR_MISMATCH, IMAGE_MISMATCH (images[] ≠ CA-ийн одоогийн зураг); 413: REQUEST_TOO_LARGE; 429: RATE_LIMITED; 503: STATE_UNAVAILABLE (сүүлийн хоёр
110
110
  * {@link RETRYABLE_ERROR_CODES}). Session олдоогүй бол 404 code-гүй.
111
111
  */
112
- type PdfRegisterErrorCode = "REQUEST_INVALID" | "REQUEST_TOO_LARGE" | "CMS_INVALID" | "SIGNATURE_INVALID" | "TIMESTAMP_INVALID" | "SIGNER_MISMATCH" | "SIGNER_CERT_INVALID" | "TOKEN_CERT_INVALID" | "TOKEN_ORG_MISMATCH" | "SESSION_MISMATCH" | "SESSION_NOT_COMPLETE" | "SESSION_FAILED" | "CLAIMED_ROLE_MISMATCH" | "REPRESENTATION_REVOKED" | "DOC_ID_CONFLICT" | "REGISTRY_CONFLICT" | "DOC_NOT_FOUND" | "PRIOR_MISMATCH" | "RATE_LIMITED" | "STATE_UNAVAILABLE";
112
+ type PdfRegisterErrorCode = "REQUEST_INVALID" | "REQUEST_TOO_LARGE" | "CMS_INVALID" | "SIGNATURE_INVALID" | "TIMESTAMP_INVALID" | "SIGNER_MISMATCH" | "SIGNER_CERT_INVALID" | "TOKEN_CERT_INVALID" | "TOKEN_ORG_MISMATCH" | "SESSION_MISMATCH" | "SESSION_NOT_COMPLETE" | "SESSION_FAILED" | "CLAIMED_ROLE_MISMATCH" | "REPRESENTATION_REVOKED" | "DOC_ID_CONFLICT" | "REGISTRY_CONFLICT" | "DOC_NOT_FOUND" | "PRIOR_MISMATCH" | "IMAGE_MISMATCH" | "RATE_LIMITED" | "STATE_UNAVAILABLE";
113
113
  /** {@link PdfRegisterErrorCode}-ийн бүх утга (runtime шалгалтад). */
114
114
  declare const PDF_REGISTER_ERROR_CODES: readonly PdfRegisterErrorCode[];
115
115
  /**
@@ -106,10 +106,10 @@ declare const ON_BEHALF_ERROR_CODES: readonly OnBehalfErrorCode[];
106
106
  * `pades_register.go`, `handlers_pdf.go`). 400: REQUEST_INVALID, CMS_INVALID, SIGNATURE_INVALID, TIMESTAMP_INVALID;
107
107
  * 403: TOKEN_ORG_MISMATCH, REPRESENTATION_REVOKED; 404: DOC_NOT_FOUND; 409: SIGNER_MISMATCH, SIGNER_CERT_INVALID,
108
108
  * TOKEN_CERT_INVALID, SESSION_MISMATCH, SESSION_NOT_COMPLETE, SESSION_FAILED, CLAIMED_ROLE_MISMATCH, DOC_ID_CONFLICT,
109
- * REGISTRY_CONFLICT, PRIOR_MISMATCH; 413: REQUEST_TOO_LARGE; 429: RATE_LIMITED; 503: STATE_UNAVAILABLE (сүүлийн хоёр
109
+ * REGISTRY_CONFLICT, PRIOR_MISMATCH, IMAGE_MISMATCH (images[] ≠ CA-ийн одоогийн зураг); 413: REQUEST_TOO_LARGE; 429: RATE_LIMITED; 503: STATE_UNAVAILABLE (сүүлийн хоёр
110
110
  * {@link RETRYABLE_ERROR_CODES}). Session олдоогүй бол 404 code-гүй.
111
111
  */
112
- type PdfRegisterErrorCode = "REQUEST_INVALID" | "REQUEST_TOO_LARGE" | "CMS_INVALID" | "SIGNATURE_INVALID" | "TIMESTAMP_INVALID" | "SIGNER_MISMATCH" | "SIGNER_CERT_INVALID" | "TOKEN_CERT_INVALID" | "TOKEN_ORG_MISMATCH" | "SESSION_MISMATCH" | "SESSION_NOT_COMPLETE" | "SESSION_FAILED" | "CLAIMED_ROLE_MISMATCH" | "REPRESENTATION_REVOKED" | "DOC_ID_CONFLICT" | "REGISTRY_CONFLICT" | "DOC_NOT_FOUND" | "PRIOR_MISMATCH" | "RATE_LIMITED" | "STATE_UNAVAILABLE";
112
+ type PdfRegisterErrorCode = "REQUEST_INVALID" | "REQUEST_TOO_LARGE" | "CMS_INVALID" | "SIGNATURE_INVALID" | "TIMESTAMP_INVALID" | "SIGNER_MISMATCH" | "SIGNER_CERT_INVALID" | "TOKEN_CERT_INVALID" | "TOKEN_ORG_MISMATCH" | "SESSION_MISMATCH" | "SESSION_NOT_COMPLETE" | "SESSION_FAILED" | "CLAIMED_ROLE_MISMATCH" | "REPRESENTATION_REVOKED" | "DOC_ID_CONFLICT" | "REGISTRY_CONFLICT" | "DOC_NOT_FOUND" | "PRIOR_MISMATCH" | "IMAGE_MISMATCH" | "RATE_LIMITED" | "STATE_UNAVAILABLE";
113
113
  /** {@link PdfRegisterErrorCode}-ийн бүх утга (runtime шалгалтад). */
114
114
  declare const PDF_REGISTER_ERROR_CODES: readonly PdfRegisterErrorCode[];
115
115
  /**
package/dist/index.cjs CHANGED
@@ -214,6 +214,7 @@ var PDF_REGISTER_ERROR_CODES = [
214
214
  "REGISTRY_CONFLICT",
215
215
  "DOC_NOT_FOUND",
216
216
  "PRIOR_MISMATCH",
217
+ "IMAGE_MISMATCH",
217
218
  "RATE_LIMITED",
218
219
  "STATE_UNAVAILABLE"
219
220
  ];
@@ -411,7 +412,8 @@ var PDF_SIGNATURE_REGISTER_FIELDS = [
411
412
  "priorCmsSha256",
412
413
  "priorRevisionSha256",
413
414
  "onBehalfOf",
414
- "signerEtsi"
415
+ "signerEtsi",
416
+ "images"
415
417
  ];
416
418
  var SHARE_FORM_FIELDS = ["file", "filename", "to", "subject", "message", "lang"];
417
419
  function routePath(route, ...args) {
@@ -619,6 +621,7 @@ function registrationFromCompleted(done, extra) {
619
621
  }
620
622
  if (extra.onBehalfOf) out.onBehalfOf = extra.onBehalfOf;
621
623
  if (extra.signerEtsi) out.signerEtsi = extra.signerEtsi;
624
+ if (done.images?.length) out.images = done.images.map((x) => ({ kind: x.kind, sha256: x.sha256 }));
622
625
  return out;
623
626
  }
624
627
  function priorSplits(n) {
@@ -680,6 +683,12 @@ function buildRegisterBody(input) {
680
683
  if (priorRev.length) body.priorRevisionSha256 = priorRev;
681
684
  if (input.onBehalfOf?.trim()) body.onBehalfOf = input.onBehalfOf.trim();
682
685
  if (input.signerEtsi?.trim()) body.signerEtsi = input.signerEtsi.trim();
686
+ if (input.images?.length) {
687
+ body.images = input.images.map((x, i) => {
688
+ if (x?.kind !== "signature" && x?.kind !== "stamp") fail2(`images[${i}].kind: signature | stamp`);
689
+ return { kind: x.kind, sha256: hex(`images[${i}].sha256`, x.sha256) };
690
+ });
691
+ }
683
692
  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}`);
684
693
  return body;
685
694
  }
package/dist/index.d.cts CHANGED
@@ -1,7 +1,7 @@
1
- import { R as RpCredentials, C as CertificateLevel, I as Interaction, S as SignatureAlgorithm, H as HashAlgorithm, N as NotificationSession, D as DeviceLinkSession, a as SessionResult, P as PersonBlock, b as RepresentationsResponse, A as AcspContext, F as FlowType } from './browser-CYpvoCRr.cjs';
2
- export { c as DEFAULT_SIGN_SESSION_TTL_MS, E as EndResult, d as NavigatorLike, O as OrgResult, e as Representation, f as SessionState, g as SignContext, h as SignatureAlgorithmParameters, i as SignatureProtocol, T as TokenCertSessionBlock, j as TokenCertStatus, k as isMobileUserAgent, p as parseExpiresAt, s as sessionExpiry, l as startExpiry } from './browser-CYpvoCRr.cjs';
3
- import { O as OnBehalfErrorCode, R as RetryableErrorCode, A as ApiError, H as HttpErrorInit } from './errors-CxAr-WIA.cjs';
4
- export { a as AppTransactionTooLargeError, b as AuthenticationError, C as CertChoiceInvalidError, D as DeviceLinkError, E as EidError, F as ForbiddenError, N as NetworkError, c as NoSigningCertificateError, d as ON_BEHALF_ERROR_CODES, P as PDF_REGISTER_ERROR_CODES, e as PdfRegisterErrorCode, f as RETRYABLE_ERROR_CODES, g as RequestInvalidError, h as ResponseTooLargeError, S as SessionFailedError, V as ValidationError, p as parseRetryAfter } from './errors-CxAr-WIA.cjs';
1
+ import { R as RpCredentials, C as CertificateLevel, I as Interaction, S as SignatureAlgorithm, H as HashAlgorithm, N as NotificationSession, D as DeviceLinkSession, a as SessionResult, P as PersonBlock, b as RepresentationsResponse, A as AcspContext, F as FlowType } from './browser-B3cWNpRM.cjs';
2
+ export { c as DEFAULT_SIGN_SESSION_TTL_MS, E as EndResult, d as NavigatorLike, O as OrgResult, e as Representation, f as SessionState, g as SignContext, h as SignatureAlgorithmParameters, i as SignatureProtocol, T as TokenCertSessionBlock, j as TokenCertStatus, k as isMobileUserAgent, p as parseExpiresAt, s as sessionExpiry, l as startExpiry } from './browser-B3cWNpRM.cjs';
3
+ import { O as OnBehalfErrorCode, R as RetryableErrorCode, A as ApiError, H as HttpErrorInit } from './errors-3JEfE-FW.cjs';
4
+ export { a as AppTransactionTooLargeError, b as AuthenticationError, C as CertChoiceInvalidError, D as DeviceLinkError, E as EidError, F as ForbiddenError, N as NetworkError, c as NoSigningCertificateError, d as ON_BEHALF_ERROR_CODES, P as PDF_REGISTER_ERROR_CODES, e as PdfRegisterErrorCode, f as RETRYABLE_ERROR_CODES, g as RequestInvalidError, h as ResponseTooLargeError, S as SessionFailedError, V as ValidationError, p as parseRetryAfter } from './errors-3JEfE-FW.cjs';
5
5
  import { X509Certificate, KeyObject } from 'node:crypto';
6
6
 
7
7
  interface HttpConfig {
@@ -219,6 +219,18 @@ interface RegisterSignatureInput {
219
219
  onBehalfOf?: string;
220
220
  /** Заавал биш (`PNOMN-…`): ирвэл CMS-ийн зурагчийн SERIALNUMBER-тэй тэнцүү (эс бөгөөс 409 `SIGNER_MISMATCH`). */
221
221
  signerEtsi?: string;
222
+ /**
223
+ * `complete().images` (0.31.0+) — харагдах дүрслэлд шигтгэсэн зураг бүрийн `{kind, sha256}` (pades APPEARANCE_SPEC.md
224
+ * §6.6): CA зурагчийн/байгууллагын хадгалсан PNG-тэй тулгана. Зураггүй бол илгээхгүй.
225
+ */
226
+ images?: PdfSignatureImage[];
227
+ }
228
+ /** {@link RegisterSignatureInput.images}-ийн нэг мөр (Go `eid.PDFSignatureImage`). */
229
+ interface PdfSignatureImage {
230
+ /** `signature` — иргэний гарын үсгийн зураг; `stamp` — байгууллагын тамганы зураг. */
231
+ kind: "signature" | "stamp";
232
+ /** CA-ийн хадгалсан PNG-ийн SHA-256 (64 жижиг hex). */
233
+ sha256: string;
222
234
  }
223
235
  /** Өмнөх нэг гарын үсгийн хоёр түлхүүр ({@link RegisterSignatureInput.priorSignatures}). */
224
236
  interface PriorSignature {
@@ -242,6 +254,8 @@ interface CompletedForRegistration {
242
254
  priorRevisionSha256?: string[];
243
255
  /** `complete().claimedRole` (0.27.0+) — хоосон биш бол `onBehalfOf` заавал. */
244
256
  claimedRole?: string;
257
+ /** `complete().images` (0.31.0+) — байвал `images` болж илгээгдэнэ. */
258
+ images?: PdfSignatureImage[];
245
259
  }
246
260
  /**
247
261
  * `pades.complete()`-ийн үр дүнгээс `registerSignature`-ийн биеийг бөглөнө (`hasPage`-ийг илгээхгүй — CA `revIndex`-ээс
@@ -1277,10 +1291,11 @@ declare class EidClient {
1277
1291
 
1278
1292
  /**
1279
1293
  * `POST /pdf/signatures`-ийн биеийн талбарууд — CA `server/internal/dto/pdf.go` `PDFSignatureRegisterRequest`-ийн JSON
1280
- * tag (CA main d948fdd4, !355). CA `DisallowUnknownFields` тул SDK зөвхөн эдгээрийг илгээнэ. Live discovery-ийн
1294
+ * tag (CA main d948fdd4, !355; `images` — APPEARANCE_SPEC §6.6, Go SDK #44, CA талд нэмэгдэж буй). CA `DisallowUnknownFields`
1295
+ * тул SDK зөвхөн эдгээрийг илгээнэ. Live discovery-ийн
1281
1296
  * `endpoints.pdf.signatures` тайлбартай гэрээний тест тулгана.
1282
1297
  */
1283
- declare const PDF_SIGNATURE_REGISTER_FIELDS: readonly ["docID", "revIndex", "medium", "sessionID", "cms", "fileName", "inSha256", "pageSha256", "sigRevSha256", "outSha256", "priorCmsSha256", "priorRevisionSha256", "onBehalfOf", "signerEtsi"];
1298
+ declare const PDF_SIGNATURE_REGISTER_FIELDS: readonly ["docID", "revIndex", "medium", "sessionID", "cms", "fileName", "inSha256", "pageSha256", "sigRevSha256", "outSha256", "priorCmsSha256", "priorRevisionSha256", "onBehalfOf", "signerEtsi", "images"];
1284
1299
  /**
1285
1300
  * `POST /share`-ийн multipart талбарууд — CA `server/internal/httpapi/handlers_share.go` `parseShareRequest` (CA main
1286
1301
  * 0329ef95, !371). CA үл мэдэгдэх талбарыг 400 REQUEST_INVALID-аар татгалздаг. Live discovery-ийн `endpoints.share`
@@ -1665,4 +1680,4 @@ declare function withReturnHint(callbackUrl: string, userAgent: string): string;
1665
1680
  */
1666
1681
  declare function createEidLogin(opts: EidLoginOptions): EidLogin;
1667
1682
 
1668
- export { APP_ATTESTATION_INVALID, AcspContext, type AcspV2Params, type ActivityCounts, type ActivityItem, type ActivityQuery, ApiError, AuthApi, type AuthDefaults, type AuthOptions, type BuildDeviceLinkInput, CITIZEN_INTERMEDIATES_PEM, CITIZEN_ISSUING_CA_SKI, CSR_KEY_REUSED, type CertChoiceOptions, type CertCounts, type CertSubject, CertificateLevel, type ClientConfig, type CompletedForRegistration, DEFAULT_BASE_URL, DEFAULT_MAX_WAIT_MS, DEFAULT_PDF_TIMEOUT_MS, DEFAULT_SHARE_TIMEOUT_MS, DeviceLinkSession, type DeviceLinkSessionType, type DeviceLinkType, EidClient, type EidLogin, type EidLoginContext, type EidLoginEvent, type EidLoginEventKind, type EidLoginIdentity, type EidLoginMode, type EidLoginOptions, type EidLoginRateLimitFn, type EidLoginRateLimits, type EidLoginRateRule, type EidLoginRequest, type EidLoginResponse, type EidLoginStore, type EidLoginSuccess, type EidLoginTx, FlowType, HashAlgorithm, Http, type HttpConfig, HttpErrorInit, Interaction, KYC_INCOMPLETE, LoginStoreFullError, MAX_APP_TRANSACTION_BYTES, MEMORY_LOGIN_STORE_MAX, NATIONAL_ROOT_CA_PEM, NO_ACTIVE_DEVICE, NotificationSession, type OcspCheckerOptions, OnBehalfErrorCode, OrganizationApi, PDF_SIGNATURE_REGISTER_FIELDS, type PdfDigestInput, type PdfDigestSession, type PdfDigestSigner, type PersonActivity, PersonApi, PersonBlock, type PersonCertificate, type PersonCertificates, type PersonChild, type PersonChildren, type PersonDevice, type PersonDevices, type PersonSummary, type PriorSignature, type QrDeviceLinkTickerOptions, type RegisterSignatureInput, type RegisterSignatureResult, RepresentationsResponse, ResponseValidator, RetryableErrorCode, type RevocationChecker, type RevocationOutcome, type RevocationStatus, RpCredentials, SHARE_ERROR_CODES, SHARE_FORM_FIELDS, SessionApi, SessionResult, type SessionTtl, ShareError, type ShareErrorCode, type ShareInfo, type ShareInput, type ShareNotSignedReason, type ShareResult, SignApi, type SignDefaults, type SignOptions, SignatureAlgorithm, type Signer, type SignerRef, TOKEN_CONFLICT_CODES, TOKEN_ERROR_CODES, TOKEN_ISSUANCE_PENDING, TokenApi, type TokenAuthChallenge, type TokenAuthResult, type TokenCertInfo, type TokenCertInput, type TokenCertItem, type TokenCertPreview, type TokenCertResult, type TokenCertStart, type TokenConflictCode, type TokenErrorCode, type TokenIdentity, type TokenLimit, type TokenOrganization, type TrustConfig, type ValidateAuthOptions, type ValidateSignOptions, type VerifiedIdentity, type VerifiedSignature, WAIT_GRACE_MS, acspV2Digest, buildAcspV2Payload, buildDeviceLink, buildRegisterBody, certificateLevelOf, createEidLogin, defaultRateLimit, deviceLinkInput, forwardedClientIp, interactionsToBase64, memoryLoginStore, ocspRevocationChecker, parseSessionResult, parseSubject, personMatchesCertificate, qrDeviceLinkTicker, randomChallenge, registrationFromCompleted, resolveBaseUrl, sha256Base64, tokenAuthDigest, tokenLimitOf, userChallengeOf, verifyPayloadSignature, verifyPrehashedSignature, verifyTokenCertificates, withReturnHint };
1683
+ export { APP_ATTESTATION_INVALID, AcspContext, type AcspV2Params, type ActivityCounts, type ActivityItem, type ActivityQuery, ApiError, AuthApi, type AuthDefaults, type AuthOptions, type BuildDeviceLinkInput, CITIZEN_INTERMEDIATES_PEM, CITIZEN_ISSUING_CA_SKI, CSR_KEY_REUSED, type CertChoiceOptions, type CertCounts, type CertSubject, CertificateLevel, type ClientConfig, type CompletedForRegistration, DEFAULT_BASE_URL, DEFAULT_MAX_WAIT_MS, DEFAULT_PDF_TIMEOUT_MS, DEFAULT_SHARE_TIMEOUT_MS, DeviceLinkSession, type DeviceLinkSessionType, type DeviceLinkType, EidClient, type EidLogin, type EidLoginContext, type EidLoginEvent, type EidLoginEventKind, type EidLoginIdentity, type EidLoginMode, type EidLoginOptions, type EidLoginRateLimitFn, type EidLoginRateLimits, type EidLoginRateRule, type EidLoginRequest, type EidLoginResponse, type EidLoginStore, type EidLoginSuccess, type EidLoginTx, FlowType, HashAlgorithm, Http, type HttpConfig, HttpErrorInit, Interaction, KYC_INCOMPLETE, LoginStoreFullError, MAX_APP_TRANSACTION_BYTES, MEMORY_LOGIN_STORE_MAX, NATIONAL_ROOT_CA_PEM, NO_ACTIVE_DEVICE, NotificationSession, type OcspCheckerOptions, OnBehalfErrorCode, OrganizationApi, PDF_SIGNATURE_REGISTER_FIELDS, type PdfDigestInput, type PdfDigestSession, type PdfDigestSigner, type PdfSignatureImage, type PersonActivity, PersonApi, PersonBlock, type PersonCertificate, type PersonCertificates, type PersonChild, type PersonChildren, type PersonDevice, type PersonDevices, type PersonSummary, type PriorSignature, type QrDeviceLinkTickerOptions, type RegisterSignatureInput, type RegisterSignatureResult, RepresentationsResponse, ResponseValidator, RetryableErrorCode, type RevocationChecker, type RevocationOutcome, type RevocationStatus, RpCredentials, SHARE_ERROR_CODES, SHARE_FORM_FIELDS, SessionApi, SessionResult, type SessionTtl, ShareError, type ShareErrorCode, type ShareInfo, type ShareInput, type ShareNotSignedReason, type ShareResult, SignApi, type SignDefaults, type SignOptions, SignatureAlgorithm, type Signer, type SignerRef, TOKEN_CONFLICT_CODES, TOKEN_ERROR_CODES, TOKEN_ISSUANCE_PENDING, TokenApi, type TokenAuthChallenge, type TokenAuthResult, type TokenCertInfo, type TokenCertInput, type TokenCertItem, type TokenCertPreview, type TokenCertResult, type TokenCertStart, type TokenConflictCode, type TokenErrorCode, type TokenIdentity, type TokenLimit, type TokenOrganization, type TrustConfig, type ValidateAuthOptions, type ValidateSignOptions, type VerifiedIdentity, type VerifiedSignature, WAIT_GRACE_MS, acspV2Digest, buildAcspV2Payload, buildDeviceLink, buildRegisterBody, certificateLevelOf, createEidLogin, defaultRateLimit, deviceLinkInput, forwardedClientIp, interactionsToBase64, memoryLoginStore, ocspRevocationChecker, parseSessionResult, parseSubject, personMatchesCertificate, qrDeviceLinkTicker, randomChallenge, registrationFromCompleted, resolveBaseUrl, sha256Base64, tokenAuthDigest, tokenLimitOf, userChallengeOf, verifyPayloadSignature, verifyPrehashedSignature, verifyTokenCertificates, withReturnHint };
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
- import { R as RpCredentials, C as CertificateLevel, I as Interaction, S as SignatureAlgorithm, H as HashAlgorithm, N as NotificationSession, D as DeviceLinkSession, a as SessionResult, P as PersonBlock, b as RepresentationsResponse, A as AcspContext, F as FlowType } from './browser-DturMWIL.js';
2
- export { c as DEFAULT_SIGN_SESSION_TTL_MS, E as EndResult, d as NavigatorLike, O as OrgResult, e as Representation, f as SessionState, g as SignContext, h as SignatureAlgorithmParameters, i as SignatureProtocol, T as TokenCertSessionBlock, j as TokenCertStatus, k as isMobileUserAgent, p as parseExpiresAt, s as sessionExpiry, l as startExpiry } from './browser-DturMWIL.js';
3
- import { O as OnBehalfErrorCode, R as RetryableErrorCode, A as ApiError, H as HttpErrorInit } from './errors-CxAr-WIA.js';
4
- export { a as AppTransactionTooLargeError, b as AuthenticationError, C as CertChoiceInvalidError, D as DeviceLinkError, E as EidError, F as ForbiddenError, N as NetworkError, c as NoSigningCertificateError, d as ON_BEHALF_ERROR_CODES, P as PDF_REGISTER_ERROR_CODES, e as PdfRegisterErrorCode, f as RETRYABLE_ERROR_CODES, g as RequestInvalidError, h as ResponseTooLargeError, S as SessionFailedError, V as ValidationError, p as parseRetryAfter } from './errors-CxAr-WIA.js';
1
+ import { R as RpCredentials, C as CertificateLevel, I as Interaction, S as SignatureAlgorithm, H as HashAlgorithm, N as NotificationSession, D as DeviceLinkSession, a as SessionResult, P as PersonBlock, b as RepresentationsResponse, A as AcspContext, F as FlowType } from './browser-X_HjiWxc.js';
2
+ export { c as DEFAULT_SIGN_SESSION_TTL_MS, E as EndResult, d as NavigatorLike, O as OrgResult, e as Representation, f as SessionState, g as SignContext, h as SignatureAlgorithmParameters, i as SignatureProtocol, T as TokenCertSessionBlock, j as TokenCertStatus, k as isMobileUserAgent, p as parseExpiresAt, s as sessionExpiry, l as startExpiry } from './browser-X_HjiWxc.js';
3
+ import { O as OnBehalfErrorCode, R as RetryableErrorCode, A as ApiError, H as HttpErrorInit } from './errors-3JEfE-FW.js';
4
+ export { a as AppTransactionTooLargeError, b as AuthenticationError, C as CertChoiceInvalidError, D as DeviceLinkError, E as EidError, F as ForbiddenError, N as NetworkError, c as NoSigningCertificateError, d as ON_BEHALF_ERROR_CODES, P as PDF_REGISTER_ERROR_CODES, e as PdfRegisterErrorCode, f as RETRYABLE_ERROR_CODES, g as RequestInvalidError, h as ResponseTooLargeError, S as SessionFailedError, V as ValidationError, p as parseRetryAfter } from './errors-3JEfE-FW.js';
5
5
  import { X509Certificate, KeyObject } from 'node:crypto';
6
6
 
7
7
  interface HttpConfig {
@@ -219,6 +219,18 @@ interface RegisterSignatureInput {
219
219
  onBehalfOf?: string;
220
220
  /** Заавал биш (`PNOMN-…`): ирвэл CMS-ийн зурагчийн SERIALNUMBER-тэй тэнцүү (эс бөгөөс 409 `SIGNER_MISMATCH`). */
221
221
  signerEtsi?: string;
222
+ /**
223
+ * `complete().images` (0.31.0+) — харагдах дүрслэлд шигтгэсэн зураг бүрийн `{kind, sha256}` (pades APPEARANCE_SPEC.md
224
+ * §6.6): CA зурагчийн/байгууллагын хадгалсан PNG-тэй тулгана. Зураггүй бол илгээхгүй.
225
+ */
226
+ images?: PdfSignatureImage[];
227
+ }
228
+ /** {@link RegisterSignatureInput.images}-ийн нэг мөр (Go `eid.PDFSignatureImage`). */
229
+ interface PdfSignatureImage {
230
+ /** `signature` — иргэний гарын үсгийн зураг; `stamp` — байгууллагын тамганы зураг. */
231
+ kind: "signature" | "stamp";
232
+ /** CA-ийн хадгалсан PNG-ийн SHA-256 (64 жижиг hex). */
233
+ sha256: string;
222
234
  }
223
235
  /** Өмнөх нэг гарын үсгийн хоёр түлхүүр ({@link RegisterSignatureInput.priorSignatures}). */
224
236
  interface PriorSignature {
@@ -242,6 +254,8 @@ interface CompletedForRegistration {
242
254
  priorRevisionSha256?: string[];
243
255
  /** `complete().claimedRole` (0.27.0+) — хоосон биш бол `onBehalfOf` заавал. */
244
256
  claimedRole?: string;
257
+ /** `complete().images` (0.31.0+) — байвал `images` болж илгээгдэнэ. */
258
+ images?: PdfSignatureImage[];
245
259
  }
246
260
  /**
247
261
  * `pades.complete()`-ийн үр дүнгээс `registerSignature`-ийн биеийг бөглөнө (`hasPage`-ийг илгээхгүй — CA `revIndex`-ээс
@@ -1277,10 +1291,11 @@ declare class EidClient {
1277
1291
 
1278
1292
  /**
1279
1293
  * `POST /pdf/signatures`-ийн биеийн талбарууд — CA `server/internal/dto/pdf.go` `PDFSignatureRegisterRequest`-ийн JSON
1280
- * tag (CA main d948fdd4, !355). CA `DisallowUnknownFields` тул SDK зөвхөн эдгээрийг илгээнэ. Live discovery-ийн
1294
+ * tag (CA main d948fdd4, !355; `images` — APPEARANCE_SPEC §6.6, Go SDK #44, CA талд нэмэгдэж буй). CA `DisallowUnknownFields`
1295
+ * тул SDK зөвхөн эдгээрийг илгээнэ. Live discovery-ийн
1281
1296
  * `endpoints.pdf.signatures` тайлбартай гэрээний тест тулгана.
1282
1297
  */
1283
- declare const PDF_SIGNATURE_REGISTER_FIELDS: readonly ["docID", "revIndex", "medium", "sessionID", "cms", "fileName", "inSha256", "pageSha256", "sigRevSha256", "outSha256", "priorCmsSha256", "priorRevisionSha256", "onBehalfOf", "signerEtsi"];
1298
+ declare const PDF_SIGNATURE_REGISTER_FIELDS: readonly ["docID", "revIndex", "medium", "sessionID", "cms", "fileName", "inSha256", "pageSha256", "sigRevSha256", "outSha256", "priorCmsSha256", "priorRevisionSha256", "onBehalfOf", "signerEtsi", "images"];
1284
1299
  /**
1285
1300
  * `POST /share`-ийн multipart талбарууд — CA `server/internal/httpapi/handlers_share.go` `parseShareRequest` (CA main
1286
1301
  * 0329ef95, !371). CA үл мэдэгдэх талбарыг 400 REQUEST_INVALID-аар татгалздаг. Live discovery-ийн `endpoints.share`
@@ -1665,4 +1680,4 @@ declare function withReturnHint(callbackUrl: string, userAgent: string): string;
1665
1680
  */
1666
1681
  declare function createEidLogin(opts: EidLoginOptions): EidLogin;
1667
1682
 
1668
- export { APP_ATTESTATION_INVALID, AcspContext, type AcspV2Params, type ActivityCounts, type ActivityItem, type ActivityQuery, ApiError, AuthApi, type AuthDefaults, type AuthOptions, type BuildDeviceLinkInput, CITIZEN_INTERMEDIATES_PEM, CITIZEN_ISSUING_CA_SKI, CSR_KEY_REUSED, type CertChoiceOptions, type CertCounts, type CertSubject, CertificateLevel, type ClientConfig, type CompletedForRegistration, DEFAULT_BASE_URL, DEFAULT_MAX_WAIT_MS, DEFAULT_PDF_TIMEOUT_MS, DEFAULT_SHARE_TIMEOUT_MS, DeviceLinkSession, type DeviceLinkSessionType, type DeviceLinkType, EidClient, type EidLogin, type EidLoginContext, type EidLoginEvent, type EidLoginEventKind, type EidLoginIdentity, type EidLoginMode, type EidLoginOptions, type EidLoginRateLimitFn, type EidLoginRateLimits, type EidLoginRateRule, type EidLoginRequest, type EidLoginResponse, type EidLoginStore, type EidLoginSuccess, type EidLoginTx, FlowType, HashAlgorithm, Http, type HttpConfig, HttpErrorInit, Interaction, KYC_INCOMPLETE, LoginStoreFullError, MAX_APP_TRANSACTION_BYTES, MEMORY_LOGIN_STORE_MAX, NATIONAL_ROOT_CA_PEM, NO_ACTIVE_DEVICE, NotificationSession, type OcspCheckerOptions, OnBehalfErrorCode, OrganizationApi, PDF_SIGNATURE_REGISTER_FIELDS, type PdfDigestInput, type PdfDigestSession, type PdfDigestSigner, type PersonActivity, PersonApi, PersonBlock, type PersonCertificate, type PersonCertificates, type PersonChild, type PersonChildren, type PersonDevice, type PersonDevices, type PersonSummary, type PriorSignature, type QrDeviceLinkTickerOptions, type RegisterSignatureInput, type RegisterSignatureResult, RepresentationsResponse, ResponseValidator, RetryableErrorCode, type RevocationChecker, type RevocationOutcome, type RevocationStatus, RpCredentials, SHARE_ERROR_CODES, SHARE_FORM_FIELDS, SessionApi, SessionResult, type SessionTtl, ShareError, type ShareErrorCode, type ShareInfo, type ShareInput, type ShareNotSignedReason, type ShareResult, SignApi, type SignDefaults, type SignOptions, SignatureAlgorithm, type Signer, type SignerRef, TOKEN_CONFLICT_CODES, TOKEN_ERROR_CODES, TOKEN_ISSUANCE_PENDING, TokenApi, type TokenAuthChallenge, type TokenAuthResult, type TokenCertInfo, type TokenCertInput, type TokenCertItem, type TokenCertPreview, type TokenCertResult, type TokenCertStart, type TokenConflictCode, type TokenErrorCode, type TokenIdentity, type TokenLimit, type TokenOrganization, type TrustConfig, type ValidateAuthOptions, type ValidateSignOptions, type VerifiedIdentity, type VerifiedSignature, WAIT_GRACE_MS, acspV2Digest, buildAcspV2Payload, buildDeviceLink, buildRegisterBody, certificateLevelOf, createEidLogin, defaultRateLimit, deviceLinkInput, forwardedClientIp, interactionsToBase64, memoryLoginStore, ocspRevocationChecker, parseSessionResult, parseSubject, personMatchesCertificate, qrDeviceLinkTicker, randomChallenge, registrationFromCompleted, resolveBaseUrl, sha256Base64, tokenAuthDigest, tokenLimitOf, userChallengeOf, verifyPayloadSignature, verifyPrehashedSignature, verifyTokenCertificates, withReturnHint };
1683
+ export { APP_ATTESTATION_INVALID, AcspContext, type AcspV2Params, type ActivityCounts, type ActivityItem, type ActivityQuery, ApiError, AuthApi, type AuthDefaults, type AuthOptions, type BuildDeviceLinkInput, CITIZEN_INTERMEDIATES_PEM, CITIZEN_ISSUING_CA_SKI, CSR_KEY_REUSED, type CertChoiceOptions, type CertCounts, type CertSubject, CertificateLevel, type ClientConfig, type CompletedForRegistration, DEFAULT_BASE_URL, DEFAULT_MAX_WAIT_MS, DEFAULT_PDF_TIMEOUT_MS, DEFAULT_SHARE_TIMEOUT_MS, DeviceLinkSession, type DeviceLinkSessionType, type DeviceLinkType, EidClient, type EidLogin, type EidLoginContext, type EidLoginEvent, type EidLoginEventKind, type EidLoginIdentity, type EidLoginMode, type EidLoginOptions, type EidLoginRateLimitFn, type EidLoginRateLimits, type EidLoginRateRule, type EidLoginRequest, type EidLoginResponse, type EidLoginStore, type EidLoginSuccess, type EidLoginTx, FlowType, HashAlgorithm, Http, type HttpConfig, HttpErrorInit, Interaction, KYC_INCOMPLETE, LoginStoreFullError, MAX_APP_TRANSACTION_BYTES, MEMORY_LOGIN_STORE_MAX, NATIONAL_ROOT_CA_PEM, NO_ACTIVE_DEVICE, NotificationSession, type OcspCheckerOptions, OnBehalfErrorCode, OrganizationApi, PDF_SIGNATURE_REGISTER_FIELDS, type PdfDigestInput, type PdfDigestSession, type PdfDigestSigner, type PdfSignatureImage, type PersonActivity, PersonApi, PersonBlock, type PersonCertificate, type PersonCertificates, type PersonChild, type PersonChildren, type PersonDevice, type PersonDevices, type PersonSummary, type PriorSignature, type QrDeviceLinkTickerOptions, type RegisterSignatureInput, type RegisterSignatureResult, RepresentationsResponse, ResponseValidator, RetryableErrorCode, type RevocationChecker, type RevocationOutcome, type RevocationStatus, RpCredentials, SHARE_ERROR_CODES, SHARE_FORM_FIELDS, SessionApi, SessionResult, type SessionTtl, ShareError, type ShareErrorCode, type ShareInfo, type ShareInput, type ShareNotSignedReason, type ShareResult, SignApi, type SignDefaults, type SignOptions, SignatureAlgorithm, type Signer, type SignerRef, TOKEN_CONFLICT_CODES, TOKEN_ERROR_CODES, TOKEN_ISSUANCE_PENDING, TokenApi, type TokenAuthChallenge, type TokenAuthResult, type TokenCertInfo, type TokenCertInput, type TokenCertItem, type TokenCertPreview, type TokenCertResult, type TokenCertStart, type TokenConflictCode, type TokenErrorCode, type TokenIdentity, type TokenLimit, type TokenOrganization, type TrustConfig, type ValidateAuthOptions, type ValidateSignOptions, type VerifiedIdentity, type VerifiedSignature, WAIT_GRACE_MS, acspV2Digest, buildAcspV2Payload, buildDeviceLink, buildRegisterBody, certificateLevelOf, createEidLogin, defaultRateLimit, deviceLinkInput, forwardedClientIp, interactionsToBase64, memoryLoginStore, ocspRevocationChecker, parseSessionResult, parseSubject, personMatchesCertificate, qrDeviceLinkTicker, randomChallenge, registrationFromCompleted, resolveBaseUrl, sha256Base64, tokenAuthDigest, tokenLimitOf, userChallengeOf, verifyPayloadSignature, verifyPrehashedSignature, verifyTokenCertificates, withReturnHint };
package/dist/index.js CHANGED
@@ -30,7 +30,7 @@ import {
30
30
  ValidationError,
31
31
  maskPath,
32
32
  parseRetryAfter
33
- } from "./chunk-H7JOACAZ.js";
33
+ } from "./chunk-R73IR6OH.js";
34
34
 
35
35
  // src/http.ts
36
36
  var DEFAULT_TIMEOUT_MS = 15e3;
@@ -189,7 +189,8 @@ var PDF_SIGNATURE_REGISTER_FIELDS = [
189
189
  "priorCmsSha256",
190
190
  "priorRevisionSha256",
191
191
  "onBehalfOf",
192
- "signerEtsi"
192
+ "signerEtsi",
193
+ "images"
193
194
  ];
194
195
  var SHARE_FORM_FIELDS = ["file", "filename", "to", "subject", "message", "lang"];
195
196
  function routePath(route, ...args) {
@@ -397,6 +398,7 @@ function registrationFromCompleted(done, extra) {
397
398
  }
398
399
  if (extra.onBehalfOf) out.onBehalfOf = extra.onBehalfOf;
399
400
  if (extra.signerEtsi) out.signerEtsi = extra.signerEtsi;
401
+ if (done.images?.length) out.images = done.images.map((x) => ({ kind: x.kind, sha256: x.sha256 }));
400
402
  return out;
401
403
  }
402
404
  function priorSplits(n) {
@@ -458,6 +460,12 @@ function buildRegisterBody(input) {
458
460
  if (priorRev.length) body.priorRevisionSha256 = priorRev;
459
461
  if (input.onBehalfOf?.trim()) body.onBehalfOf = input.onBehalfOf.trim();
460
462
  if (input.signerEtsi?.trim()) body.signerEtsi = input.signerEtsi.trim();
463
+ if (input.images?.length) {
464
+ body.images = input.images.map((x, i) => {
465
+ if (x?.kind !== "signature" && x?.kind !== "stamp") fail2(`images[${i}].kind: signature | stamp`);
466
+ return { kind: x.kind, sha256: hex(`images[${i}].sha256`, x.sha256) };
467
+ });
468
+ }
461
469
  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}`);
462
470
  return body;
463
471
  }