@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/dist/pades.cjs CHANGED
@@ -21,6 +21,9 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  var pades_exports = {};
22
22
  __export(pades_exports, {
23
23
  CertificateRevokedError: () => CertificateRevokedError,
24
+ DEFAULT_ORG_STAMP_SIZE: () => DEFAULT_ORG_STAMP_SIZE,
25
+ DEFAULT_SIGNATURE_STAMP_SIZE: () => DEFAULT_SIGNATURE_STAMP_SIZE,
26
+ DEFAULT_STAMP_SIZE: () => DEFAULT_STAMP_SIZE,
24
27
  PADES_ERROR_CODES: () => PADES_ERROR_CODES,
25
28
  PROFILE_VERSION: () => PROFILE_VERSION,
26
29
  PadesError: () => PadesError,
@@ -1407,7 +1410,7 @@ function zlibInflate(src, limit = 64 << 20, initial) {
1407
1410
  function inflateRaw(src, limit = 64 << 20, info, initial) {
1408
1411
  return inflate(src, limit, info, initial, false);
1409
1412
  }
1410
- function zlibInflateStrict(src, limit) {
1413
+ function zlibInflateStrict(src, limit, exact = false) {
1411
1414
  if (src.length < 2) throw new InflateError("zlib: header \u0430\u043B\u0433\u0430");
1412
1415
  const cmf = src[0];
1413
1416
  const flg = src[1];
@@ -1425,6 +1428,7 @@ function zlibInflateStrict(src, limit) {
1425
1428
  if (at + 4 > src.length) throw new InflateError("zlib: adler32 \u0430\u043B\u0433\u0430");
1426
1429
  const want = (src[at] << 24 | src[at + 1] << 16 | src[at + 2] << 8 | src[at + 3]) >>> 0;
1427
1430
  if (adler32(out) !== want) throw new InflateError("zlib: adler32 \u0442\u0430\u0430\u0440\u0430\u0445\u0433\u04AF\u0439");
1431
+ 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");
1428
1432
  return out;
1429
1433
  }
1430
1434
  function adler32(b) {
@@ -1732,10 +1736,12 @@ var Lexer = class {
1732
1736
  const out = [];
1733
1737
  for (; ; ) {
1734
1738
  let c = this.readByte();
1735
- while (isSpace(c)) c = this.readByte();
1739
+ while (isSpace(c) && !this.eof) c = this.readByte();
1740
+ if (this.eof) throw new PdfError("unterminated hex string");
1736
1741
  if (c === 62) break;
1737
1742
  let c2 = this.readByte();
1738
- while (isSpace(c2)) c2 = this.readByte();
1743
+ while (isSpace(c2) && !this.eof) c2 = this.readByte();
1744
+ if (this.eof) throw new PdfError("unterminated hex string");
1739
1745
  const x = unhex(c) << 4 | unhex(c2);
1740
1746
  if (unhex(c) < 0 || unhex(c2) < 0 || x < 0) throw new PdfError("malformed hex string");
1741
1747
  out.push(x);
@@ -1747,6 +1753,7 @@ var Lexer = class {
1747
1753
  let depth = 1;
1748
1754
  for (; ; ) {
1749
1755
  let c = this.readByte();
1756
+ if (this.eof) throw new PdfError("unterminated literal string");
1750
1757
  if (c === 40) {
1751
1758
  depth++;
1752
1759
  out.push(c);
@@ -1891,6 +1898,7 @@ var Lexer = class {
1891
1898
  const tok = this.readToken();
1892
1899
  if (isKw(tok, "]")) break;
1893
1900
  if (tok === EOF_TOKEN) throw new PdfError("unterminated array");
1901
+ if (isKw(tok, "endobj")) throw new PdfError("unterminated array");
1894
1902
  this.unreadToken(tok);
1895
1903
  x.push(asObj(this.readObject()));
1896
1904
  }
@@ -2249,6 +2257,7 @@ var Reader = class {
2249
2257
  for (let i = 0; i < n; i++) {
2250
2258
  const id = b.readToken();
2251
2259
  const off = b.readToken();
2260
+ if (id === EOF_TOKEN || off === EOF_TOKEN) break;
2252
2261
  const idn = id instanceof PInt ? Number(BigInt.asUintN(32, id.v)) : 0;
2253
2262
  if (idn === ptr.id) {
2254
2263
  const o = off instanceof PInt ? Number(off.v) : 0;
@@ -3338,6 +3347,61 @@ function toUnicode(f) {
3338
3347
  // src/pades/page/appearance.ts
3339
3348
  var AppearanceError = class extends PdfError {
3340
3349
  };
3350
+ var MAX_IMAGE_SIDE = 1600;
3351
+ var MAX_IMAGE_ALPHA_BYTES = 300 << 10;
3352
+ var isIntIn = (v, lo, hi) => Number.isInteger(v) && v >= lo && v <= hi;
3353
+ function checkPdfImage(im) {
3354
+ const bad = (msg) => new AppearanceError(`\u0437\u0443\u0440\u0430\u0433: ${msg}`);
3355
+ 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");
3356
+ if (!Array.isArray(im.color) || im.color.length !== 3) throw bad("\u04E9\u043D\u0433\u04E9 0\u2026255");
3357
+ for (const c of im.color) if (!isIntIn(c, 0, 255)) throw bad("\u04E9\u043D\u0433\u04E9 0\u2026255");
3358
+ if (!(im.alpha instanceof Uint8Array) || im.alpha.length === 0 || im.alpha.length > MAX_IMAGE_ALPHA_BYTES) throw bad("alpha 1 B\u2026300 KiB");
3359
+ if (im.alpha.length >= 2 && im.alpha[1] & 32) throw bad("alpha preset dictionary (FDICT)");
3360
+ let n;
3361
+ try {
3362
+ n = zlibInflateStrict(im.alpha, im.w * im.h, true).length;
3363
+ } catch (e) {
3364
+ if (!(e instanceof InflateError)) throw e;
3365
+ n = -1;
3366
+ }
3367
+ 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)");
3368
+ }
3369
+ var idiv = (a, b) => Math.trunc(a / b);
3370
+ function apFit(iw, ih, bw, bh) {
3371
+ if (iw * bh >= ih * bw) return [bw, Math.max(1, idiv(bw * ih, iw))];
3372
+ return [Math.max(1, idiv(bh * iw, ih)), bh];
3373
+ }
3374
+ function apLayoutImages(p) {
3375
+ const l = { boxH: p.h, rowH: p.h, sig: [0, 0, 0, 0], stamp: [0, 0, 0, 0] };
3376
+ if (!p.sig && !p.stamp) return l;
3377
+ 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)");
3378
+ if (p.stamp) l.boxH = idiv(p.h * 4, 5);
3379
+ const band = idiv(l.boxH * 9, 22);
3380
+ l.rowH = l.boxH - band;
3381
+ const sh = idiv(band * 14, 15);
3382
+ const sy = l.rowH - idiv(band * 2, 15);
3383
+ let sw = idiv(p.w * 15, 22);
3384
+ let sx = idiv(p.w - sw, 2);
3385
+ if (p.stamp) {
3386
+ const d = idiv(l.boxH * 2, 3);
3387
+ const qx = Math.min(idiv(p.w * 41, 60) - idiv(d, 2), p.w - d);
3388
+ if (qx < 0 || d <= 0) throw small();
3389
+ const [dw, dh] = apFit(p.stamp.w, p.stamp.h, d, d);
3390
+ l.stamp = [qx + idiv(d - dw, 2), p.h - d + idiv(d - dh, 2), dw, dh];
3391
+ sx = idiv(p.w, 30);
3392
+ sw = qx + idiv(d, 2) - sx;
3393
+ }
3394
+ if (p.sig) {
3395
+ if (sw <= 0 || sh <= 0) throw small();
3396
+ const [dw, dh] = apFit(p.sig.w, p.sig.h, sw, sh);
3397
+ const dx = p.stamp ? sx : sx + idiv(sw - dw, 2);
3398
+ l.sig = [dx, sy + idiv(sh - dh, 2), dw, dh];
3399
+ }
3400
+ return l;
3401
+ }
3402
+ function apDrawImage(w, name, r) {
3403
+ w.op(`q ${num100(r[2])} 0 0 ${num100(r[3])} ${num100(r[0])} ${num100(r[1])} cm /${name} Do Q`);
3404
+ }
3341
3405
  var AP_PAD = 400;
3342
3406
  var AP_GAP = 400;
3343
3407
  var AP_MIN_MODULE = 100;
@@ -3383,6 +3447,10 @@ function appearanceContent(p) {
3383
3447
  if (label === void 0) throw new AppearanceError(`\u0445\u044D\u043B ${p.lang}`);
3384
3448
  if (!asciiURL(p.url)) throw new AppearanceError("URL ASCII \u0431\u0438\u0448");
3385
3449
  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");
3450
+ 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)");
3451
+ for (const im of [p.sig, p.stamp]) if (im) checkPdfImage(im);
3452
+ const il = apLayoutImages(p);
3453
+ const rowH = il.rowH;
3386
3454
  let m;
3387
3455
  try {
3388
3456
  m = qrEncode(latin1(p.url));
@@ -3390,14 +3458,14 @@ function appearanceContent(p) {
3390
3458
  throw new AppearanceError(String(e));
3391
3459
  }
3392
3460
  const n = m.length;
3393
- const mod = Math.trunc((p.h - 2 * AP_PAD) / n);
3461
+ const mod = Math.trunc((rowH - 2 * AP_PAD) / n);
3394
3462
  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)`);
3395
3463
  const tx = AP_PAD + mod * n + AP_GAP;
3396
3464
  const tw = p.w - tx - AP_PAD;
3397
3465
  const [reg, bld] = loadFonts();
3398
3466
  const w = new PageWriter(reg, bld);
3399
3467
  let lines;
3400
- for (let f = AP_MAX_SIZE; f >= AP_MIN_SIZE && lines === void 0 && tw > 0; f--) lines = apLayout(w, p, label, f, tw);
3468
+ for (let f = AP_MAX_SIZE; f >= AP_MIN_SIZE && lines === void 0 && tw > 0; f--) lines = apLayout(w, p, label, f, tw, rowH);
3401
3469
  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)");
3402
3470
  let total = 0;
3403
3471
  for (const l of lines) total += l.size * AP_LEADING;
@@ -3409,8 +3477,13 @@ function appearanceContent(p) {
3409
3477
  }
3410
3478
  w.op(`${C_OK} RG`);
3411
3479
  w.op("1 w");
3412
- w.op(`0.5 0.5 ${num100(p.w - 100)} ${num100(p.h - 100)} re S`);
3413
- w.op(`q ${num100(mod)} 0 0 ${num100(mod)} ${num100(AP_PAD)} ${num100(Math.trunc((p.h - mod * n) / 2))} cm`);
3480
+ w.op(`0.5 0.5 ${num100(p.w - 100)} ${num100(il.boxH - 100)} re S`);
3481
+ if (p.sig || p.stamp) {
3482
+ w.op("0.5 w");
3483
+ w.op(`0 ${num100(rowH)} m ${num100(p.w)} ${num100(rowH)} l S`);
3484
+ }
3485
+ if (p.sig) apDrawImage(w, "Sig", il.sig);
3486
+ w.op(`q ${num100(mod)} 0 0 ${num100(mod)} ${num100(AP_PAD)} ${num100(Math.trunc((rowH - mod * n) / 2))} cm`);
3414
3487
  w.op("0 0 0 rg");
3415
3488
  for (let r = 0; r < n; r++) {
3416
3489
  for (let c = 0; c < n; ) {
@@ -3425,17 +3498,18 @@ function appearanceContent(p) {
3425
3498
  }
3426
3499
  w.op("f");
3427
3500
  w.op("Q");
3428
- let cursor = p.h - AP_PAD - Math.trunc((p.h - 2 * AP_PAD - total) / 2);
3501
+ let cursor = rowH - AP_PAD - Math.trunc((rowH - 2 * AP_PAD - total) / 2);
3429
3502
  for (const l of lines) {
3430
3503
  cursor -= l.size * AP_LEADING;
3431
3504
  w.op(`${l.color} rg`);
3432
3505
  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`);
3433
3506
  }
3507
+ if (p.stamp) apDrawImage(w, "Stamp", il.stamp);
3434
3508
  if (cm !== "") w.op("Q");
3435
3509
  w.op("EMC");
3436
3510
  return w.ops;
3437
3511
  }
3438
- function apLayout(w, p, label, f, tw) {
3512
+ function apLayout(w, p, label, f, tw, rowH) {
3439
3513
  const b = f - AP_BODY_DELTA;
3440
3514
  const limit = tw * 10;
3441
3515
  const lines = [];
@@ -3449,20 +3523,40 @@ function apLayout(w, p, label, f, tw) {
3449
3523
  if (l.text === "" || w.width1000(l.font, l.size, l.text) > limit) return void 0;
3450
3524
  total += l.size * AP_LEADING;
3451
3525
  }
3452
- if (total > p.h - 2 * AP_PAD) return void 0;
3526
+ if (total > rowH - 2 * AP_PAD) return void 0;
3453
3527
  return lines;
3454
3528
  }
3529
+ function appearanceObjectCount(p) {
3530
+ return 11 + (p.sig ? 2 : 0) + (p.stamp ? 2 : 0);
3531
+ }
3455
3532
  function appearanceObjects(p, ids) {
3533
+ if (ids.length !== appearanceObjectCount(p)) throw new AppearanceError("\u043E\u0431\u044A\u0435\u043A\u0442\u044B\u043D \u0442\u043E\u043E");
3456
3534
  const [reg, bld] = loadFonts();
3457
3535
  const { bw, bh } = apRotation(p.rotate, p.w, p.h);
3458
3536
  const content = appearanceContent(p);
3537
+ let res = `/Font << /F1 ${ids[1]} 0 R /F2 ${ids[6]} 0 R >>`;
3538
+ const imgs = [];
3539
+ let next = 11;
3540
+ if (p.sig || p.stamp) {
3541
+ res += " /XObject <<";
3542
+ for (const [name, im] of [["Sig", p.sig], ["Stamp", p.stamp]]) {
3543
+ if (!im) continue;
3544
+ const base = ids[next];
3545
+ const mask = ids[next + 1];
3546
+ next += 2;
3547
+ res += ` /${name} ${base} 0 R`;
3548
+ imgs.push(
3549
+ streamObj(` /Type /XObject /Subtype /Image /Width 1 /Height 1 /ColorSpace /DeviceRGB /BitsPerComponent 8 /SMask ${mask} 0 R`, Uint8Array.from(im.color)),
3550
+ streamObj(` /Type /XObject /Subtype /Image /Width ${im.w} /Height ${im.h} /ColorSpace /DeviceGray /BitsPerComponent 8 /Filter /FlateDecode`, im.alpha)
3551
+ );
3552
+ }
3553
+ res += " >>";
3554
+ }
3459
3555
  return [
3460
- streamObj(
3461
- ` /Type /XObject /Subtype /Form /BBox [0 0 ${num100(bw)} ${num100(bh)}] /Resources << /Font << /F1 ${ids[1]} 0 R /F2 ${ids[6]} 0 R >> >>`,
3462
- latin1(content)
3463
- ),
3556
+ streamObj(` /Type /XObject /Subtype /Form /BBox [0 0 ${num100(bw)} ${num100(bh)}] /Resources << ${res} >>`, latin1(content)),
3464
3557
  ...fontBodies(ids.slice(1, 6), reg),
3465
- ...fontBodies(ids.slice(6, 11), bld)
3558
+ ...fontBodies(ids.slice(6, 11), bld),
3559
+ ...imgs
3466
3560
  ];
3467
3561
  }
3468
3562
  function visibleWidget(fieldName, rect, pageID, pageGen, sigID, formID) {
@@ -4643,7 +4737,7 @@ async function prepareSignature(base, signingTime, signerName, reason, vis) {
4643
4737
  const sigID = inc.reserve();
4644
4738
  const fieldID = inc.reserve();
4645
4739
  const catID = inc.reserve();
4646
- const apIDs = vis ? Array.from({ length: 11 }, () => inc.reserve()) : [];
4740
+ const apIDs = vis ? Array.from({ length: appearanceObjectCount(vis) }, () => inc.reserve()) : [];
4647
4741
  let sig = `<<
4648
4742
  /Type /Sig
4649
4743
  /Filter /Adobe.PPKLite
@@ -4685,7 +4779,10 @@ async function prepareSignature(base, signingTime, signerName, reason, vis) {
4685
4779
  placement = placeOnPage(page, box, rot, vis.x, vis.y, vis.w, vis.h, vis.exact === true);
4686
4780
  if (placement.x !== vis.x || placement.y !== vis.y) rect = visibleRect(box, rot, placement.x, placement.y, vis.w, vis.h);
4687
4781
  }
4688
- const bodies = appearanceObjects({ w: vis.w, h: vis.h, rotate: rot, name: vis.name, role: vis.role, lang: vis.lang, date: vis.date, url: vis.url }, apIDs);
4782
+ const bodies = appearanceObjects(
4783
+ { w: vis.w, h: vis.h, rotate: rot, name: vis.name, role: vis.role, lang: vis.lang, date: vis.date, url: vis.url, sig: vis.sig, stamp: vis.stamp },
4784
+ apIDs
4785
+ );
4689
4786
  inc.writeObject(fieldID, visibleWidget(fieldName, rect, page.ptr.id, page.ptr.gen, sigID, apIDs[0]));
4690
4787
  bodies.forEach((b2, i) => inc.writeObject(apIDs[i], b2));
4691
4788
  }
@@ -5030,6 +5127,7 @@ function encodeState(s) {
5030
5127
  };
5031
5128
  if (s.pageSha256) head.pageSha256 = s.pageSha256;
5032
5129
  if (s.claimedRole) head.claimedRole = s.claimedRole;
5130
+ if (s.images?.length) head.images = s.images.map((x) => ({ kind: x.kind, sha256: x.sha256 }));
5033
5131
  head.preparedSha256 = s.preparedSha256;
5034
5132
  const h = enc.encode(JSON.stringify(head));
5035
5133
  const len = new Uint8Array(4);
@@ -5055,6 +5153,7 @@ async function decodeState(b) {
5055
5153
  hasPage: j.hasPage === true,
5056
5154
  pageSha256: str("pageSha256"),
5057
5155
  claimedRole: str("claimedRole"),
5156
+ images: stateImages(j.images),
5058
5157
  preparedSha256: str("preparedSha256"),
5059
5158
  pdf
5060
5159
  };
@@ -5064,6 +5163,16 @@ async function decodeState(b) {
5064
5163
  }
5065
5164
  return s;
5066
5165
  }
5166
+ function stateImages(v) {
5167
+ if (v === void 0 || v === null) return void 0;
5168
+ if (!Array.isArray(v)) throw new Error("state images \u0431\u0443\u0440\u0443\u0443");
5169
+ const out = v.map((x) => {
5170
+ const o = x;
5171
+ if (!o || o.kind !== "signature" && o.kind !== "stamp" || typeof o.sha256 !== "string") throw new Error("state images \u0431\u0443\u0440\u0443\u0443");
5172
+ return { kind: o.kind, sha256: o.sha256 };
5173
+ });
5174
+ return out.length ? out : void 0;
5175
+ }
5067
5176
 
5068
5177
  // src/pades.ts
5069
5178
  var PROFILE_VERSION = "pades-client/1";
@@ -5098,6 +5207,21 @@ var PadesError = class extends EidError {
5098
5207
  return this.code === "TSA_UNAVAILABLE" || this.code === "LTV_UNAVAILABLE";
5099
5208
  }
5100
5209
  };
5210
+ var DEFAULT_STAMP_SIZE = { width: 220, height: 64 };
5211
+ var DEFAULT_SIGNATURE_STAMP_SIZE = { width: 220, height: 110 };
5212
+ var DEFAULT_ORG_STAMP_SIZE = { width: 240, height: 147.5 };
5213
+ function appearanceSize(a) {
5214
+ if (a.width !== 0 || a.height !== 0) return { width: a.width, height: a.height };
5215
+ if (a.stampImage) return DEFAULT_ORG_STAMP_SIZE;
5216
+ if (a.signatureImage) return DEFAULT_SIGNATURE_STAMP_SIZE;
5217
+ return DEFAULT_STAMP_SIZE;
5218
+ }
5219
+ var SHA256_HEX_RE = /^[0-9a-f]{64}$/;
5220
+ var BASE64_STD_RE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
5221
+ function imageData(im) {
5222
+ if (im === void 0) return void 0;
5223
+ return { w: im.width, h: im.height, color: im.color, alpha: fromB64(im.alpha) };
5224
+ }
5101
5225
  var MAX_OUTPUT_BYTES = 10 << 20;
5102
5226
  var MAX_FILE_NAME = 120;
5103
5227
  var PAGE_BRAND = "eID Mongolia";
@@ -5197,6 +5321,9 @@ async function prepare(pdf, opts) {
5197
5321
  }
5198
5322
  const first = pos === "first";
5199
5323
  checkAppearance(opts);
5324
+ if (opts.appearance?.stampImage && !opts.claimedRole) {
5325
+ throw new PadesError("REQUEST_INVALID", "appearance: stampImage \u0437\u04E9\u0432\u0445\u04E9\u043D claimedRole (onBehalfOf)-\u0442\u043E\u0439");
5326
+ }
5200
5327
  const now = opts.signingTime ?? /* @__PURE__ */ new Date();
5201
5328
  if (Number.isNaN(now.getTime())) throw new PadesError("REQUEST_INVALID", "signingTime \u0431\u0443\u0440\u0443\u0443 Date");
5202
5329
  const inHex = toHex(await sha256(doc));
@@ -5270,6 +5397,7 @@ async function prepare(pdf, opts) {
5270
5397
  hasPage,
5271
5398
  pageSha256: pageHex,
5272
5399
  claimedRole: role,
5400
+ images: prepImages(opts.appearance),
5273
5401
  preparedSha256: toHex(await sha256(prep.pdf)),
5274
5402
  pdf: prep.pdf
5275
5403
  });
@@ -5293,6 +5421,24 @@ function checkAppearance(o) {
5293
5421
  if (a.exact !== void 0 && typeof a.exact !== "boolean") throw bad("exact: boolean");
5294
5422
  const role = o.claimedRole ?? "";
5295
5423
  if (role !== "" && /[\p{Cc}\p{Cf}\p{Cs}]/u.test(role)) throw bad("claimedRole-\u0434 \u0443\u0434\u0438\u0440\u0434\u0430\u0445 \u0442\u044D\u043C\u0434\u044D\u0433\u0442");
5424
+ for (const [name, im] of [["signatureImage", a.signatureImage], ["stampImage", a.stampImage]]) {
5425
+ if (im === void 0) continue;
5426
+ if (im === null || typeof im !== "object") throw bad(`${name}: \u043E\u0431\u044A\u0435\u043A\u0442`);
5427
+ if (typeof im.sha256 !== "string" || !SHA256_HEX_RE.test(im.sha256)) throw bad(`${name}.sha256: \u0436\u0438\u0436\u0438\u0433 hex SHA-256`);
5428
+ if (typeof im.alpha !== "string" || !BASE64_STD_RE.test(im.alpha)) throw bad(`${name}.alpha: \u0441\u0442\u0430\u043D\u0434\u0430\u0440\u0442 base64`);
5429
+ try {
5430
+ checkPdfImage(imageData(im));
5431
+ } catch (e) {
5432
+ if (e instanceof AppearanceError) throw bad(`${name}: ${e.message.replace(/^зураг: /, "")}`);
5433
+ throw e;
5434
+ }
5435
+ }
5436
+ }
5437
+ function prepImages(a) {
5438
+ const out = [];
5439
+ if (a?.signatureImage) out.push({ kind: "signature", sha256: a.signatureImage.sha256 });
5440
+ if (a?.stampImage) out.push({ kind: "stamp", sha256: a.stampImage.sha256 });
5441
+ return out.length ? out : void 0;
5296
5442
  }
5297
5443
  function visibleSpec(doc, o, name, now, docId, revIndex) {
5298
5444
  const a = o.appearance;
@@ -5307,12 +5453,15 @@ function visibleSpec(doc, o, name, now, docId, revIndex) {
5307
5453
  if (page > n) throw new PadesError("REQUEST_INVALID", `appearance: page ${page} > \u0445\u0443\u0443\u0434\u0430\u0441\u043D\u044B \u0442\u043E\u043E ${n}`);
5308
5454
  const z = new Date(now.getTime() + 8 * 36e5);
5309
5455
  const p2 = (v) => String(v).padStart(2, "0");
5456
+ const size = appearanceSize(a);
5310
5457
  return {
5311
5458
  page,
5312
5459
  x: round100(a.x),
5313
5460
  y: round100(a.y),
5314
- w: round100(a.width),
5315
- h: round100(a.height),
5461
+ w: round100(size.width),
5462
+ h: round100(size.height),
5463
+ sig: imageData(a.signatureImage),
5464
+ stamp: imageData(a.stampImage),
5316
5465
  name: goTrim(name),
5317
5466
  role: o.claimedRole ?? "",
5318
5467
  lang: a.lang || o.lang || "mn",
@@ -5345,8 +5494,9 @@ async function suggestPlacement(pdf, appearance) {
5345
5494
  const id = docIdFromPage(doc);
5346
5495
  if (id !== "") verifyUri = VERIFY_URL_PREFIX + id;
5347
5496
  }
5348
- const w = round100(appearance.width);
5349
- const h = round100(appearance.height);
5497
+ const size = appearanceSize(appearance);
5498
+ const w = round100(size.width);
5499
+ const h = round100(size.height);
5350
5500
  let s;
5351
5501
  try {
5352
5502
  s = suggestVisible(doc, verifyUri, appearance.page ?? 0, round100(appearance.x), round100(appearance.y), w, h, appearance.exact === true);
@@ -5507,12 +5657,16 @@ async function complete2(state, signature, opts = {}) {
5507
5657
  priorCmsSha256: prior,
5508
5658
  priorRevisionSha256: priorRev,
5509
5659
  signerCert: cert.raw,
5510
- claimedRole: st.claimedRole
5660
+ claimedRole: st.claimedRole,
5661
+ ...st.images?.length ? { images: st.images.map((x) => ({ ...x })) } : {}
5511
5662
  };
5512
5663
  }
5513
5664
  // Annotate the CommonJS export names for ESM import in node:
5514
5665
  0 && (module.exports = {
5515
5666
  CertificateRevokedError,
5667
+ DEFAULT_ORG_STAMP_SIZE,
5668
+ DEFAULT_SIGNATURE_STAMP_SIZE,
5669
+ DEFAULT_STAMP_SIZE,
5516
5670
  PADES_ERROR_CODES,
5517
5671
  PROFILE_VERSION,
5518
5672
  PadesError,
package/dist/pades.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { E as EidError } from './errors-CxAr-WIA.cjs';
1
+ import { E as EidError } from './errors-3JEfE-FW.cjs';
2
2
  import { F as FetchFn } from './fetch-BjfH46q9.cjs';
3
3
 
4
4
  /** Олгогчийн гарын үсэгтэй «revoked» хариу (OCSP эсвэл CRL) — complete-д дахин оролдохгүй хатуу алдаа (Go ErrCertificateRevoked). */
@@ -66,6 +66,9 @@ interface PadesPrepareOptions {
66
66
  * `x, y` нь хүссэн байрлал: тэнд хуудасны агуулга байвал дүрслэл чөлөөт зай руу шилжинэ (PLACEMENT_SPEC.md) — эцсийн
67
67
  * байрлал {@link PadesPrepared.placement}-д. `exact: true` бол яг энд зурна (шилжүүлэхгүй, §6a). Урьдчилан харах /
68
68
  * координат хөрвүүлэхэд {@link suggestPlacement}.
69
+ *
70
+ * `width` ба `height` хоёулаа 0 бол анхдагч хэмжээ (APPEARANCE_SPEC.md §6.3, 0.31.0+): зураггүй 220 × 64, `signatureImage`-тэй
71
+ * 220 × 110, `stampImage`-тэй (гарын үсэгтэй/үгүй) 240 × 147.5 — {@link DEFAULT_STAMP_SIZE} г.м.
69
72
  */
70
73
  interface PadesAppearance {
71
74
  /**
@@ -88,7 +91,62 @@ interface PadesAppearance {
88
91
  * false / absent (default) = the rect is only the preferred spot. Not written into the PDF. Since 0.29.0.
89
92
  */
90
93
  exact?: boolean;
94
+ /**
95
+ * The signer's handwritten-signature image (CA: `GET /v3/person/etsi/{etsi}/signature-image`) drawn inside the stamp
96
+ * (APPEARANCE_SPEC.md §6). Absent = none (byte-identical to the stamp without images). Since 0.31.0.
97
+ */
98
+ signatureImage?: PdfImage;
99
+ /**
100
+ * The organization's stamp image (CA: `representations[].stampImage`); only with `claimedRole` (onBehalfOf), else
101
+ * `REQUEST_INVALID` in {@link prepare}. The round stamp overlaps the box top-right and sticks out above it —
102
+ * `width`/`height` are the whole widget rect (APPEARANCE_SPEC.md §6.3). Since 0.31.0.
103
+ */
104
+ stampImage?: PdfImage;
91
105
  }
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
+ }
129
+ /** One image drawn in a signature's stamp, as registered with the CA (`POST /pdf/signatures` `images`, APPEARANCE_SPEC §6.6). */
130
+ interface PadesImageRef {
131
+ kind: "signature" | "stamp";
132
+ sha256: string;
133
+ }
134
+ /**
135
+ * Default stamp sizes (pt) when `appearance.width` and `height` are both 0 (APPEARANCE_SPEC.md §6.3): without images, with
136
+ * a signature image, and with a stamp image (with or without a signature image; the height includes the stamp's overflow).
137
+ */
138
+ declare const DEFAULT_STAMP_SIZE: {
139
+ readonly width: 220;
140
+ readonly height: 64;
141
+ };
142
+ declare const DEFAULT_SIGNATURE_STAMP_SIZE: {
143
+ readonly width: 220;
144
+ readonly height: 110;
145
+ };
146
+ declare const DEFAULT_ORG_STAMP_SIZE: {
147
+ readonly width: 240;
148
+ readonly height: 147.5;
149
+ };
92
150
  interface PadesPrepared {
93
151
  /** SHA-256(DER(signedAttrs)) — 32 байт; `eid.signPdfDigest({dtbs})` / токены `C_Sign`-ийн оролт. */
94
152
  dtbs: Uint8Array;
@@ -208,6 +266,11 @@ interface PadesCompleted {
208
266
  * тулгана.
209
267
  */
210
268
  claimedRole: string;
269
+ /**
270
+ * The images drawn in this signature's stamp (`appearance.signatureImage`, then `stampImage`) as `{kind, sha256}`;
271
+ * `registrationFromCompleted` sends them as `images` (APPEARANCE_SPEC.md §6.6). Absent without images. Since 0.31.0.
272
+ */
273
+ images?: PadesImageRef[];
211
274
  }
212
275
  /** PDF/CMS профайлын хувилбар. */
213
276
  declare function profileVersion(): string;
@@ -246,4 +309,4 @@ declare function suggestPlacement(pdf: Uint8Array, appearance: PadesAppearance):
246
309
  */
247
310
  declare function complete(state: Uint8Array | ArrayBuffer, signature: Uint8Array | string, opts?: PadesCompleteOptions): Promise<PadesCompleted>;
248
311
 
249
- export { CertificateRevokedError, PADES_ERROR_CODES, PROFILE_VERSION, type PadesAppearance, type PadesCompleteOptions, type PadesCompleted, PadesError, type PadesErrorCode, type PadesPlacement, type PadesPlacementStatus, type PadesPrepareOptions, type PadesPrepared, type PlacementSuggestion, complete, prepare, profileVersion, suggestPlacement };
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 };
package/dist/pades.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { E as EidError } from './errors-CxAr-WIA.js';
1
+ import { E as EidError } from './errors-3JEfE-FW.js';
2
2
  import { F as FetchFn } from './fetch-BjfH46q9.js';
3
3
 
4
4
  /** Олгогчийн гарын үсэгтэй «revoked» хариу (OCSP эсвэл CRL) — complete-д дахин оролдохгүй хатуу алдаа (Go ErrCertificateRevoked). */
@@ -66,6 +66,9 @@ interface PadesPrepareOptions {
66
66
  * `x, y` нь хүссэн байрлал: тэнд хуудасны агуулга байвал дүрслэл чөлөөт зай руу шилжинэ (PLACEMENT_SPEC.md) — эцсийн
67
67
  * байрлал {@link PadesPrepared.placement}-д. `exact: true` бол яг энд зурна (шилжүүлэхгүй, §6a). Урьдчилан харах /
68
68
  * координат хөрвүүлэхэд {@link suggestPlacement}.
69
+ *
70
+ * `width` ба `height` хоёулаа 0 бол анхдагч хэмжээ (APPEARANCE_SPEC.md §6.3, 0.31.0+): зураггүй 220 × 64, `signatureImage`-тэй
71
+ * 220 × 110, `stampImage`-тэй (гарын үсэгтэй/үгүй) 240 × 147.5 — {@link DEFAULT_STAMP_SIZE} г.м.
69
72
  */
70
73
  interface PadesAppearance {
71
74
  /**
@@ -88,7 +91,62 @@ interface PadesAppearance {
88
91
  * false / absent (default) = the rect is only the preferred spot. Not written into the PDF. Since 0.29.0.
89
92
  */
90
93
  exact?: boolean;
94
+ /**
95
+ * The signer's handwritten-signature image (CA: `GET /v3/person/etsi/{etsi}/signature-image`) drawn inside the stamp
96
+ * (APPEARANCE_SPEC.md §6). Absent = none (byte-identical to the stamp without images). Since 0.31.0.
97
+ */
98
+ signatureImage?: PdfImage;
99
+ /**
100
+ * The organization's stamp image (CA: `representations[].stampImage`); only with `claimedRole` (onBehalfOf), else
101
+ * `REQUEST_INVALID` in {@link prepare}. The round stamp overlaps the box top-right and sticks out above it —
102
+ * `width`/`height` are the whole widget rect (APPEARANCE_SPEC.md §6.3). Since 0.31.0.
103
+ */
104
+ stampImage?: PdfImage;
91
105
  }
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
+ }
129
+ /** One image drawn in a signature's stamp, as registered with the CA (`POST /pdf/signatures` `images`, APPEARANCE_SPEC §6.6). */
130
+ interface PadesImageRef {
131
+ kind: "signature" | "stamp";
132
+ sha256: string;
133
+ }
134
+ /**
135
+ * Default stamp sizes (pt) when `appearance.width` and `height` are both 0 (APPEARANCE_SPEC.md §6.3): without images, with
136
+ * a signature image, and with a stamp image (with or without a signature image; the height includes the stamp's overflow).
137
+ */
138
+ declare const DEFAULT_STAMP_SIZE: {
139
+ readonly width: 220;
140
+ readonly height: 64;
141
+ };
142
+ declare const DEFAULT_SIGNATURE_STAMP_SIZE: {
143
+ readonly width: 220;
144
+ readonly height: 110;
145
+ };
146
+ declare const DEFAULT_ORG_STAMP_SIZE: {
147
+ readonly width: 240;
148
+ readonly height: 147.5;
149
+ };
92
150
  interface PadesPrepared {
93
151
  /** SHA-256(DER(signedAttrs)) — 32 байт; `eid.signPdfDigest({dtbs})` / токены `C_Sign`-ийн оролт. */
94
152
  dtbs: Uint8Array;
@@ -208,6 +266,11 @@ interface PadesCompleted {
208
266
  * тулгана.
209
267
  */
210
268
  claimedRole: string;
269
+ /**
270
+ * The images drawn in this signature's stamp (`appearance.signatureImage`, then `stampImage`) as `{kind, sha256}`;
271
+ * `registrationFromCompleted` sends them as `images` (APPEARANCE_SPEC.md §6.6). Absent without images. Since 0.31.0.
272
+ */
273
+ images?: PadesImageRef[];
211
274
  }
212
275
  /** PDF/CMS профайлын хувилбар. */
213
276
  declare function profileVersion(): string;
@@ -246,4 +309,4 @@ declare function suggestPlacement(pdf: Uint8Array, appearance: PadesAppearance):
246
309
  */
247
310
  declare function complete(state: Uint8Array | ArrayBuffer, signature: Uint8Array | string, opts?: PadesCompleteOptions): Promise<PadesCompleted>;
248
311
 
249
- export { CertificateRevokedError, PADES_ERROR_CODES, PROFILE_VERSION, type PadesAppearance, type PadesCompleteOptions, type PadesCompleted, PadesError, type PadesErrorCode, type PadesPlacement, type PadesPlacementStatus, type PadesPrepareOptions, type PadesPrepared, type PlacementSuggestion, complete, prepare, profileVersion, suggestPlacement };
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 };