@gerege-systems/eid-mongolia-sdk 0.18.0 → 0.18.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -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
 
@@ -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
- /** FAILED үед: endResult (USER_REFUSED, TIMEOUT …) эсвэл CSR_DIGEST_MISMATCH, TOKEN_LIMIT_REACHED г.м. */
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
- /** FAILED үед: endResult (USER_REFUSED, TIMEOUT …) эсвэл CSR_DIGEST_MISMATCH, TOKEN_LIMIT_REACHED г.м. */
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;
@@ -1,2 +1,2 @@
1
- export { D as DeviceLinkSession, d as NavigatorLike, k as isMobileUserAgent } from './browser-DFnRVCfN.cjs';
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-BPhROZkH.js';
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/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 DISCOVERY_PATH = "/.well-known/eid";
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(DISCOVERY_PATH);
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-DFnRVCfN.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-DFnRVCfN.cjs';
1
+ import { R as RpCredentials, C as CertificateLevel, I as Interaction, S as SignatureAlgorithm, H as HashAlgorithm, N as NotificationSession, D as DeviceLinkSession, a as SessionResult, P as PersonBlock, b as RepresentationsResponse, A as AcspContext, F as FlowType } from './browser-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-BPhROZkH.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-BPhROZkH.js';
1
+ import { R as RpCredentials, C as CertificateLevel, I as Interaction, S as SignatureAlgorithm, H as HashAlgorithm, N as NotificationSession, D as DeviceLinkSession, a as SessionResult, P as PersonBlock, b as RepresentationsResponse, A as AcspContext, F as FlowType } from './browser-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 DISCOVERY_PATH = "/.well-known/eid";
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(DISCOVERY_PATH);
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.0",
3
+ "version": "0.18.1",
4
4
  "description": "e-ID Mongolia Relying Party SDK — иргэнээр утсаар нь нэвтрэлт ба хууль ёсны цахим гарын үсэг (RP-API v3, Smart-ID нийцтэй).",
5
5
  "license": "MIT",
6
6
  "type": "module",