@gerege-systems/eid-mongolia-sdk 0.18.0 → 0.18.2
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 +17 -4
- package/bin/convert-assets.mjs +55 -3
- package/bin/eid-convert.worker.js +17 -2
- package/dist/{browser-BPhROZkH.d.ts → browser-CcQqyw_e.d.ts} +5 -1
- package/dist/{browser-DFnRVCfN.d.cts → browser-DDt-m7-E.d.cts} +5 -1
- package/dist/browser.d.cts +1 -1
- package/dist/browser.d.ts +1 -1
- package/dist/convert.d.ts +5 -0
- package/dist/convert.js +12 -3
- package/dist/index.cjs +29 -3
- package/dist/index.d.cts +42 -4
- package/dist/index.d.ts +42 -4
- package/dist/index.js +28 -3
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -449,6 +449,7 @@ const st = await eid.token.issueCertificate({ signerEtsi, csrAuth, csrSign, toke
|
|
|
449
449
|
const res = await eid.token.certificateResult(st.sessionId);
|
|
450
450
|
verifyTokenCertificates(res, csrAuth, csrSign); // гэрчилгээ бүр CSR-ийн түлхүүртэй
|
|
451
451
|
// 409 TOKEN_LIMIT_REACHED → tokenLimitOf(err): { kind, limit, organization? }
|
|
452
|
+
// 409 TOKEN_IN_USE — serial өөр иргэнд; 409 TOKEN_SCOPE_CHANGE — сунгалт scope солих гэсэн (доор)
|
|
452
453
|
|
|
453
454
|
// токеноор нэвтрэх (AUTH эрх)
|
|
454
455
|
const ch = await eid.token.authChallenge();
|
|
@@ -458,6 +459,13 @@ const who = await eid.token.authVerify(ch.challengeId, authCertDer, rs);
|
|
|
458
459
|
// токеноор PDF: §3d — prepare() → токен CKM_ECDSA(dtbs) → r||s → complete() → registerSignature() (sessionID-гүй, medium "token")
|
|
459
460
|
```
|
|
460
461
|
|
|
462
|
+
**Сунгалт scope-ийг хадгална** (CA 2026-10-16, discovery `tokenCertificate.scopeLockedOnRenewal: true` —
|
|
463
|
+
`eid.token.certificateInfo()`): ижил `tokenSerial` дээр иргэний ACTIVE бүртгэл байвал олголт = сунгалт; байгууллагын
|
|
464
|
+
токен зөвхөн тэр байгууллагаар (`onBehalfOf` ижил), хувийн токен зөвхөн хувиараа. Өөр scope бол `POST` (эсвэл
|
|
465
|
+
батлалтын дараа `certificateResult`) 409 `TOKEN_SCOPE_CHANGE`, session-ий `tokenCertificate.errorCode` мөн ийм — override
|
|
466
|
+
байхгүй. Scope солих = иргэн eID апп-аас токеноо цуцлаад (`/v3/mobile/tokens/{tokenSerial}/revoke`) шинээр олгуулна;
|
|
467
|
+
хэрэглэгчид: «Токены төрлийг (хувийн/байгууллага) солихын тулд eID апп-аас токеныг цуцлаад шинээр олгуулна уу».
|
|
468
|
+
|
|
461
469
|
`/token/auth/*` нь `/.well-known/eid`-ийн `endpoints.token.auth_challenge` / `auth_verify`-д жагсаагдсан (AUTH эрх) —
|
|
462
470
|
гэрээний тест бусад route-ийн адил шалгана.
|
|
463
471
|
|
|
@@ -610,7 +618,7 @@ if (isWordFile(file)) {
|
|
|
610
618
|
|
|
611
619
|
| Функц | Тайлбар |
|
|
612
620
|
|---|---|
|
|
613
|
-
| `wordToPdf(file, { assetsBase, onProgress?, signal?, fileName? })` | `{ pdf, pages, warnings }`. Нэг worker-ийг дахин ашиглана, дуудлагууд
|
|
621
|
+
| `wordToPdf(file, { assetsBase, onProgress?, signal?, fileName?, verbose? })` | `{ pdf, pages, warnings }`. Нэг worker-ийг дахин ашиглана, дуудлагууд дараалалд. `verbose: true` — LibreOffice-ийн оношилгооны лог консолд (анхдагч чимээгүй; утга солигдвол worker дахин асна) |
|
|
614
622
|
| `converterStatus({ assetsBase })` | `{ cached, downloadBytes }` — татахаас өмнө хэмжээг хэлэх (gzip хэмжээ, кэштэй бол 0) |
|
|
615
623
|
| `isWordFile(file \| name)` | .docx / .doc эсэх (нэр, MIME). Агуулгыг `wordToPdf` эхний байтаар шалгана |
|
|
616
624
|
| `disposeConverter()` | worker-ийг зогсоож санах ойг чөлөөлнө (кэш үлдэнэ) |
|
|
@@ -626,6 +634,11 @@ if (isWordFile(file)) {
|
|
|
626
634
|
- Worker-ийн скриптүүдэд (`<assetsBase><хувилбар>/*.js`) **тусдаа CSP**: `default-src 'self'; script-src 'self'
|
|
627
635
|
'wasm-unsafe-eval' 'unsafe-eval'` (Emscripten-д `eval` хэрэгтэй — зөвхөн worker-т). Хуудасны хатуу CSP (nonce +
|
|
628
636
|
`'strict-dynamic'`) хэвээр байна; хуудсанд `connect-src 'self'` хангалттай.
|
|
637
|
+
- Консол: LibreOffice хувиргалт бүрд «warn:vcl…», «[LOK C++] …» гэх мэт оношилгооны мөр (алдаа биш) хэвлэдэг.
|
|
638
|
+
`eid-mongolia-convert-assets` (≥ 0.18.2) upstream worker-ийг (`@matbee/libreoffice-converter@2.7.2`-ийн sha256-аар
|
|
639
|
+
баталгаажсан үед л) patch хийж эдгээрийг `verbose: true`-гүй бол гаргахгүй; `manifest.json`-д `"patched": true`. Hash
|
|
640
|
+
таарахгүй бол patch-гүй хуулж анхааруулна — хувиргалт ажиллана, лог л гарна. SDK шинэчилсний дараа asset-ийг дахин
|
|
641
|
+
хуул (`rev` солигдож worker-ийн immutable кэш шинэчлэгдэнэ; soffice.wasm/.data дахин татагдахгүй).
|
|
629
642
|
- MPL-2.0: `<хувилбар>/NOTICE.txt` (эх код, лицензийн холбоос) asset-уудтай хамт үйлчилгээнд байна — хэрэглэгчийн
|
|
630
643
|
нүүрэнд (тусламж/лиценз хэсэгт) LibreOffice-ийг дурд.
|
|
631
644
|
|
|
@@ -645,8 +658,8 @@ Calibri / Cambria / Courier New-ийн Liberation / Carlito / Caladea орлуу
|
|
|
645
658
|
Гарын үсэг зурсан PDF-ээ дараагийн гарын үсэг зурагч / хүлээн авагч руу хавсралтаар илгээнэ (`POST /share`). CA файлыг
|
|
646
659
|
**хадгалахгүй**: eID-ийн хүчинтэй гарын үсэгтэй эсэхийг шалгаад илгээж, хаяна. Хүлээн авагч бүрт тусдаа имэйл.
|
|
647
660
|
|
|
648
|
-
> CA
|
|
649
|
-
> `
|
|
661
|
+
> CA дээр үргэлж асаалттай (2026-10-16-наас туг байхгүй). Хязгаар, квотыг `await eid.shareInfo()`-ээс уншина;
|
|
662
|
+
> `enabled` false бол имэйлийн үйлчилгээ түр тохируулагдаагүй (503).
|
|
650
663
|
|
|
651
664
|
```ts
|
|
652
665
|
import { ShareError } from "@gerege-systems/eid-mongolia-sdk";
|
|
@@ -680,7 +693,7 @@ if (info.enabled) {
|
|
|
680
693
|
| 422 | `FILE_NOT_SIGNED` | `.reason`: `no_signature` \| `invalid` \| `untrusted` |
|
|
681
694
|
| 429 | `RATE_LIMITED` | квот; `.retryAfterMs`, `.retryable` |
|
|
682
695
|
| 502 | `MAIL_FAILED` | `.sent`, `.failed`, `.recipients` — зөвхөн `failed`-ийг дахин илгээ |
|
|
683
|
-
| 503 | `
|
|
696
|
+
| 503 | `MAIL_UNAVAILABLE`, `VALIDATOR_UNAVAILABLE`, `VALIDATOR_BUSY` (`SHARE_DISABLED` — хуучин CA) | тохиргоо / ачаалал (`VALIDATOR_*` — Retry-After) |
|
|
684
697
|
|
|
685
698
|
401 → `AuthenticationError`, 403 (SIGN эрхгүй, IP/mTLS) → `ForbiddenError`. Квот: RP тутам цагт 30 / өдөрт 200 хүсэлт,
|
|
686
699
|
хүлээн авагч тутам өдөрт 10 имэйл (бодит утгыг `shareInfo().quota`-аас). Хугацаа анхдагч 150 с (`timeoutMs`).
|
package/bin/convert-assets.mjs
CHANGED
|
@@ -7,7 +7,13 @@
|
|
|
7
7
|
// <хавтас>/<хувилбар>/eid-convert.worker.js, browser.worker.global.js
|
|
8
8
|
// <хавтас>/<хувилбар>/LICENSE-MPL-2.0.txt, NOTICE.txt
|
|
9
9
|
//
|
|
10
|
+
// browser.worker.global.js-ийг (зөвхөн sha256 нь QUIET_PATCH-тай таарвал) чимээгүй болгоно: upstream LibreOffice-ийн
|
|
11
|
+
// stdout/stderr-ийг (print/printErr) үргэлж console.log/console.error руу илгээдэг — хувиргалт бүрд ~28 улаан мөр
|
|
12
|
+
// («warn:vcl…», «[LOK C++] …»). Patch-ийн дараа зөвхөн `wordToPdf({ verbose: true })` үед (worker `?verbose=1`).
|
|
13
|
+
// Hash таарахгүй бол patch-гүй хуулж анхааруулна (build унахгүй) — хувиргалт ажиллана, лог л гарна.
|
|
14
|
+
//
|
|
10
15
|
// `wordToPdf({ assetsBase: "<URL>/" })` нь <хавтас>-ын URL-ийг авна. Хуучин хувилбарын дэд хавтсыг устгана.
|
|
16
|
+
import { createHash } from "node:crypto";
|
|
11
17
|
import { createRequire } from "node:module";
|
|
12
18
|
import { createReadStream, createWriteStream, existsSync, mkdirSync, readdirSync, rmSync, statSync, copyFileSync, writeFileSync, readFileSync } from "node:fs";
|
|
13
19
|
import { join, dirname } from "node:path";
|
|
@@ -58,7 +64,44 @@ async function gzipSize(path) {
|
|
|
58
64
|
return n;
|
|
59
65
|
}
|
|
60
66
|
|
|
67
|
+
const sha256 = (buf) => createHash("sha256").update(buf).digest("hex");
|
|
68
|
+
|
|
69
|
+
/** Мэдэгдэж буй upstream файл → яг нэг удаа таарах ёстой солилтууд. */
|
|
70
|
+
const QUIET_PATCH = {
|
|
71
|
+
file: "browser.worker.global.js",
|
|
72
|
+
// @matbee/libreoffice-converter@2.7.2 dist/browser.worker.global.js
|
|
73
|
+
sha256: "9401aff2213772d7114fe417e3f34eb359905ae3a4e94a735644d926d593e276",
|
|
74
|
+
replace: [
|
|
75
|
+
["print:console.log,printErr:console.error}", "print:self.EID_CONVERT_VERBOSE?console.log:()=>{},printErr:self.EID_CONVERT_VERBOSE?console.error:()=>{}}"],
|
|
76
|
+
// Энд (runtime асасны дараа) ENV-д бичих нь LibreOffice-д хүрдэггүй — үйлчлэх утга нь soffice.js-ийн preRun "+WARN"
|
|
77
|
+
// (2026-10-16 Chromium-д хэмжсэн: "-WARN-INFO"-тэй ч «warn:» мөрүүд хэвээр). Консол руу гарахыг printErr зогсооно;
|
|
78
|
+
// "+ALL"-ийг зөвхөн upstream дахин уншдаг болбол бүх лог асахгүйн тулд солино.
|
|
79
|
+
['a.ENV.SAL_LOG="+ALL"', 'a.ENV.SAL_LOG="-WARN-INFO"'],
|
|
80
|
+
['console.log("[Worker] Set SAL_LOG to +ALL")', 'console.log("[Worker] Set SAL_LOG to "+a.ENV.SAL_LOG)'],
|
|
81
|
+
],
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
/** Patch хийсэн агуулга эсвэл null (hash / солилт таарахгүй — шалтгааныг хэвлэнэ). */
|
|
85
|
+
function quiet(buf) {
|
|
86
|
+
const got = sha256(buf);
|
|
87
|
+
if (got !== QUIET_PATCH.sha256) {
|
|
88
|
+
console.warn(`анхааруулга: ${PKG}/dist/${QUIET_PATCH.file} sha256 ${got} — мэдэгдэж буй ${QUIET_PATCH.sha256} биш; лог чимээгүй болгох patch-гүй хуулав (хувиргалт ажиллана, консолд LibreOffice-ийн лог гарна)`);
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
let s = buf.toString("utf8");
|
|
92
|
+
for (const [from, to] of QUIET_PATCH.replace) {
|
|
93
|
+
if (s.split(from).length !== 2) {
|
|
94
|
+
console.warn(`анхааруулга: ${QUIET_PATCH.file}-д «${from}» яг нэг удаа олдсонгүй — patch-гүй хуулав`);
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
s = s.replace(from, () => to);
|
|
98
|
+
}
|
|
99
|
+
return Buffer.from(s, "utf8");
|
|
100
|
+
}
|
|
101
|
+
|
|
61
102
|
const files = {};
|
|
103
|
+
let patched = false;
|
|
104
|
+
const rev = createHash("sha256");
|
|
62
105
|
for (const [name, rel] of Object.entries(FILES)) {
|
|
63
106
|
const from = rel === null ? new URL(name, import.meta.url).pathname : join(src, rel);
|
|
64
107
|
if (!existsSync(from)) {
|
|
@@ -66,7 +109,16 @@ for (const [name, rel] of Object.entries(FILES)) {
|
|
|
66
109
|
process.exit(1);
|
|
67
110
|
}
|
|
68
111
|
const to = join(out, dir, name);
|
|
69
|
-
|
|
112
|
+
if (name === QUIET_PATCH.file) {
|
|
113
|
+
const buf = readFileSync(from);
|
|
114
|
+
const q = quiet(buf);
|
|
115
|
+
patched = q !== null;
|
|
116
|
+
writeFileSync(to, q ?? buf);
|
|
117
|
+
} else {
|
|
118
|
+
copyFileSync(from, to);
|
|
119
|
+
}
|
|
120
|
+
// Worker-ийн скриптүүд `<хувилбар>/` дор immutable кэштэй — агуулга солигдвол (patch, SDK шинэчлэл) rev-ээр URL солино.
|
|
121
|
+
if (name.endsWith(".js")) rev.update(name).update("\0").update(readFileSync(to));
|
|
70
122
|
files[name] = { bytes: statSync(to).size, gzip: await gzipSize(to) };
|
|
71
123
|
}
|
|
72
124
|
// MPL-2.0 §3.2: эх кодын байршил ба лиценз дагалдана.
|
|
@@ -74,6 +126,6 @@ writeFileSync(join(out, dir, "NOTICE.txt"),
|
|
|
74
126
|
`${PKG}@${version} (${license}) — LibreOffice WebAssembly build.\n` +
|
|
75
127
|
`Source: https://github.com/matbeedotcom/libreoffice-document-converter (tag v${version}); LibreOffice: https://www.libreoffice.org/about-us/source-code/\n` +
|
|
76
128
|
`License text: https://www.mozilla.org/MPL/2.0/\n`);
|
|
77
|
-
writeFileSync(join(out, "manifest.json"), JSON.stringify({ format: 1, converter: PKG, version, dir, files }, null, 2) + "\n");
|
|
129
|
+
writeFileSync(join(out, "manifest.json"), JSON.stringify({ format: 1, converter: PKG, version, dir, rev: rev.digest("hex").slice(0, 16), patched, files }, null, 2) + "\n");
|
|
78
130
|
const sum = (k) => Object.values(files).reduce((s, f) => s + f[k], 0);
|
|
79
|
-
console.log(`${PKG}@${version} → ${join(out, dir)} (${(sum("bytes") / 1e6).toFixed(1)} MB, gzip ${(sum("gzip") / 1e6).toFixed(1)} MB)`);
|
|
131
|
+
console.log(`${PKG}@${version} → ${join(out, dir)} (${(sum("bytes") / 1e6).toFixed(1)} MB, gzip ${(sum("gzip") / 1e6).toFixed(1)} MB)${patched ? ", лог чимээгүй (patch)" : ""}`);
|
|
@@ -1,8 +1,20 @@
|
|
|
1
1
|
// @gerege-systems/eid-mongolia-sdk/convert — хувиргагчийн worker. `?cache=<нэр>` бол soffice.wasm / soffice.data-г
|
|
2
2
|
// SDK-ийн урьдчилж татсан Cache Storage-аас өгнө (дахин татахгүй, blob URL-гүй); олдохгүй бол ердийн fetch.
|
|
3
|
+
// `?verbose=1` үгүй бол хувиргагчийн оношилгооны лог (console.log/info/debug, LibreOffice-ийн stdout/stderr) консолд
|
|
4
|
+
// гарахгүй — `wordToPdf({ verbose: true })`. `?v=<rev>` — manifest-ийн rev (immutable кэшийг шинэчлэх).
|
|
3
5
|
// Дараа нь @matbee/libreoffice-converter-ийн worker-ийг ачаална. CSP: script-src 'self' 'wasm-unsafe-eval' 'unsafe-eval'.
|
|
4
6
|
(function () {
|
|
5
|
-
var
|
|
7
|
+
var q = new URL(self.location.href).searchParams;
|
|
8
|
+
// browser.worker.global.js (eid-mongolia-convert-assets-ийн patch) print/printErr, SAL_LOG-ийг үүгээр сонгоно.
|
|
9
|
+
self.EID_CONVERT_VERBOSE = q.get("verbose") === "1";
|
|
10
|
+
if (!self.EID_CONVERT_VERBOSE) {
|
|
11
|
+
var off = function () {};
|
|
12
|
+
// console.error/warn үлдэнэ (жинхэнэ алдаа); upstream-ийн «[Worker] …», «[FS OPEN CALL] …» нь console.log.
|
|
13
|
+
self.console.log = off;
|
|
14
|
+
self.console.info = off;
|
|
15
|
+
self.console.debug = off;
|
|
16
|
+
}
|
|
17
|
+
var name = q.get("cache");
|
|
6
18
|
if (!name || typeof caches === "undefined") return;
|
|
7
19
|
var orig = self.fetch.bind(self);
|
|
8
20
|
self.fetch = function (input, init) {
|
|
@@ -15,4 +27,7 @@
|
|
|
15
27
|
.then(function (hit) { return hit || orig(input, init); });
|
|
16
28
|
};
|
|
17
29
|
})();
|
|
18
|
-
|
|
30
|
+
(function () {
|
|
31
|
+
var v = new URL(self.location.href).searchParams.get("v");
|
|
32
|
+
importScripts("browser.worker.global.js" + (v ? "?v=" + encodeURIComponent(v) : ""));
|
|
33
|
+
})();
|
|
@@ -232,7 +232,11 @@ type TokenCertStatus = "PENDING" | "ISSUED" | "FAILED" | "EXPIRED";
|
|
|
232
232
|
/** GET /session/{id}-ийн `tokenCertificate` (TOKEN_CERT §Төлөв). */
|
|
233
233
|
interface TokenCertSessionBlock {
|
|
234
234
|
status: TokenCertStatus | string;
|
|
235
|
-
/**
|
|
235
|
+
/**
|
|
236
|
+
* FAILED үед: endResult (USER_REFUSED, TIMEOUT …) эсвэл CSR_DIGEST_MISMATCH, SIGNER_CERT_CHANGED, SIGNATURE_INVALID,
|
|
237
|
+
* SESSION_MISMATCH, REPRESENTATION_REVOKED, KYC_INCOMPLETE, TOKEN_LIMIT_REACHED, TOKEN_IN_USE, TOKEN_SCOPE_CHANGE,
|
|
238
|
+
* ISSUANCE_FAILED, REGISTRY_FAILED.
|
|
239
|
+
*/
|
|
236
240
|
errorCode?: string;
|
|
237
241
|
authSerialHex?: string;
|
|
238
242
|
signSerialHex?: string;
|
|
@@ -232,7 +232,11 @@ type TokenCertStatus = "PENDING" | "ISSUED" | "FAILED" | "EXPIRED";
|
|
|
232
232
|
/** GET /session/{id}-ийн `tokenCertificate` (TOKEN_CERT §Төлөв). */
|
|
233
233
|
interface TokenCertSessionBlock {
|
|
234
234
|
status: TokenCertStatus | string;
|
|
235
|
-
/**
|
|
235
|
+
/**
|
|
236
|
+
* FAILED үед: endResult (USER_REFUSED, TIMEOUT …) эсвэл CSR_DIGEST_MISMATCH, SIGNER_CERT_CHANGED, SIGNATURE_INVALID,
|
|
237
|
+
* SESSION_MISMATCH, REPRESENTATION_REVOKED, KYC_INCOMPLETE, TOKEN_LIMIT_REACHED, TOKEN_IN_USE, TOKEN_SCOPE_CHANGE,
|
|
238
|
+
* ISSUANCE_FAILED, REGISTRY_FAILED.
|
|
239
|
+
*/
|
|
236
240
|
errorCode?: string;
|
|
237
241
|
authSerialHex?: string;
|
|
238
242
|
signSerialHex?: string;
|
package/dist/browser.d.cts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export { D as DeviceLinkSession, d as NavigatorLike, k as isMobileUserAgent } from './browser-
|
|
1
|
+
export { D as DeviceLinkSession, d as NavigatorLike, k as isMobileUserAgent } from './browser-DDt-m7-E.cjs';
|
|
2
2
|
export { D as DeviceLinkError, E as EidError } from './errors-pK1L0s4N.cjs';
|
package/dist/browser.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export { D as DeviceLinkSession, d as NavigatorLike, k as isMobileUserAgent } from './browser-
|
|
1
|
+
export { D as DeviceLinkSession, d as NavigatorLike, k as isMobileUserAgent } from './browser-CcQqyw_e.js';
|
|
2
2
|
export { D as DeviceLinkError, E as EidError } from './errors-pK1L0s4N.js';
|
package/dist/convert.d.ts
CHANGED
|
@@ -68,6 +68,11 @@ interface WordToPdfOptions {
|
|
|
68
68
|
signal?: AbortSignal;
|
|
69
69
|
/** Оролт `Uint8Array` бол өргөтгөл таних нэр (".docx" / ".doc"). `File` бол түүний нэр. */
|
|
70
70
|
fileName?: string;
|
|
71
|
+
/**
|
|
72
|
+
* Хувиргагчийн (LibreOffice) оношилгооны логийг хөтчийн консолд гаргах — анхдагч false (чимээгүй). Worker асах үед
|
|
73
|
+
* үйлчилнэ: утга солигдвол worker дахин асна. Чимээгүй горим `eid-mongolia-convert-assets` ≥ 0.18.2-оор хуулсан asset шаардана.
|
|
74
|
+
*/
|
|
75
|
+
verbose?: boolean;
|
|
71
76
|
}
|
|
72
77
|
interface WordToPdfResult {
|
|
73
78
|
pdf: Uint8Array;
|
package/dist/convert.js
CHANGED
|
@@ -1207,6 +1207,9 @@ function parseManifest(v) {
|
|
|
1207
1207
|
if (!m || m.format !== 1 || m.converter !== CONVERTER_PACKAGE || typeof m.version !== "string" || typeof m.dir !== "string" || !/^(?!\.{1,2}\/$)[A-Za-z0-9._-]+\/$/.test(m.dir) || !m.files) {
|
|
1208
1208
|
throw new ConvertError("ASSETS_UNAVAILABLE", "manifest.json \u0431\u0443\u0440\u0443\u0443 \u2014 `eid-mongolia-convert-assets`-\u044D\u044D\u0440 \u0434\u0430\u0445\u0438\u043D \u04AF\u04AF\u0441\u0433\u044D");
|
|
1209
1209
|
}
|
|
1210
|
+
if (m.rev !== void 0 && (typeof m.rev !== "string" || !/^[0-9a-f]{8,64}$/.test(m.rev))) {
|
|
1211
|
+
throw new ConvertError("ASSETS_UNAVAILABLE", "manifest.json-\u0438\u0439\u043D rev \u0431\u0443\u0440\u0443\u0443");
|
|
1212
|
+
}
|
|
1210
1213
|
for (const a of ASSETS) {
|
|
1211
1214
|
const f = m.files[a];
|
|
1212
1215
|
if (!f || !Number.isSafeInteger(f.bytes) || f.bytes <= 0) throw new ConvertError("ASSETS_UNAVAILABLE", `manifest.json-\u0434 ${a} \u0430\u043B\u0433\u0430`);
|
|
@@ -1342,7 +1345,8 @@ async function start(opts, signal) {
|
|
|
1342
1345
|
const root = base(opts.assetsBase);
|
|
1343
1346
|
const m = await loadManifest(root, signal);
|
|
1344
1347
|
const key = root + m.dir;
|
|
1345
|
-
|
|
1348
|
+
const verbose = opts.verbose === true;
|
|
1349
|
+
if (live && live.key === key && live.verbose === verbose) return live;
|
|
1346
1350
|
if (live) kill(live);
|
|
1347
1351
|
let mod;
|
|
1348
1352
|
try {
|
|
@@ -1351,13 +1355,18 @@ async function start(opts, signal) {
|
|
|
1351
1355
|
throw new ConvertError("ASSETS_UNAVAILABLE", `${CONVERTER_PACKAGE} \u0441\u0443\u0443\u0433\u0430\u0430\u0433\u04AF\u0439 (optional peerDependency)`, { cause: e });
|
|
1352
1356
|
}
|
|
1353
1357
|
const cache = await prefetch(root, m, opts.onProgress, signal);
|
|
1354
|
-
const l = { key, conv: null, sink: null };
|
|
1358
|
+
const l = { key, verbose, conv: null, sink: null };
|
|
1359
|
+
const q = new URLSearchParams();
|
|
1360
|
+
if (cache) q.set("cache", cache);
|
|
1361
|
+
if (m.rev) q.set("v", m.rev);
|
|
1362
|
+
if (verbose) q.set("verbose", "1");
|
|
1355
1363
|
l.conv = new mod.WorkerBrowserConverter({
|
|
1356
1364
|
sofficeJs: key + "soffice.js",
|
|
1357
1365
|
sofficeWasm: key + "soffice.wasm",
|
|
1358
1366
|
sofficeData: key + "soffice.data",
|
|
1359
1367
|
sofficeWorkerJs: key + "soffice.worker.js",
|
|
1360
|
-
browserWorkerJs: key + "eid-convert.worker.js" + (
|
|
1368
|
+
browserWorkerJs: key + "eid-convert.worker.js" + (q.toString() ? "?" + q.toString() : ""),
|
|
1369
|
+
verbose,
|
|
1361
1370
|
onProgress: (p) => l.sink?.(p)
|
|
1362
1371
|
});
|
|
1363
1372
|
live = l;
|
package/dist/index.cjs
CHANGED
|
@@ -49,6 +49,7 @@ __export(index_exports, {
|
|
|
49
49
|
SessionFailedError: () => SessionFailedError,
|
|
50
50
|
ShareError: () => ShareError,
|
|
51
51
|
SignApi: () => SignApi,
|
|
52
|
+
TOKEN_CONFLICT_CODES: () => TOKEN_CONFLICT_CODES,
|
|
52
53
|
TokenApi: () => TokenApi,
|
|
53
54
|
ValidationError: () => ValidationError,
|
|
54
55
|
acspV2Digest: () => acspV2Digest,
|
|
@@ -1224,6 +1225,8 @@ function hexSha256Equal(hex, data) {
|
|
|
1224
1225
|
if (typeof hex !== "string" || !/^[0-9a-fA-F]{64}$/.test(hex)) return false;
|
|
1225
1226
|
return (0, import_node_crypto3.timingSafeEqual)((0, import_node_crypto3.createHash)("sha256").update(data).digest(), Buffer.from(hex, "hex"));
|
|
1226
1227
|
}
|
|
1228
|
+
var TOKEN_CONFLICT_CODES = ["TOKEN_LIMIT_REACHED", "TOKEN_IN_USE", "TOKEN_SCOPE_CHANGE"];
|
|
1229
|
+
var DISCOVERY_PATH = "/.well-known/eid";
|
|
1227
1230
|
var TOKEN_RESULT_TIMEOUT_MS = 3e4;
|
|
1228
1231
|
var TokenApi = class {
|
|
1229
1232
|
constructor(http, creds) {
|
|
@@ -1235,6 +1238,11 @@ var TokenApi = class {
|
|
|
1235
1238
|
/**
|
|
1236
1239
|
* POST /token/certificate — токены AUTH + SIGN гэрчилгээ олголт эхлүүлнэ (иргэн утсаараа батална). CA-ийн буцаасан
|
|
1237
1240
|
* CSR hash-ууд илгээсэнтэй таарахгүй бол ValidationError.
|
|
1241
|
+
*
|
|
1242
|
+
* Сунгалт: ижил `tokenSerial` дээр энэ иргэний ACTIVE бүртгэл байвал олголт = сунгалт, **scope-ийг хадгална** —
|
|
1243
|
+
* байгууллагын токен зөвхөн тэр байгууллагаар (`onBehalfOf` ижил), хувийн токен зөвхөн хувиараа. Өөр scope бол
|
|
1244
|
+
* 409 `TOKEN_SCOPE_CHANGE` (override үгүй); scope солих = иргэн eID апп-аас токеноо цуцлаад шинээр олгуулна.
|
|
1245
|
+
* Бусад 409: `TOKEN_LIMIT_REACHED` ({@link tokenLimitOf}), `TOKEN_IN_USE` ({@link TokenConflictCode}).
|
|
1238
1246
|
*/
|
|
1239
1247
|
async issueCertificate(input) {
|
|
1240
1248
|
if (!input.signerEtsi?.trim() || !input.csrAuth?.length || !input.csrSign?.length || !input.tokenSerial?.trim()) {
|
|
@@ -1264,9 +1272,26 @@ var TokenApi = class {
|
|
|
1264
1272
|
...typeof r.expiresAt === "string" ? { expiresAt: r.expiresAt } : {}
|
|
1265
1273
|
};
|
|
1266
1274
|
}
|
|
1275
|
+
/** Discovery-ийн `tokenCertificate` блок. Блок байхгүй (хуучин CA) бол `enabled: false`. */
|
|
1276
|
+
async certificateInfo() {
|
|
1277
|
+
const d = rec4(await this.http.get(DISCOVERY_PATH));
|
|
1278
|
+
const t = rec4(d.tokenCertificate);
|
|
1279
|
+
return {
|
|
1280
|
+
enabled: t.enabled === true,
|
|
1281
|
+
issue: String(t.issue ?? ""),
|
|
1282
|
+
result: String(t.result ?? ""),
|
|
1283
|
+
permission: String(t.permission ?? ""),
|
|
1284
|
+
certificateLevel: String(t.certificateLevel ?? ""),
|
|
1285
|
+
keyAlgorithm: String(t.keyAlgorithm ?? ""),
|
|
1286
|
+
onBehalfOf: String(t.onBehalfOf ?? ""),
|
|
1287
|
+
scopeLockedOnRenewal: t.scopeLockedOnRenewal === true,
|
|
1288
|
+
raw: d.tokenCertificate
|
|
1289
|
+
};
|
|
1290
|
+
}
|
|
1267
1291
|
/**
|
|
1268
1292
|
* GET /token/certificate/{sessionID} — олгосон AUTH + SIGN гэрчилгээ + гинж. Токенд бичихээс өмнө
|
|
1269
|
-
* {@link verifyTokenCertificates}-ээр CSR-ийн түлхүүртэй тулга.
|
|
1293
|
+
* {@link verifyTokenCertificates}-ээр CSR-ийн түлхүүртэй тулга. Эхлэл ба батлалтын хооронд нөхцөл өөрчлөгдсөн бол
|
|
1294
|
+
* 409 ({@link TokenConflictCode}) — гэрчилгээ гараагүй.
|
|
1270
1295
|
*/
|
|
1271
1296
|
async certificateResult(sessionId) {
|
|
1272
1297
|
const raw = await this.http.get(routePath(RP_ROUTES.tokenCertificateResult, sessionId), TOKEN_RESULT_TIMEOUT_MS);
|
|
@@ -1428,7 +1453,7 @@ var ShareError = class extends ApiError {
|
|
|
1428
1453
|
if (Array.isArray(o.recipients)) this.recipients = o.recipients.map(String);
|
|
1429
1454
|
}
|
|
1430
1455
|
};
|
|
1431
|
-
var
|
|
1456
|
+
var DISCOVERY_PATH2 = "/.well-known/eid";
|
|
1432
1457
|
function parseObject(text) {
|
|
1433
1458
|
try {
|
|
1434
1459
|
const v = JSON.parse(text);
|
|
@@ -1467,7 +1492,7 @@ async function shareFile(http, input) {
|
|
|
1467
1492
|
};
|
|
1468
1493
|
}
|
|
1469
1494
|
async function shareInfo(http) {
|
|
1470
|
-
const d = await http.get(
|
|
1495
|
+
const d = await http.get(DISCOVERY_PATH2);
|
|
1471
1496
|
const s = d.share && typeof d.share === "object" ? d.share : {};
|
|
1472
1497
|
const q = s.quota && typeof s.quota === "object" ? s.quota : {};
|
|
1473
1498
|
return {
|
|
@@ -3417,6 +3442,7 @@ function createEidLogin(opts) {
|
|
|
3417
3442
|
SessionFailedError,
|
|
3418
3443
|
ShareError,
|
|
3419
3444
|
SignApi,
|
|
3445
|
+
TOKEN_CONFLICT_CODES,
|
|
3420
3446
|
TokenApi,
|
|
3421
3447
|
ValidationError,
|
|
3422
3448
|
acspV2Digest,
|
package/dist/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
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-
|
|
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-
|
|
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-DDt-m7-E.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-DDt-m7-E.cjs';
|
|
3
3
|
import { A as ApiError, H as HttpErrorInit } from './errors-pK1L0s4N.cjs';
|
|
4
4
|
export { a as AuthenticationError, C as CertChoiceInvalidError, D as DeviceLinkError, E as EidError, F as ForbiddenError, N as NetworkError, b as NoSigningCertificateError, O as ON_BEHALF_ERROR_CODES, c as OnBehalfErrorCode, R as RETRYABLE_ERROR_CODES, d as RequestInvalidError, e as ResponseTooLargeError, f as RetryableErrorCode, S as SessionFailedError, V as ValidationError, p as parseRetryAfter } from './errors-pK1L0s4N.cjs';
|
|
5
5
|
import { X509Certificate, KeyObject } from 'node:crypto';
|
|
@@ -602,6 +602,36 @@ interface TokenLimit {
|
|
|
602
602
|
/** Зөвхөн ORGANIZATION-д (NTRMN-…). */
|
|
603
603
|
organization?: string;
|
|
604
604
|
}
|
|
605
|
+
/**
|
|
606
|
+
* Токены олголтын 409 кодууд (`ApiError.code`; session-ий `tokenCertificate.errorCode`-д ч ирнэ):
|
|
607
|
+
* - `TOKEN_LIMIT_REACHED` — иргэний токены хязгаар хүрсэн ({@link tokenLimitOf});
|
|
608
|
+
* - `TOKEN_IN_USE` — `tokenSerial` өөр иргэнд хүчинтэй гэрчилгээтэй бүртгэлтэй;
|
|
609
|
+
* - `TOKEN_SCOPE_CHANGE` — сунгалт scope-ийг солих гэсэн (хувийн ↔ байгууллага, эсвэл өөр `onBehalfOf`). Override
|
|
610
|
+
* байхгүй: иргэн eID апп-аас токеноо цуцалж (`/v3/mobile/tokens/{tokenSerial}/revoke`) байж шинэ scope-оор олгуулна.
|
|
611
|
+
*/
|
|
612
|
+
type TokenConflictCode = "TOKEN_LIMIT_REACHED" | "TOKEN_IN_USE" | "TOKEN_SCOPE_CHANGE";
|
|
613
|
+
/** {@link TokenConflictCode}-ийн бүх утга (runtime шалгалтад). */
|
|
614
|
+
declare const TOKEN_CONFLICT_CODES: readonly TokenConflictCode[];
|
|
615
|
+
/** Discovery (`/.well-known/eid`)-ийн `tokenCertificate` блок. */
|
|
616
|
+
interface TokenCertInfo {
|
|
617
|
+
enabled: boolean;
|
|
618
|
+
/** `POST` олголтын бүтэн URL. */
|
|
619
|
+
issue: string;
|
|
620
|
+
/** `GET` үр дүнгийн URL template (`{sessionID}`). */
|
|
621
|
+
result: string;
|
|
622
|
+
/** Шаардлагатай RP эрх (TOKEN_ISSUE). */
|
|
623
|
+
permission: string;
|
|
624
|
+
certificateLevel: string;
|
|
625
|
+
keyAlgorithm: string;
|
|
626
|
+
/** `"optional"` — хоосон = хувийн токен. */
|
|
627
|
+
onBehalfOf: string;
|
|
628
|
+
/**
|
|
629
|
+
* true — сунгалт (ижил `tokenSerial` дээр ACTIVE бүртгэлтэй) scope-ийг хадгална; өөр scope бол 409
|
|
630
|
+
* `TOKEN_SCOPE_CHANGE`. Хуучин CA-д талбар алга → false.
|
|
631
|
+
*/
|
|
632
|
+
scopeLockedOnRenewal: boolean;
|
|
633
|
+
raw: unknown;
|
|
634
|
+
}
|
|
605
635
|
declare class TokenApi {
|
|
606
636
|
private readonly http;
|
|
607
637
|
private readonly creds;
|
|
@@ -609,11 +639,19 @@ declare class TokenApi {
|
|
|
609
639
|
/**
|
|
610
640
|
* POST /token/certificate — токены AUTH + SIGN гэрчилгээ олголт эхлүүлнэ (иргэн утсаараа батална). CA-ийн буцаасан
|
|
611
641
|
* CSR hash-ууд илгээсэнтэй таарахгүй бол ValidationError.
|
|
642
|
+
*
|
|
643
|
+
* Сунгалт: ижил `tokenSerial` дээр энэ иргэний ACTIVE бүртгэл байвал олголт = сунгалт, **scope-ийг хадгална** —
|
|
644
|
+
* байгууллагын токен зөвхөн тэр байгууллагаар (`onBehalfOf` ижил), хувийн токен зөвхөн хувиараа. Өөр scope бол
|
|
645
|
+
* 409 `TOKEN_SCOPE_CHANGE` (override үгүй); scope солих = иргэн eID апп-аас токеноо цуцлаад шинээр олгуулна.
|
|
646
|
+
* Бусад 409: `TOKEN_LIMIT_REACHED` ({@link tokenLimitOf}), `TOKEN_IN_USE` ({@link TokenConflictCode}).
|
|
612
647
|
*/
|
|
613
648
|
issueCertificate(input: TokenCertInput): Promise<TokenCertStart>;
|
|
649
|
+
/** Discovery-ийн `tokenCertificate` блок. Блок байхгүй (хуучин CA) бол `enabled: false`. */
|
|
650
|
+
certificateInfo(): Promise<TokenCertInfo>;
|
|
614
651
|
/**
|
|
615
652
|
* GET /token/certificate/{sessionID} — олгосон AUTH + SIGN гэрчилгээ + гинж. Токенд бичихээс өмнө
|
|
616
|
-
* {@link verifyTokenCertificates}-ээр CSR-ийн түлхүүртэй тулга.
|
|
653
|
+
* {@link verifyTokenCertificates}-ээр CSR-ийн түлхүүртэй тулга. Эхлэл ба батлалтын хооронд нөхцөл өөрчлөгдсөн бол
|
|
654
|
+
* 409 ({@link TokenConflictCode}) — гэрчилгээ гараагүй.
|
|
617
655
|
*/
|
|
618
656
|
certificateResult(sessionId: string): Promise<TokenCertResult>;
|
|
619
657
|
/** POST /token/auth/challenge — энэ RP-д холбогдсон нэг удаагийн challenge (2 мин). */
|
|
@@ -1431,4 +1469,4 @@ declare function withReturnHint(callbackUrl: string, userAgent: string): string;
|
|
|
1431
1469
|
*/
|
|
1432
1470
|
declare function createEidLogin(opts: EidLoginOptions): EidLogin;
|
|
1433
1471
|
|
|
1434
|
-
export { AcspContext, type AcspV2Params, type ActivityCounts, type ActivityItem, type ActivityQuery, ApiError, AuthApi, type AuthDefaults, type AuthOptions, type BuildDeviceLinkInput, CITIZEN_ISSUING_CA_SKI, type CertChoiceOptions, type CertCounts, type CertSubject, CertificateLevel, type ClientConfig, type CompletedForRegistration, DEFAULT_BASE_URL, 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, NotificationSession, type OcspCheckerOptions, 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, type RevocationChecker, type RevocationOutcome, type RevocationStatus, RpCredentials, SHARE_ERROR_CODES, SHARE_FORM_FIELDS, SessionApi, SessionResult, ShareError, type ShareErrorCode, type ShareInfo, type ShareInput, type ShareNotSignedReason, type ShareResult, SignApi, type SignDefaults, type SignOptions, SignatureAlgorithm, type Signer, type SignerRef, TokenApi, type TokenAuthChallenge, type TokenAuthResult, type TokenCertInput, type TokenCertItem, type TokenCertResult, type TokenCertStart, type TokenIdentity, type TokenLimit, type TokenOrganization, type TrustConfig, type ValidateAuthOptions, type ValidateSignOptions, type VerifiedIdentity, type VerifiedSignature, acspV2Digest, buildAcspV2Payload, buildDeviceLink, buildRegisterBody, createEidLogin, defaultRateLimit, deviceLinkInput, forwardedClientIp, interactionsToBase64, memoryLoginStore, ocspRevocationChecker, parseSessionResult, parseSubject, personMatchesCertificate, qrDeviceLinkTicker, randomChallenge, registrationFromCompleted, resolveBaseUrl, sha256Base64, tokenAuthDigest, tokenLimitOf, userChallengeOf, verifyPayloadSignature, verifyPrehashedSignature, verifyTokenCertificates, withReturnHint };
|
|
1472
|
+
export { AcspContext, type AcspV2Params, type ActivityCounts, type ActivityItem, type ActivityQuery, ApiError, AuthApi, type AuthDefaults, type AuthOptions, type BuildDeviceLinkInput, CITIZEN_ISSUING_CA_SKI, type CertChoiceOptions, type CertCounts, type CertSubject, CertificateLevel, type ClientConfig, type CompletedForRegistration, DEFAULT_BASE_URL, 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, NotificationSession, type OcspCheckerOptions, 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, type RevocationChecker, type RevocationOutcome, type RevocationStatus, RpCredentials, SHARE_ERROR_CODES, SHARE_FORM_FIELDS, SessionApi, SessionResult, ShareError, type ShareErrorCode, type ShareInfo, type ShareInput, type ShareNotSignedReason, type ShareResult, SignApi, type SignDefaults, type SignOptions, SignatureAlgorithm, type Signer, type SignerRef, TOKEN_CONFLICT_CODES, TokenApi, type TokenAuthChallenge, type TokenAuthResult, type TokenCertInfo, type TokenCertInput, type TokenCertItem, type TokenCertResult, type TokenCertStart, type TokenConflictCode, type TokenIdentity, type TokenLimit, type TokenOrganization, type TrustConfig, type ValidateAuthOptions, type ValidateSignOptions, type VerifiedIdentity, type VerifiedSignature, acspV2Digest, buildAcspV2Payload, buildDeviceLink, buildRegisterBody, 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,5 +1,5 @@
|
|
|
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-
|
|
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-
|
|
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-CcQqyw_e.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-CcQqyw_e.js';
|
|
3
3
|
import { A as ApiError, H as HttpErrorInit } from './errors-pK1L0s4N.js';
|
|
4
4
|
export { a as AuthenticationError, C as CertChoiceInvalidError, D as DeviceLinkError, E as EidError, F as ForbiddenError, N as NetworkError, b as NoSigningCertificateError, O as ON_BEHALF_ERROR_CODES, c as OnBehalfErrorCode, R as RETRYABLE_ERROR_CODES, d as RequestInvalidError, e as ResponseTooLargeError, f as RetryableErrorCode, S as SessionFailedError, V as ValidationError, p as parseRetryAfter } from './errors-pK1L0s4N.js';
|
|
5
5
|
import { X509Certificate, KeyObject } from 'node:crypto';
|
|
@@ -602,6 +602,36 @@ interface TokenLimit {
|
|
|
602
602
|
/** Зөвхөн ORGANIZATION-д (NTRMN-…). */
|
|
603
603
|
organization?: string;
|
|
604
604
|
}
|
|
605
|
+
/**
|
|
606
|
+
* Токены олголтын 409 кодууд (`ApiError.code`; session-ий `tokenCertificate.errorCode`-д ч ирнэ):
|
|
607
|
+
* - `TOKEN_LIMIT_REACHED` — иргэний токены хязгаар хүрсэн ({@link tokenLimitOf});
|
|
608
|
+
* - `TOKEN_IN_USE` — `tokenSerial` өөр иргэнд хүчинтэй гэрчилгээтэй бүртгэлтэй;
|
|
609
|
+
* - `TOKEN_SCOPE_CHANGE` — сунгалт scope-ийг солих гэсэн (хувийн ↔ байгууллага, эсвэл өөр `onBehalfOf`). Override
|
|
610
|
+
* байхгүй: иргэн eID апп-аас токеноо цуцалж (`/v3/mobile/tokens/{tokenSerial}/revoke`) байж шинэ scope-оор олгуулна.
|
|
611
|
+
*/
|
|
612
|
+
type TokenConflictCode = "TOKEN_LIMIT_REACHED" | "TOKEN_IN_USE" | "TOKEN_SCOPE_CHANGE";
|
|
613
|
+
/** {@link TokenConflictCode}-ийн бүх утга (runtime шалгалтад). */
|
|
614
|
+
declare const TOKEN_CONFLICT_CODES: readonly TokenConflictCode[];
|
|
615
|
+
/** Discovery (`/.well-known/eid`)-ийн `tokenCertificate` блок. */
|
|
616
|
+
interface TokenCertInfo {
|
|
617
|
+
enabled: boolean;
|
|
618
|
+
/** `POST` олголтын бүтэн URL. */
|
|
619
|
+
issue: string;
|
|
620
|
+
/** `GET` үр дүнгийн URL template (`{sessionID}`). */
|
|
621
|
+
result: string;
|
|
622
|
+
/** Шаардлагатай RP эрх (TOKEN_ISSUE). */
|
|
623
|
+
permission: string;
|
|
624
|
+
certificateLevel: string;
|
|
625
|
+
keyAlgorithm: string;
|
|
626
|
+
/** `"optional"` — хоосон = хувийн токен. */
|
|
627
|
+
onBehalfOf: string;
|
|
628
|
+
/**
|
|
629
|
+
* true — сунгалт (ижил `tokenSerial` дээр ACTIVE бүртгэлтэй) scope-ийг хадгална; өөр scope бол 409
|
|
630
|
+
* `TOKEN_SCOPE_CHANGE`. Хуучин CA-д талбар алга → false.
|
|
631
|
+
*/
|
|
632
|
+
scopeLockedOnRenewal: boolean;
|
|
633
|
+
raw: unknown;
|
|
634
|
+
}
|
|
605
635
|
declare class TokenApi {
|
|
606
636
|
private readonly http;
|
|
607
637
|
private readonly creds;
|
|
@@ -609,11 +639,19 @@ declare class TokenApi {
|
|
|
609
639
|
/**
|
|
610
640
|
* POST /token/certificate — токены AUTH + SIGN гэрчилгээ олголт эхлүүлнэ (иргэн утсаараа батална). CA-ийн буцаасан
|
|
611
641
|
* CSR hash-ууд илгээсэнтэй таарахгүй бол ValidationError.
|
|
642
|
+
*
|
|
643
|
+
* Сунгалт: ижил `tokenSerial` дээр энэ иргэний ACTIVE бүртгэл байвал олголт = сунгалт, **scope-ийг хадгална** —
|
|
644
|
+
* байгууллагын токен зөвхөн тэр байгууллагаар (`onBehalfOf` ижил), хувийн токен зөвхөн хувиараа. Өөр scope бол
|
|
645
|
+
* 409 `TOKEN_SCOPE_CHANGE` (override үгүй); scope солих = иргэн eID апп-аас токеноо цуцлаад шинээр олгуулна.
|
|
646
|
+
* Бусад 409: `TOKEN_LIMIT_REACHED` ({@link tokenLimitOf}), `TOKEN_IN_USE` ({@link TokenConflictCode}).
|
|
612
647
|
*/
|
|
613
648
|
issueCertificate(input: TokenCertInput): Promise<TokenCertStart>;
|
|
649
|
+
/** Discovery-ийн `tokenCertificate` блок. Блок байхгүй (хуучин CA) бол `enabled: false`. */
|
|
650
|
+
certificateInfo(): Promise<TokenCertInfo>;
|
|
614
651
|
/**
|
|
615
652
|
* GET /token/certificate/{sessionID} — олгосон AUTH + SIGN гэрчилгээ + гинж. Токенд бичихээс өмнө
|
|
616
|
-
* {@link verifyTokenCertificates}-ээр CSR-ийн түлхүүртэй тулга.
|
|
653
|
+
* {@link verifyTokenCertificates}-ээр CSR-ийн түлхүүртэй тулга. Эхлэл ба батлалтын хооронд нөхцөл өөрчлөгдсөн бол
|
|
654
|
+
* 409 ({@link TokenConflictCode}) — гэрчилгээ гараагүй.
|
|
617
655
|
*/
|
|
618
656
|
certificateResult(sessionId: string): Promise<TokenCertResult>;
|
|
619
657
|
/** POST /token/auth/challenge — энэ RP-д холбогдсон нэг удаагийн challenge (2 мин). */
|
|
@@ -1431,4 +1469,4 @@ declare function withReturnHint(callbackUrl: string, userAgent: string): string;
|
|
|
1431
1469
|
*/
|
|
1432
1470
|
declare function createEidLogin(opts: EidLoginOptions): EidLogin;
|
|
1433
1471
|
|
|
1434
|
-
export { AcspContext, type AcspV2Params, type ActivityCounts, type ActivityItem, type ActivityQuery, ApiError, AuthApi, type AuthDefaults, type AuthOptions, type BuildDeviceLinkInput, CITIZEN_ISSUING_CA_SKI, type CertChoiceOptions, type CertCounts, type CertSubject, CertificateLevel, type ClientConfig, type CompletedForRegistration, DEFAULT_BASE_URL, 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, NotificationSession, type OcspCheckerOptions, 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, type RevocationChecker, type RevocationOutcome, type RevocationStatus, RpCredentials, SHARE_ERROR_CODES, SHARE_FORM_FIELDS, SessionApi, SessionResult, ShareError, type ShareErrorCode, type ShareInfo, type ShareInput, type ShareNotSignedReason, type ShareResult, SignApi, type SignDefaults, type SignOptions, SignatureAlgorithm, type Signer, type SignerRef, TokenApi, type TokenAuthChallenge, type TokenAuthResult, type TokenCertInput, type TokenCertItem, type TokenCertResult, type TokenCertStart, type TokenIdentity, type TokenLimit, type TokenOrganization, type TrustConfig, type ValidateAuthOptions, type ValidateSignOptions, type VerifiedIdentity, type VerifiedSignature, acspV2Digest, buildAcspV2Payload, buildDeviceLink, buildRegisterBody, createEidLogin, defaultRateLimit, deviceLinkInput, forwardedClientIp, interactionsToBase64, memoryLoginStore, ocspRevocationChecker, parseSessionResult, parseSubject, personMatchesCertificate, qrDeviceLinkTicker, randomChallenge, registrationFromCompleted, resolveBaseUrl, sha256Base64, tokenAuthDigest, tokenLimitOf, userChallengeOf, verifyPayloadSignature, verifyPrehashedSignature, verifyTokenCertificates, withReturnHint };
|
|
1472
|
+
export { AcspContext, type AcspV2Params, type ActivityCounts, type ActivityItem, type ActivityQuery, ApiError, AuthApi, type AuthDefaults, type AuthOptions, type BuildDeviceLinkInput, CITIZEN_ISSUING_CA_SKI, type CertChoiceOptions, type CertCounts, type CertSubject, CertificateLevel, type ClientConfig, type CompletedForRegistration, DEFAULT_BASE_URL, 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, NotificationSession, type OcspCheckerOptions, 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, type RevocationChecker, type RevocationOutcome, type RevocationStatus, RpCredentials, SHARE_ERROR_CODES, SHARE_FORM_FIELDS, SessionApi, SessionResult, ShareError, type ShareErrorCode, type ShareInfo, type ShareInput, type ShareNotSignedReason, type ShareResult, SignApi, type SignDefaults, type SignOptions, SignatureAlgorithm, type Signer, type SignerRef, TOKEN_CONFLICT_CODES, TokenApi, type TokenAuthChallenge, type TokenAuthResult, type TokenCertInfo, type TokenCertInput, type TokenCertItem, type TokenCertResult, type TokenCertStart, type TokenConflictCode, type TokenIdentity, type TokenLimit, type TokenOrganization, type TrustConfig, type ValidateAuthOptions, type ValidateSignOptions, type VerifiedIdentity, type VerifiedSignature, acspV2Digest, buildAcspV2Payload, buildDeviceLink, buildRegisterBody, 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
|
@@ -1039,6 +1039,8 @@ function hexSha256Equal(hex, data) {
|
|
|
1039
1039
|
if (typeof hex !== "string" || !/^[0-9a-fA-F]{64}$/.test(hex)) return false;
|
|
1040
1040
|
return timingSafeEqual(createHash2("sha256").update(data).digest(), Buffer.from(hex, "hex"));
|
|
1041
1041
|
}
|
|
1042
|
+
var TOKEN_CONFLICT_CODES = ["TOKEN_LIMIT_REACHED", "TOKEN_IN_USE", "TOKEN_SCOPE_CHANGE"];
|
|
1043
|
+
var DISCOVERY_PATH = "/.well-known/eid";
|
|
1042
1044
|
var TOKEN_RESULT_TIMEOUT_MS = 3e4;
|
|
1043
1045
|
var TokenApi = class {
|
|
1044
1046
|
constructor(http, creds) {
|
|
@@ -1050,6 +1052,11 @@ var TokenApi = class {
|
|
|
1050
1052
|
/**
|
|
1051
1053
|
* POST /token/certificate — токены AUTH + SIGN гэрчилгээ олголт эхлүүлнэ (иргэн утсаараа батална). CA-ийн буцаасан
|
|
1052
1054
|
* CSR hash-ууд илгээсэнтэй таарахгүй бол ValidationError.
|
|
1055
|
+
*
|
|
1056
|
+
* Сунгалт: ижил `tokenSerial` дээр энэ иргэний ACTIVE бүртгэл байвал олголт = сунгалт, **scope-ийг хадгална** —
|
|
1057
|
+
* байгууллагын токен зөвхөн тэр байгууллагаар (`onBehalfOf` ижил), хувийн токен зөвхөн хувиараа. Өөр scope бол
|
|
1058
|
+
* 409 `TOKEN_SCOPE_CHANGE` (override үгүй); scope солих = иргэн eID апп-аас токеноо цуцлаад шинээр олгуулна.
|
|
1059
|
+
* Бусад 409: `TOKEN_LIMIT_REACHED` ({@link tokenLimitOf}), `TOKEN_IN_USE` ({@link TokenConflictCode}).
|
|
1053
1060
|
*/
|
|
1054
1061
|
async issueCertificate(input) {
|
|
1055
1062
|
if (!input.signerEtsi?.trim() || !input.csrAuth?.length || !input.csrSign?.length || !input.tokenSerial?.trim()) {
|
|
@@ -1079,9 +1086,26 @@ var TokenApi = class {
|
|
|
1079
1086
|
...typeof r.expiresAt === "string" ? { expiresAt: r.expiresAt } : {}
|
|
1080
1087
|
};
|
|
1081
1088
|
}
|
|
1089
|
+
/** Discovery-ийн `tokenCertificate` блок. Блок байхгүй (хуучин CA) бол `enabled: false`. */
|
|
1090
|
+
async certificateInfo() {
|
|
1091
|
+
const d = rec4(await this.http.get(DISCOVERY_PATH));
|
|
1092
|
+
const t = rec4(d.tokenCertificate);
|
|
1093
|
+
return {
|
|
1094
|
+
enabled: t.enabled === true,
|
|
1095
|
+
issue: String(t.issue ?? ""),
|
|
1096
|
+
result: String(t.result ?? ""),
|
|
1097
|
+
permission: String(t.permission ?? ""),
|
|
1098
|
+
certificateLevel: String(t.certificateLevel ?? ""),
|
|
1099
|
+
keyAlgorithm: String(t.keyAlgorithm ?? ""),
|
|
1100
|
+
onBehalfOf: String(t.onBehalfOf ?? ""),
|
|
1101
|
+
scopeLockedOnRenewal: t.scopeLockedOnRenewal === true,
|
|
1102
|
+
raw: d.tokenCertificate
|
|
1103
|
+
};
|
|
1104
|
+
}
|
|
1082
1105
|
/**
|
|
1083
1106
|
* GET /token/certificate/{sessionID} — олгосон AUTH + SIGN гэрчилгээ + гинж. Токенд бичихээс өмнө
|
|
1084
|
-
* {@link verifyTokenCertificates}-ээр CSR-ийн түлхүүртэй тулга.
|
|
1107
|
+
* {@link verifyTokenCertificates}-ээр CSR-ийн түлхүүртэй тулга. Эхлэл ба батлалтын хооронд нөхцөл өөрчлөгдсөн бол
|
|
1108
|
+
* 409 ({@link TokenConflictCode}) — гэрчилгээ гараагүй.
|
|
1085
1109
|
*/
|
|
1086
1110
|
async certificateResult(sessionId) {
|
|
1087
1111
|
const raw = await this.http.get(routePath(RP_ROUTES.tokenCertificateResult, sessionId), TOKEN_RESULT_TIMEOUT_MS);
|
|
@@ -1243,7 +1267,7 @@ var ShareError = class extends ApiError {
|
|
|
1243
1267
|
if (Array.isArray(o.recipients)) this.recipients = o.recipients.map(String);
|
|
1244
1268
|
}
|
|
1245
1269
|
};
|
|
1246
|
-
var
|
|
1270
|
+
var DISCOVERY_PATH2 = "/.well-known/eid";
|
|
1247
1271
|
function parseObject(text) {
|
|
1248
1272
|
try {
|
|
1249
1273
|
const v = JSON.parse(text);
|
|
@@ -1282,7 +1306,7 @@ async function shareFile(http, input) {
|
|
|
1282
1306
|
};
|
|
1283
1307
|
}
|
|
1284
1308
|
async function shareInfo(http) {
|
|
1285
|
-
const d = await http.get(
|
|
1309
|
+
const d = await http.get(DISCOVERY_PATH2);
|
|
1286
1310
|
const s = d.share && typeof d.share === "object" ? d.share : {};
|
|
1287
1311
|
const q = s.quota && typeof s.quota === "object" ? s.quota : {};
|
|
1288
1312
|
return {
|
|
@@ -2683,6 +2707,7 @@ export {
|
|
|
2683
2707
|
SessionFailedError,
|
|
2684
2708
|
ShareError,
|
|
2685
2709
|
SignApi,
|
|
2710
|
+
TOKEN_CONFLICT_CODES,
|
|
2686
2711
|
TokenApi,
|
|
2687
2712
|
ValidationError,
|
|
2688
2713
|
acspV2Digest,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@gerege-systems/eid-mongolia-sdk",
|
|
3
|
-
"version": "0.18.
|
|
3
|
+
"version": "0.18.2",
|
|
4
4
|
"description": "e-ID Mongolia Relying Party SDK — иргэнээр утсаар нь нэвтрэлт ба хууль ёсны цахим гарын үсэг (RP-API v3, Smart-ID нийцтэй).",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|