autogram-sdk
Version:
SDK for Autogram signer
4 lines • 11 kB
JavaScript
var A=Object.create;var p=Object.defineProperty,B=Object.defineProperties,k=Object.getOwnPropertyDescriptor,x=Object.getOwnPropertyDescriptors,G=Object.getOwnPropertyNames,C=Object.getOwnPropertySymbols,N=Object.getPrototypeOf,I=Object.prototype.hasOwnProperty,R=Object.prototype.propertyIsEnumerable;var v=(o,t,e)=>t in o?p(o,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[t]=e,y=(o,t)=>{for(var e in t||(t={}))I.call(t,e)&&v(o,e,t[e]);if(C)for(var e of C(t))R.call(t,e)&&v(o,e,t[e]);return o},K=(o,t)=>B(o,x(t));var q=(o,t)=>{for(var e in t)p(o,e,{get:t[e],enumerable:!0})},T=(o,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of G(t))!I.call(o,n)&&n!==e&&p(o,n,{get:()=>t[n],enumerable:!(i=k(t,n))||i.enumerable});return o};var m=(o,t,e)=>(e=o!=null?A(N(o)):{},T(t||!o||!o.__esModule?p(e,"default",{value:o,enumerable:!0}):e,o)),O=o=>T(p({},"__esModule",{value:!0}),o);var s=(o,t,e)=>new Promise((i,n)=>{var g=u=>{try{b(e.next(u))}catch(f){n(f)}},c=u=>{try{b(e.throw(u))}catch(f){n(f)}},b=u=>u.done?i(u.value):Promise.resolve(u.value).then(g,c);b((e=e.apply(o,t)).next())});var L={};q(L,{AutogramVMobileIntegration:()=>d,AutogramVMobileSimulation:()=>h,GetDocumentsResponse:()=>w,randomUUID:()=>P});module.exports=O(L);var _=require("jose"),r=m(require("zod")),U=require("js-base64");var d=class{constructor(t){this.keyPair=null;this.integrationGuid=null;this._subtleCrypto=null;this.apiClient=new D,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 i={};if(e){let n=yield this.getIntegrationBearerToken(!0);console.log("Integration JWT",n),i={integration:n}}return this.apiClient.qrCodeUrl(y({guid:t.guid,key:t.encryptionKey},i))})}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 i=yield this.apiClient.postDocuments(t,yield this.getIntegrationBearerToken(),e);return{guid:i.guid,encryptionKey:e,lastModified:i.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 i=yield this.apiClient.getDocument({guid:t.guid},t.encryptionKey,t.lastModified);if(console.log(i),i.status==="signed")return i.document;i.status,yield V(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 _.SignJWT({}).setProtectedHeader({alg:"ES256"}).setJti(P()).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(E)}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(E)})}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)})}},D=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),i=this.baseUrl+this._registerIntegration;return console.log("Registering integration",{url:i,requestBody:e}),fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:e}).then(n=>s(this,null,function*(){let g=yield n.text();return console.log("Integration registration response",{text:g,status:n.status,statusText:n.statusText}),JSON.parse(g)})).catch(n=>{throw console.error("Integration registration failed",n),n}).then(n=>z.parse(n))}getIntegrationDevices(){return fetch(this.baseUrl+this._getIntegrationDevices,{method:"GET"}).then(t=>J.parse(t.json()))}postDocuments(t,e,i){return s(this,null,function*(){if(!i)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":i},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(j.parse(c)))}let g=yield n.json();return K(y({},M.parse(g)),{lastModified:n.headers.get("Last-Modified")})})}getDocument(t,e,i){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},i?{"If-Modified-Since":i}:null)});if(n.status==304)return{status:"pending"};if(n.status!=200){let c=j.parse(yield n.json());throw console.error("API Error",c),new Error(JSON.stringify(c))}let g=yield n.json();return{status:"signed",document:w.parse(g)}})}signRequest(t,e){return fetch(this.baseUrl+this._signRequest,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)}).then(i=>i.json())}qrCodeUrl(t){return this.baseUrl+this._getQrCodeUrl+"?"+new URLSearchParams(t).toString()}},z=r.default.object({guid:r.default.string()}),J=r.default.array(r.default.object({deviceId:r.default.string(),platform:r.default.string(),displayName:r.default.string()})),M=r.default.object({guid:r.default.string()}),j=r.default.object({code:r.default.string(),message:r.default.string(),details:r.default.string().optional()}),w=r.default.object({filename:r.default.string(),mimeType:r.default.string(),content:r.default.string(),signers:r.default.array(r.default.object({signedBy:r.default.string().optional(),issuedBy:r.default.string().optional()})).optional()});function E(o){return U.Base64.fromUint8Array(new Uint8Array(o))}function P(){return globalThis.crypto.randomUUID()}function V(o){return s(this,null,function*(){return new Promise(t=>setTimeout(t,o))})}var l=m(require("cross-fetch")),a=m(require("zod"));var h=class{constructor(){this.apiClient=new S}parseUrl(t){let e=new URL(t),i=e.searchParams.get("guid"),n=e.searchParams.get("key"),g=e.searchParams.get("integration");if(console.log({guid:i,key:n,integrationJwt:g}),!i||!n)throw new Error("Invalid URL");this.guid=i,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)})}},S=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,l.default)(this.baseUrl+this._getDocumentVisualization.replace("{guid}",t.guid),{method:"GET",headers:{Accept:"application/json","Content-Type":"application/json","X-Encryption-Key":e}}).then(i=>i.json()).then(F.parse)}getDocumentSignatureParameters(t,e){return(0,l.default)(this.baseUrl+this._getDocumentSignatureParameters.replace("{guid}",t.guid),{method:"GET",headers:{Accept:"application/json","Content-Type":"application/json","X-Encryption-Key":e}}).then(i=>i.json())}postDocumentDataToSign(t,e,i){return(0,l.default)(this.baseUrl+this._postDocumentDataToSign.replace("{guid}",t.guid),{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","X-Encryption-Key":i},body:JSON.stringify(e)}).then(n=>n.json()).then(Q.parse)}postDocumentSign(t,e,i){return(0,l.default)(this.baseUrl+this._postDocumentSign.replace("{guid}",t.guid),{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","X-Encryption-Key":i},body:JSON.stringify(e)}).then(n=>n.json()).then(X.parse)}},F=a.default.object({mimeType:a.default.string(),filename:a.default.string().optional(),content:a.default.string()}),Q=a.default.object({dataToSign:a.default.string(),signingTime:a.default.number(),signingCertificate:a.default.string()}),X=a.default.object({filename:a.default.string(),mimeType:a.default.string(),content:a.default.string(),signedBy:a.default.string(),issuedBy:a.default.string()});
//# sourceMappingURL=index.js.map