@gerege-systems/eid-mongolia-sdk 0.30.1 → 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) {
@@ -3343,6 +3347,61 @@ function toUnicode(f) {
3343
3347
  // src/pades/page/appearance.ts
3344
3348
  var AppearanceError = class extends PdfError {
3345
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
+ }
3346
3405
  var AP_PAD = 400;
3347
3406
  var AP_GAP = 400;
3348
3407
  var AP_MIN_MODULE = 100;
@@ -3388,6 +3447,10 @@ function appearanceContent(p) {
3388
3447
  if (label === void 0) throw new AppearanceError(`\u0445\u044D\u043B ${p.lang}`);
3389
3448
  if (!asciiURL(p.url)) throw new AppearanceError("URL ASCII \u0431\u0438\u0448");
3390
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;
3391
3454
  let m;
3392
3455
  try {
3393
3456
  m = qrEncode(latin1(p.url));
@@ -3395,14 +3458,14 @@ function appearanceContent(p) {
3395
3458
  throw new AppearanceError(String(e));
3396
3459
  }
3397
3460
  const n = m.length;
3398
- const mod = Math.trunc((p.h - 2 * AP_PAD) / n);
3461
+ const mod = Math.trunc((rowH - 2 * AP_PAD) / n);
3399
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)`);
3400
3463
  const tx = AP_PAD + mod * n + AP_GAP;
3401
3464
  const tw = p.w - tx - AP_PAD;
3402
3465
  const [reg, bld] = loadFonts();
3403
3466
  const w = new PageWriter(reg, bld);
3404
3467
  let lines;
3405
- 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);
3406
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)");
3407
3470
  let total = 0;
3408
3471
  for (const l of lines) total += l.size * AP_LEADING;
@@ -3414,8 +3477,13 @@ function appearanceContent(p) {
3414
3477
  }
3415
3478
  w.op(`${C_OK} RG`);
3416
3479
  w.op("1 w");
3417
- w.op(`0.5 0.5 ${num100(p.w - 100)} ${num100(p.h - 100)} re S`);
3418
- 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`);
3419
3487
  w.op("0 0 0 rg");
3420
3488
  for (let r = 0; r < n; r++) {
3421
3489
  for (let c = 0; c < n; ) {
@@ -3430,17 +3498,18 @@ function appearanceContent(p) {
3430
3498
  }
3431
3499
  w.op("f");
3432
3500
  w.op("Q");
3433
- 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);
3434
3502
  for (const l of lines) {
3435
3503
  cursor -= l.size * AP_LEADING;
3436
3504
  w.op(`${l.color} rg`);
3437
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`);
3438
3506
  }
3507
+ if (p.stamp) apDrawImage(w, "Stamp", il.stamp);
3439
3508
  if (cm !== "") w.op("Q");
3440
3509
  w.op("EMC");
3441
3510
  return w.ops;
3442
3511
  }
3443
- function apLayout(w, p, label, f, tw) {
3512
+ function apLayout(w, p, label, f, tw, rowH) {
3444
3513
  const b = f - AP_BODY_DELTA;
3445
3514
  const limit = tw * 10;
3446
3515
  const lines = [];
@@ -3454,20 +3523,40 @@ function apLayout(w, p, label, f, tw) {
3454
3523
  if (l.text === "" || w.width1000(l.font, l.size, l.text) > limit) return void 0;
3455
3524
  total += l.size * AP_LEADING;
3456
3525
  }
3457
- if (total > p.h - 2 * AP_PAD) return void 0;
3526
+ if (total > rowH - 2 * AP_PAD) return void 0;
3458
3527
  return lines;
3459
3528
  }
3529
+ function appearanceObjectCount(p) {
3530
+ return 11 + (p.sig ? 2 : 0) + (p.stamp ? 2 : 0);
3531
+ }
3460
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");
3461
3534
  const [reg, bld] = loadFonts();
3462
3535
  const { bw, bh } = apRotation(p.rotate, p.w, p.h);
3463
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
+ }
3464
3555
  return [
3465
- streamObj(
3466
- ` /Type /XObject /Subtype /Form /BBox [0 0 ${num100(bw)} ${num100(bh)}] /Resources << /Font << /F1 ${ids[1]} 0 R /F2 ${ids[6]} 0 R >> >>`,
3467
- latin1(content)
3468
- ),
3556
+ streamObj(` /Type /XObject /Subtype /Form /BBox [0 0 ${num100(bw)} ${num100(bh)}] /Resources << ${res} >>`, latin1(content)),
3469
3557
  ...fontBodies(ids.slice(1, 6), reg),
3470
- ...fontBodies(ids.slice(6, 11), bld)
3558
+ ...fontBodies(ids.slice(6, 11), bld),
3559
+ ...imgs
3471
3560
  ];
3472
3561
  }
3473
3562
  function visibleWidget(fieldName, rect, pageID, pageGen, sigID, formID) {
@@ -4648,7 +4737,7 @@ async function prepareSignature(base, signingTime, signerName, reason, vis) {
4648
4737
  const sigID = inc.reserve();
4649
4738
  const fieldID = inc.reserve();
4650
4739
  const catID = inc.reserve();
4651
- const apIDs = vis ? Array.from({ length: 11 }, () => inc.reserve()) : [];
4740
+ const apIDs = vis ? Array.from({ length: appearanceObjectCount(vis) }, () => inc.reserve()) : [];
4652
4741
  let sig = `<<
4653
4742
  /Type /Sig
4654
4743
  /Filter /Adobe.PPKLite
@@ -4690,7 +4779,10 @@ async function prepareSignature(base, signingTime, signerName, reason, vis) {
4690
4779
  placement = placeOnPage(page, box, rot, vis.x, vis.y, vis.w, vis.h, vis.exact === true);
4691
4780
  if (placement.x !== vis.x || placement.y !== vis.y) rect = visibleRect(box, rot, placement.x, placement.y, vis.w, vis.h);
4692
4781
  }
4693
- 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
+ );
4694
4786
  inc.writeObject(fieldID, visibleWidget(fieldName, rect, page.ptr.id, page.ptr.gen, sigID, apIDs[0]));
4695
4787
  bodies.forEach((b2, i) => inc.writeObject(apIDs[i], b2));
4696
4788
  }
@@ -5035,6 +5127,7 @@ function encodeState(s) {
5035
5127
  };
5036
5128
  if (s.pageSha256) head.pageSha256 = s.pageSha256;
5037
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 }));
5038
5131
  head.preparedSha256 = s.preparedSha256;
