autogram-sdk
Version:
SDK for Autogram signer
4 lines • 13.3 kB
JavaScript
var F=Object.create;var f=Object.defineProperty,H=Object.defineProperties,X=Object.getOwnPropertyDescriptor,$=Object.getOwnPropertyDescriptors,Q=Object.getOwnPropertyNames,R=Object.getOwnPropertySymbols,W=Object.getPrototypeOf,_=Object.prototype.hasOwnProperty,Y=Object.prototype.propertyIsEnumerable;var k=(o,t,e)=>t in o?f(o,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[t]=e,y=(o,t)=>{for(var e in t||(t={}))_.call(t,e)&&k(o,e,t[e]);if(R)for(var e of R(t))Y.call(t,e)&&k(o,e,t[e]);return o},G=(o,t)=>H(o,$(t));var Z=(o,t)=>{for(var e in t)f(o,e,{get:t[e],enumerable:!0})},N=(o,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Q(t))!_.call(o,n)&&n!==e&&f(o,n,{get:()=>t[n],enumerable:!(r=X(t,n))||r.enumerable});return o};var b=(o,t,e)=>(e=o!=null?F(W(o)):{},N(t||!o||!o.__esModule?f(e,"default",{value:o,enumerable:!0}):e,o)),tt=o=>N(f({},"__esModule",{value:!0}),o);var s=(o,t,e)=>new Promise((r,n)=>{var i=u=>{try{p(e.next(u))}catch(m){n(m)}},c=u=>{try{p(e.throw(u))}catch(m){n(m)}},p=u=>u.done?r(u.value):Promise.resolve(u.value).then(i,c);p((e=e.apply(o,t)).next())});var ct={};Z(ct,{AVMGetDocumentsResponse:()=>C,AutogramVMobileIntegration:()=>D,AutogramVMobileSimulation:()=>w,DesktopUserCancelledSigningException:()=>d,desktopApiClient:()=>U,randomUUID:()=>A});module.exports=tt(ct);var I=b(require("cross-fetch"));var et=Array.from(Array(256).keys()).map(o=>o.toString(16).padStart(2,"0"));function q(o){return Array.prototype.map.call(o,t=>et[t]).join("")}function O(o){return new DataView(o.buffer,0).getUint32(0)}function K(o){return crypto.getRandomValues(new Uint8Array(o))}function U(o){let t={serverProtocol:"http",serverHost:"localhost",serverPort:37200,customProtocol:"autogram",disableSecurity:!1,requestsOrigin:typeof location!="undefined"?location.origin:"*",secretKey:q(K(32)),secretInitialNonce:O(K(4)),language:"sk"},e=y(y({},t),o),r=new URL(`${e.serverProtocol}://${e.serverHost}:${e.serverPort}`);return{getLaunchURL(n="listen"){let i=new URLSearchParams;return i.set("protocol",e.serverProtocol),i.set("port",e.serverPort.toString()),i.set("host",e.serverHost),i.set("origin",e.requestsOrigin),e.language&&i.set("language",e.language),e.disableSecurity||(e.secretKey&&i.set("key",e.secretKey),e.secretInitialNonce&&i.set("nonce",e.secretInitialNonce.toString())),`${e.customProtocol}://${n}?${i}`},info(){let n=new URL("info",r),i={cache:"no-store"};return(0,I.default)(n.toString(),i).then(c=>c.json())},waitForStatus(n,i=60,c=4,p){let u=new URL("info",r);return new Promise((m,h)=>s(this,null,function*(){let l,T,j=new Error("No request ever finished"),P=!1;p&&p.signal.addEventListener("abort",()=>{l.signal.aborted||l.abort(),P=!0,h(new Error("Aborted"))});let L=setTimeout(()=>{l.signal.aborted||l.abort(),P=!0,h(j)},i*1e3);for(;!P;){l=new AbortController;let B=setTimeout(()=>{l.signal.aborted||l.abort()},(c+1)*1e3);try{if(T=yield(yield(0,I.default)(u.toString(),{cache:"no-store",signal:l.signal})).json(),T.status===n){P=!0,clearTimeout(L),clearTimeout(B),m(T);break}}catch(v){clearTimeout(B),v.name!=="AbortError"&&(j=v)}yield new Promise(v=>setTimeout(v,c*1e3))}}))},sign(n,i={level:"XAdES_BASELINE_B",checkPDFACompliance:!0},c="application/xml"){let p=new URL("sign",r),m={method:"POST",headers:{"Content-Type":"text/plain"},cache:"no-store",body:JSON.stringify({document:n,parameters:i,payloadMimeType:c})};return(0,I.default)(p.toString(),m).then(h=>{if(h.status==204)throw new d;return h.json()})}}}var d=class{};var z=require("jose"),a=b(require("zod")),J=require("js-base64");var D=class{constructor(t){this.keyPair=null;this.integrationGuid=null;this._subtleCrypto=null;this.apiClient=new x,this.db=t}get subtleCrypto(){if(!this._subtleCrypto)throw new Error("SubtleCrypto not available");return this._subtleCrypto}loadOrRegister(){return s(this,null,function*(){this.loadSubtleCrypto(),this.keyPair=yield this.getKeyPairFromDb(),this.integrationGuid=yield this.getIntegrationGuidFromDb(),console.log(this.keyPair),(!this.keyPair||!this.integrationGuid)&&(yield this.register()),console.log("keys init",{public:yield this.getPublicKeyStr(),guid:this.integrationGuid})})}getQrCodeUrl(t,e=!1){return s(this,null,function*(){if(!this.integrationGuid)throw new Error("Integration guid missing");if(!t.guid||!t.encryptionKey)throw console.log(t),new Error("Document guid or key missing");let r={};if(e){let n=yield this.getIntegrationBearerToken(!0);console.log("Integration JWT",n),r={integration:n}}return this.apiClient.qrCodeUrl(y({guid:t.guid,key:t.encryptionKey},r))})}register(){return s(this,null,function*(){if(this.keyPair&&this.integrationGuid)throw new Error("Already registered.");yield this.generateKeys();let t=yield this.getPublicKeyStr();console.log("Registering integration",t);let e=yield this.apiClient.registerIntegration({platform:"extension",displayName:"Autogram Extension",publicKey:`-----BEGIN PUBLIC KEY-----
`+t+`
-----END PUBLIC KEY-----`});this.integrationGuid=e.guid,yield this.saveIntegrationGuid(e.guid),console.log("Integration registered",e)})}addDocument(t){return s(this,null,function*(){let e=yield this.initDocumentKey();console.log("Sending document",t);let r=yield this.apiClient.postDocuments(t,yield this.getIntegrationBearerToken(),e);return{guid:r.guid,encryptionKey:e,lastModified:r.lastModified}})}waitForSignature(t,e){return s(this,null,function*(){if(!t.guid||!t.encryptionKey||!t.lastModified)throw console.log(t),new Error("Document guid, key or last-modified missing");for(this.apiClient.signRequest({documentGuid:t.guid,documentEncryptionKey:t.encryptionKey},yield this.getIntegrationBearerToken());!e.signal.aborted;){let r=yield this.apiClient.getDocument({guid:t.guid},t.encryptionKey,t.lastModified);if(console.log(r),r.status==="signed")return r.document;r.status,yield it(1e3)}throw new Error("Aborted")})}loadSubtleCrypto(){return s(this,null,function*(){if(!this._subtleCrypto){let t=globalThis.crypto.subtle;if(t){this._subtleCrypto=t;return}try{let e=yield import("crypto");this._subtleCrypto=e.webcrypto.subtle;return}catch(e){throw new Error("SubtleCrypto not available")}}})}getIntegrationBearerToken(t=!1){return s(this,null,function*(){if(!this.keyPair)throw new Error("Key pair missing");if(!this.integrationGuid)throw new Error("Integration guid missing");let e=new z.SignJWT({}).setProtectedHeader({alg:"ES256"}).setJti(A()).setSubject(this.integrationGuid);return t&&(e=e.setAudience("device")),e=e.setExpirationTime("5min"),e.sign(this.keyPair.privateKey)})}exportRawBase64(t){return this.subtleCrypto.exportKey("raw",t).then(M)}generateKeys(){return s(this,null,function*(){console.log("Generating keys");let t=yield this.subtleCrypto.generateKey({name:"ECDSA",namedCurve:"P-256"},!0,["sign","verify"]);console.log("Key pair generated",t),yield this.saveKeyPair(t),this.keyPair=t,console.log("Keys generated",this.keyPair)})}saveKeyPair(t){return s(this,null,function*(){return this.db.set("keyPair",t)})}getKeyPairFromDb(){return s(this,null,function*(){return this.db.get("keyPair").then(t=>t||null)})}saveIntegrationGuid(t){return s(this,null,function*(){return this.db.set("integrationGuid",t)})}getIntegrationGuidFromDb(){return s(this,null,function*(){return this.db.get("integrationGuid").then(t=>t||null)})}getPublicKeyStr(){return s(this,null,function*(){if(!this.keyPair)throw new Error("Key pair missing");return this.subtleCrypto.exportKey("spki",this.keyPair.publicKey).then(M)})}initDocumentKey(){return s(this,null,function*(){let t=yield this.subtleCrypto.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]);return yield this.exportRawBase64(t)})}},x=class{constructor(){this._registerIntegration="/integrations";this._getIntegrationDevices="/integration-devices";this._documents="/documents";this._getDocument="/documents/{guid}";this._signRequest="/sign-request";this._getQrCodeUrl="/qr-code";this.baseUrl="https://autogram.slovensko.digital/api/v1"}registerIntegration(t){let e=JSON.stringify(t),r=this.baseUrl+this._registerIntegration;return console.log("Registering integration",{url:r,requestBody:e}),fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:e}).then(n=>s(this,null,function*(){let i=yield n.text();return console.log("Integration registration response",{text:i,status:n.status,statusText:n.statusText}),JSON.parse(i)})).catch(n=>{throw console.error("Integration registration failed",n),n}).then(n=>nt.parse(n))}getIntegrationDevices(){return fetch(this.baseUrl+this._getIntegrationDevices,{method:"GET"}).then(t=>ot.parse(t.json()))}postDocuments(t,e,r){return s(this,null,function*(){if(!r)throw new Error("Document encryption key missing");if(!e)throw new Error("Bearer token missing");let n=yield fetch(this.baseUrl+this._documents,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+e,"X-Encryption-Key":r},body:JSON.stringify(t)});if(n.status!==200){console.log("API Error",n.status,n.statusText);let c=yield n.json();throw new Error(JSON.stringify(V.parse(c)))}let i=yield n.json();return G(y({},rt.parse(i)),{lastModified:n.headers.get("Last-Modified")})})}getDocument(t,e,r){return s(this,null,function*(){if(!e)throw new Error("Document encryption key missing");let n=yield fetch(this.baseUrl+this._getDocument.replace("{guid}",t.guid),{method:"GET",headers:y({"Content-Type":"application/json",Accept:"application/json","X-Encryption-Key":e},r?{"If-Modified-Since":r}:null)});if(n.status==304)return{status:"pending"};if(n.status!=200){let c=V.parse(yield n.json());throw console.error("API Error",c),new Error(JSON.stringify(c))}let i=yield n.json();return{status:"signed",document:C.parse(i)}})}signRequest(t,e){return fetch(this.baseUrl+this._signRequest,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)}).then(r=>r.json())}qrCodeUrl(t){return this.baseUrl+this._getQrCodeUrl+"?"+new URLSearchParams(t).toString()}},nt=a.default.object({guid:a.default.string()}),ot=a.default.array(a.default.object({deviceId:a.default.string(),platform:a.default.string(),displayName:a.default.string()})),rt=a.default.object({guid:a.default.string()}),V=a.default.object({code:a.default.string(),message:a.default.string(),details:a.default.string().optional()}),C=a.default.object({filename:a.default.string(),mimeType:a.default.string(),content:a.default.string(),signers:a.default.array(a.default.object({signedBy:a.default.string().optional(),issuedBy:a.default.string().optional()})).optional()});function M(o){return J.Base64.fromUint8Array(new Uint8Array(o))}function A(){return globalThis.crypto.randomUUID()}function it(o){return s(this,null,function*(){return new Promise(t=>setTimeout(t,o))})}var S=b(require("cross-fetch")),g=b(require("zod"));var w=class{constructor(){this.apiClient=new E}parseUrl(t){let e=new URL(t),r=e.searchParams.get("guid"),n=e.searchParams.get("key"),i=e.searchParams.get("integration");if(console.log({guid:r,key:n,integrationJwt:i}),!r||!n)throw new Error("Invalid URL");this.guid=r,this.encryptionKey=n}visualizeDocument(){return console.log("Document visualized",this.guid,this.encryptionKey),this.apiClient.getDocumentVisualization({guid:this.guid},this.encryptionKey).then(t=>(console.log("Document visualization",t),t))}signDocument(){return s(this,null,function*(){let t=yield this.apiClient.getDocumentSignatureParameters({guid:this.guid},this.encryptionKey);console.log("Signature parameters",t)})}},E=class{constructor(){this._getDocumentVisualization="/documents/{guid}/visualization";this._getDocumentSignatureParameters="/documents/{guid}/parameters";this._postDocumentDataToSign="/documents/{guid}/datatosign";this._postDocumentSign="/documents/{guid}/sign";this.baseUrl="https://autogram.slovensko.digital/api/v1"}getDocumentVisualization(t,e){return(0,S.default)(this.baseUrl+this._getDocumentVisualization.replace("{guid}",t.guid),{method:"GET",headers:{Accept:"application/json","Content-Type":"application/json","X-Encryption-Key":e}}).then(r=>r.json()).then(st.parse)}getDocumentSignatureParameters(t,e){return(0,S.default)(this.baseUrl+this._getDocumentSignatureParameters.replace("{guid}",t.guid),{method:"GET",headers:{Accept:"application/json","Content-Type":"application/json","X-Encryption-Key":e}}).then(r=>r.json())}postDocumentDataToSign(t,e,r){return(0,S.default)(this.baseUrl+this._postDocumentDataToSign.replace("{guid}",t.guid),{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","X-Encryption-Key":r},body:JSON.stringify(e)}).then(n=>n.json()).then(at.parse)}postDocumentSign(t,e,r){return(0,S.default)(this.baseUrl+this._postDocumentSign.replace("{guid}",t.guid),{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","X-Encryption-Key":r},body:JSON.stringify(e)}).then(n=>n.json()).then(gt.parse)}},st=g.default.object({mimeType:g.default.string(),filename:g.default.string().optional(),content:g.default.string()}),at=g.default.object({dataToSign:g.default.string(),signingTime:g.default.number(),signingCertificate:g.default.string()}),gt=g.default.object({filename:g.default.string(),mimeType:g.default.string(),content:g.default.string(),signedBy:g.default.string(),issuedBy:g.default.string()});
//# sourceMappingURL=index.js.map