UNPKG

edockit

Version:

A JavaScript library for listing, parsing, and verifying the contents and signatures of electronic documents (eDoc) and Associated Signature Containers (ASiC-E), supporting EU eIDAS standards for digital signatures and electronic seals.

16 lines (15 loc) 26.8 kB
/*! * MIT License * Copyright (c) 2025 Edgars Jēkabsons, ZenomyTech SIA */(function(T,I){typeof exports=="object"&&typeof module!="undefined"?I(exports,require("fflate"),require("@peculiar/x509")):typeof define=="function"&&define.amd?define(["exports","fflate","@peculiar/x509"],I):(T=typeof globalThis!="undefined"?globalThis:T||self,I(T.edockit={},T.fflate,T.peculiarX509))})(this,function(T,I,z){"use strict";function k(n,t){const e=[],r=t.split(",").map(u=>u.trim()),a=[];for(const u of r){const o=u.split(/\\:|:/).filter(Boolean);o.length===1?a.push({name:o[0]}):o.length===2&&a.push({ns:o[0],name:o[1]})}function s(u){if(u){if(u.nodeType===1){const o=u,c=o.nodeName,i=o.localName;for(const l of a){if(l.ns&&c===`${l.ns}:${l.name}`){e.push(o);break}if(i===l.name||c===l.name){e.push(o);break}if(c.endsWith(`:${l.name}`)){e.push(o);break}}}if(u.childNodes)for(let o=0;o<u.childNodes.length;o++)s(u.childNodes[o])}}return s(n),e}const F={ds:"http://www.w3.org/2000/09/xmldsig#",dsig11:"http://www.w3.org/2009/xmldsig11#",dsig2:"http://www.w3.org/2010/xmldsig2#",ec:"http://www.w3.org/2001/10/xml-exc-c14n#",dsig_more:"http://www.w3.org/2001/04/xmldsig-more#",xenc:"http://www.w3.org/2001/04/xmlenc#",xenc11:"http://www.w3.org/2009/xmlenc11#",xades:"http://uri.etsi.org/01903/v1.3.2#",xades141:"http://uri.etsi.org/01903/v1.4.1#",asic:"http://uri.etsi.org/02918/v1.2.1#"};function j(){if(typeof window!="undefined"&&window.DOMParser)return new window.DOMParser;try{const{DOMParser:n}=require("@xmldom/xmldom");return new n}catch(n){throw new Error("XML DOM parser not available. In Node.js environments, please install @xmldom/xmldom package.")}}function oe(n,t,e=F){try{if(typeof document!="undefined"&&document.evaluate){const r=R(e);return document.evaluate(t,n,r,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue}else{const r=require("xpath"),a=e;try{const s=r.select(t,n,a);return s.length>0?s[0]:null}catch(s){if(typeof s=="object"&&s!==null&&"message"in s&&typeof s.message=="string"&&s.message.includes("Cannot resolve QName")){const u=t.match(/local-name\(\)='([^']+)'/);if(u&&u[1]){const o=`.//*[local-name()='${u[1]}']`,c=r.select(o,n);return c.length>0?c[0]:null}}throw s}}}catch(r){return console.error(`XPath evaluation failed for "${t}":`,r),null}}function ae(n,t,e=F){try{if(typeof document!="undefined"&&document.evaluate){const r=R(e),a=document.evaluate(t,n,r,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null),s=[];for(let u=0;u<a.snapshotLength;u++)s.push(a.snapshotItem(u));return s}else{const r=require("xpath"),a=e;try{return r.select(t,n,a)}catch(s){if(typeof s=="object"&&s!==null&&"message"in s&&typeof s.message=="string"&&s.message.includes("Cannot resolve QName")){const u=t.match(/local-name\(\)='([^']+)'/);if(u&&u[1]){const o=`.//*[local-name()='${u[1]}']`;return r.select(o,n)}}throw s}}}catch(r){return console.error(`XPath evaluation failed for "${t}":`,r),[]}}function R(n){return function(t){return t===null?null:n[t]||null}}function U(n){const t=n.split(",").map(r=>r.trim()),e=[];for(const r of t){const a=r.split(/\\:|:/).filter(Boolean);a.length===1?e.push(`.//*[local-name()='${a[0]}']`):a.length===2&&e.push(`.//${a[0]}:${a[1]} | .//*[local-name()='${a[1]}']`)}return e.join(" | ")}function x(n,t){if(typeof n.querySelector=="function")try{const r=n.querySelector(t);if(r)return r}catch(r){}const e=k(n,t);if(e.length>0)return e[0];try{const r=U(t);return oe(n,r)}catch(r){return console.warn("XPath query failed, using direct DOM traversal as fallback"),null}}function K(n,t){if(typeof n.querySelectorAll=="function")try{const r=n.querySelectorAll(t);if(r.length>0){const a=[];for(let s=0;s<r.length;s++)a.push(r[s]);return a}}catch(r){}const e=k(n,t);if(e.length>0)return e;try{const r=U(t);return ae(n,r)}catch(r){return console.warn("XPath query failed, using direct DOM traversal as fallback"),[]}}function se(n){if(typeof window!="undefined"&&window.XMLSerializer)return new window.XMLSerializer().serializeToString(n);try{const{XMLSerializer:t}=require("@xmldom/xmldom");return new t().serializeToString(n)}catch(t){throw new Error("XML Serializer not available. In Node.js environments, please install @xmldom/xmldom package.")}}const O={default:"c14n","http://www.w3.org/TR/2001/REC-xml-c14n-20010315":"c14n","http://www.w3.org/2006/12/xml-c14n11":"c14n11","http://www.w3.org/2001/10/xml-exc-c14n#":"c14n_exc"},V={c14n:{beforeChildren:()=>"",afterChildren:()=>"",betweenChildren:()=>"",afterElement:()=>"",isCanonicalizationMethod:"c14n"},c14n11:{beforeChildren:(n,t)=>t?"":n?` `:"",afterChildren:(n,t)=>t?"":n?` `:"",betweenChildren:(n,t,e)=>e?"":n&&t?` `:"",afterElement:()=>"",isCanonicalizationMethod:"c14n11"},c14n_exc:{beforeChildren:()=>"",afterChildren:()=>"",betweenChildren:()=>"",afterElement:()=>"",isCanonicalizationMethod:"c14n_exc"}},S={ELEMENT_NODE:1,TEXT_NODE:3};class b{constructor(t=V.c14n){this.method=t}static fromMethod(t){const e=O[t];if(!e)throw new Error(`Unsupported canonicalization method: ${t}`);return new b(V[e])}setMethod(t){this.method=t}static escapeXml(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}static collectNamespaces(t,e=new Map){let r=t;for(;r&&r.nodeType===S.ELEMENT_NODE;){const a=r,s=a.getAttribute("xmlns");s!==null&&!e.has("")&&e.set("",s);const u=a.attributes;for(let o=0;o<u.length;o++){const c=u[o];if(c.name.startsWith("xmlns:")){const i=c.name.substring(6);e.has(i)||e.set(i,c.value)}}r=r.parentNode}return e}static collectUsedNamespaces(t,e=new Map,r=[]){const a=new Map,s=new Set;function u(o,c=!1){if(o.nodeType===S.ELEMENT_NODE){const i=o,l=i.namespaceURI,g=i.prefix||"";if(g&&l&&(c||!s.has(g))){s.add(g);const f=e.get(g);f&&f===l&&!a.has(g)&&a.set(g,f)}const p=i.attributes;for(let f=0;f<p.length;f++){const m=p[f];if(m.name.includes(":")&&!m.name.startsWith("xmlns:")){const y=m.name.split(":")[0];if(c||!s.has(y)){s.add(y);const d=e.get(y);d&&!a.has(y)&&a.set(y,d)}}}for(const f of r){const m=e.get(f);m&&!a.has(f)&&a.set(f,m)}for(let f=0;f<o.childNodes.length;f++)u(o.childNodes[f],!1)}}return u(t,!0),a}static isBase64Element(t){if(t.nodeType!==S.ELEMENT_NODE)return!1;const e=t,r=e.localName||e.nodeName.split(":").pop()||"";return this.base64Elements.has(r)}static analyzeWhitespace(t){const e=t.nodeType===S.ELEMENT_NODE?t:t.documentElement;function r(a){if(a.nodeType===S.ELEMENT_NODE){a._whitespace={hasMixedContent:!1,hasExistingLinebreaks:!1,originalContent:{}};const s=Array.from(a.childNodes);let u=!1,o=!1,c=!1;for(const i of s)if(i.nodeType===S.TEXT_NODE&&(i.nodeValue||"").trim().length>0){u=!0;break}for(const i of s)if(i.nodeType===S.ELEMENT_NODE){o=!0;break}for(let i=0;i<s.length;i++){const l=s[i];if(l.nodeType===S.TEXT_NODE){const g=l.nodeValue||"";l._originalText=g,g.includes(` `)&&(c=!0)}else l.nodeType===S.ELEMENT_NODE&&r(l)}a._whitespace.hasMixedContent=u&&o,a._whitespace.hasExistingLinebreaks=c}}r(e)}canonicalize(t,e=new Map,r={isStartingNode:!0}){var a,s,u;if(!t)return"";let o="";if(t.nodeType===S.ELEMENT_NODE){const c=new Map(e),i=t,l=i.getAttribute("xmlns");l!==null&&c.set("",l);const g=i.attributes;for(let w=0;w<g.length;w++){const N=g[w];if(N.name.startsWith("xmlns:")){const E=N.name.substring(6);c.set(E,N.value)}}const p=i.prefix||"",f=i.localName||i.nodeName.split(":").pop()||"",m=p?`${p}:${f}`:f;if(o+="<"+m,r.isStartingNode){const w=b.collectNamespaces(t),N=Array.from(w.entries()).sort((E,v)=>E[0]===""?-1:v[0]===""?1:E[0].localeCompare(v[0]));for(const[E,v]of N)E===""?o+=` xmlns="${v}"`:o+=` xmlns:${E}="${v}"`}else{const w=Array.from(c.entries()).filter(([N,E])=>!e.has(N)||e.get(N)!==E).sort((N,E)=>N[0]===""?-1:E[0]===""?1:N[0].localeCompare(E[0]));for(const[N,E]of w)N===""?o+=` xmlns="${E}"`:o+=` xmlns:${N}="${E}"`}const y=i.attributes,d=[];for(let w=0;w<y.length;w++){const N=y[w];N.name.startsWith("xmlns")||d.push(N)}d.sort((w,N)=>w.name.localeCompare(N.name));for(const w of d)o+=` ${w.name}="${b.escapeXml(w.value)}"`;o+=">";const h=Array.from(t.childNodes);let C=!1,A=!1;const $=((a=t._whitespace)==null?void 0:a.hasMixedContent)||!1;for(const w of h)if(w.nodeType===S.ELEMENT_NODE){C=!0;break}const X=this.method.isCanonicalizationMethod==="c14n11"&&C&&!((s=t._whitespace)!=null&&s.hasExistingLinebreaks)&&!$;X&&(o+=this.method.beforeChildren(C,$));for(let w=0;w<h.length;w++){const N=h[w],E=N.nodeType===S.ELEMENT_NODE,v=w<h.length-1?h[w+1]:null;if(v&&(v.nodeType,S.ELEMENT_NODE),N.nodeType===S.TEXT_NODE){const D=N.nodeValue||"";b.isBase64Element(t)?o+=D.replace(/\r/g,"&#xD;"):o+=N._originalText||D,A=!1;continue}E&&(A&&this.method.isCanonicalizationMethod==="c14n11"&&!((u=t._whitespace)!=null&&u.hasExistingLinebreaks)&&!$&&(o+=this.method.betweenChildren(!0,!0,$)),o+=this.canonicalize(N,c,{isStartingNode:!1}),A=!0)}X&&(o+=this.method.afterChildren(C,$)),o+="</"+m+">"}else if(t.nodeType===S.TEXT_NODE){const c=t._originalText||t.nodeValue||"";o+=b.escapeXml(c)}return o}canonicalizeExclusive(t,e=new Map,r={}){if(!t)return"";const{inclusiveNamespacePrefixList:a=[],isStartingNode:s=!0}=r;let u="";if(t.nodeType===S.ELEMENT_NODE){const o=t,c=b.collectNamespaces(o),i=s?b.collectUsedNamespaces(o,c,a):new Map,l=o.prefix||"",g=o.localName||o.nodeName.split(":").pop()||"",p=l?`${l}:${g}`:g;if(u+="<"+p,s){const d=Array.from(i.entries()).sort((h,C)=>h[0]===""?-1:C[0]===""?1:h[0].localeCompare(C[0]));for(const[h,C]of d)h===""?u+=` xmlns="${C}"`:u+=` xmlns:${h}="${C}"`}const f=o.attributes,m=[];for(let d=0;d<f.length;d++){const h=f[d];h.name.startsWith("xmlns")||m.push(h)}m.sort((d,h)=>d.name.localeCompare(h.name));for(const d of m)u+=` ${d.name}="${b.escapeXml(d.value)}"`;u+=">";const y=Array.from(t.childNodes);for(let d=0;d<y.length;d++){const h=y[d];if(h.nodeType===S.TEXT_NODE){const C=h.nodeValue||"";b.isBase64Element(t)?u+=C.replace(/\r/g,"&#xD;"):u+=b.escapeXml(C)}else h.nodeType===S.ELEMENT_NODE&&(u+=this.canonicalizeExclusive(h,new Map([...e,...i]),{inclusiveNamespacePrefixList:a,isStartingNode:!1}))}u+="</"+p+">"}else if(t.nodeType===S.TEXT_NODE){const o=t.nodeValue||"";u+=b.escapeXml(o)}return u}static c14n(t){return this.analyzeWhitespace(t),new b(V.c14n).canonicalize(t)}static c14n11(t){return this.analyzeWhitespace(t),new b(V.c14n11).canonicalize(t)}static c14n_exc(t,e=[]){return this.analyzeWhitespace(t),new b(V.c14n_exc).canonicalizeExclusive(t,new Map,{inclusiveNamespacePrefixList:e})}static canonicalize(t,e,r={}){switch(O[e]||O.default){case"c14n":return this.c14n(t);case"c14n11":return this.c14n11(t);case"c14n_exc":return this.c14n_exc(t,r.inclusiveNamespacePrefixList||[]);default:throw new Error(`Unsupported canonicalization method: ${e}`)}}}b.base64Elements=new Set(["DigestValue","X509Certificate","EncapsulatedTimeStamp","EncapsulatedOCSPValue","IssuerSerialV2"]);var le=(n,t,e)=>new Promise((r,a)=>{var s=c=>{try{o(e.next(c))}catch(i){a(i)}},u=c=>{try{o(e.throw(c))}catch(i){a(i)}},o=c=>c.done?r(c.value):Promise.resolve(c.value).then(s,u);o((e=e.apply(n,t)).next())});function ce(n){if(!n)return"";const t=n.replace(/\s+/g,""),e=[];for(let r=0;r<t.length;r+=64)e.push(t.substring(r,r+64));return`-----BEGIN CERTIFICATE----- ${e.join(` `)} -----END CERTIFICATE-----`}function q(n){var t,e,r,a,s,u,o,c;const i={validFrom:n.notBefore,validTo:n.notAfter,issuer:{}};try{if(typeof n.subject=="object"&&n.subject!==null){const l=n.subject;i.commonName=l.commonName,i.organization=l.organizationName,i.country=l.countryName}if(typeof n.issuer=="object"&&n.issuer!==null){const l=n.issuer;i.issuer.commonName=l.commonName,i.issuer.organization=l.organizationName,i.issuer.country=l.countryName}}catch(l){console.warn("Could not extract subject/issuer as objects:",l)}try{if(typeof n.subject=="string"){const l=n.subject.split(",");for(const g of l){const[p,f]=g.trim().split("=");p==="CN"&&(i.commonName=i.commonName||f),p==="O"&&(i.organization=i.organization||f),p==="C"&&(i.country=i.country||f),p==="SN"&&(i.surname=f),(p==="G"||p==="GN")&&(i.givenName=f),(p==="SERIALNUMBER"||p==="2.5.4.5")&&(i.serialNumber=f==null?void 0:f.replace("PNOLV-",""))}}if(typeof n.issuer=="string"){const l=n.issuer.split(",");for(const g of l){const[p,f]=g.trim().split("=");p==="CN"&&(i.issuer.commonName=i.issuer.commonName||f),p==="O"&&(i.issuer.organization=i.issuer.organization||f),p==="C"&&(i.issuer.country=i.issuer.country||f)}}}catch(l){console.warn("Could not extract subject/issuer as strings:",l)}try{if("subjectName"in n&&(t=n.subjectName)!=null&&t.getField){const l=n.subjectName;i.commonName=i.commonName||((e=l.getField("CN"))==null?void 0:e[0]),i.surname=i.surname||((r=l.getField("SN"))==null?void 0:r[0]),i.givenName=i.givenName||((a=l.getField("G"))==null?void 0:a[0]),i.serialNumber=i.serialNumber||((u=(s=l.getField("2.5.4.5"))==null?void 0:s[0])==null?void 0:u.replace("PNOLV-","")),i.country=i.country||((o=l.getField("C"))==null?void 0:o[0]),i.organization=i.organization||((c=l.getField("O"))==null?void 0:c[0])}}catch(l){console.warn("Could not extract fields using getField method:",l)}return!i.serialNumber&&n.serialNumber&&(i.serialNumber=n.serialNumber),i}function B(n){return le(this,null,function*(){try{let t=n;if(!n.includes("-----BEGIN CERTIFICATE-----")){const a=n.replace(/[\r\n\s]/g,"");t=ce(a)}const e=new z.X509Certificate(t),r=q(e);return{subject:{commonName:r.commonName,organization:r.organization,country:r.country,surname:r.surname,givenName:r.givenName,serialNumber:r.serialNumber},validFrom:r.validFrom,validTo:r.validTo,issuer:r.issuer,serialNumber:e.serialNumber}}catch(t){throw console.error("Certificate parsing error:",t),new Error("Failed to parse certificate: "+(t instanceof Error?t.message:String(t)))}})}function ue(n,t=new Date){const e="notBefore"in n?n.notBefore:n.validFrom,r="notAfter"in n?n.notAfter:n.validTo;return t<e?{isValid:!1,reason:`Certificate not yet valid. Valid from ${e.toISOString()}`}:t>r?{isValid:!1,reason:`Certificate expired. Valid until ${r.toISOString()}`}:{isValid:!0}}function fe(n){const{subject:t}=n;return t.givenName&&t.surname?`${t.givenName} ${t.surname}`:t.commonName?t.commonName:t.serialNumber||"Unknown Signer"}function de(n){const{validFrom:t,validTo:e}=n,r=a=>a.toLocaleDateString(void 0,{year:"numeric",month:"long",day:"numeric"});return`${r(t)} to ${r(e)}`}function H(n){if(!n)return"";const t=n.replace(/\s+/g,""),e=[];for(let r=0;r<t.length;r+=64)e.push(t.substring(r,r+64));return`-----BEGIN CERTIFICATE----- ${e.join(` `)} -----END CERTIFICATE-----`}var me=Object.defineProperty,he=Object.defineProperties,ge=Object.getOwnPropertyDescriptors,W=Object.getOwnPropertySymbols,pe=Object.prototype.hasOwnProperty,ye=Object.prototype.propertyIsEnumerable,G=(n,t,e)=>t in n?me(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,Y=(n,t)=>{for(var e in t||(t={}))pe.call(t,e)&&G(n,e,t[e]);if(W)for(var e of W(t))ye.call(t,e)&&G(n,e,t[e]);return n},Q=(n,t)=>he(n,ge(t));function Ee(n){return Array.from(n.keys()).filter(t=>t.match(/META-INF\/signatures\d*\.xml$/)||t.match(/META-INF\/.*signatures.*\.xml$/i))}function we(n,t){const e=new TextDecoder().decode(n),r=j().parseFromString(e,"application/xml"),a=K(r,"ds\\:Signature, Signature");if(a.length===0){if(console.warn(`No Signature elements found in ${t}`),e.includes("XAdESSignatures")){const u=r.documentElement;if(u){const c=x(u,"ds\\:Signature, Signature");if(c){let i=Z(c,r);return i.rawXml=e,i}}const o=Ne(e);if(o)return Q(Y({},o),{rawXml:e})}return null}let s=Z(a[0],r);return s.rawXml=e,s}function Z(n,t){var e,r,a;const s=n.getAttribute("Id")||"unknown",u=x(n,"ds\\:SignedInfo, SignedInfo");if(!u)throw new Error("SignedInfo element not found");const o=x(u,"ds\\:CanonicalizationMethod, CanonicalizationMethod");let c=O.default;o&&(c=o.getAttribute("Algorithm")||c);let i="";i=se(u);const l=x(u,"ds\\:SignatureMethod, SignatureMethod"),g=(l==null?void 0:l.getAttribute("Algorithm"))||"",p=x(n,"ds\\:SignatureValue, SignatureValue"),f=((e=p==null?void 0:p.textContent)==null?void 0:e.replace(/\s+/g,""))||"",m=x(n,"ds\\:X509Certificate, X509Certificate");let y="",d="",h,C;if(m)y=((a=m.textContent)==null?void 0:a.replace(/\s+/g,""))||"";else{const E=x(n,"ds\\:KeyInfo, KeyInfo");if(E){const v=x(E,"ds\\:X509Data, X509Data");if(v){const D=x(v,"ds\\:X509Certificate, X509Certificate");D&&(y=((r=D.textContent)==null?void 0:r.replace(/\s+/g,""))||"")}}}if(y){d=H(y);try{const E=new z.X509Certificate(d),v=E.publicKey.algorithm;C=Q(Y({algorithm:v.name},"namedCurve"in v?{namedCurve:v.namedCurve}:{}),{rawData:E.publicKey.rawData}),h=q(E)}catch(E){console.error("Failed to extract certificate information:",E)}}const A=x(t,"xades\\:SigningTime, SigningTime"),$=A&&A.textContent?new Date(A.textContent.trim()):new Date,X=[],w={},N=K(u,"ds\\:Reference, Reference");for(const E of N){const v=E.getAttribute("URI")||"",D=E.getAttribute("Type")||"";if(!v||v.startsWith("#")||D.includes("SignedProperties"))continue;let L=v;try{L=decodeURIComponent(v)}catch(Ve){console.error(`Failed to decode URI: ${v}`,Ve)}const ie=L.startsWith("./")?L.substring(2):L;X.push(ie);const _=x(E,"ds\\:DigestValue, DigestValue");_&&_.textContent&&(w[ie]=_.textContent.replace(/\s+/g,""))}return{id:s,signingTime:$,certificate:y,certificatePEM:d,publicKey:C,signerInfo:h,signedChecksums:w,references:X,algorithm:g,signatureValue:f,signedInfoXml:i,canonicalizationMethod:c}}function Ne(n){try{const t=n.match(/<ds:Signature[^>]*Id=["']([^"']*)["']/),e=t&&t[1]?t[1]:"unknown",r=n.match(/<ds:SignatureValue[^>]*>([\s\S]*?)<\/ds:SignatureValue>/),a=r&&r[1]?r[1].replace(/\s+/g,""):"",s=n.match(/<ds:X509Certificate>([\s\S]*?)<\/ds:X509Certificate>/),u=s&&s[1]?s[1].replace(/\s+/g,""):"",o=n.match(/<ds:SignatureMethod[^>]*Algorithm=["']([^"']*)["']/),c=o&&o[1]?o[1]:"",i=n.match(/<xades:SigningTime>([\s\S]*?)<\/xades:SigningTime>/),l=i&&i[1]?new Date(i[1].trim()):new Date,g=[],p={},f=/<ds:Reference[^>]*URI=["']([^#][^"']*)["'][^>]*>[\s\S]*?<ds:DigestValue>([\s\S]*?)<\/ds:DigestValue>/g;let m;for(;(m=f.exec(n))!==null;)if(m[1]&&!m[1].startsWith("#")){const d=decodeURIComponent(m[1]);g.push(d),m[2]&&(p[d]=m[2].replace(/\s+/g,""))}const y=H(u);return{id:e,signingTime:l,certificate:u,certificatePEM:y,signedChecksums:p,references:g,algorithm:c,signatureValue:a}}catch(t){return console.error("Error in fallback text parsing:",t),null}}function ve(n){try{const t=I.unzipSync(n),e=new Map,r=[],a=[];Object.entries(t).forEach(([i,l])=>{e.set(i,l),i.startsWith("META-INF/")||i==="mimetype"?a.push(i):r.push(i)});const s=[],u=Ee(e),o=new Set;for(const i of u){const l=e.get(i);if(l)try{const g=we(l,i);g&&(s.push(g),g.references&&g.references.length>0&&g.references.forEach(p=>{e.has(p)&&o.add(p)}))}catch(g){console.error(`Error parsing signature ${i}:`,g)}}const c=Array.from(o);return{files:e,documentFileList:r,metadataFileList:a,signedFileList:c,signatures:s}}catch(t){throw new Error(`Failed to parse eDoc container: ${t instanceof Error?t.message:String(t)}`)}}function Se(n){const t=()=>{},e=new Uint8Array(n);if(e[0]!==48)return n;const r=[6,9,42,134,72,134,247,13,1,1,1];let a=-1;for(let m=0;m<=e.length-r.length;m++){let y=!0;for(let d=0;d<r.length;d++)if(e[m+d]!==r[d]){y=!1;break}if(y){a=m;break}}if(a===-1)return n;let s=-1;for(let m=a+r.length;m<e.length;m++)if(e[m]===3){s=m;break}if(s===-1)return n;let u=0;(e[s+1]&128)===0?u=1:u=1+(e[s+1]&127);const o=s+1+u;if(o>=e.length)return n;const c=o+1;if(c>=e.length||e[c]!==48)return n;let i=0;(e[c+1]&128)===0?i=1:i=1+(e[c+1]&127);const l=c+1+i;if(l>=e.length||e[l]!==2)return n;let g=0,p=0;if((e[l+1]&128)===0)p=e[l+1],g=1;else{const m=e[l+1]&127;g=1+m,p=0;for(let y=0;y<m;y++)p=p<<8|e[l+2+y]}const f=l+1+g;if(f>=e.length)return n;if((e[f]&128)!==0){const m=new Uint8Array(e.length+1);if(m.set(e.slice(0,f)),m[f]=0,m.set(e.slice(f),f+1),(e[l+1]&128)===0)m[l+1]=e[l+1]+1;else{const y=e[l+1]&127;let d=0;for(let h=0;h<y;h++)d=d<<8|e[l+2+h];d+=1;for(let h=y-1;h>=0;h--)m[l+2+h]=d&255,d>>=8}if((e[c+1]&128)===0)m[c+1]=e[c+1]+1;else{const y=e[c+1]&127;let d=0;for(let h=0;h<y;h++)d=d<<8|e[c+2+h];d+=1;for(let h=y-1;h>=0;h--)m[c+2+h]=d&255,d>>=8}if((e[s+1]&128)===0)m[s+1]=e[s+1]+1;else{const y=e[s+1]&127;let d=0;for(let h=0;h<y;h++)d=d<<8|e[s+2+h];d+=1;for(let h=y-1;h>=0;h--)m[s+2+h]=d&255,d>>=8}if((e[1]&128)===0)m[1]=e[1]+1;else{const y=e[1]&127;let d=0;for(let h=0;h<y;h++)d=d<<8|e[2+h];d+=1;for(let h=y-1;h>=0;h--)m[2+h]=d&255,d>>=8}return t("Fixed key length: "+m.length),m.buffer}return n}var be=Object.defineProperty,J=Object.getOwnPropertySymbols,Ce=Object.prototype.hasOwnProperty,Te=Object.prototype.propertyIsEnumerable,ee=(n,t,e)=>t in n?be(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,xe=(n,t)=>{for(var e in t||(t={}))Ce.call(t,e)&&ee(n,e,t[e]);if(J)for(var e of J(t))Te.call(t,e)&&ee(n,e,t[e]);return n},M=(n,t,e)=>new Promise((r,a)=>{var s=c=>{try{o(e.next(c))}catch(i){a(i)}},u=c=>{try{o(e.throw(c))}catch(i){a(i)}},o=c=>c.done?r(c.value):Promise.resolve(c.value).then(s,u);o((e=e.apply(n,t)).next())});function P(){return typeof window!="undefined"&&typeof window.crypto!="undefined"&&typeof window.crypto.subtle!="undefined"}function te(n,t){return M(this,null,function*(){const e=t.replace(/-/g,"").toLowerCase();let r;if(e.includes("sha256"))r="sha256";else if(e.includes("sha1"))r="sha1";else if(e.includes("sha384"))r="sha384";else if(e.includes("sha512"))r="sha512";else throw new Error(`Unsupported digest algorithm: ${t}`);return P()?Me(n,r):Ae(n,r)})}function Me(n,t){return M(this,null,function*(){const e={sha1:"SHA-1",sha256:"SHA-256",sha384:"SHA-384",sha512:"SHA-512"}[t];if(!e)throw new Error(`Unsupported browser digest algorithm: ${t}`);const r=yield window.crypto.subtle.digest(e,n),a=Array.from(new Uint8Array(r));return btoa(String.fromCharCode.apply(null,a))})}function Ae(n,t){return new Promise((e,r)=>{try{const a=require("crypto").createHash(t);a.update(Buffer.from(n)),e(a.digest("base64"))}catch(a){r(new Error(`Node digest computation failed: ${a instanceof Error?a.message:String(a)}`))}})}function ne(n,t){return M(this,null,function*(){const e={};let r=!0,a="SHA-256";n.algorithm&&(n.algorithm.includes("sha1")?a="SHA-1":n.algorithm.includes("sha384")?a="SHA-384":n.algorithm.includes("sha512")&&(a="SHA-512"));const s=Object.entries(n.signedChecksums).map(u=>M(this,[u],function*([o,c]){const i=t.get(o);if(i){const l=yield te(i,a),g=c===l;e[o]={expected:c,actual:l,matches:g,fileFound:!0},g||(r=!1)}else{const l=o.includes("/")?o.split("/").pop():o;let g=!1;if(l){for(const[p,f]of t.entries())if(p.endsWith(l)){const m=yield te(f,a),y=c===m;e[o]={expected:c,actual:m,matches:y,fileFound:!0},y||(r=!1),g=!0;break}}g||(e[o]={expected:c,actual:"",matches:!1,fileFound:!1},r=!1)}}));return yield Promise.all(s),{isValid:r,details:e}})}function $e(n){return M(this,arguments,function*(t,e=new Date){try{const r=new z.X509Certificate(t),a=ue(r,e),s=yield B(t);return{isValid:a.isValid,reason:a.reason,info:s}}catch(r){return{isValid:!1,reason:`Certificate parsing error: ${r instanceof Error?r.message:String(r)}`}}})}function re(){return P()?window.crypto.subtle:crypto.subtle}function De(n){if(typeof atob=="function"){const t=atob(n),e=new Uint8Array(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}else{const t=Buffer.from(n,"base64");return new Uint8Array(t)}}function Oe(n,t,e,r,a){return M(this,null,function*(){try{const s=j().parseFromString(n,"application/xml"),u=x(s,"ds:SignedInfo");if(!u)return{isValid:!1,reason:"SignedInfo element not found in provided XML"};const o=a||O.default,c=b.canonicalize(u,o),i=t.replace(/\s+/g,"");let l;try{l=De(i)}catch(f){return{isValid:!1,reason:`Failed to decode signature value: ${f instanceof Error?f.message:String(f)}`}}let g;try{const f=re();P()&&r.name==="RSASSA-PKCS1-v1_5"&&(e=Se(e)),g=yield f.importKey("spki",e,r,!1,["verify"])}catch(f){const m=f instanceof Error?f:new Error(String(f));let y="Unknown reason",d="KEY_IMPORT_ERROR";if(m.name==="DataError"?(y="Key data format is invalid or incompatible",d="INVALID_KEY_FORMAT"):m.name==="NotSupportedError"?(y="Algorithm or parameters not supported",d="UNSUPPORTED_ALGORITHM"):m.message.includes("namedCurve")?(y="Missing or invalid namedCurve parameter",d="INVALID_CURVE"):m.message.includes("hash")&&(y="Incompatible or unsupported hash algorithm",d="INVALID_HASH"),r.name==="ECDSA"){const h=e.byteLength;y+=` (Key length: ${h})`}return{isValid:!1,reason:`Failed to import public key: ${y}`,errorDetails:{category:d,originalMessage:m.message,algorithm:xe({},r),environment:P()?"browser":"node",keyLength:e.byteLength}}}const p=new TextEncoder().encode(c);try{const f=yield re().verify(r,g,l,p);return{isValid:f,reason:f?void 0:"Signature verification failed"}}catch(f){return{isValid:!1,reason:`Signature verification error: ${f instanceof Error?f.message:String(f)}`}}}catch(s){return{isValid:!1,reason:`SignedInfo verification error: ${s instanceof Error?s.message:String(s)}`}}})}function Ie(n,t){return M(this,arguments,function*(e,r,a={}){const s=[],u=yield $e(e.certificatePEM,a.verifyTime||e.signingTime);if(!u.isValid){const i=`Certificate validation error: ${u.reason||"Unknown reason"}`;s.push(i)}const o=a.verifyChecksums!==!1?yield ne(e,r):{isValid:!0,details:{}};if(!o.isValid){const i=Object.entries(o.details).filter(([l,g])=>!g.matches).map(([l])=>l).join(", ");s.push(`Checksum validation failed for files: ${i}`)}let c={isValid:!0};if(a.verifySignatures!==!1&&e.rawXml&&e.signatureValue&&e.publicKey){const i=e.algorithm||"",l={name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"};if(i.includes("ecdsa-sha256")?(l.name="ECDSA",l.hash="SHA-256",e.publicKey.namedCurve&&(l.namedCurve=e.publicKey.namedCurve)):i.includes("rsa-sha1")&&(l.hash="SHA-1"),c=yield Oe(e.rawXml,e.signatureValue,e.publicKey.rawData,l,e.canonicalizationMethod),!c.isValid){let g=c.reason||"XML signature verification failed";if(c.errorDetails){const p=c.errorDetails;g+=` [Category: ${p.category}, Environment: ${p.environment}`,p.algorithm&&(g+=`, Algorithm: ${p.algorithm.name}`,p.algorithm.namedCurve&&(g+=`, Curve: ${p.algorithm.namedCurve}`)),p.keyLength&&(g+=`, Key length: ${p.keyLength} bytes`),g+="]"}s.push(g)}}else if(a.verifySignatures!==!1){const i=[];e.rawXml||i.push("Signature XML"),e.signatureValue||i.push("SignatureValue"),e.publicKey||i.push("Public Key"),s.push(`Cannot verify XML signature: missing ${i.join(", ")}`),c={isValid:!1,reason:`Missing required components: ${i.join(", ")}`}}return{isValid:u.isValid&&o.isValid&&c.isValid,certificate:u,checksums:o,signature:a.verifySignatures!==!1?c:void 0,errors:s.length>0?s:void 0}})}T.CANONICALIZATION_METHODS=O,T.XMLCanonicalizer=b,T.formatValidityPeriod=de,T.getSignerDisplayName=fe,T.parseCertificate=B,T.parseEdoc=ve,T.verifyChecksums=ne,T.verifySignature=Ie,Object.defineProperty(T,"__esModule",{value:!0})}); //# sourceMappingURL=index.umd.js.map