5039
5132
  const h = enc.encode(JSON.stringify(head));
5040
5133
  const len = new Uint8Array(4);
@@ -5060,6 +5153,7 @@ async function decodeState(b) {
5060
5153
  hasPage: j.hasPage === true,
5061
5154
  pageSha256: str("pageSha256"),
5062
5155
  claimedRole: str("claimedRole"),
5156
+ images: stateImages(j.images),
5063
5157
  preparedSha256: str("preparedSha256"),
5064
5158
  pdf
5065
5159
  };
@@ -5069,6 +5163,16 @@ async function decodeState(b) {
5069
5163
  }
5070
5164
  return s;
5071
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
+ }
5072
5176
 
5073
5177
  // src/pades.ts
5074
5178
  var PROFILE_VERSION = "pades-client/1";
@@ -5103,6 +5207,21 @@ var PadesError = class extends EidError {
5103
5207
  return this.code === "TSA_UNAVAILABLE" || this.code === "LTV_UNAVAILABLE";
5104
5208
  }
5105
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
+ }
5106
5225
  var MAX_OUTPUT_BYTES = 10 << 20;
5107
5226
  var MAX_FILE_NAME = 120;
5108
5227
  var PAGE_BRAND = "eID Mongolia";
@@ -5202,6 +5321,9 @@ async function prepare(pdf, opts) {
5202
5321
  }
5203
5322
  const first = pos === "first";
