@vitia.ai/secure-api-client-vue 0.1.3 → 0.1.4

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/dist/index.cjs CHANGED
@@ -61,5 +61,5 @@
61
61
  ${e.join(`
62
62
  `)}`:`${t} :`}}Ht=Q;d.Constructed=Ht;Q.NAME="CONSTRUCTED";class Lt extends x{fromBER(e,t,r){return t}toBER(e){return T}}Lt.override="EndOfContentValueBlock";var Rt;class Mt extends A{constructor(e={}){super(e,Lt),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}}Rt=Mt;d.EndOfContent=Rt;Mt.NAME=ae;var Ot;class Dt extends A{constructor(e={}){super(e,x),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,t,r){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=r,t+r>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):t+r}toBER(e,t){const r=new ArrayBuffer(2);if(!e){const s=new Uint8Array(r);s[0]=5,s[1]=0}return t&&t.write(r),r}onAsciiEncoding(){return`${this.constructor.NAME}`}}Ot=Dt;d.Null=Ot;Dt.NAME="NULL";class $t extends L(x){get value(){for(const e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=y.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}fromBER(e,t,r){const s=y.toUint8Array(e);return H(this,s,t,r)?(this.valueHexView=s.subarray(t,t+r),r>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,xt.call(this),this.blockLength=r,t+r):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}}$t.NAME="BooleanValueBlock";var Pt;class Ft extends A{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(e={}){super(e,$t),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}}Pt=Ft;d.Boolean=Pt;Ft.NAME="BOOLEAN";class jt extends L(O){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,r){let s=0;if(this.isConstructed){if(this.isHexOnly=!1,s=O.prototype.fromBER.call(this,e,t,r),s===-1)return s;for(let i=0;i<this.value.length;i++){const o=this.value[i].constructor.NAME;if(o===ae){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(o!==Et)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,s=super.fromBER(e,t,r),this.blockLength=r;return s}toBER(e,t){return this.isConstructed?O.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}}jt.NAME="OctetStringValueBlock";var Re;class qt extends A{constructor({idBlock:e={},lenBlock:t={},...r}={}){var s,i;(s=r.isConstructed)!==null&&s!==void 0||(r.isConstructed=!!(!((i=r.value)===null||i===void 0)&&i.length)),super({idBlock:{isConstructed:r.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!r.isIndefiniteForm},...r},jt),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,r){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,r===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),t;if(!this.valueBlock.isConstructed){const i=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+r);try{if(i.byteLength){const o=we(i,0,i.byteLength);o.offset!==-1&&o.offset===r&&(this.valueBlock.value=[o.result])}}catch{}}return super.fromBER(e,t,r)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return Q.prototype.onAsciiEncoding.call(this);const e=this.constructor.NAME,t=v.ToHex(this.valueBlock.valueHexView);return`${e} : ${t}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;const e=[];for(const t of this.valueBlock.value)t instanceof Re&&e.push(t.valueBlock.valueHexView);return y.concat(e)}}Re=qt;d.OctetString=Re;qt.NAME=Et;class Gt extends L(O){constructor({unusedBits:e=0,isConstructed:t=!1,...r}={}){super(r),this.unusedBits=e,this.isConstructed=t,this.blockLength=this.valueHexView.byteLength}fromBER(e,t,r){if(!r)return t;let s=-1;if(this.isConstructed){if(s=O.prototype.fromBER.call(this,e,t,r),s===-1)return s;for(const c of this.value){const a=c.constructor.NAME;if(a===ae){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(a!==pt)return this.error="BIT STRING may consists of BIT STRINGs only",-1;const u=c.valueBlock;if(this.unusedBits>0&&u.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=u.unusedBits}return s}const i=y.toUint8Array(e);if(!H(this,i,t,r))return-1;const o=i.subarray(t,t+r);if(this.unusedBits=o[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){const c=o.subarray(1);try{if(c.byteLength){const a=we(c,0,c.byteLength);a.offset!==-1&&a.offset===r-1&&(this.value=[a.result])}}catch{}}return this.valueHexView=o.subarray(1),this.blockLength=o.length,t+r}toBER(e,t){if(this.isConstructed)return O.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength){const s=new Uint8Array(1);return s[0]=0,s.buffer}const r=new Uint8Array(this.valueHexView.length+1);return r[0]=this.unusedBits,r.set(this.valueHexView,1),r.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}}Gt.NAME="BitStringValueBlock";var Jt;class Me extends A{constructor({idBlock:e={},lenBlock:t={},...r}={}){var s,i;(s=r.isConstructed)!==null&&s!==void 0||(r.isConstructed=!!(!((i=r.value)===null||i===void 0)&&i.length)),super({idBlock:{isConstructed:r.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!r.isIndefiniteForm},...r},Gt),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,r){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,r)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return Q.prototype.onAsciiEncoding.call(this);{const e=[],t=this.valueBlock.valueHexView;for(const o of t)e.push(o.toString(2).padStart(8,"0"));const r=e.join(""),s=this.constructor.NAME,i=r.substring(0,r.length-this.valueBlock.unusedBits);return`${s} : ${i}`}}}Jt=Me;d.BitString=Jt;Me.NAME=pt;var Kt;function Ts(n,e){const t=new Uint8Array([0]),r=new Uint8Array(n),s=new Uint8Array(e);let i=r.slice(0);const o=i.length-1,c=s.slice(0),a=c.length-1;let u=0;const f=a<o?o:a;let h=0;for(let l=f;l>=0;l--,h++){switch(!0){case h<c.length:u=i[o-h]+c[a-h]+t[0];break;default:u=i[o-h]+t[0]}switch(t[0]=u/10,!0){case h>=i.length:i=Ne(new Uint8Array([u%10]),i);break;default:i[o-h]=u%10}}return t[0]>0&&(i=Ne(t,i)),i}function it(n){if(n>=se.length)for(let e=se.length;e<=n;e++){const t=new Uint8Array([0]);let r=se[e-1].slice(0);for(let s=r.length-1;s>=0;s--){const i=new Uint8Array([(r[s]<<1)+t[0]]);t[0]=i[0]/10,r[s]=i[0]%10}t[0]>0&&(r=Ne(t,r)),se.push(r)}return se[n]}function Cs(n,e){let t=0;const r=new Uint8Array(n),s=new Uint8Array(e),i=r.slice(0),o=i.length-1,c=s.slice(0),a=c.length-1;let u,f=0;for(let h=a;h>=0;h--,f++)switch(u=i[o-f]-c[a-f]-t,!0){case u<0:t=1,i[o-f]=u+10;break;default:t=0,i[o-f]=u}if(t>0)for(let h=o-a+1;h>=0;h--,f++)if(u=i[o-f]-t,u<0)t=1,i[o-f]=u+10;else{t=0,i[o-f]=u;break}return i.slice()}class Oe extends L(x){setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=xt.call(this)))}constructor({value:e,...t}={}){super(t),this._valueDec=0,t.valueHex&&this.setValueHex(),e!==void 0&&(this.valueDec=e)}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(ps(e))}get valueDec(){return this._valueDec}fromDER(e,t,r,s=0){const i=this.fromBER(e,t,r);if(i===-1)return i;const o=this.valueHexView;return o[0]===0&&o[1]&128?this.valueHexView=o.subarray(1):s!==0&&o.length<s&&(s-o.length>1&&(s=o.length+1),this.valueHexView=o.subarray(s-o.length)),i}toDER(e=!1){const t=this.valueHexView;switch(!0){case(t[0]&128)!==0:{const r=new Uint8Array(this.valueHexView.length+1);r[0]=0,r.set(t,1),this.valueHexView=r}break;case(t[0]===0&&(t[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(e)}fromBER(e,t,r){const s=super.fromBER(e,t,r);return s===-1||this.setValueHex(),s}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){const e=this.valueHexView.length*8-1;let t=new Uint8Array(this.valueHexView.length*8/3),r=0,s;const i=this.valueHexView;let o="",c=!1;for(let a=i.byteLength-1;a>=0;a--){s=i[a];for(let u=0;u<8;u++){if((s&1)===1)switch(r){case e:t=Cs(it(r),t),o="-";break;default:t=Ts(t,it(r))}r++,s>>=1}}for(let a=0;a<t.length;a++)t[a]&&(c=!0),c&&(o+=nt.charAt(t[a]));return c===!1&&(o+=nt.charAt(0)),o}}Kt=Oe;Oe.NAME="IntegerValueBlock";Object.defineProperty(Kt.prototype,"valueHex",{set:function(n){this.valueHexView=new Uint8Array(n),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var oe;class De extends A{constructor(e={}){super(e,Oe),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return de(),BigInt(this.valueBlock.toString())}static fromBigInt(e){de();const t=BigInt(e),r=new He,s=t.toString(16).replace(/^-/,""),i=new Uint8Array(v.FromHex(s));if(t<0){const c=new Uint8Array(i.length+(i[0]&128?1:0));c[0]|=128;const u=BigInt(`0x${v.ToHex(c)}`)+t,f=y.toUint8Array(v.FromHex(u.toString(16)));f[0]|=128,r.write(f)}else i[0]&128&&r.write(new Uint8Array([0])),r.write(i);return new oe({valueHex:r.final()})}convertToDER(){const e=new oe({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new oe({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}}oe=De;d.Integer=oe;De.NAME="INTEGER";var Wt;class Zt extends De{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}}Wt=Zt;d.Enumerated=Wt;Zt.NAME="ENUMERATED";class Ie extends L(x){constructor({valueDec:e=-1,isFirstSid:t=!1,...r}={}){super(r),this.valueDec=e,this.isFirstSid=t}fromBER(e,t,r){if(!r)return t;const s=y.toUint8Array(e);if(!H(this,s,t,r))return-1;const i=s.subarray(t,t+r);this.valueHexView=new Uint8Array(r);for(let c=0;c<r&&(this.valueHexView[c]=i[c]&127,this.blockLength++,!!(i[c]&128));c++);const o=new Uint8Array(this.blockLength);for(let c=0;c<this.blockLength;c++)o[c]=this.valueHexView[c];return this.valueHexView=o,i[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=X(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){de();let t=BigInt(e).toString(2);for(;t.length%7;)t="0"+t;const r=new Uint8Array(t.length/7);for(let s=0;s<r.length;s++)r[s]=parseInt(t.slice(s*7,s*7+7),2)+(s+1<r.length?128:0);this.fromBER(r.buffer,0,r.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);const s=this.valueHexView,i=new Uint8Array(this.blockLength);for(let o=0;o<this.blockLength-1;o++)i[o]=s[o]|128;return i[this.blockLength-1]=s[this.blockLength-1],i.buffer}const t=j(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",T;const r=new Uint8Array(t.byteLength);if(!e){const s=new Uint8Array(t),i=t.byteLength-1;for(let o=0;o<i;o++)r[o]=s[o]|128;r[i]=s[i]}return r}toString(){let e="";if(this.isHexOnly)e=v.ToHex(this.valueHexView);else if(this.isFirstSid){let t=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",t-=40):(e="2.",t-=80),e+=t.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}}Ie.NAME="sidBlock";class zt extends x{constructor({value:e=Y,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,r){let s=t;for(;r>0;){const i=new Ie;if(s=i.fromBER(e,s,r),s===-1)return this.blockLength=0,this.error=i.error,s;this.value.length===0&&(i.isFirstSid=!0),this.blockLength+=i.blockLength,r-=i.blockLength,this.value.push(i)}return s}toBER(e){const t=[];for(let r=0;r<this.value.length;r++){const s=this.value[r].toBER(e);if(s.byteLength===0)return this.error=this.value[r].error,T;t.push(s)}return _e(t)}fromString(e){this.value=[];let t=0,r=0,s="",i=!1;do if(r=e.indexOf(".",t),r===-1?s=e.substring(t):s=e.substring(t,r),t=r+1,i){const o=this.value[0];let c=0;switch(o.valueDec){case 0:break;case 1:c=40;break;case 2:c=80;break;default:this.value=[];return}const a=parseInt(s,10);if(isNaN(a))return;o.valueDec=a+c,i=!1}else{const o=new Ie;if(s>Number.MAX_SAFE_INTEGER){de();const c=BigInt(s);o.valueBigInt=c}else if(o.valueDec=parseInt(s,10),isNaN(o.valueDec))return;this.value.length||(o.isFirstSid=!0,i=!0),this.value.push(o)}while(r!==-1)}toString(){let e="",t=!1;for(let r=0;r<this.value.length;r++){t=this.value[r].isHexOnly;let s=this.value[r].toString();r!==0&&(e=`${e}.`),t?(s=`{${s}}`,this.value[r].isFirstSid?e=`2.{${s} - 80}`:e+=s):e+=s}return e}toJSON(){const e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}}zt.NAME="ObjectIdentifierValueBlock";var Xt;class $e extends A{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,zt),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}}Xt=$e;d.ObjectIdentifier=Xt;$e.NAME="OBJECT IDENTIFIER";class Ue extends L(q){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,r){if(r===0)return t;const s=y.toUint8Array(e);if(!H(this,s,t,r))return-1;const i=s.subarray(t,t+r);this.valueHexView=new Uint8Array(r);for(let c=0;c<r&&(this.valueHexView[c]=i[c]&127,this.blockLength++,!!(i[c]&128));c++);const o=new Uint8Array(this.blockLength);for(let c=0;c<this.blockLength;c++)o[c]=this.valueHexView[c];return this.valueHexView=o,i[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=X(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);const s=this.valueHexView,i=new Uint8Array(this.blockLength);for(let o=0;o<this.blockLength-1;o++)i[o]=s[o]|128;return i[this.blockLength-1]=s[this.blockLength-1],i.buffer}const t=j(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",T;const r=new Uint8Array(t.byteLength);if(!e){const s=new Uint8Array(t),i=t.byteLength-1;for(let o=0;o<i;o++)r[o]=s[o]|128;r[i]=s[i]}return r.buffer}toString(){let e="";return this.isHexOnly?e=v.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}}Ue.NAME="relativeSidBlock";class Yt extends x{constructor({value:e=Y,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,r){let s=t;for(;r>0;){const i=new Ue;if(s=i.fromBER(e,s,r),s===-1)return this.blockLength=0,this.error=i.error,s;this.blockLength+=i.blockLength,r-=i.blockLength,this.value.push(i)}return s}toBER(e,t){const r=[];for(let s=0;s<this.value.length;s++){const i=this.value[s].toBER(e);if(i.byteLength===0)return this.error=this.value[s].error,T;r.push(i)}return _e(r)}fromString(e){this.value=[];let t=0,r=0,s="";do{r=e.indexOf(".",t),r===-1?s=e.substring(t):s=e.substring(t,r),t=r+1;const i=new Ue;if(i.valueDec=parseInt(s,10),isNaN(i.valueDec))return!0;this.value.push(i)}while(r!==-1);return!0}toString(){let e="",t=!1;for(let r=0;r<this.value.length;r++){t=this.value[r].isHexOnly;let s=this.value[r].toString();r!==0&&(e=`${e}.`),t&&(s=`{${s}}`),e+=s}return e}toJSON(){const e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}}Yt.NAME="RelativeObjectIdentifierValueBlock";var Qt;class er extends A{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,Yt),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}}Qt=er;d.RelativeObjectIdentifier=Qt;er.NAME="RelativeObjectIdentifier";var tr;class ge extends Q{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}}tr=ge;d.Sequence=tr;ge.NAME="SEQUENCE";var rr;class sr extends Q{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}}rr=sr;d.Set=rr;sr.NAME="SET";class nr extends L(x){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=Y}toJSON(){return{...super.toJSON(),value:this.value}}}nr.NAME="StringValueBlock";class ir extends nr{}ir.NAME="SimpleStringValueBlock";class N extends Vt{constructor({...e}={}){super(e,ir)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,y.toUint8Array(e))}fromString(e){const t=e.length,r=this.valueBlock.valueHexView=new Uint8Array(t);for(let s=0;s<t;s++)r[s]=e.charCodeAt(s);this.valueBlock.value=e}}N.NAME="SIMPLE STRING";class or extends N{fromBuffer(e){this.valueBlock.valueHexView=y.toUint8Array(e);try{this.valueBlock.value=v.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=v.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(v.FromUtf8String(e)),this.valueBlock.value=e}}or.NAME="Utf8StringValueBlock";var cr;class G extends or{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}}cr=G;d.Utf8String=cr;G.NAME="UTF8String";class ar extends N{fromBuffer(e){this.valueBlock.value=v.ToUtf16String(e),this.valueBlock.valueHexView=y.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(v.FromUtf16String(e))}}ar.NAME="BmpStringValueBlock";var lr;class ur extends ar{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}}lr=ur;d.BmpString=lr;ur.NAME="BMPString";class hr extends N{fromBuffer(e){const t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),r=new Uint8Array(t);for(let s=0;s<r.length;s+=4)r[s]=r[s+3],r[s+1]=r[s+2],r[s+2]=0,r[s+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(t))}fromString(e){const t=e.length,r=this.valueBlock.valueHexView=new Uint8Array(t*4);for(let s=0;s<t;s++){const i=j(e.charCodeAt(s),8),o=new Uint8Array(i);if(o.length>4)continue;const c=4-o.length;for(let a=o.length-1;a>=0;a--)r[s*4+a+c]=o[a]}this.valueBlock.value=e}}hr.NAME="UniversalStringValueBlock";var fr;class dr extends hr{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}}fr=dr;d.UniversalString=fr;dr.NAME="UniversalString";var gr;class wr extends N{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}}gr=wr;d.NumericString=gr;wr.NAME="NumericString";var yr;class Br extends N{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}}yr=Br;d.PrintableString=yr;Br.NAME="PrintableString";var br;class vr extends N{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}}br=vr;d.TeletexString=br;vr.NAME="TeletexString";var kr;class mr extends N{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}}kr=mr;d.VideotexString=kr;mr.NAME="VideotexString";var Ar;class Sr extends N{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}}Ar=Sr;d.IA5String=Ar;Sr.NAME="IA5String";var xr;class Er extends N{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}}xr=Er;d.GraphicString=xr;Er.NAME="GraphicString";var pr;class Pe extends N{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}}pr=Pe;d.VisibleString=pr;Pe.NAME="VisibleString";var Nr;class Ir extends N{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}}Nr=Ir;d.GeneralString=Nr;Ir.NAME="GeneralString";var Ur;class Vr extends N{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}}Ur=Vr;d.CharacterString=Ur;Vr.NAME="CharacterString";var Tr;class Fe extends Pe{constructor({value:e,valueDate:t,...r}={}){if(super(r),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let s=0;s<e.length;s++)this.valueBlock.valueHexView[s]=e.charCodeAt(s)}t&&(this.fromDate(t),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,y.toUint8Array(e)))}toBuffer(){const e=this.toString(),t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let s=0;s<e.length;s++)r[s]=e.charCodeAt(s);return t}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){const r=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(e);if(r===null){this.error="Wrong input string for conversion";return}const s=parseInt(r[1],10);s>=50?this.year=1900+s:this.year=2e3+s,this.month=parseInt(r[2],10),this.day=parseInt(r[3],10),this.hour=parseInt(r[4],10),this.minute=parseInt(r[5],10),this.second=parseInt(r[6],10)}toString(e="iso"){if(e==="iso"){const t=new Array(7);return t[0]=E(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=E(this.month,2),t[2]=E(this.day,2),t[3]=E(this.hour,2),t[4]=E(this.minute,2),t[5]=E(this.second,2),t[6]="Z",t.join("")}return super.toString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}}Tr=Fe;d.UTCTime=Tr;Fe.NAME="UTCTime";var Cr;class _r extends Fe{constructor(e={}){var t;super(e),(t=this.millisecond)!==null&&t!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){const e=Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond);return new Date(e)}fromString(e){let t=!1,r="",s="",i=0,o,c=0,a=0;if(e[e.length-1]==="Z")r=e.substring(0,e.length-1),t=!0;else{const h=new Number(e[e.length-1]);if(isNaN(h.valueOf()))throw new Error("Wrong input string for conversion");r=e}if(t){if(r.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(r.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let h=1,l=r.indexOf("+"),g="";if(l===-1&&(l=r.indexOf("-"),h=-1),l!==-1){if(g=r.substring(l+1),r=r.substring(0,l),g.length!==2&&g.length!==4)throw new Error("Wrong input string for conversion");let w=parseInt(g.substring(0,2),10);if(isNaN(w.valueOf()))throw new Error("Wrong input string for conversion");if(c=h*w,g.length===4){if(w=parseInt(g.substring(2,4),10),isNaN(w.valueOf()))throw new Error("Wrong input string for conversion");a=h*w}}}let u=r.indexOf(".");if(u===-1&&(u=r.indexOf(",")),u!==-1){const h=new Number(`0${r.substring(u)}`);if(isNaN(h.valueOf()))throw new Error("Wrong input string for conversion");i=h.valueOf(),s=r.substring(0,u)}else s=r;switch(!0){case s.length===8:if(o=/(\d{4})(\d{2})(\d{2})/ig,u!==-1)throw new Error("Wrong input string for conversion");break;case s.length===10:if(o=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let h=60*i;this.minute=Math.floor(h),h=60*(h-this.minute),this.second=Math.floor(h),h=1e3*(h-this.second),this.millisecond=Math.floor(h)}break;case s.length===12:if(o=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let h=60*i;this.second=Math.floor(h),h=1e3*(h-this.second),this.millisecond=Math.floor(h)}break;case s.length===14:if(o=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){const h=1e3*i;this.millisecond=Math.floor(h)}break;default:throw new Error("Wrong input string for conversion")}const f=o.exec(s);if(f===null)throw new Error("Wrong input string for conversion");for(let h=1;h<f.length;h++)switch(h){case 1:this.year=parseInt(f[h],10);break;case 2:this.month=parseInt(f[h],10);break;case 3:this.day=parseInt(f[h],10);break;case 4:this.hour=parseInt(f[h],10)+c;break;case 5:this.minute=parseInt(f[h],10)+a;break;case 6:this.second=parseInt(f[h],10);break;default:throw new Error("Wrong input string for conversion")}if(t===!1){const h=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=h.getUTCFullYear(),this.month=h.getUTCMonth(),this.day=h.getUTCDay(),this.hour=h.getUTCHours(),this.minute=h.getUTCMinutes(),this.second=h.getUTCSeconds(),this.millisecond=h.getUTCMilliseconds()}}toString(e="iso"){if(e==="iso"){const t=[];return t.push(E(this.year,4)),t.push(E(this.month,2)),t.push(E(this.day,2)),t.push(E(this.hour,2)),t.push(E(this.minute,2)),t.push(E(this.second,2)),this.millisecond!==0&&(t.push("."),t.push(E(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}}Cr=_r;d.GeneralizedTime=Cr;_r.NAME="GeneralizedTime";var Hr;class Lr extends G{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}}Hr=Lr;d.DATE=Hr;Lr.NAME="DATE";var Rr;class Mr extends G{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}}Rr=Mr;d.TimeOfDay=Rr;Mr.NAME="TimeOfDay";var Or;class Dr extends G{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}}Or=Dr;d.DateTime=Or;Dr.NAME="DateTime";var $r;class Pr extends G{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}}$r=Pr;d.Duration=$r;Pr.NAME="Duration";var Fr;class jr extends G{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}}Fr=jr;d.TIME=Fr;jr.NAME="TIME";function _s(n){const e=n.slice().buffer,t=new ge({value:[new $e({value:"1.3.101.110"})]}),r=new Me({valueHex:e}),s=new ge({value:[t,r]});return new Uint8Array(s.toBER())}function Hs(n){const e=n.slice().buffer,s=Us(e).result.valueBlock.value[1];return new Uint8Array(s.valueBlock.valueHex)}function ne(n){let e="";for(let t=0;t<n.length;t++)e+=String.fromCharCode(n[t]);return btoa(e)}function ie(n){const e=n.replace(/\s+/g,""),t=atob(e),r=new Uint8Array(t.length);for(let s=0;s<t.length;s++)r[s]=t.charCodeAt(s);return r}function ot(n){if(n instanceof ArrayBuffer)return n;const e=n,{buffer:t,byteOffset:r,byteLength:s}=e;if(t instanceof ArrayBuffer)return t.slice(r,r+s);const i=new Uint8Array(s);return i.set(new Uint8Array(t,r,s)),i.buffer}function ce(n){return n.buffer}async function Ls(n,e,t,r){const s=await crypto.subtle.importKey("raw",ce(n),"HKDF",!1,["deriveBits"]),i=await crypto.subtle.deriveBits({name:"HKDF",hash:"SHA-256",salt:ce(e),info:ce(t)},s,r*8);return new Uint8Array(i)}async function Rs(n){return crypto.subtle.importKey("raw",ce(n),{name:"HMAC",hash:"SHA-256"},!1,["sign"])}async function Ms(n,e){const t=await crypto.subtle.sign("HMAC",n,ce(e));return new Uint8Array(t)}function Os(n){const e=n.replace(/\r/g,"").match(/-----BEGIN [^-]+-----([\s\S]*?)-----END [^-]+-----/);if(!e)throw new Error("Invalid PEM");const t=e[1].replace(/[\n\r\s]/g,""),r=atob(t),s=new Uint8Array(r.length);for(let i=0;i<r.length;i++)s[i]=r.charCodeAt(i);return s.buffer}async function Ds(n,e,t){const r=Os(n),s=await crypto.subtle.importKey("spki",r,{name:"ECDSA",namedCurve:"P-256"},!0,["verify"]);return crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},s,ot(t),ot(e))}class qr{constructor(e){this.ws=null,this.listeners={},this.subscriptions={request:{},status:{},topic:{}},this._shouldReconnect=!0,this._reconnectAttempt=0,this.generateRandomString=t=>{let r="";for(;r.length<t;)r+=Math.random().toString(36).substring(2,2+(t-r.length));return r},this.client=e}scheduleReconnect(){if(!this._shouldReconnect)return;const e=Math.min(3e4,1e3*2**this._reconnectAttempt);this._reconnectAttempt++,setTimeout(()=>{this._connectPromise=void 0,this.connect().catch(()=>{})},e)}close(){var e;this._shouldReconnect=!1,this._connectPromise=void 0,(e=this.ws)==null||e.close(),this.ws=null}async connect(){var e;if(await this.client.ensureSession(),!this.client.getAccessToken())throw new Error("Cannot connect to notifications: user is not logged in.");if(!(this.ws&&(this.ws.readyState===WebSocket.OPEN||this.ws.readyState===WebSocket.CONNECTING))){if(this._connectPromise)return this._connectPromise;this._connectPromise=(async()=>{const{ans:t}=await this.client.get("/url/notifications"),{url:r}=t.data[0];this.ws=new WebSocket(r),this.ws.onopen=()=>{this._reconnectAttempt=0,console.log("Notifications connected")},this.ws.onmessage=async s=>{try{const i=JSON.parse(s.data),o=await this.client.decryptAndVerify(i),c=this.subscriptions.request[o==null?void 0:o.correlation_id];c&&Object.values(c).length>0&&Object.values(c).forEach(f=>f(o));const a=this.subscriptions.status[o==null?void 0:o.status];a&&Object.values(a).length>0&&Object.values(a).forEach(f=>f(o));const u=this.subscriptions.topic[o==null?void 0:o.topic];u&&Object.values(u).length>0&&Object.values(u).forEach(f=>f(o)),Object.values(this.listeners).forEach(f=>f(o))}catch(i){console.warn("Failed to process notification:",i)}},this.ws.onerror=s=>{console.error("Notifications error",s)},this.ws.onclose=()=>{this.scheduleReconnect(),console.log("Notifications closed")}})();try{await this._connectPromise}finally{((e=this.ws)==null?void 0:e.readyState)===WebSocket.OPEN?this._connectPromise=void 0:(!this.ws||this.ws.readyState===WebSocket.CLOSED)&&(this._connectPromise=void 0)}}}unsuscribe(e,t,r){delete this.subscriptions[e][t][r]}unlisten(e){delete this.listeners[e]}suscribe(e,t,r,s){let i=s;return i==null&&(i=this.generateRandomString(16)),this.subscriptions[e]||(this.subscriptions[e]={}),this.subscriptions[e][t]||(this.subscriptions[e][t]={}),this.subscriptions[e][t][i]=r,()=>this.unsuscribe(e,t,i)}onMessage(e,t){let r=t;return r==null&&(r=this.generateRandomString(16)),this.listeners[r]=e,()=>this.unlisten(r)}disconnect(){var e;(e=this.ws)==null||e.close(),this.ws=null}}const ct="secure_api_session_v1";class Gr{constructor(e){this.session=null,this.baseUrl=e.baseUrl,this.clientId=e.clientId,this.serverPublicKeyPem=e.serverPublicKeyPem,this.clientIdentityKeyPromise=Ps(e.clientIdentityPrivateKeyPem),this.loadPersistedSession(),this.notifications=new qr(this)}loadPersistedSession(){try{const e=localStorage.getItem(ct);if(!e)return;const t=JSON.parse(e);if(!t)return;t.sessionId&&t.sessionExpiresAt?this.session={sessionId:t.sessionId,sessionExpiresAt:t.sessionExpiresAt,encKey:void 0,macKey:void 0,userId:t.userId,accessToken:t.accessToken,tokenType:t.tokenType,expiresAt:t.expiresAt,refreshToken:t.refreshToken}:this.session={sessionId:"",sessionExpiresAt:"",encKey:void 0,macKey:void 0,userId:t.userId,accessToken:t.accessToken,tokenType:t.tokenType,expiresAt:t.expiresAt,refreshToken:t.refreshToken}}catch{}}persistSession(){try{const e=this.session,t=e?{sessionId:e.sessionId,sessionExpiresAt:e.sessionExpiresAt,userId:e.userId,accessToken:e.accessToken,tokenType:e.tokenType,expiresAt:e.expiresAt,refreshToken:e.refreshToken}:{};localStorage.setItem(ct,JSON.stringify(t))}catch{}}async handshake(){const e=await this.clientIdentityKeyPromise,t=xe.utils.randomSecretKey(),r=xe.getPublicKey(t),s=_s(r),i=ne(s),o=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},e,Fs(s)),c=js(new Uint8Array(o)),a=ne(c),u=await fetch(`${this.baseUrl}/handshake`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:this.clientId,user_id:this.getUserId(),client_pub:i,client_sig:a,client_alg:"ES256"})});if(!u.ok)throw new Error(`Handshake failed: ${u.status} ${u.statusText}`);const f=await u.json(),{session_id:h,server_pub:l,server_sig:g,session_expires_at:w}=f;if(window.__akv={server_pub:l,server_sig:g},!h||!l||!g)throw new Error("Handshake response missing fields");const m=ie(l),b=ie(g);if(!await Ds(this.serverPublicKeyPem,m,b))throw new Error("Server signature verification failed");const le=Hs(m),ye=xe.getSharedSecret(t,le),Be=new Uint8Array(0),ee=new TextEncoder().encode("health-api-v1"),J=await Ls(ye,Be,ee,64),K=J.slice(0,32),be=J.slice(32,64),ue=await crypto.subtle.importKey("raw",K,"AES-GCM",!1,["encrypt","decrypt"]),te=await Rs(be);this.updateSession({sessionId:h,encKey:ue,macKey:te,sessionExpiresAt:w})}getUserId(){var e;return(e=this.session)==null?void 0:e.userId}getAccessToken(){var e;return(e=this.session)==null?void 0:e.accessToken}updateSession(e){if(!this.session){this.session=e,this.persistSession();return}Object.assign(this.session,e),this.persistSession()}getSession(){if(!this.session)throw new Error("No session");return this.session}async encryptBody(e){if(!e)return{ciphertextB64:"",ivB64:""};await this.ensureSession();const{encKey:t}=this.session,r=crypto.getRandomValues(new Uint8Array(12)),s=new TextEncoder().encode(JSON.stringify(e)),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},t,s);return{ciphertextB64:ne(new Uint8Array(i)),ivB64:ne(r)}}async signRequest(e,t,r){await this.ensureSession();const{sessionId:s,macKey:i}=this.session,o=e.toUpperCase()==="GET"?"":{data:Array.isArray(r)?r:[r]},{ciphertextB64:c,ivB64:a}=await this.encryptBody(o),u=Math.floor(Date.now()/1e3).toString();let f=t;f.includes("?")&&(f=f.split("?")[0]);const h=`${e.toUpperCase()} ${f}
63
63
  ${u}
64
- ${c}`,l=await Ms(i,new TextEncoder().encode(h)),g=ne(l),w=new Headers({"X-Session-Id":s,"X-Client-Id":this.clientId,"X-Timestamp":u,"X-Signature":g,"Content-Type":"application/json"});return this.getUserId()&&w.append("X-User-Id",this.getUserId()),this.getAccessToken()&&!this.isTokenExpired()&&w.append("Authorization",`Bearer ${this.getAccessToken()}`),{headers:w,payload:{content:c,iv:a}}}async get(e){const{headers:t}=await this.signRequest("GET",e,null),r=await fetch(`${this.baseUrl}${e}`,{method:"GET",headers:t});if(!r.ok)throw new Error(`GET ${e} failed: ${r.status} ${r.statusText}`);return this.decryptAndVerify(await r.json())}async post(e,t){const{headers:r,payload:s}=await this.signRequest("POST",e,t),i=await fetch(`${this.baseUrl}${e}`,{method:"POST",headers:r,body:JSON.stringify(s)});if(!i.ok)throw new Error(`POST ${e} failed: ${i.status} ${i.statusText}`);return e.endsWith("/handshake")?await i.json():this.decryptAndVerify(await i.json())}async ensureSession(){var t,r,s;(!this.session||!this.session.sessionId||!this.session.sessionExpiresAt||!this.session.encKey||!this.session.macKey)&&await this.handshake();const e=new Date(Date.now()+5*60*1e3);(t=this.session)!=null&&t.sessionExpiresAt&&new Date((r=this.session)==null?void 0:r.sessionExpiresAt)<e&&await this.extendHandshake(),(s=this.session)!=null&&s.accessToken&&this.isTokenExpired()&&await this.refresh()}async extendHandshake(){await this.post("/handshake/extend",{}).then(async e=>{var t;e&&(e.session_id!==((t=this.session)==null?void 0:t.sessionId)?await this.handshake():this.updateSession({sessionExpiresAt:e.session_expires_at}))}).catch(async e=>{await this.handshake()})}async decryptAndVerify(e){const{ciphertext:t,iv:r,signature:s,...i}=e;if(!t||!r||!s)throw new Error("Malformed notification");const{encKey:o,macKey:c}=this.getSession(),a=ie(s),u=await crypto.subtle.sign("HMAC",c,new TextEncoder().encode(t));if(!this.constantTimeEqual(a,new Uint8Array(u)))throw new Error("Invalid notification signature");const f=Uint8Array.from(ie(r)),h=Uint8Array.from(ie(t)),l=await crypto.subtle.decrypt({name:"AES-GCM",iv:f},o,h),g=new TextDecoder().decode(l);return{...JSON.parse(g),...i}}constantTimeEqual(e,t){if(e.length!==t.length)return!1;let r=0;for(let s=0;s<e.length;s++)r|=e[s]^t[s];return r===0}async login(e){(!this.session||!this.session.sessionId||!this.session.sessionExpiresAt||!this.session.encKey||!this.session.macKey)&&await this.handshake(),this.updateSession({accessToken:void 0,tokenType:void 0,expiresAt:void 0,refreshToken:void 0});const t={};"username"in e&&"password"in e&&(t.username=e.username,t.password=e.password,t.scope=e.scope,t.oauth_session=e.oauthSession),"email"in e&&"socialLoginId"in e&&(t.email=e.email,t.social_login_id=e.socialLoginId,t.scope=e.scope,t.oauth_session=e.oauthSession),"jwt"in e&&this.updateSession({accessToken:e.jwt,tokenType:"Bearer"}),"refreshToken"in e&&(t.refresh_token=e.refreshToken);const r=await this.post("/oauth/authorize",t),{access_token:s,token_type:i,expires_at:o,refresh_token:c}=r.data[0];return s&&this.updateSession({accessToken:s}),i&&this.updateSession({tokenType:i}),o&&this.updateSession({expiresAt:o}),c&&this.updateSession({refreshToken:c}),{accessToken:s,tokenType:i,expiresAt:o,refreshToken:c}}async refresh(){const e=this.getSession();if(!(e!=null&&e.refreshToken))throw new Error("No refresh token available");if(e&&e.refreshToken)return this.login({refreshToken:e.refreshToken})}isTokenExpired(){const e=this.getSession();if(!(e!=null&&e.expiresAt))return!0;if(e&&e.expiresAt)return Math.floor(Date.now()/1e3)>=e.expiresAt}}function $s(n){const e=n.replace(/-----BEGIN PRIVATE KEY-----/,"").replace(/-----END PRIVATE KEY-----/,"").replace(/\s+/g,""),t=atob(e),r=new Uint8Array(t.length);for(let s=0;s<t.length;s++)r[s]=t.charCodeAt(s);return r.buffer}async function Ps(n){const e=$s(n);return crypto.subtle.importKey("pkcs8",e,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"])}function Fs(n){return Uint8Array.from(n).buffer}function js(n){const e=n.slice(0,32),t=n.slice(32,64);function r(f){let h=0;for(;h<f.length-1&&f[h]===0;)h++;return f.slice(h)}function s(f){const h=r(f);if(h[0]&128){const l=new Uint8Array(h.length+1);return l[0]=0,l.set(h,1),l}return h}const i=s(e),o=s(t),c=2+i.length+2+o.length,a=new Uint8Array(2+c);let u=0;return a[u++]=48,a[u++]=c,a[u++]=2,a[u++]=i.length,a.set(i,u),u+=i.length,a[u++]=2,a[u++]=o.length,a.set(o,u),a}const Jr=Symbol("SDK_CLIENT"),qs={install(n,e){const t=new Gr(e);n.provide(Jr,t)}};exports.Notifications=qr;exports.SDK_CLIENT=Jr;exports.SdkPlugin=qs;exports.SecureApiClient=Gr;
64
+ ${c}`,l=await Ms(i,new TextEncoder().encode(h)),g=ne(l),w=new Headers({"X-Session-Id":s,"X-Client-Id":this.clientId,"X-Timestamp":u,"X-Signature":g,"Content-Type":"application/json"});return this.getUserId()&&w.append("X-User-Id",this.getUserId()),this.getAccessToken()&&!this.isTokenExpired()&&w.append("Authorization",`Bearer ${this.getAccessToken()}`),{headers:w,payload:{content:c,iv:a}}}async get(e){const{headers:t}=await this.signRequest("GET",e,null),r=await fetch(`${this.baseUrl}${e}`,{method:"GET",headers:t});if(!r.ok)throw new Error(`GET ${e} failed: ${r.status} ${r.statusText}`);return this.decryptAndVerify(await r.json())}async post(e,t){const{headers:r,payload:s}=await this.signRequest("POST",e,t),i=await fetch(`${this.baseUrl}${e}`,{method:"POST",headers:r,body:JSON.stringify(s)});if(!i.ok)throw new Error(`POST ${e} failed: ${i.status} ${i.statusText}`);return e.endsWith("/handshake")?await i.json():this.decryptAndVerify(await i.json())}async ensureSession(){var t,r,s;(!this.session||!this.session.sessionId||!this.session.sessionExpiresAt||!this.session.encKey||!this.session.macKey)&&await this.handshake();const e=new Date(Date.now()+5*60*1e3);(t=this.session)!=null&&t.sessionExpiresAt&&new Date((r=this.session)==null?void 0:r.sessionExpiresAt)<e&&await this.extendHandshake(),(s=this.session)!=null&&s.accessToken&&this.isTokenExpired()&&await this.refresh()}async extendHandshake(){await this.post("/handshake/extend",{}).then(async e=>{var t;e&&(e.session_id!==((t=this.session)==null?void 0:t.sessionId)?await this.handshake():this.updateSession({sessionExpiresAt:e.data[0].session_expires_at}))}).catch(async e=>{await this.handshake()})}async decryptAndVerify(e){const{ciphertext:t,iv:r,signature:s,...i}=e;if(!t||!r||!s)throw new Error("Malformed notification");const{encKey:o,macKey:c}=this.getSession(),a=ie(s),u=await crypto.subtle.sign("HMAC",c,new TextEncoder().encode(t));if(!this.constantTimeEqual(a,new Uint8Array(u)))throw new Error("Invalid notification signature");const f=Uint8Array.from(ie(r)),h=Uint8Array.from(ie(t)),l=await crypto.subtle.decrypt({name:"AES-GCM",iv:f},o,h),g=new TextDecoder().decode(l);return{...JSON.parse(g),...i}}constantTimeEqual(e,t){if(e.length!==t.length)return!1;let r=0;for(let s=0;s<e.length;s++)r|=e[s]^t[s];return r===0}async login(e){(!this.session||!this.session.sessionId||!this.session.sessionExpiresAt||!this.session.encKey||!this.session.macKey)&&await this.handshake(),this.updateSession({accessToken:void 0,tokenType:void 0,expiresAt:void 0,refreshToken:void 0});const t={};"username"in e&&"password"in e&&(t.username=e.username,t.password=e.password,t.scope=e.scope,t.oauth_session=e.oauthSession),"email"in e&&"socialLoginId"in e&&(t.email=e.email,t.social_login_id=e.socialLoginId,t.scope=e.scope,t.oauth_session=e.oauthSession),"jwt"in e&&this.updateSession({accessToken:e.jwt,tokenType:"Bearer"}),"refreshToken"in e&&(t.refresh_token=e.refreshToken);const r=await this.post("/oauth/authorize",t),{access_token:s,token_type:i,expires_at:o,refresh_token:c}=r.data[0];return s&&this.updateSession({accessToken:s}),i&&this.updateSession({tokenType:i}),o&&this.updateSession({expiresAt:o}),c&&this.updateSession({refreshToken:c}),{accessToken:s,tokenType:i,expiresAt:o,refreshToken:c}}async refresh(){const e=this.getSession();if(!(e!=null&&e.refreshToken))throw new Error("No refresh token available");if(e&&e.refreshToken)return this.login({refreshToken:e.refreshToken})}isTokenExpired(){const e=this.getSession();if(!(e!=null&&e.expiresAt))return!0;if(e&&e.expiresAt)return Math.floor(Date.now()/1e3)>=e.expiresAt}}function $s(n){const e=n.replace(/-----BEGIN PRIVATE KEY-----/,"").replace(/-----END PRIVATE KEY-----/,"").replace(/\s+/g,""),t=atob(e),r=new Uint8Array(t.length);for(let s=0;s<t.length;s++)r[s]=t.charCodeAt(s);return r.buffer}async function Ps(n){const e=$s(n);return crypto.subtle.importKey("pkcs8",e,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"])}function Fs(n){return Uint8Array.from(n).buffer}function js(n){const e=n.slice(0,32),t=n.slice(32,64);function r(f){let h=0;for(;h<f.length-1&&f[h]===0;)h++;return f.slice(h)}function s(f){const h=r(f);if(h[0]&128){const l=new Uint8Array(h.length+1);return l[0]=0,l.set(h,1),l}return h}const i=s(e),o=s(t),c=2+i.length+2+o.length,a=new Uint8Array(2+c);let u=0;return a[u++]=48,a[u++]=c,a[u++]=2,a[u++]=i.length,a.set(i,u),u+=i.length,a[u++]=2,a[u++]=o.length,a.set(o,u),a}const Jr=Symbol("SDK_CLIENT"),qs={install(n,e){const t=new Gr(e);n.provide(Jr,t)}};exports.Notifications=qr;exports.SDK_CLIENT=Jr;exports.SdkPlugin=qs;exports.SecureApiClient=Gr;
65
65
  //# sourceMappingURL=index.cjs.map