5204
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
+ }
5205
5327
  const now = opts.signingTime ?? /* @__PURE__ */ new Date();
5206
5328
  if (Number.isNaN(now.getTime())) throw new PadesError("REQUEST_INVALID", "signingTime \u0431\u0443\u0440\u0443\u0443 Date");
5207
5329
  const inHex = toHex(await sha256(doc));
@@ -5275,6 +5397,7 @@ async function prepare(pdf, opts) {
5275
5397
  hasPage,
5276
5398
  pageSha256: pageHex,
5277
5399
  claimedRole: role,
5400
+ images: prepImages(opts.appearance),
5278
5401
  preparedSha256: toHex(await sha256(prep.pdf)),
5279
5402
  pdf: prep.pdf
5280
5403
  });
@@ -5298,6 +5421,24 @@ function checkAppearance(o) {
5298
5421
  if (a.exact !== void 0 && typeof a.exact !== "boolean") throw bad("exact: boolean");
5299
5422
  const role = o.claimedRole ?? "";
5300
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;
5301
5442
  }
5302
5443
  function visibleSpec(doc, o, name, now, docId, revIndex) {
5303
5444
  const a = o.appearance;
@@ -5312,12 +5453,15 @@ function visibleSpec(doc, o, name, now, docId, revIndex) {
5312
5453
  if (page > n) throw new PadesError("REQUEST_INVALID", `appearance: page ${page} > \u0445\u0443\u0443\u0434\u0430\u0441\u043D\u044B \u0442\u043E\u043E ${n}`);
5313
5454
  const z = new Date(now.getTime() + 8 * 36e5);
5314
5455
  const p2 = (v) => String(v).padStart(2, "0");
5456
+ const size = appearanceSize(a);
5315
5457
  return {
5316
5458
  page,
5317
5459
  x: round100(a.x),
5318
5460
  y: round100(a.y),
5319
- w: round100(a.width),
5320
- h: round100(a.height),
5461
+ w: round100(size.width),
5462
+ h: round100(size.height),
5463
+ sig: imageData(a.signatureImage),
5464
+ stamp: imageData(a.stampImage),
5321
5465
  name: goTrim(name),
5322
5466
  role: o.claimedRole ?? "",
5323
5467
  lang: a.lang || o.lang || "mn",
@@ -5350,8 +5494,9 @@ async function suggestPlacement(pdf, appearance) {
5350
5494
  const id = docIdFromPage(doc);
5351
5495
  if (id !== "") verifyUri = VERIFY_URL_PREFIX + id;
5352
5496
  }
5353
- const w = round100(appearance.width);
5354
- const h = round100(appearance.height);
5497
+ const size = appearanceSize(appearance);
5498
+ const w = round100(size.width);
5499
+ const h = round100(size.height);
5355
5500
  let s;
5356
5501
  try {
5357
5502
  s = suggestVisible(doc, verifyUri, appearance.page ?? 0, round100(appearance.x), round100(appearance.y), w, h, appearance.exact === true);
@@ -5512,12 +5657,16 @@ async function complete2(state, signature, opts = {}) {
5512
5657
  priorCmsSha256: prior,
5513
5658
  priorRevisionSha256: priorRev,
5514
5659
  signerCert: cert.raw,
5515
- claimedRole: st.claimedRole
5660
+ claimedRole: st.claimedRole,
5661
+ ...st.images?.length ? { images: st.images.map((x) => ({ ...x })) } : {}
5516
5662
  };
5517
5663
  }
5518
5664
  // Annotate the CommonJS export names for ESM import in node:
5519
5665
  0 && (module.exports = {
5520
5666
  CertificateRevokedError,
5667
+ DEFAULT_ORG_STAMP_SIZE,
5668
+ DEFAULT_SIGNATURE_STAMP_SIZE,
5669
+ DEFAULT_STAMP_SIZE,
5521
5670
  PADES_ERROR_CODES,
5522
5671
  PROFILE_VERSION,
5523
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 };