@ledgerhq/device-management-kit 0.0.0-rn-ble-perf-20251009143619 → 0.0.0-rn-hid-issues-20251022142715

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.
Files changed (29) hide show
  1. package/lib/cjs/src/api/device-action/model/UserInteractionRequired.js +1 -1
  2. package/lib/cjs/src/api/device-action/model/UserInteractionRequired.js.map +2 -2
  3. package/lib/cjs/src/api/logger-subscriber/service/ConsoleLogger.js +1 -1
  4. package/lib/cjs/src/api/logger-subscriber/service/ConsoleLogger.js.map +3 -3
  5. package/lib/cjs/src/api/secure-channel/task/ConnectToSecureChannelTask.js +1 -1
  6. package/lib/cjs/src/api/secure-channel/task/ConnectToSecureChannelTask.js.map +3 -3
  7. package/lib/cjs/src/internal/device-session/model/DeviceSession.js +1 -1
  8. package/lib/cjs/src/internal/device-session/model/DeviceSession.js.map +3 -3
  9. package/lib/cjs/src/internal/device-session/service/DefaultDeviceSessionService.js +1 -1
  10. package/lib/cjs/src/internal/device-session/service/DefaultDeviceSessionService.js.map +2 -2
  11. package/lib/esm/src/api/device-action/model/UserInteractionRequired.js +1 -1
  12. package/lib/esm/src/api/device-action/model/UserInteractionRequired.js.map +2 -2
  13. package/lib/esm/src/api/logger-subscriber/service/ConsoleLogger.js +1 -1
  14. package/lib/esm/src/api/logger-subscriber/service/ConsoleLogger.js.map +3 -3
  15. package/lib/esm/src/api/secure-channel/task/ConnectToSecureChannelTask.js +1 -1
  16. package/lib/esm/src/api/secure-channel/task/ConnectToSecureChannelTask.js.map +3 -3
  17. package/lib/esm/src/internal/device-session/model/DeviceSession.js +1 -1
  18. package/lib/esm/src/internal/device-session/model/DeviceSession.js.map +3 -3
  19. package/lib/esm/src/internal/device-session/service/DefaultDeviceSessionService.js +1 -1
  20. package/lib/esm/src/internal/device-session/service/DefaultDeviceSessionService.js.map +2 -2
  21. package/lib/types/src/api/device-action/model/UserInteractionRequired.d.ts +2 -1
  22. package/lib/types/src/api/device-action/model/UserInteractionRequired.d.ts.map +1 -1
  23. package/lib/types/src/api/logger-subscriber/service/ConsoleLogger.d.ts +1 -0
  24. package/lib/types/src/api/logger-subscriber/service/ConsoleLogger.d.ts.map +1 -1
  25. package/lib/types/src/api/secure-channel/task/ConnectToSecureChannelTask.d.ts.map +1 -1
  26. package/lib/types/src/internal/device-session/model/DeviceSession.d.ts.map +1 -1
  27. package/lib/types/src/internal/device-session/service/DefaultDeviceSessionService.d.ts.map +1 -1
  28. package/lib/types/tsconfig.prod.tsbuildinfo +1 -1
  29. package/package.json +3 -3
@@ -1,2 +1,2 @@
1
- "use strict";var s=Object.defineProperty;var i=Object.getOwnPropertyDescriptor;var w=Object.getOwnPropertyNames;var S=Object.prototype.hasOwnProperty;var c=(l,p)=>{for(var g in p)s(l,g,{get:p[g],enumerable:!0})},f=(l,p,g,a)=>{if(p&&typeof p=="object"||typeof p=="function")for(let n of w(p))!S.call(l,n)&&n!==g&&s(l,n,{get:()=>p[n],enumerable:!(a=i(p,n))||a.enumerable});return l};var h=l=>f(s({},"__esModule",{value:!0}),l);var k={};c(k,{UserInteractionRequired:()=>A});module.exports=h(k);var A=(o=>(o.None="none",o.UnlockDevice="unlock-device",o.AllowSecureConnection="allow-secure-connection",o.ConfirmOpenApp="confirm-open-app",o.SignTransaction="sign-transaction",o.SignTypedData="sign-typed-data",o.AllowListApps="allow-list-apps",o.VerifyAddress="verify-address",o.SignPersonalMessage="sign-personal-message",o.SignDelegationAuthorization="sign-delegation-authorization",o.Web3ChecksOptIn="web3-checks-opt-in",o))(A||{});0&&(module.exports={UserInteractionRequired});
1
+ "use strict";var g=Object.defineProperty;var A=Object.getOwnPropertyDescriptor;var y=Object.getOwnPropertyNames;var S=Object.prototype.hasOwnProperty;var i=(l,s)=>{for(var a in s)g(l,a,{get:s[a],enumerable:!0})},w=(l,s,a,n)=>{if(s&&typeof s=="object"||typeof s=="function")for(let o of y(s))!S.call(l,o)&&o!==a&&g(l,o,{get:()=>s[o],enumerable:!(n=A(s,o))||n.enumerable});return l};var h=l=>w(g({},"__esModule",{value:!0}),l);var k={};i(k,{UserInteractionRequired:()=>f});module.exports=h(k);var f=(p=>(p.None="none",p.UnlockDevice="unlock-device",p.AllowSecureConnection="allow-secure-connection",p.ConfirmOpenApp="confirm-open-app",p.SignTransaction="sign-transaction",p.SignTypedData="sign-typed-data",p.AllowListApps="allow-list-apps",p.VerifyAddress="verify-address",p.SignPersonalMessage="sign-personal-message",p.SignDelegationAuthorization="sign-delegation-authorization",p.Web3ChecksOptIn="web3-checks-opt-in",p.VerifySafeAddress="verify-safe-address",p))(f||{});0&&(module.exports={UserInteractionRequired});
2
2
  //# sourceMappingURL=UserInteractionRequired.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/api/device-action/model/UserInteractionRequired.ts"],
4
- "sourcesContent": ["/**\n * The user interaction required on the device to move further in a device action.\n * This is used to inform the users about the action they need to take on the device.\n */\nexport enum UserInteractionRequired {\n None = \"none\",\n UnlockDevice = \"unlock-device\",\n AllowSecureConnection = \"allow-secure-connection\",\n ConfirmOpenApp = \"confirm-open-app\",\n SignTransaction = \"sign-transaction\",\n SignTypedData = \"sign-typed-data\",\n AllowListApps = \"allow-list-apps\",\n VerifyAddress = \"verify-address\",\n SignPersonalMessage = \"sign-personal-message\",\n SignDelegationAuthorization = \"sign-delegation-authorization\",\n Web3ChecksOptIn = \"web3-checks-opt-in\",\n}\n"],
5
- "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,6BAAAE,IAAA,eAAAC,EAAAH,GAIO,IAAKE,OACVA,EAAA,KAAO,OACPA,EAAA,aAAe,gBACfA,EAAA,sBAAwB,0BACxBA,EAAA,eAAiB,mBACjBA,EAAA,gBAAkB,mBAClBA,EAAA,cAAgB,kBAChBA,EAAA,cAAgB,kBAChBA,EAAA,cAAgB,iBAChBA,EAAA,oBAAsB,wBACtBA,EAAA,4BAA8B,gCAC9BA,EAAA,gBAAkB,qBAXRA,OAAA",
4
+ "sourcesContent": ["/**\n * The user interaction required on the device to move further in a device action.\n * This is used to inform the users about the action they need to take on the device.\n */\nexport enum UserInteractionRequired {\n None = \"none\",\n UnlockDevice = \"unlock-device\",\n AllowSecureConnection = \"allow-secure-connection\",\n ConfirmOpenApp = \"confirm-open-app\",\n SignTransaction = \"sign-transaction\",\n SignTypedData = \"sign-typed-data\",\n AllowListApps = \"allow-list-apps\",\n VerifyAddress = \"verify-address\",\n SignPersonalMessage = \"sign-personal-message\",\n SignDelegationAuthorization = \"sign-delegation-authorization\",\n Web3ChecksOptIn = \"web3-checks-opt-in\",\n VerifySafeAddress = \"verify-safe-address\",\n}\n"],
5
+ "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,6BAAAE,IAAA,eAAAC,EAAAH,GAIO,IAAKE,OACVA,EAAA,KAAO,OACPA,EAAA,aAAe,gBACfA,EAAA,sBAAwB,0BACxBA,EAAA,eAAiB,mBACjBA,EAAA,gBAAkB,mBAClBA,EAAA,cAAgB,kBAChBA,EAAA,cAAgB,kBAChBA,EAAA,cAAgB,iBAChBA,EAAA,oBAAsB,wBACtBA,EAAA,4BAA8B,gCAC9BA,EAAA,gBAAkB,qBAClBA,EAAA,kBAAoB,sBAZVA,OAAA",
6
6
  "names": ["UserInteractionRequired_exports", "__export", "UserInteractionRequired", "__toCommonJS"]
7
7
  }
@@ -1,2 +1,2 @@
1
- "use strict";var i=Object.defineProperty;var c=Object.getOwnPropertyDescriptor;var L=Object.getOwnPropertyNames;var g=Object.prototype.hasOwnProperty;var b=(t,e)=>{for(var o in e)i(t,o,{get:e[o],enumerable:!0})},n=(t,e,o,l)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of L(e))!g.call(t,r)&&r!==o&&i(t,r,{get:()=>e[r],enumerable:!(l=c(e,r))||l.enumerable});return t};var s=t=>n(i({},"__esModule",{value:!0}),t);var f={};b(f,{ConsoleLogger:()=>v});module.exports=s(f);var a=require("../../logger-subscriber/model/LogLevel");class v{maxLevel;constructor(e=a.LogLevel.Debug){this.maxLevel=e}log(e,o,l){const r=`[${l.tag}]`;switch(e){case a.LogLevel.Info:{this.maxLevel>=a.LogLevel.Info&&console.info(r,o,l.data);break}case a.LogLevel.Warning:{this.maxLevel>=a.LogLevel.Warning&&console.warn(r,o,l.data);break}case a.LogLevel.Debug:{this.maxLevel>=a.LogLevel.Debug&&console.debug(r,o,l.data);break}case a.LogLevel.Error:{this.maxLevel>=a.LogLevel.Error&&console.error(r,o,l.data);break}case a.LogLevel.Fatal:{this.maxLevel>=a.LogLevel.Fatal&&console.error(r,o,l.data);break}default:console.log(r,o,l.data)}}}0&&(module.exports={ConsoleLogger});
1
+ "use strict";var l=Object.defineProperty;var g=Object.getOwnPropertyDescriptor;var s=Object.getOwnPropertyNames;var c=Object.prototype.hasOwnProperty;var L=(o,e)=>{for(var a in e)l(o,a,{get:e[a],enumerable:!0})},h=(o,e,a,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of s(e))!c.call(o,r)&&r!==a&&l(o,r,{get:()=>e[r],enumerable:!(i=g(e,r))||i.enumerable});return o};var n=o=>h(l({},"__esModule",{value:!0}),o);var v={};L(v,{ConsoleLogger:()=>b});module.exports=n(v);var t=require("../../logger-subscriber/model/LogLevel");class b{maxLevel;constructor(e=t.LogLevel.Debug){this.maxLevel=e}log(e,a,i){const r=`[${i.tag}]`;switch(e){case t.LogLevel.Info:{this.maxLevel>=t.LogLevel.Info&&this.logWithData(r,console.info,a,i);break}case t.LogLevel.Warning:{this.maxLevel>=t.LogLevel.Warning&&this.logWithData(r,console.warn,a,i);break}case t.LogLevel.Debug:{this.maxLevel>=t.LogLevel.Debug&&this.logWithData(r,console.debug,a,i);break}case t.LogLevel.Error:{this.maxLevel>=t.LogLevel.Error&&this.logWithData(r,console.error,a,i);break}case t.LogLevel.Fatal:{this.maxLevel>=t.LogLevel.Fatal&&this.logWithData(r,console.error,a,i);break}default:this.logWithData(r,console.log,a,i)}}logWithData(e,a,i,r){r.data?a(e,i,r.data):a(e,i)}}0&&(module.exports={ConsoleLogger});
2
2
  //# sourceMappingURL=ConsoleLogger.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/api/logger-subscriber/service/ConsoleLogger.ts"],
4
- "sourcesContent": ["import { LogLevel } from \"@api/logger-subscriber/model/LogLevel\";\nimport { type LogSubscriberOptions } from \"@api/logger-subscriber/model/LogSubscriberOptions\";\nimport { type LoggerSubscriberService } from \"@api/logger-subscriber/service/LoggerSubscriberService\";\n\nexport class ConsoleLogger implements LoggerSubscriberService {\n private readonly maxLevel: LogLevel;\n\n constructor(level: LogLevel = LogLevel.Debug) {\n this.maxLevel = level;\n }\n\n log(\n level: LogLevel | null,\n message: string,\n options: LogSubscriberOptions,\n ): void {\n const tag = `[${options.tag}]`;\n\n switch (level) {\n case LogLevel.Info: {\n if (this.maxLevel >= LogLevel.Info) {\n console.info(tag, message, options.data);\n }\n break;\n }\n case LogLevel.Warning: {\n if (this.maxLevel >= LogLevel.Warning) {\n console.warn(tag, message, options.data);\n }\n break;\n }\n case LogLevel.Debug: {\n if (this.maxLevel >= LogLevel.Debug) {\n console.debug(tag, message, options.data);\n }\n break;\n }\n case LogLevel.Error: {\n if (this.maxLevel >= LogLevel.Error) {\n console.error(tag, message, options.data);\n }\n break;\n }\n case LogLevel.Fatal: {\n if (this.maxLevel >= LogLevel.Fatal) {\n console.error(tag, message, options.data);\n }\n break;\n }\n default:\n console.log(tag, message, options.data);\n }\n }\n}\n"],
5
- "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,mBAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAAyB,iDAIlB,MAAMF,CAAiD,CAC3C,SAEjB,YAAYG,EAAkB,WAAS,MAAO,CAC5C,KAAK,SAAWA,CAClB,CAEA,IACEA,EACAC,EACAC,EACM,CACN,MAAMC,EAAM,IAAID,EAAQ,GAAG,IAE3B,OAAQF,EAAO,CACb,KAAK,WAAS,KAAM,CACd,KAAK,UAAY,WAAS,MAC5B,QAAQ,KAAKG,EAAKF,EAASC,EAAQ,IAAI,EAEzC,KACF,CACA,KAAK,WAAS,QAAS,CACjB,KAAK,UAAY,WAAS,SAC5B,QAAQ,KAAKC,EAAKF,EAASC,EAAQ,IAAI,EAEzC,KACF,CACA,KAAK,WAAS,MAAO,CACf,KAAK,UAAY,WAAS,OAC5B,QAAQ,MAAMC,EAAKF,EAASC,EAAQ,IAAI,EAE1C,KACF,CACA,KAAK,WAAS,MAAO,CACf,KAAK,UAAY,WAAS,OAC5B,QAAQ,MAAMC,EAAKF,EAASC,EAAQ,IAAI,EAE1C,KACF,CACA,KAAK,WAAS,MAAO,CACf,KAAK,UAAY,WAAS,OAC5B,QAAQ,MAAMC,EAAKF,EAASC,EAAQ,IAAI,EAE1C,KACF,CACA,QACE,QAAQ,IAAIC,EAAKF,EAASC,EAAQ,IAAI,CAC1C,CACF,CACF",
6
- "names": ["ConsoleLogger_exports", "__export", "ConsoleLogger", "__toCommonJS", "import_LogLevel", "level", "message", "options", "tag"]
4
+ "sourcesContent": ["import { LogLevel } from \"@api/logger-subscriber/model/LogLevel\";\nimport { type LogSubscriberOptions } from \"@api/logger-subscriber/model/LogSubscriberOptions\";\nimport { type LoggerSubscriberService } from \"@api/logger-subscriber/service/LoggerSubscriberService\";\n\nexport class ConsoleLogger implements LoggerSubscriberService {\n private readonly maxLevel: LogLevel;\n\n constructor(level: LogLevel = LogLevel.Debug) {\n this.maxLevel = level;\n }\n\n log(\n level: LogLevel | null,\n message: string,\n options: LogSubscriberOptions,\n ): void {\n const tag = `[${options.tag}]`;\n\n switch (level) {\n case LogLevel.Info: {\n if (this.maxLevel >= LogLevel.Info) {\n this.logWithData(tag, console.info, message, options);\n }\n break;\n }\n case LogLevel.Warning: {\n if (this.maxLevel >= LogLevel.Warning) {\n this.logWithData(tag, console.warn, message, options);\n }\n break;\n }\n case LogLevel.Debug: {\n if (this.maxLevel >= LogLevel.Debug) {\n this.logWithData(tag, console.debug, message, options);\n }\n break;\n }\n case LogLevel.Error: {\n if (this.maxLevel >= LogLevel.Error) {\n this.logWithData(tag, console.error, message, options);\n }\n break;\n }\n case LogLevel.Fatal: {\n if (this.maxLevel >= LogLevel.Fatal) {\n this.logWithData(tag, console.error, message, options);\n }\n break;\n }\n default:\n this.logWithData(tag, console.log, message, options);\n }\n }\n\n private logWithData(\n tag: string,\n logFunction: (...args: unknown[]) => void,\n message: string,\n options: LogSubscriberOptions,\n ): void {\n if (options.data) {\n logFunction(tag, message, options.data);\n } else {\n logFunction(tag, message);\n }\n }\n}\n"],
5
+ "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,mBAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAAyB,iDAIlB,MAAMF,CAAiD,CAC3C,SAEjB,YAAYG,EAAkB,WAAS,MAAO,CAC5C,KAAK,SAAWA,CAClB,CAEA,IACEA,EACAC,EACAC,EACM,CACN,MAAMC,EAAM,IAAID,EAAQ,GAAG,IAE3B,OAAQF,EAAO,CACb,KAAK,WAAS,KAAM,CACd,KAAK,UAAY,WAAS,MAC5B,KAAK,YAAYG,EAAK,QAAQ,KAAMF,EAASC,CAAO,EAEtD,KACF,CACA,KAAK,WAAS,QAAS,CACjB,KAAK,UAAY,WAAS,SAC5B,KAAK,YAAYC,EAAK,QAAQ,KAAMF,EAASC,CAAO,EAEtD,KACF,CACA,KAAK,WAAS,MAAO,CACf,KAAK,UAAY,WAAS,OAC5B,KAAK,YAAYC,EAAK,QAAQ,MAAOF,EAASC,CAAO,EAEvD,KACF,CACA,KAAK,WAAS,MAAO,CACf,KAAK,UAAY,WAAS,OAC5B,KAAK,YAAYC,EAAK,QAAQ,MAAOF,EAASC,CAAO,EAEvD,KACF,CACA,KAAK,WAAS,MAAO,CACf,KAAK,UAAY,WAAS,OAC5B,KAAK,YAAYC,EAAK,QAAQ,MAAOF,EAASC,CAAO,EAEvD,KACF,CACA,QACE,KAAK,YAAYC,EAAK,QAAQ,IAAKF,EAASC,CAAO,CACvD,CACF,CAEQ,YACNC,EACAC,EACAH,EACAC,EACM,CACFA,EAAQ,KACVE,EAAYD,EAAKF,EAASC,EAAQ,IAAI,EAEtCE,EAAYD,EAAKF,CAAO,CAE5B,CACF",
6
+ "names": ["ConsoleLogger_exports", "__export", "ConsoleLogger", "__toCommonJS", "import_LogLevel", "level", "message", "options", "tag", "logFunction"]
7
7
  }
@@ -1,2 +1,2 @@
1
- "use strict";var M=Object.create;var C=Object.defineProperty;var R=Object.getOwnPropertyDescriptor;var O=Object.getOwnPropertyNames;var I=Object.getPrototypeOf,D=Object.prototype.hasOwnProperty;var U=(s,e)=>{for(var o in e)C(s,o,{get:e[o],enumerable:!0})},_=(s,e,o,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let u of O(e))!D.call(s,u)&&u!==o&&C(s,u,{get:()=>e[u],enumerable:!(r=R(e,u))||r.enumerable});return s};var N=(s,e,o)=>(o=s!=null?M(I(s)):{},_(e||!s||!s.__esModule?C(o,"default",{value:s,enumerable:!0}):o,s)),P=s=>_(C({},"__esModule",{value:!0}),s);var L={};U(L,{ConnectToSecureChannelTask:()=>W});module.exports=P(L);var A=N(require("isomorphic-ws")),T=require("rxjs"),g=require("../../command/utils/CommandUtils"),n=require("../../secure-channel/task/types"),k=require("../../secure-channel/utils"),m=require("../../utils/HexaString"),t=require("../../../internal/secure-channel/model/Errors");class W{constructor(e,o){this._api=e;this._args=o;if(this._args.connection.isRight())this._connection=this._args.connection.extract();else throw new t.SecureChannelError(`Invalid WebSocket connection: ${String(this._args.connection.extract())}`)}_connection;run(){const e=this._api.disableRefresher("connectToSecureChannel");return new T.Observable(r=>{let u=!1,d=!1,v=!1;const p=f=>{r.next({type:n.SecureChannelEventType.Error,error:f}),r.complete(),d=!0};return this._connection.onopen=()=>{r.next({type:n.SecureChannelEventType.Opened})},this._connection.onerror=f=>{d||(r.next({type:n.SecureChannelEventType.Error,error:new t.SecureChannelError({url:this._connection.url,errorMessage:f.message})}),r.complete())},this._connection.onclose=()=>{d||(v?r.next({type:n.SecureChannelEventType.Closed}):r.next({type:n.SecureChannelEventType.Error,error:new t.SecureChannelError({url:this._connection.url,errorMessage:"Connection closed unexpectedly"})}),r.complete())},this._connection.onmessage=async f=>{if(u)return;let i;try{const c=JSON.parse(String(f.data));if(this.isInMessageType(c))i=c;else throw new Error("Data does not match InMessageType")}catch{p(new t.SecureChannelError({url:this._connection.url,errorMessage:`Invalid message received: ${String(f.data)}`}));return}switch(i.query){case n.InMessageQueryEnum.EXCHANGE:{const{nonce:c,data:S}=i;if(typeof S!="string"){p(new t.SecureChannelError(`${n.InMessageQueryEnum.EXCHANGE} data type should be an APDU`));return}const a=(0,m.hexaStringToBuffer)(S);if(a===null||a.length<5){p(new t.SecureChannelError(`Received invalid APDU data: ${S}`));return}r.next({type:n.SecureChannelEventType.PreExchange,payload:{nonce:c,apdu:a}});let y=!1;(0,k.willRequestPermission)(a)&&!this.isSecureConnectionAllowed()&&(y=!0,r.next({type:n.SecureChannelEventType.PermissionRequested}));const E=await this._api.sendApdu(a);if(u)return;E.caseOf({Left:l=>{p(new t.SecureChannelError(l))},Right:l=>{let h;const w=this.mapDeviceError(l);w===null?(h=n.OutMessageResponseEnum.SUCCESS,r.next({type:n.SecureChannelEventType.Exchange,payload:{nonce:c,apdu:a,data:l.data,status:l.statusCode}}),y&&r.next({type:n.SecureChannelEventType.PermissionGranted})):(h=n.OutMessageResponseEnum.ERROR,p(w));const x={nonce:c,response:h,data:(0,m.bufferToHexaString)(l.data,!1)};this._connection.send(JSON.stringify(x))}});break}case n.InMessageQueryEnum.BULK:{d=!0,this._connection.close();const c=Date.now();if(console.log("[ConnectToSecureChannelTask] BULK started"),!Array.isArray(i.data)||i.data.length===0||!i.data.every(a=>typeof a=="string")){p(new t.SecureChannelError("Invalid bulk data received"));return}for(let a=0,y=i.data.length;a<y;a++){const E=(0,m.hexaStringToBuffer)(i.data[a]);if(E===null||E.length<5){p(new t.SecureChannelError(`Received invalid APDU bulk data: ${i.data[a]}`));return}const l=await this._api.sendApdu(E);if(u)return;if(l.isLeft()){p(new t.SecureChannelError(l.extract()));return}else if(l.isRight()){const h=this.mapDeviceError(l.extract());if(h===null)r.next({type:n.SecureChannelEventType.Progress,payload:{progress:+Number((a+1)/y).toFixed(2),index:a,total:y}});else{p(h);return}}}const S=Date.now();console.log("[ConnectToSecureChannelTask] BULK finished in",S-c,"ms"),v=!0,r.complete();break}case n.InMessageQueryEnum.SUCCESS:{if(d)break;const c=i.result??i.data;c&&r.next({type:n.SecureChannelEventType.Result,payload:c??""}),v=!0,r.complete();break}case n.InMessageQueryEnum.WARNING:{if(d)break;r.next({type:n.SecureChannelEventType.Warning,payload:{message:String(i.data)}});break}case n.InMessageQueryEnum.ERROR:{if(d)break;p(new t.SecureChannelError({url:this._connection.url,errorMessage:String(i.data)}))}}},()=>{e(),u=!0,this._connection.readyState===A.default.OPEN&&this._connection.close()}})}isSecureConnectionAllowed(){const e=this._api.getDeviceSessionState();return"isSecureConnectionAllowed"in e&&e.isSecureConnectionAllowed}isInMessageType(e){if(typeof e!="object"||!e)return!1;const o=e;return typeof o.uuid=="string"&&typeof o.session=="string"&&typeof o.query=="string"&&Object.values(n.InMessageQueryEnum).includes(o.query)&&typeof o.nonce=="number"}mapDeviceError(e){return g.CommandUtils.isSuccessResponse(e)?null:g.CommandUtils.isLockedDeviceResponse(e)?new t.SecureChannelError({url:this._connection.url,errorMessage:"Device is locked"},t.SecureChannelErrorType.DeviceLocked):g.CommandUtils.isRefusedByUser(e)?new t.SecureChannelError({url:this._connection.url,errorMessage:"User refused on the device"},t.SecureChannelErrorType.RefusedByUser):g.CommandUtils.isAppAlreadyInstalled(e)?new t.SecureChannelError({url:this._connection.url,errorMessage:"App already installed"},t.SecureChannelErrorType.AppAlreadyInstalled):g.CommandUtils.isOutOfMemory(e)?new t.SecureChannelError({url:this._connection.url,errorMessage:"Out of memory"},t.SecureChannelErrorType.OutOfMemory):new t.SecureChannelError({url:this._connection.url,errorMessage:`Invalid status code: ${(0,m.bufferToHexaString)(e.statusCode)}`})}}0&&(module.exports={ConnectToSecureChannelTask});
1
+ "use strict";var R=Object.create;var E=Object.defineProperty;var T=Object.getOwnPropertyDescriptor;var O=Object.getOwnPropertyNames;var I=Object.getPrototypeOf,D=Object.prototype.hasOwnProperty;var U=(i,e)=>{for(var s in e)E(i,s,{get:e[s],enumerable:!0})},_=(i,e,s,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let c of O(e))!D.call(i,c)&&c!==s&&E(i,c,{get:()=>e[c],enumerable:!(r=T(e,c))||r.enumerable});return i};var N=(i,e,s)=>(s=i!=null?R(I(i)):{},_(e||!i||!i.__esModule?E(s,"default",{value:i,enumerable:!0}):s,i)),P=i=>_(E({},"__esModule",{value:!0}),i);var q={};U(q,{ConnectToSecureChannelTask:()=>W});module.exports=P(q);var A=N(require("isomorphic-ws")),x=require("rxjs"),g=require("../../command/utils/CommandUtils"),n=require("../../secure-channel/task/types"),M=require("../../secure-channel/utils"),m=require("../../utils/HexaString"),t=require("../../../internal/secure-channel/model/Errors");class W{constructor(e,s){this._api=e;this._args=s;if(this._args.connection.isRight())this._connection=this._args.connection.extract();else throw new t.SecureChannelError(`Invalid WebSocket connection: ${String(this._args.connection.extract())}`)}_connection;run(){const e=this._api.disableRefresher("connectToSecureChannel");return new x.Observable(r=>{let c=!1,p=!1,v=!1;const l=y=>{r.next({type:n.SecureChannelEventType.Error,error:y}),r.complete(),p=!0};return this._connection.onopen=()=>{r.next({type:n.SecureChannelEventType.Opened})},this._connection.onerror=y=>{p||(r.next({type:n.SecureChannelEventType.Error,error:new t.SecureChannelError({url:this._connection.url,errorMessage:y.message})}),r.complete())},this._connection.onclose=()=>{p||(v?r.next({type:n.SecureChannelEventType.Closed}):r.next({type:n.SecureChannelEventType.Error,error:new t.SecureChannelError({url:this._connection.url,errorMessage:"Connection closed unexpectedly"})}),r.complete())},this._connection.onmessage=async y=>{if(c)return;let a;try{const o=JSON.parse(String(y.data));if(this.isInMessageType(o))a=o;else throw new Error("Data does not match InMessageType")}catch{l(new t.SecureChannelError({url:this._connection.url,errorMessage:`Invalid message received: ${String(y.data)}`}));return}switch(a.query){case n.InMessageQueryEnum.EXCHANGE:{const{nonce:o,data:d}=a;if(typeof d!="string"){l(new t.SecureChannelError(`${n.InMessageQueryEnum.EXCHANGE} data type should be an APDU`));return}const u=(0,m.hexaStringToBuffer)(d);if(u===null||u.length<5){l(new t.SecureChannelError(`Received invalid APDU data: ${d}`));return}r.next({type:n.SecureChannelEventType.PreExchange,payload:{nonce:o,apdu:u}});let f=!1;(0,M.willRequestPermission)(u)&&!this.isSecureConnectionAllowed()&&(f=!0,r.next({type:n.SecureChannelEventType.PermissionRequested}));const S=await this._api.sendApdu(u);if(c)return;S.caseOf({Left:h=>{l(new t.SecureChannelError(h))},Right:h=>{let C;const w=this.mapDeviceError(h);w===null?(C=n.OutMessageResponseEnum.SUCCESS,r.next({type:n.SecureChannelEventType.Exchange,payload:{nonce:o,apdu:u,data:h.data,status:h.statusCode}}),f&&r.next({type:n.SecureChannelEventType.PermissionGranted})):(C=n.OutMessageResponseEnum.ERROR,l(w));const k={nonce:o,response:C,data:(0,m.bufferToHexaString)(h.data,!1)};this._connection.send(JSON.stringify(k))}});break}case n.InMessageQueryEnum.BULK:{if(p=!0,this._connection.close(),!Array.isArray(a.data)||a.data.length===0||!a.data.every(o=>typeof o=="string")){l(new t.SecureChannelError("Invalid bulk data received"));return}for(let o=0,d=a.data.length;o<d;o++){const u=(0,m.hexaStringToBuffer)(a.data[o]);if(u===null||u.length<5){l(new t.SecureChannelError(`Received invalid APDU bulk data: ${a.data[o]}`));return}const f=await this._api.sendApdu(u);if(c)return;if(f.isLeft()){l(new t.SecureChannelError(f.extract()));return}else if(f.isRight()){const S=this.mapDeviceError(f.extract());if(S===null)r.next({type:n.SecureChannelEventType.Progress,payload:{progress:+Number((o+1)/d).toFixed(2),index:o,total:d}});else{l(S);return}}}v=!0,r.complete();break}case n.InMessageQueryEnum.SUCCESS:{if(p)break;const o=a.result??a.data;o&&r.next({type:n.SecureChannelEventType.Result,payload:o??""}),v=!0,r.complete();break}case n.InMessageQueryEnum.WARNING:{if(p)break;r.next({type:n.SecureChannelEventType.Warning,payload:{message:String(a.data)}});break}case n.InMessageQueryEnum.ERROR:{if(p)break;l(new t.SecureChannelError({url:this._connection.url,errorMessage:String(a.data)}))}}},()=>{e(),c=!0,this._connection.readyState===A.default.OPEN&&this._connection.close()}})}isSecureConnectionAllowed(){const e=this._api.getDeviceSessionState();return"isSecureConnectionAllowed"in e&&e.isSecureConnectionAllowed}isInMessageType(e){if(typeof e!="object"||!e)return!1;const s=e;return typeof s.uuid=="string"&&typeof s.session=="string"&&typeof s.query=="string"&&Object.values(n.InMessageQueryEnum).includes(s.query)&&typeof s.nonce=="number"}mapDeviceError(e){return g.CommandUtils.isSuccessResponse(e)?null:g.CommandUtils.isLockedDeviceResponse(e)?new t.SecureChannelError({url:this._connection.url,errorMessage:"Device is locked"},t.SecureChannelErrorType.DeviceLocked):g.CommandUtils.isRefusedByUser(e)?new t.SecureChannelError({url:this._connection.url,errorMessage:"User refused on the device"},t.SecureChannelErrorType.RefusedByUser):g.CommandUtils.isAppAlreadyInstalled(e)?new t.SecureChannelError({url:this._connection.url,errorMessage:"App already installed"},t.SecureChannelErrorType.AppAlreadyInstalled):g.CommandUtils.isOutOfMemory(e)?new t.SecureChannelError({url:this._connection.url,errorMessage:"Out of memory"},t.SecureChannelErrorType.OutOfMemory):new t.SecureChannelError({url:this._connection.url,errorMessage:`Invalid status code: ${(0,m.bufferToHexaString)(e.statusCode)}`})}}0&&(module.exports={ConnectToSecureChannelTask});
2
2
  //# sourceMappingURL=ConnectToSecureChannelTask.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/api/secure-channel/task/ConnectToSecureChannelTask.ts"],
4
- "sourcesContent": ["import WebSocket from \"isomorphic-ws\";\nimport { type Either } from \"purify-ts\";\nimport { Observable } from \"rxjs\";\n\nimport { CommandUtils } from \"@api/command/utils/CommandUtils\";\nimport { type InternalApi } from \"@api/device-action/DeviceAction\";\nimport { type ApduResponse } from \"@api/device-session/ApduResponse\";\nimport {\n InMessageQueryEnum,\n type InMessageType,\n OutMessageResponseEnum,\n type OutMessageType,\n type SecureChannelEvent,\n SecureChannelEventType,\n} from \"@api/secure-channel/task/types\";\nimport { willRequestPermission } from \"@api/secure-channel/utils\";\nimport { bufferToHexaString, hexaStringToBuffer } from \"@api/utils/HexaString\";\nimport {\n SecureChannelError,\n SecureChannelErrorType,\n type WebSocketConnectionError,\n} from \"@internal/secure-channel/model/Errors\";\n\nexport type ConnectToSecureChannelTaskArgs = {\n connection: Either<WebSocketConnectionError, WebSocket>;\n};\n\nexport class ConnectToSecureChannelTask {\n private readonly _connection: WebSocket;\n constructor(\n private readonly _api: InternalApi,\n private readonly _args: ConnectToSecureChannelTaskArgs,\n ) {\n if (this._args.connection.isRight()) {\n this._connection = this._args.connection.extract();\n } else {\n throw new SecureChannelError(\n `Invalid WebSocket connection: ${String(this._args.connection.extract())}`,\n );\n }\n }\n\n run(): Observable<SecureChannelEvent> {\n const reenableRefresher = this._api.disableRefresher(\n \"connectToSecureChannel\",\n );\n\n const obs = new Observable<SecureChannelEvent>((subscriber) => {\n let unsubscribed: boolean = false;\n let ignoreNetworkEvents = false;\n let communicationFinished = false;\n\n const notifyError = (error: SecureChannelError) => {\n subscriber.next({\n type: SecureChannelEventType.Error,\n error,\n });\n subscriber.complete();\n\n // Netowrks events can be ignored once the obervable has been completed\n ignoreNetworkEvents = true;\n };\n\n this._connection.onopen = () => {\n subscriber.next({\n type: SecureChannelEventType.Opened,\n });\n };\n\n this._connection.onerror = (error) => {\n if (ignoreNetworkEvents) {\n return;\n }\n\n subscriber.next({\n type: SecureChannelEventType.Error,\n error: new SecureChannelError({\n url: this._connection.url,\n errorMessage: error.message,\n }),\n });\n subscriber.complete();\n };\n\n this._connection.onclose = () => {\n if (ignoreNetworkEvents) {\n return;\n }\n\n if (communicationFinished) {\n subscriber.next({\n type: SecureChannelEventType.Closed,\n });\n } else {\n subscriber.next({\n type: SecureChannelEventType.Error,\n error: new SecureChannelError({\n url: this._connection.url,\n errorMessage: \"Connection closed unexpectedly\",\n }),\n });\n }\n subscriber.complete();\n };\n\n this._connection.onmessage = async (event) => {\n // When unsubscribed, ignore the message\n if (unsubscribed) {\n return;\n }\n\n // Parse input message\n let input: InMessageType;\n try {\n const jsonData = JSON.parse(String(event.data));\n if (this.isInMessageType(jsonData)) {\n input = jsonData;\n } else {\n throw new Error(\"Data does not match InMessageType\");\n }\n } catch (_) {\n notifyError(\n new SecureChannelError({\n url: this._connection.url,\n errorMessage: `Invalid message received: ${String(event.data)}`,\n }),\n );\n return;\n }\n\n // Execute message query\n switch (input.query) {\n case InMessageQueryEnum.EXCHANGE: {\n const { nonce, data } = input;\n\n // Exchange query should contain a single APDU\n if (typeof data !== \"string\") {\n notifyError(\n new SecureChannelError(\n `${InMessageQueryEnum.EXCHANGE} data type should be an APDU`,\n ),\n );\n return;\n }\n\n // APDU should be a valid hex string\n const apdu = hexaStringToBuffer(data);\n if (apdu === null || apdu.length < 5) {\n notifyError(\n new SecureChannelError(`Received invalid APDU data: ${data}`),\n );\n return;\n }\n subscriber.next({\n type: SecureChannelEventType.PreExchange,\n payload: { nonce, apdu },\n });\n\n // Notify permission requested\n let permissionRequested = false;\n if (\n willRequestPermission(apdu) &&\n !this.isSecureConnectionAllowed()\n ) {\n permissionRequested = true;\n subscriber.next({\n type: SecureChannelEventType.PermissionRequested,\n });\n }\n\n // Send APDU to the device\n const response = await this._api.sendApdu(apdu);\n if (unsubscribed) {\n return;\n }\n\n // Map device response\n response.caseOf({\n Left: (error) => {\n notifyError(new SecureChannelError(error));\n },\n Right: (apduResponse: ApduResponse) => {\n let outMessageResponse: OutMessageResponseEnum;\n const deviceError = this.mapDeviceError(apduResponse);\n if (deviceError === null) {\n outMessageResponse = OutMessageResponseEnum.SUCCESS;\n\n // Emit event for the exchange\n subscriber.next({\n type: SecureChannelEventType.Exchange,\n payload: {\n nonce,\n apdu,\n data: apduResponse.data,\n status: apduResponse.statusCode,\n },\n });\n\n // If manager consent was requested, notify the \"granted\" event\n if (permissionRequested) {\n subscriber.next({\n type: SecureChannelEventType.PermissionGranted,\n });\n }\n } else {\n outMessageResponse = OutMessageResponseEnum.ERROR;\n notifyError(deviceError);\n }\n\n // Send the message back to the server\n const message: OutMessageType = {\n nonce,\n response: outMessageResponse,\n data: bufferToHexaString(apduResponse.data, false),\n };\n this._connection.send(JSON.stringify(message));\n },\n });\n break;\n }\n case InMessageQueryEnum.BULK: {\n // Network not needed anymore during bulk APDUs sending\n ignoreNetworkEvents = true;\n this._connection.close();\n\n const startTime = Date.now();\n console.log(\"[ConnectToSecureChannelTask] BULK started\");\n\n // A valid array of APDUs is required in a bulk query\n if (\n !Array.isArray(input.data) ||\n input.data.length === 0 ||\n !input.data.every((data) => typeof data === \"string\")\n ) {\n notifyError(new SecureChannelError(\"Invalid bulk data received\"));\n return;\n }\n\n for (let i = 0, len = input.data.length; i < len; i++) {\n // APDU should be a valid hex string\n const apdu = hexaStringToBuffer(input.data[i]!);\n if (apdu === null || apdu.length < 5) {\n notifyError(\n new SecureChannelError(\n `Received invalid APDU bulk data: ${input.data[i]}`,\n ),\n );\n return;\n }\n\n // Send APDU to the device\n const response = await this._api.sendApdu(apdu);\n if (unsubscribed) {\n return;\n }\n\n // Map device response\n if (response.isLeft()) {\n notifyError(new SecureChannelError(response.extract()));\n return;\n } else if (response.isRight()) {\n const deviceError = this.mapDeviceError(response.extract());\n if (deviceError === null) {\n // Notify the progress\n subscriber.next({\n type: SecureChannelEventType.Progress,\n payload: {\n progress: +Number((i + 1) / len).toFixed(2),\n index: i,\n total: len,\n },\n });\n } else {\n notifyError(deviceError);\n return;\n }\n }\n }\n\n const endTime = Date.now();\n console.log(\n \"[ConnectToSecureChannelTask] BULK finished in\",\n endTime - startTime,\n \"ms\",\n );\n communicationFinished = true;\n subscriber.complete();\n break;\n }\n case InMessageQueryEnum.SUCCESS: {\n if (ignoreNetworkEvents) {\n break;\n }\n // Emit the result if there is any\n const payload = input.result ?? input.data;\n if (payload) {\n subscriber.next({\n type: SecureChannelEventType.Result,\n payload: payload ?? \"\",\n });\n }\n communicationFinished = true;\n subscriber.complete();\n break;\n }\n case InMessageQueryEnum.WARNING: {\n if (ignoreNetworkEvents) {\n break;\n }\n subscriber.next({\n type: SecureChannelEventType.Warning,\n payload: { message: String(input.data) },\n });\n break;\n }\n case InMessageQueryEnum.ERROR: {\n if (ignoreNetworkEvents) {\n break;\n }\n notifyError(\n new SecureChannelError({\n url: this._connection.url,\n errorMessage: String(input.data),\n }),\n );\n }\n }\n };\n\n return () => {\n reenableRefresher();\n unsubscribed = true;\n // Close the connection if it is open when unsubscribing\n if (this._connection.readyState === WebSocket.OPEN) {\n this._connection.close();\n }\n };\n });\n\n return obs;\n }\n\n /**\n * Determines if a secure connection is already allowed based on the current device session state.\n *\n * @returns {boolean} `true` if a secure connection is allowed, otherwise `false`.\n */\n isSecureConnectionAllowed(): boolean {\n const deviceSessionState = this._api.getDeviceSessionState();\n return (\n \"isSecureConnectionAllowed\" in deviceSessionState &&\n deviceSessionState.isSecureConnectionAllowed\n );\n }\n\n isInMessageType(data: unknown): data is InMessageType {\n if (typeof data !== \"object\" || !data) {\n return false;\n }\n\n const message = data as InMessageType;\n return (\n typeof message.uuid === \"string\" &&\n typeof message.session === \"string\" &&\n typeof message.query === \"string\" &&\n Object.values(InMessageQueryEnum).includes(message.query) &&\n typeof message.nonce === \"number\"\n );\n }\n\n mapDeviceError(apduResponse: ApduResponse): SecureChannelError | null {\n if (CommandUtils.isSuccessResponse(apduResponse)) {\n return null;\n }\n\n // Device is locked\n if (CommandUtils.isLockedDeviceResponse(apduResponse)) {\n return new SecureChannelError(\n {\n url: this._connection.url,\n errorMessage: `Device is locked`,\n },\n SecureChannelErrorType.DeviceLocked,\n );\n }\n\n // User refused the permission\n if (CommandUtils.isRefusedByUser(apduResponse)) {\n return new SecureChannelError(\n {\n url: this._connection.url,\n errorMessage: \"User refused on the device\",\n },\n SecureChannelErrorType.RefusedByUser,\n );\n }\n\n // App already installed\n if (CommandUtils.isAppAlreadyInstalled(apduResponse)) {\n return new SecureChannelError(\n {\n url: this._connection.url,\n errorMessage: \"App already installed\",\n },\n SecureChannelErrorType.AppAlreadyInstalled,\n );\n }\n\n // Out of memory\n if (CommandUtils.isOutOfMemory(apduResponse)) {\n return new SecureChannelError(\n {\n url: this._connection.url,\n errorMessage: \"Out of memory\",\n },\n SecureChannelErrorType.OutOfMemory,\n );\n }\n\n return new SecureChannelError({\n url: this._connection.url,\n errorMessage: `Invalid status code: ${bufferToHexaString(\n apduResponse.statusCode,\n )}`,\n });\n }\n}\n"],
5
- "mappings": "0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,gCAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAAsB,4BAEtBC,EAA2B,gBAE3BC,EAA6B,2CAG7BC,EAOO,0CACPC,EAAsC,qCACtCC,EAAuD,iCACvDC,EAIO,iDAMA,MAAMR,CAA2B,CAEtC,YACmBS,EACAC,EACjB,CAFiB,UAAAD,EACA,WAAAC,EAEjB,GAAI,KAAK,MAAM,WAAW,QAAQ,EAChC,KAAK,YAAc,KAAK,MAAM,WAAW,QAAQ,MAEjD,OAAM,IAAI,qBACR,iCAAiC,OAAO,KAAK,MAAM,WAAW,QAAQ,CAAC,CAAC,EAC1E,CAEJ,CAZiB,YAcjB,KAAsC,CACpC,MAAMC,EAAoB,KAAK,KAAK,iBAClC,wBACF,EAsSA,OApSY,IAAI,aAAgCC,GAAe,CAC7D,IAAIC,EAAwB,GACxBC,EAAsB,GACtBC,EAAwB,GAE5B,MAAMC,EAAeC,GAA8B,CACjDL,EAAW,KAAK,CACd,KAAM,yBAA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wB,sBACpCA,EAAa,UACf,CAAC,EACH,CAAC,CACH,CACF",
6
- "names": ["ConnectToSecureChannelTask_exports", "__export", "ConnectToSecureChannelTask", "__toCommonJS", "import_isomorphic_ws", "import_rxjs", "import_CommandUtils", "import_types", "import_utils", "import_HexaString", "import_Errors", "_api", "_args", "reenableRefresher", "subscriber", "unsubscribed", "ignoreNetworkEvents", "communicationFinished", "notifyError", "error", "event", "input", "jsonData", "nonce", "data", "apdu", "permissionRequested", "response", "apduResponse", "outMessageResponse", "deviceError", "message", "startTime", "i", "len", "endTime", "payload", "WebSocket", "deviceSessionState"]
4
+ "sourcesContent": ["import WebSocket from \"isomorphic-ws\";\nimport { type Either } from \"purify-ts\";\nimport { Observable } from \"rxjs\";\n\nimport { CommandUtils } from \"@api/command/utils/CommandUtils\";\nimport { type InternalApi } from \"@api/device-action/DeviceAction\";\nimport { type ApduResponse } from \"@api/device-session/ApduResponse\";\nimport {\n InMessageQueryEnum,\n type InMessageType,\n OutMessageResponseEnum,\n type OutMessageType,\n type SecureChannelEvent,\n SecureChannelEventType,\n} from \"@api/secure-channel/task/types\";\nimport { willRequestPermission } from \"@api/secure-channel/utils\";\nimport { bufferToHexaString, hexaStringToBuffer } from \"@api/utils/HexaString\";\nimport {\n SecureChannelError,\n SecureChannelErrorType,\n type WebSocketConnectionError,\n} from \"@internal/secure-channel/model/Errors\";\n\nexport type ConnectToSecureChannelTaskArgs = {\n connection: Either<WebSocketConnectionError, WebSocket>;\n};\n\nexport class ConnectToSecureChannelTask {\n private readonly _connection: WebSocket;\n constructor(\n private readonly _api: InternalApi,\n private readonly _args: ConnectToSecureChannelTaskArgs,\n ) {\n if (this._args.connection.isRight()) {\n this._connection = this._args.connection.extract();\n } else {\n throw new SecureChannelError(\n `Invalid WebSocket connection: ${String(this._args.connection.extract())}`,\n );\n }\n }\n\n run(): Observable<SecureChannelEvent> {\n const reenableRefresher = this._api.disableRefresher(\n \"connectToSecureChannel\",\n );\n\n const obs = new Observable<SecureChannelEvent>((subscriber) => {\n let unsubscribed: boolean = false;\n let ignoreNetworkEvents = false;\n let communicationFinished = false;\n\n const notifyError = (error: SecureChannelError) => {\n subscriber.next({\n type: SecureChannelEventType.Error,\n error,\n });\n subscriber.complete();\n\n // Netowrks events can be ignored once the obervable has been completed\n ignoreNetworkEvents = true;\n };\n\n this._connection.onopen = () => {\n subscriber.next({\n type: SecureChannelEventType.Opened,\n });\n };\n\n this._connection.onerror = (error) => {\n if (ignoreNetworkEvents) {\n return;\n }\n\n subscriber.next({\n type: SecureChannelEventType.Error,\n error: new SecureChannelError({\n url: this._connection.url,\n errorMessage: error.message,\n }),\n });\n subscriber.complete();\n };\n\n this._connection.onclose = () => {\n if (ignoreNetworkEvents) {\n return;\n }\n\n if (communicationFinished) {\n subscriber.next({\n type: SecureChannelEventType.Closed,\n });\n } else {\n subscriber.next({\n type: SecureChannelEventType.Error,\n error: new SecureChannelError({\n url: this._connection.url,\n errorMessage: \"Connection closed unexpectedly\",\n }),\n });\n }\n subscriber.complete();\n };\n\n this._connection.onmessage = async (event) => {\n // When unsubscribed, ignore the message\n if (unsubscribed) {\n return;\n }\n\n // Parse input message\n let input: InMessageType;\n try {\n const jsonData = JSON.parse(String(event.data));\n if (this.isInMessageType(jsonData)) {\n input = jsonData;\n } else {\n throw new Error(\"Data does not match InMessageType\");\n }\n } catch (_) {\n notifyError(\n new SecureChannelError({\n url: this._connection.url,\n errorMessage: `Invalid message received: ${String(event.data)}`,\n }),\n );\n return;\n }\n\n // Execute message query\n switch (input.query) {\n case InMessageQueryEnum.EXCHANGE: {\n const { nonce, data } = input;\n\n // Exchange query should contain a single APDU\n if (typeof data !== \"string\") {\n notifyError(\n new SecureChannelError(\n `${InMessageQueryEnum.EXCHANGE} data type should be an APDU`,\n ),\n );\n return;\n }\n\n // APDU should be a valid hex string\n const apdu = hexaStringToBuffer(data);\n if (apdu === null || apdu.length < 5) {\n notifyError(\n new SecureChannelError(`Received invalid APDU data: ${data}`),\n );\n return;\n }\n subscriber.next({\n type: SecureChannelEventType.PreExchange,\n payload: { nonce, apdu },\n });\n\n // Notify permission requested\n let permissionRequested = false;\n if (\n willRequestPermission(apdu) &&\n !this.isSecureConnectionAllowed()\n ) {\n permissionRequested = true;\n subscriber.next({\n type: SecureChannelEventType.PermissionRequested,\n });\n }\n\n // Send APDU to the device\n const response = await this._api.sendApdu(apdu);\n if (unsubscribed) {\n return;\n }\n\n // Map device response\n response.caseOf({\n Left: (error) => {\n notifyError(new SecureChannelError(error));\n },\n Right: (apduResponse: ApduResponse) => {\n let outMessageResponse: OutMessageResponseEnum;\n const deviceError = this.mapDeviceError(apduResponse);\n if (deviceError === null) {\n outMessageResponse = OutMessageResponseEnum.SUCCESS;\n\n // Emit event for the exchange\n subscriber.next({\n type: SecureChannelEventType.Exchange,\n payload: {\n nonce,\n apdu,\n data: apduResponse.data,\n status: apduResponse.statusCode,\n },\n });\n\n // If manager consent was requested, notify the \"granted\" event\n if (permissionRequested) {\n subscriber.next({\n type: SecureChannelEventType.PermissionGranted,\n });\n }\n } else {\n outMessageResponse = OutMessageResponseEnum.ERROR;\n notifyError(deviceError);\n }\n\n // Send the message back to the server\n const message: OutMessageType = {\n nonce,\n response: outMessageResponse,\n data: bufferToHexaString(apduResponse.data, false),\n };\n this._connection.send(JSON.stringify(message));\n },\n });\n break;\n }\n case InMessageQueryEnum.BULK: {\n // Network not needed anymore during bulk APDUs sending\n ignoreNetworkEvents = true;\n this._connection.close();\n\n // A valid array of APDUs is required in a bulk query\n if (\n !Array.isArray(input.data) ||\n input.data.length === 0 ||\n !input.data.every((data) => typeof data === \"string\")\n ) {\n notifyError(new SecureChannelError(\"Invalid bulk data received\"));\n return;\n }\n\n for (let i = 0, len = input.data.length; i < len; i++) {\n // APDU should be a valid hex string\n const apdu = hexaStringToBuffer(input.data[i]!);\n if (apdu === null || apdu.length < 5) {\n notifyError(\n new SecureChannelError(\n `Received invalid APDU bulk data: ${input.data[i]}`,\n ),\n );\n return;\n }\n\n // Send APDU to the device\n const response = await this._api.sendApdu(apdu);\n if (unsubscribed) {\n return;\n }\n\n // Map device response\n if (response.isLeft()) {\n notifyError(new SecureChannelError(response.extract()));\n return;\n } else if (response.isRight()) {\n const deviceError = this.mapDeviceError(response.extract());\n if (deviceError === null) {\n // Notify the progress\n subscriber.next({\n type: SecureChannelEventType.Progress,\n payload: {\n progress: +Number((i + 1) / len).toFixed(2),\n index: i,\n total: len,\n },\n });\n } else {\n notifyError(deviceError);\n return;\n }\n }\n }\n communicationFinished = true;\n subscriber.complete();\n break;\n }\n case InMessageQueryEnum.SUCCESS: {\n if (ignoreNetworkEvents) {\n break;\n }\n // Emit the result if there is any\n const payload = input.result ?? input.data;\n if (payload) {\n subscriber.next({\n type: SecureChannelEventType.Result,\n payload: payload ?? \"\",\n });\n }\n communicationFinished = true;\n subscriber.complete();\n break;\n }\n case InMessageQueryEnum.WARNING: {\n if (ignoreNetworkEvents) {\n break;\n }\n subscriber.next({\n type: SecureChannelEventType.Warning,\n payload: { message: String(input.data) },\n });\n break;\n }\n case InMessageQueryEnum.ERROR: {\n if (ignoreNetworkEvents) {\n break;\n }\n notifyError(\n new SecureChannelError({\n url: this._connection.url,\n errorMessage: String(input.data),\n }),\n );\n }\n }\n };\n\n return () => {\n reenableRefresher();\n unsubscribed = true;\n // Close the connection if it is open when unsubscribing\n if (this._connection.readyState === WebSocket.OPEN) {\n this._connection.close();\n }\n };\n });\n\n return obs;\n }\n\n /**\n * Determines if a secure connection is already allowed based on the current device session state.\n *\n * @returns {boolean} `true` if a secure connection is allowed, otherwise `false`.\n */\n isSecureConnectionAllowed(): boolean {\n const deviceSessionState = this._api.getDeviceSessionState();\n return (\n \"isSecureConnectionAllowed\" in deviceSessionState &&\n deviceSessionState.isSecureConnectionAllowed\n );\n }\n\n isInMessageType(data: unknown): data is InMessageType {\n if (typeof data !== \"object\" || !data) {\n return false;\n }\n\n const message = data as InMessageType;\n return (\n typeof message.uuid === \"string\" &&\n typeof message.session === \"string\" &&\n typeof message.query === \"string\" &&\n Object.values(InMessageQueryEnum).includes(message.query) &&\n typeof message.nonce === \"number\"\n );\n }\n\n mapDeviceError(apduResponse: ApduResponse): SecureChannelError | null {\n if (CommandUtils.isSuccessResponse(apduResponse)) {\n return null;\n }\n\n // Device is locked\n if (CommandUtils.isLockedDeviceResponse(apduResponse)) {\n return new SecureChannelError(\n {\n url: this._connection.url,\n errorMessage: `Device is locked`,\n },\n SecureChannelErrorType.DeviceLocked,\n );\n }\n\n // User refused the permission\n if (CommandUtils.isRefusedByUser(apduResponse)) {\n return new SecureChannelError(\n {\n url: this._connection.url,\n errorMessage: \"User refused on the device\",\n },\n SecureChannelErrorType.RefusedByUser,\n );\n }\n\n // App already installed\n if (CommandUtils.isAppAlreadyInstalled(apduResponse)) {\n return new SecureChannelError(\n {\n url: this._connection.url,\n errorMessage: \"App already installed\",\n },\n SecureChannelErrorType.AppAlreadyInstalled,\n );\n }\n\n // Out of memory\n if (CommandUtils.isOutOfMemory(apduResponse)) {\n return new SecureChannelError(\n {\n url: this._connection.url,\n errorMessage: \"Out of memory\",\n },\n SecureChannelErrorType.OutOfMemory,\n );\n }\n\n return new SecureChannelError({\n url: this._connection.url,\n errorMessage: `Invalid status code: ${bufferToHexaString(\n apduResponse.statusCode,\n )}`,\n });\n }\n}\n"],
5
+ "mappings": "0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,gCAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAAsB,4BAEtBC,EAA2B,gBAE3BC,EAA6B,2CAG7BC,EAOO,0CACPC,EAAsC,qCACtCC,EAAuD,iCACvDC,EAIO,iDAMA,MAAMR,CAA2B,CAEtC,YACmBS,EACAC,EACjB,CAFiB,UAAAD,EACA,WAAAC,EAEjB,GAAI,KAAK,MAAM,WAAW,QAAQ,EAChC,KAAK,YAAc,KAAK,MAAM,WAAW,QAAQ,MAEjD,OAAM,IAAI,qBACR,iCAAiC,OAAO,KAAK,MAAM,WAAW,QAAQ,CAAC,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IACtB,aAAc,eAChB,EACA,yBAAuB,WACzB,EAGK,IAAI,qBAAmB,CAC5B,IAAK,KAAK,YAAY,IACtB,aAAc,2BAAwB,sBACpCA,EAAa,UACf,CAAC,EACH,CAAC,CACH,CACF",
6
+ "names": ["ConnectToSecureChannelTask_exports", "__export", "ConnectToSecureChannelTask", "__toCommonJS", "import_isomorphic_ws", "import_rxjs", "import_CommandUtils", "import_types", "import_utils", "import_HexaString", "import_Errors", "_api", "_args", "reenableRefresher", "subscriber", "unsubscribed", "ignoreNetworkEvents", "communicationFinished", "notifyError", "error", "event", "input", "jsonData", "nonce", "data", "apdu", "permissionRequested", "response", "apduResponse", "outMessageResponse", "deviceError", "message", "i", "len", "payload", "WebSocket", "deviceSessionState"]
7
7
  }
@@ -1,2 +1,2 @@
1
- "use strict";var a=Object.defineProperty;var A=Object.getOwnPropertyDescriptor;var C=Object.getOwnPropertyNames;var R=Object.prototype.hasOwnProperty;var b=(n,e)=>{for(var t in e)a(n,t,{get:e[t],enumerable:!0})},y=(n,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of C(e))!R.call(n,i)&&i!==t&&a(n,i,{get:()=>e[i],enumerable:!(s=A(e,i))||s.enumerable});return n};var T=n=>y(a({},"__esModule",{value:!0}),n);var I={};b(I,{DeviceSession:()=>O});module.exports=T(I);var v=require("rxjs"),d=require("uuid"),h=require("../../../api/command/utils/CommandUtils"),p=require("../../../api/device/DeviceStatus"),S=require("../../../api/device-session/DeviceSessionState"),u=require("../../device-session/data/DeviceSessionRefresherConst"),m=require("../../device-session/service/MutexService"),D=require("../../device-session/service/RefresherService"),l=require("./DevicePinger"),o=require("./DeviceSessionEventDispatcher"),_=require("./DeviceSessionRefresher"),f=require("./DeviceSessionStateHandler");class O{_id;_connectedDevice;_deviceState;_managerApiService;_secureChannelService;_logger;_refresherOptions;_pinger;_deviceSessionRefresher;_refresherService;_commandMutex=new m.MutexService;_sessionEventDispatcher=new o.DeviceSessionEventDispatcher;constructor({connectedDevice:e,id:t=(0,d.v4)()},s,i,r,g){this._id=t,this._connectedDevice=e,this._logger=s("device-session"),this._managerApiService=i,this._secureChannelService=r,this._refresherOptions={...u.DEVICE_SESSION_REFRESHER_DEFAULT_OPTIONS,...g},this._deviceState=new v.BehaviorSubject({sessionStateType:S.DeviceSessionStateType.Connected,deviceStatus:p.DeviceStatus.CONNECTED,deviceModelId:this._connectedDevice.deviceModel.id}),this._pinger=new l.DevicePinger(s,e,this._sessionEventDispatcher,(c,E)=>this.sendCommand(c,E)),this._deviceSessionRefresher=new _.DeviceSessionRefresher(s,this._refresherOptions,this._sessionEventDispatcher,this._connectedDevice),new f.DeviceSessionStateHandler(s,this._sessionEventDispatcher,this._connectedDevice,this._deviceState,c=>this.setDeviceSessionState(c)),this._refresherService=new D.RefresherService(s,{start:()=>this._deviceSessionRefresher.restartRefresher(),stop:()=>this._deviceSessionRefresher.stopRefresher()})}async initialiseSession(){try{await this._pinger.ping()}catch(e){throw this._logger.error("Error while initialising session",{data:{error:e}}),e}finally{this._refresherOptions.isRefresherDisabled||this._deviceSessionRefresher.startRefresher()}}get id(){return this._id}get connectedDevice(){return this._connectedDevice}get state(){return this._deviceState.asObservable()}getDeviceSessionState(){return this._deviceState.getValue()}setDeviceSessionState(e){this._deviceState.next(e)}async sendApdu(e,t={isPolling:!1,triggersDisconnection:!1,abortTimeout:void 0}){const s=await this._commandMutex.lock();try{this._sessionEventDispatcher.dispatch({eventName:o.SessionEvents.DEVICE_STATE_UPDATE_BUSY});const i=await this._connectedDevice.sendApdu(e,t.triggersDisconnection,t.abortTimeout);return i.ifRight(r=>{h.CommandUtils.isLockedDeviceResponse(r)?this._sessionEventDispatcher.dispatch({eventName:o.SessionEvents.DEVICE_STATE_UPDATE_LOCKED}):this._sessionEventDispatcher.dispatch({eventName:o.SessionEvents.DEVICE_STATE_UPDATE_CONNECTED})}).ifLeft(()=>{this._sessionEventDispatcher.dispatch({eventName:o.SessionEvents.DEVICE_STATE_UPDATE_CONNECTED})}),i}finally{s()}}async sendCommand(e,t){const s=e.getApdu();return(await this.sendApdu(s.getRawApdu(),{isPolling:!1,triggersDisconnection:e.triggersDisconnection??!1,abortTimeout:t})).caseOf({Left:r=>{throw r},Right:r=>e.parseResponse(r,this._connectedDevice.deviceModel.id)})}executeDeviceAction(e){const{observable:t,cancel:s}=e._execute({sendApdu:async i=>this.sendApdu(i),sendCommand:async(i,r)=>this.sendCommand(i,r),getDeviceModel:()=>this._connectedDevice.deviceModel,getDeviceSessionState:()=>this._deviceState.getValue(),getDeviceSessionStateObservable:()=>this.state,setDeviceSessionState:i=>(this.setDeviceSessionState(i),this._deviceState.getValue()),disableRefresher:i=>this._refresherService.disableRefresher(i),getManagerApiService:()=>this._managerApiService,getSecureChannelService:()=>this._secureChannelService});return{observable:t,cancel:s}}close(){this._updateDeviceStatus(p.DeviceStatus.NOT_CONNECTED),this._deviceState.complete(),this._deviceSessionRefresher.stopRefresher()}disableRefresher(e){return this._refresherService.disableRefresher(e)}_updateDeviceStatus(e){const t=this._deviceState.getValue();this._deviceState.next({...t,deviceStatus:e})}}0&&(module.exports={DeviceSession});
1
+ "use strict";var v=Object.defineProperty;var C=Object.getOwnPropertyDescriptor;var R=Object.getOwnPropertyNames;var A=Object.prototype.hasOwnProperty;var y=(n,e)=>{for(var t in e)v(n,t,{get:e[t],enumerable:!0})},T=(n,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of R(e))!A.call(n,i)&&i!==t&&v(n,i,{get:()=>e[i],enumerable:!(s=C(e,i))||s.enumerable});return n};var O=n=>T(v({},"__esModule",{value:!0}),n);var x={};y(x,{DeviceSession:()=>I});module.exports=O(x);var d=require("rxjs"),h=require("uuid"),S=require("../../../api/command/utils/CommandUtils"),p=require("../../../api/device/DeviceStatus"),u=require("../../../api/device-session/DeviceSessionState"),c=require("../../../api/index"),m=require("../../device-session/data/DeviceSessionRefresherConst"),D=require("../../device-session/service/MutexService"),l=require("../../device-session/service/RefresherService"),_=require("./DevicePinger"),o=require("./DeviceSessionEventDispatcher"),f=require("./DeviceSessionRefresher"),g=require("./DeviceSessionStateHandler");class I{_id;_connectedDevice;_deviceState;_managerApiService;_secureChannelService;_logger;_refresherOptions;_pinger;_deviceSessionRefresher;_refresherService;_commandMutex=new D.MutexService;_sessionEventDispatcher=new o.DeviceSessionEventDispatcher;constructor({connectedDevice:e,id:t=(0,h.v4)()},s,i,r,E){this._id=t,this._connectedDevice=e,this._logger=s("device-session"),this._managerApiService=i,this._secureChannelService=r,this._refresherOptions={...m.DEVICE_SESSION_REFRESHER_DEFAULT_OPTIONS,...E},this._deviceState=new d.BehaviorSubject({sessionStateType:u.DeviceSessionStateType.Connected,deviceStatus:p.DeviceStatus.CONNECTED,deviceModelId:this._connectedDevice.deviceModel.id}),this._pinger=new _.DevicePinger(s,e,this._sessionEventDispatcher,(a,b)=>this.sendCommand(a,b)),this._deviceSessionRefresher=new f.DeviceSessionRefresher(s,this._refresherOptions,this._sessionEventDispatcher,this._connectedDevice),new g.DeviceSessionStateHandler(s,this._sessionEventDispatcher,this._connectedDevice,this._deviceState,a=>this.setDeviceSessionState(a)),this._refresherService=new l.RefresherService(s,{start:()=>this._deviceSessionRefresher.restartRefresher(),stop:()=>this._deviceSessionRefresher.stopRefresher()})}async initialiseSession(){try{await this._pinger.ping()}catch(e){throw this._logger.error("Error while initialising session",{data:{error:e}}),e}finally{this._refresherOptions.isRefresherDisabled||this._deviceSessionRefresher.startRefresher()}}get id(){return this._id}get connectedDevice(){return this._connectedDevice}get state(){return this._deviceState.asObservable()}getDeviceSessionState(){return this._deviceState.getValue()}setDeviceSessionState(e){this._deviceState.next(e)}async sendApdu(e,t={isPolling:!1,triggersDisconnection:!1,abortTimeout:void 0}){const s=await this._commandMutex.lock();try{this._sessionEventDispatcher.dispatch({eventName:o.SessionEvents.DEVICE_STATE_UPDATE_BUSY}),this._logger.debug(`[exchange] => ${(0,c.bufferToHexaString)(e,!1)}`);const i=await this._connectedDevice.sendApdu(e,t.triggersDisconnection,t.abortTimeout);return i.ifRight(r=>{this._logger.debug(`[exchange] <= ${(0,c.bufferToHexaString)(r.data,!1)}${(0,c.bufferToHexaString)(r.statusCode,!1)}`),S.CommandUtils.isLockedDeviceResponse(r)?this._sessionEventDispatcher.dispatch({eventName:o.SessionEvents.DEVICE_STATE_UPDATE_LOCKED}):this._sessionEventDispatcher.dispatch({eventName:o.SessionEvents.DEVICE_STATE_UPDATE_CONNECTED})}).ifLeft(()=>{this._sessionEventDispatcher.dispatch({eventName:o.SessionEvents.DEVICE_STATE_UPDATE_CONNECTED})}),i}finally{s()}}async sendCommand(e,t){const s=e.getApdu();return(await this.sendApdu(s.getRawApdu(),{isPolling:!1,triggersDisconnection:e.triggersDisconnection??!1,abortTimeout:t})).caseOf({Left:r=>{throw r},Right:r=>e.parseResponse(r,this._connectedDevice.deviceModel.id)})}executeDeviceAction(e){const{observable:t,cancel:s}=e._execute({sendApdu:async i=>this.sendApdu(i),sendCommand:async(i,r)=>this.sendCommand(i,r),getDeviceModel:()=>this._connectedDevice.deviceModel,getDeviceSessionState:()=>this._deviceState.getValue(),getDeviceSessionStateObservable:()=>this.state,setDeviceSessionState:i=>(this.setDeviceSessionState(i),this._deviceState.getValue()),disableRefresher:i=>this._refresherService.disableRefresher(i),getManagerApiService:()=>this._managerApiService,getSecureChannelService:()=>this._secureChannelService});return{observable:t,cancel:s}}close(){this._updateDeviceStatus(p.DeviceStatus.NOT_CONNECTED),this._deviceState.complete(),this._deviceSessionRefresher.stopRefresher()}disableRefresher(e){return this._refresherService.disableRefresher(e)}_updateDeviceStatus(e){const t=this._deviceState.getValue();this._deviceState.next({...t,deviceStatus:e})}}0&&(module.exports={DeviceSession});
2
2
  //# sourceMappingURL=DeviceSession.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/internal/device-session/model/DeviceSession.ts"],
4
- "sourcesContent": ["import { type Either } from \"purify-ts\";\nimport { BehaviorSubject, type Observable } from \"rxjs\";\nimport { v4 as uuidv4 } from \"uuid\";\n\nimport { type Command } from \"@api/command/Command\";\nimport { type CommandResult } from \"@api/command/model/CommandResult\";\nimport { CommandUtils } from \"@api/command/utils/CommandUtils\";\nimport { DeviceStatus } from \"@api/device/DeviceStatus\";\nimport {\n type DeviceAction,\n type DeviceActionIntermediateValue,\n type ExecuteDeviceActionReturnType,\n} from \"@api/device-action/DeviceAction\";\nimport { type ApduResponse } from \"@api/device-session/ApduResponse\";\nimport {\n type DeviceSessionState,\n DeviceSessionStateType,\n} from \"@api/device-session/DeviceSessionState\";\nimport { type DeviceSessionId } from \"@api/device-session/types\";\nimport { type DmkError } from \"@api/Error\";\nimport { type LoggerPublisherService } from \"@api/logger-publisher/service/LoggerPublisherService\";\nimport { type TransportConnectedDevice } from \"@api/transport/model/TransportConnectedDevice\";\nimport { DEVICE_SESSION_REFRESHER_DEFAULT_OPTIONS } from \"@internal/device-session/data/DeviceSessionRefresherConst\";\nimport { MutexService } from \"@internal/device-session/service/MutexService\";\nimport { RefresherService } from \"@internal/device-session/service/RefresherService\";\nimport { type ManagerApiService } from \"@internal/manager-api/service/ManagerApiService\";\nimport { type SecureChannelService } from \"@internal/secure-channel/service/SecureChannelService\";\n\nimport { DevicePinger } from \"./DevicePinger\";\nimport {\n DeviceSessionEventDispatcher,\n SessionEvents,\n} from \"./DeviceSessionEventDispatcher\";\nimport { DeviceSessionRefresher } from \"./DeviceSessionRefresher\";\nimport { DeviceSessionStateHandler } from \"./DeviceSessionStateHandler\";\n\nexport type SessionConstructorArgs = {\n connectedDevice: TransportConnectedDevice;\n id?: DeviceSessionId;\n};\n\nexport type DeviceSessionRefresherOptions = {\n isRefresherDisabled: boolean;\n pollingInterval?: number;\n};\n\ntype SendApduOptions = {\n isPolling?: boolean;\n triggersDisconnection?: boolean;\n abortTimeout?: number;\n};\n\n/**\n * Represents a session with a device.\n */\nexport class DeviceSession {\n private readonly _id: DeviceSessionId;\n private readonly _connectedDevice: TransportConnectedDevice;\n private readonly _deviceState: BehaviorSubject<DeviceSessionState>;\n private readonly _managerApiService: ManagerApiService;\n private readonly _secureChannelService: SecureChannelService;\n private readonly _logger: LoggerPublisherService;\n private readonly _refresherOptions: DeviceSessionRefresherOptions;\n private _pinger: DevicePinger;\n private _deviceSessionRefresher: DeviceSessionRefresher;\n private readonly _refresherService: RefresherService;\n private _commandMutex = new MutexService();\n private _sessionEventDispatcher = new DeviceSessionEventDispatcher();\n\n constructor(\n { connectedDevice, id = uuidv4() }: SessionConstructorArgs,\n loggerModuleFactory: (tag: string) => LoggerPublisherService,\n managerApiService: ManagerApiService,\n secureChannelService: SecureChannelService,\n deviceSessionRefresherOptions: DeviceSessionRefresherOptions | undefined,\n ) {\n this._id = id;\n this._connectedDevice = connectedDevice;\n this._logger = loggerModuleFactory(\"device-session\");\n this._managerApiService = managerApiService;\n this._secureChannelService = secureChannelService;\n this._refresherOptions = {\n ...DEVICE_SESSION_REFRESHER_DEFAULT_OPTIONS,\n ...deviceSessionRefresherOptions,\n };\n this._deviceState = new BehaviorSubject<DeviceSessionState>({\n sessionStateType: DeviceSessionStateType.Connected,\n deviceStatus: DeviceStatus.CONNECTED,\n deviceModelId: this._connectedDevice.deviceModel.id,\n });\n\n this._pinger = new DevicePinger(\n loggerModuleFactory,\n connectedDevice,\n this._sessionEventDispatcher,\n (command, abortTimeout) => this.sendCommand(command, abortTimeout),\n );\n this._deviceSessionRefresher = new DeviceSessionRefresher(\n loggerModuleFactory,\n this._refresherOptions,\n this._sessionEventDispatcher,\n this._connectedDevice,\n );\n new DeviceSessionStateHandler(\n loggerModuleFactory,\n this._sessionEventDispatcher,\n this._connectedDevice,\n this._deviceState,\n (state) => this.setDeviceSessionState(state),\n );\n\n this._refresherService = new RefresherService(loggerModuleFactory, {\n start: () => this._deviceSessionRefresher.restartRefresher(),\n stop: () => this._deviceSessionRefresher.stopRefresher(),\n });\n }\n\n public async initialiseSession(): Promise<void> {\n try {\n await this._pinger.ping();\n } catch (error) {\n this._logger.error(\"Error while initialising session\", {\n data: { error },\n });\n throw error;\n } finally {\n if (!this._refresherOptions.isRefresherDisabled) {\n this._deviceSessionRefresher.startRefresher();\n }\n }\n }\n\n public get id(): DeviceSessionId {\n return this._id;\n }\n\n public get connectedDevice(): TransportConnectedDevice {\n return this._connectedDevice;\n }\n\n public get state(): Observable<DeviceSessionState> {\n return this._deviceState.asObservable();\n }\n\n public getDeviceSessionState(): DeviceSessionState {\n return this._deviceState.getValue();\n }\n\n public setDeviceSessionState(state: DeviceSessionState): void {\n this._deviceState.next(state);\n }\n\n public async sendApdu(\n rawApdu: Uint8Array,\n options: SendApduOptions = {\n isPolling: false,\n triggersDisconnection: false,\n abortTimeout: undefined,\n },\n ): Promise<Either<DmkError, ApduResponse>> {\n const release = await this._commandMutex.lock();\n\n try {\n this._sessionEventDispatcher.dispatch({\n eventName: SessionEvents.DEVICE_STATE_UPDATE_BUSY,\n });\n const result = await this._connectedDevice.sendApdu(\n rawApdu,\n options.triggersDisconnection,\n options.abortTimeout,\n );\n\n result\n .ifRight((response: ApduResponse) => {\n if (CommandUtils.isLockedDeviceResponse(response)) {\n this._sessionEventDispatcher.dispatch({\n eventName: SessionEvents.DEVICE_STATE_UPDATE_LOCKED,\n });\n } else {\n this._sessionEventDispatcher.dispatch({\n eventName: SessionEvents.DEVICE_STATE_UPDATE_CONNECTED,\n });\n }\n })\n .ifLeft(() => {\n this._sessionEventDispatcher.dispatch({\n eventName: SessionEvents.DEVICE_STATE_UPDATE_CONNECTED,\n });\n });\n return result;\n } finally {\n release();\n }\n }\n\n public async sendCommand<Response, Args, ErrorStatusCodes>(\n command: Command<Response, Args, ErrorStatusCodes>,\n abortTimeout?: number,\n ): Promise<CommandResult<Response, ErrorStatusCodes>> {\n const apdu = command.getApdu();\n\n const response = await this.sendApdu(apdu.getRawApdu(), {\n isPolling: false,\n triggersDisconnection: command.triggersDisconnection ?? false,\n abortTimeout,\n });\n\n return response.caseOf({\n Left: (err) => {\n throw err;\n },\n Right: (r) =>\n command.parseResponse(r, this._connectedDevice.deviceModel.id),\n });\n }\n\n public executeDeviceAction<\n Output,\n Input,\n E extends DmkError,\n IntermediateValue extends DeviceActionIntermediateValue,\n >(\n deviceAction: DeviceAction<Output, Input, E, IntermediateValue>,\n ): ExecuteDeviceActionReturnType<Output, E, IntermediateValue> {\n const { observable, cancel } = deviceAction._execute({\n sendApdu: async (apdu: Uint8Array) => this.sendApdu(apdu),\n sendCommand: async <Response, ErrorStatusCodes, Args>(\n command: Command<Response, ErrorStatusCodes, Args>,\n abortTimeout?: number,\n ) => this.sendCommand(command, abortTimeout),\n getDeviceModel: () => this._connectedDevice.deviceModel,\n getDeviceSessionState: () => this._deviceState.getValue(),\n getDeviceSessionStateObservable: () => this.state,\n setDeviceSessionState: (state: DeviceSessionState) => {\n this.setDeviceSessionState(state);\n return this._deviceState.getValue();\n },\n disableRefresher: (blockerId: string) =>\n this._refresherService.disableRefresher(blockerId),\n getManagerApiService: () => this._managerApiService,\n getSecureChannelService: () => this._secureChannelService,\n });\n return { observable, cancel };\n }\n\n public close(): void {\n this._updateDeviceStatus(DeviceStatus.NOT_CONNECTED);\n this._deviceState.complete();\n this._deviceSessionRefresher.stopRefresher();\n }\n\n public disableRefresher(id: string): () => void {\n return this._refresherService.disableRefresher(id);\n }\n\n private _updateDeviceStatus(deviceStatus: DeviceStatus): void {\n const state = this._deviceState.getValue();\n this._deviceState.next({ ...state, deviceStatus });\n }\n}\n"],
5
- "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,mBAAAE,IAAA,eAAAC,EAAAH,GACA,IAAAI,EAAiD,gBACjDC,EAA6B,gBAI7BC,EAA6B,2CAC7BC,EAA6B,oCAO7BC,EAGO,kDAKPC,EAAyD,qEACzDC,EAA6B,yDAC7BC,EAAiC,6DAIjCC,EAA6B,0BAC7BC,EAGO,0CACPC,EAAuC,oCACvCC,EAA0C,uCAqBnC,MAAMb,CAAc,CACR,IACA,iBACA,aACA,mBACA,sBACA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,KAAK,iBAAiB,YAC5C,sBAAuB,IAAM,KAAK,aAAa,SAAS,EACxD,gCAAiC,IAAM,KAAK,MAC5C,sBAAwBC,IACtB,KAAK,sBAAsBA,CAAK,EACzB,KAAK,aAAa,SAAS,GAEpC,iBAAmBY,GACjB,KAAK,kBAAkB,iBAAiBA,CAAS,EACnD,qBAAsB,IAAM,KAAK,mBACjC,wBAAyB,IAAM,KAAK,qBACtC,CAAC,EACD,MAAO,CAAE,WAAAF,EAAY,OAAAC,CAAO,CAC9B,CAEO,OAAc,CACnB,KAAK,oBAAoB,eAAa,aAAa,EACnD,KAAK,aAAa,SAAS,EAC3B,KAAK,wBAAwB,cAAc,CAC7C,CAEO,iBAAiBnB,EAAwB,CAC9C,OAAO,KAAK,kBAAkB,iBAAiBA,CAAE,CACnD,CAEQ,oBAAoBqB,EAAkC,CAC5D,MAAMb,EAAQ,KAAK,aAAa,SAAS,EACzC,KAAK,aAAa,KAAK,CAAE,GAAGA,EAAO,aAAAa,CAAa,CAAC,CACnD,CACF",
6
- "names": ["DeviceSession_exports", "__export", "DeviceSession", "__toCommonJS", "import_rxjs", "import_uuid", "import_CommandUtils", "import_DeviceStatus", "import_DeviceSessionState", "import_DeviceSessionRefresherConst", "import_MutexService", "import_RefresherService", "import_DevicePinger", "import_DeviceSessionEventDispatcher", "import_DeviceSessionRefresher", "import_DeviceSessionStateHandler", "connectedDevice", "id", "uuidv4", "loggerModuleFactory", "managerApiService", "secureChannelService", "deviceSessionRefresherOptions", "command", "abortTimeout", "state", "error", "rawApdu", "options", "release", "result", "response", "apdu", "err", "deviceAction", "observable", "cancel", "blockerId", "deviceStatus"]
4
+ "sourcesContent": ["import { type Either } from \"purify-ts\";\nimport { BehaviorSubject, type Observable } from \"rxjs\";\nimport { v4 as uuidv4 } from \"uuid\";\n\nimport { type Command } from \"@api/command/Command\";\nimport { type CommandResult } from \"@api/command/model/CommandResult\";\nimport { CommandUtils } from \"@api/command/utils/CommandUtils\";\nimport { DeviceStatus } from \"@api/device/DeviceStatus\";\nimport {\n type DeviceAction,\n type DeviceActionIntermediateValue,\n type ExecuteDeviceActionReturnType,\n} from \"@api/device-action/DeviceAction\";\nimport { type ApduResponse } from \"@api/device-session/ApduResponse\";\nimport {\n type DeviceSessionState,\n DeviceSessionStateType,\n} from \"@api/device-session/DeviceSessionState\";\nimport { type DeviceSessionId } from \"@api/device-session/types\";\nimport { type DmkError } from \"@api/Error\";\nimport { bufferToHexaString } from \"@api/index\";\nimport { type LoggerPublisherService } from \"@api/logger-publisher/service/LoggerPublisherService\";\nimport { type TransportConnectedDevice } from \"@api/transport/model/TransportConnectedDevice\";\nimport { DEVICE_SESSION_REFRESHER_DEFAULT_OPTIONS } from \"@internal/device-session/data/DeviceSessionRefresherConst\";\nimport { MutexService } from \"@internal/device-session/service/MutexService\";\nimport { RefresherService } from \"@internal/device-session/service/RefresherService\";\nimport { type ManagerApiService } from \"@internal/manager-api/service/ManagerApiService\";\nimport { type SecureChannelService } from \"@internal/secure-channel/service/SecureChannelService\";\n\nimport { DevicePinger } from \"./DevicePinger\";\nimport {\n DeviceSessionEventDispatcher,\n SessionEvents,\n} from \"./DeviceSessionEventDispatcher\";\nimport { DeviceSessionRefresher } from \"./DeviceSessionRefresher\";\nimport { DeviceSessionStateHandler } from \"./DeviceSessionStateHandler\";\n\nexport type SessionConstructorArgs = {\n connectedDevice: TransportConnectedDevice;\n id?: DeviceSessionId;\n};\n\nexport type DeviceSessionRefresherOptions = {\n isRefresherDisabled: boolean;\n pollingInterval?: number;\n};\n\ntype SendApduOptions = {\n isPolling?: boolean;\n triggersDisconnection?: boolean;\n abortTimeout?: number;\n};\n\n/**\n * Represents a session with a device.\n */\nexport class DeviceSession {\n private readonly _id: DeviceSessionId;\n private readonly _connectedDevice: TransportConnectedDevice;\n private readonly _deviceState: BehaviorSubject<DeviceSessionState>;\n private readonly _managerApiService: ManagerApiService;\n private readonly _secureChannelService: SecureChannelService;\n private readonly _logger: LoggerPublisherService;\n private readonly _refresherOptions: DeviceSessionRefresherOptions;\n private _pinger: DevicePinger;\n private _deviceSessionRefresher: DeviceSessionRefresher;\n private readonly _refresherService: RefresherService;\n private _commandMutex = new MutexService();\n private _sessionEventDispatcher = new DeviceSessionEventDispatcher();\n\n constructor(\n { connectedDevice, id = uuidv4() }: SessionConstructorArgs,\n loggerModuleFactory: (tag: string) => LoggerPublisherService,\n managerApiService: ManagerApiService,\n secureChannelService: SecureChannelService,\n deviceSessionRefresherOptions: DeviceSessionRefresherOptions | undefined,\n ) {\n this._id = id;\n this._connectedDevice = connectedDevice;\n this._logger = loggerModuleFactory(\"device-session\");\n this._managerApiService = managerApiService;\n this._secureChannelService = secureChannelService;\n this._refresherOptions = {\n ...DEVICE_SESSION_REFRESHER_DEFAULT_OPTIONS,\n ...deviceSessionRefresherOptions,\n };\n this._deviceState = new BehaviorSubject<DeviceSessionState>({\n sessionStateType: DeviceSessionStateType.Connected,\n deviceStatus: DeviceStatus.CONNECTED,\n deviceModelId: this._connectedDevice.deviceModel.id,\n });\n\n this._pinger = new DevicePinger(\n loggerModuleFactory,\n connectedDevice,\n this._sessionEventDispatcher,\n (command, abortTimeout) => this.sendCommand(command, abortTimeout),\n );\n this._deviceSessionRefresher = new DeviceSessionRefresher(\n loggerModuleFactory,\n this._refresherOptions,\n this._sessionEventDispatcher,\n this._connectedDevice,\n );\n new DeviceSessionStateHandler(\n loggerModuleFactory,\n this._sessionEventDispatcher,\n this._connectedDevice,\n this._deviceState,\n (state) => this.setDeviceSessionState(state),\n );\n\n this._refresherService = new RefresherService(loggerModuleFactory, {\n start: () => this._deviceSessionRefresher.restartRefresher(),\n stop: () => this._deviceSessionRefresher.stopRefresher(),\n });\n }\n\n public async initialiseSession(): Promise<void> {\n try {\n await this._pinger.ping();\n } catch (error) {\n this._logger.error(\"Error while initialising session\", {\n data: { error },\n });\n throw error;\n } finally {\n if (!this._refresherOptions.isRefresherDisabled) {\n this._deviceSessionRefresher.startRefresher();\n }\n }\n }\n\n public get id(): DeviceSessionId {\n return this._id;\n }\n\n public get connectedDevice(): TransportConnectedDevice {\n return this._connectedDevice;\n }\n\n public get state(): Observable<DeviceSessionState> {\n return this._deviceState.asObservable();\n }\n\n public getDeviceSessionState(): DeviceSessionState {\n return this._deviceState.getValue();\n }\n\n public setDeviceSessionState(state: DeviceSessionState): void {\n this._deviceState.next(state);\n }\n\n public async sendApdu(\n rawApdu: Uint8Array,\n options: SendApduOptions = {\n isPolling: false,\n triggersDisconnection: false,\n abortTimeout: undefined,\n },\n ): Promise<Either<DmkError, ApduResponse>> {\n const release = await this._commandMutex.lock();\n\n try {\n this._sessionEventDispatcher.dispatch({\n eventName: SessionEvents.DEVICE_STATE_UPDATE_BUSY,\n });\n\n this._logger.debug(`[exchange] => ${bufferToHexaString(rawApdu, false)}`);\n const result = await this._connectedDevice.sendApdu(\n rawApdu,\n options.triggersDisconnection,\n options.abortTimeout,\n );\n\n result\n .ifRight((response: ApduResponse) => {\n this._logger.debug(\n `[exchange] <= ${bufferToHexaString(response.data, false)}${bufferToHexaString(response.statusCode, false)}`,\n );\n if (CommandUtils.isLockedDeviceResponse(response)) {\n this._sessionEventDispatcher.dispatch({\n eventName: SessionEvents.DEVICE_STATE_UPDATE_LOCKED,\n });\n } else {\n this._sessionEventDispatcher.dispatch({\n eventName: SessionEvents.DEVICE_STATE_UPDATE_CONNECTED,\n });\n }\n })\n .ifLeft(() => {\n this._sessionEventDispatcher.dispatch({\n eventName: SessionEvents.DEVICE_STATE_UPDATE_CONNECTED,\n });\n });\n return result;\n } finally {\n release();\n }\n }\n\n public async sendCommand<Response, Args, ErrorStatusCodes>(\n command: Command<Response, Args, ErrorStatusCodes>,\n abortTimeout?: number,\n ): Promise<CommandResult<Response, ErrorStatusCodes>> {\n const apdu = command.getApdu();\n\n const response = await this.sendApdu(apdu.getRawApdu(), {\n isPolling: false,\n triggersDisconnection: command.triggersDisconnection ?? false,\n abortTimeout,\n });\n\n return response.caseOf({\n Left: (err) => {\n throw err;\n },\n Right: (r) =>\n command.parseResponse(r, this._connectedDevice.deviceModel.id),\n });\n }\n\n public executeDeviceAction<\n Output,\n Input,\n E extends DmkError,\n IntermediateValue extends DeviceActionIntermediateValue,\n >(\n deviceAction: DeviceAction<Output, Input, E, IntermediateValue>,\n ): ExecuteDeviceActionReturnType<Output, E, IntermediateValue> {\n const { observable, cancel } = deviceAction._execute({\n sendApdu: async (apdu: Uint8Array) => this.sendApdu(apdu),\n sendCommand: async <Response, ErrorStatusCodes, Args>(\n command: Command<Response, ErrorStatusCodes, Args>,\n abortTimeout?: number,\n ) => this.sendCommand(command, abortTimeout),\n getDeviceModel: () => this._connectedDevice.deviceModel,\n getDeviceSessionState: () => this._deviceState.getValue(),\n getDeviceSessionStateObservable: () => this.state,\n setDeviceSessionState: (state: DeviceSessionState) => {\n this.setDeviceSessionState(state);\n return this._deviceState.getValue();\n },\n disableRefresher: (blockerId: string) =>\n this._refresherService.disableRefresher(blockerId),\n getManagerApiService: () => this._managerApiService,\n getSecureChannelService: () => this._secureChannelService,\n });\n return { observable, cancel };\n }\n\n public close(): void {\n this._updateDeviceStatus(DeviceStatus.NOT_CONNECTED);\n this._deviceState.complete();\n this._deviceSessionRefresher.stopRefresher();\n }\n\n public disableRefresher(id: string): () => void {\n return this._refresherService.disableRefresher(id);\n }\n\n private _updateDeviceStatus(deviceStatus: DeviceStatus): void {\n const state = this._deviceState.getValue();\n this._deviceState.next({ ...state, deviceStatus });\n }\n}\n"],
5
+ "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,mBAAAE,IAAA,eAAAC,EAAAH,GACA,IAAAI,EAAiD,gBACjDC,EAA6B,gBAI7BC,EAA6B,2CAC7BC,EAA6B,oCAO7BC,EAGO,kDAGPC,EAAmC,sBAGnCC,EAAyD,qEACzDC,EAA6B,yDAC7BC,EAAiC,6DAIjCC,EAA6B,0BAC7BC,EAGO,0CACPC,EAAuC,oCACvCC,EAA0C,uCAqBnC,MAAMd,CAAc,CACR,IACA,iBACA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MLW,EAC6D,CAC7D,KAAM,CAAE,WAAAC,EAAY,OAAAC,CAAO,EAAIF,EAAa,SAAS,CACnD,SAAU,MAAOF,GAAqB,KAAK,SAASA,CAAI,EACxD,YAAa,MACXT,EACAC,IACG,KAAK,YAAYD,EAASC,CAAY,EAC3C,eAAgB,IAAM,KAAK,iBAAiB,YAC5C,sBAAuB,IAAM,KAAK,aAAa,SAAS,EACxD,gCAAiC,IAAM,KAAK,MAC5C,sBAAwBC,IACtB,KAAK,sBAAsBA,CAAK,EACzB,KAAK,aAAa,SAAS,GAEpC,iBAAmBY,GACjB,KAAK,kBAAkB,iBAAiBA,CAAS,EACnD,qBAAsB,IAAM,KAAK,mBACjC,wBAAyB,IAAM,KAAK,qBACtC,CAAC,EACD,MAAO,CAAE,WAAAF,EAAY,OAAAC,CAAO,CAC9B,CAEO,OAAc,CACnB,KAAK,oBAAoB,eAAa,aAAa,EACnD,KAAK,aAAa,SAAS,EAC3B,KAAK,wBAAwB,cAAc,CAC7C,CAEO,iBAAiBnB,EAAwB,CAC9C,OAAO,KAAK,kBAAkB,iBAAiBA,CAAE,CACnD,CAEQ,oBAAoBqB,EAAkC,CAC5D,MAAMb,EAAQ,KAAK,aAAa,SAAS,EACzC,KAAK,aAAa,KAAK,CAAE,GAAGA,EAAO,aAAAa,CAAa,CAAC,CACnD,CACF",
6
+ "names": ["DeviceSession_exports", "__export", "DeviceSession", "__toCommonJS", "import_rxjs", "import_uuid", "import_CommandUtils", "import_DeviceStatus", "import_DeviceSessionState", "import_api", "import_DeviceSessionRefresherConst", "import_MutexService", "import_RefresherService", "import_DevicePinger", "import_DeviceSessionEventDispatcher", "import_DeviceSessionRefresher", "import_DeviceSessionStateHandler", "connectedDevice", "id", "uuidv4", "loggerModuleFactory", "managerApiService", "secureChannelService", "deviceSessionRefresherOptions", "command", "abortTimeout", "state", "error", "rawApdu", "options", "release", "result", "response", "apdu", "err", "deviceAction", "observable", "cancel", "blockerId", "deviceStatus"]
7
7
  }
@@ -1,2 +1,2 @@
1
- "use strict";var n=Object.defineProperty;var d=Object.getOwnPropertyDescriptor;var m=Object.getOwnPropertyNames;var f=Object.prototype.hasOwnProperty;var _=(o,e)=>{for(var i in e)n(o,i,{get:e[i],enumerable:!0})},p=(o,e,i,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of m(e))!f.call(o,t)&&t!==i&&n(o,t,{get:()=>e[t],enumerable:!(s=d(e,t))||s.enumerable});return o};var D=o=>p(n({},"__esModule",{value:!0}),o),l=(o,e,i,s)=>{for(var t=s>1?void 0:s?d(e,i):e,g=o.length-1,v;g>=0;g--)(v=o[g])&&(t=(s?v(e,i,t):v(t))||t);return s&&t&&n(e,i,t),t},u=(o,e)=>(i,s)=>e(i,s,o);var y={};_(y,{DefaultDeviceSessionService:()=>r});module.exports=D(y);var c=require("inversify"),a=require("purify-ts"),S=require("rxjs"),h=require("../../device-session/model/Errors"),b=require("../../logger-publisher/di/loggerTypes");let r=class{_sessions;_logger;_sessionsSubject;constructor(e){this._sessions=[],this._sessionsSubject=new S.ReplaySubject,this._logger=e("DeviceSessionService")}get sessionsObs(){return this._sessionsSubject.asObservable()}addDeviceSession(e){return this._sessions.find(s=>s.id===e.id)?(this._logger.warn("DeviceSession already exists",{data:{deviceSession:e}}),this):(this._sessions.push(e),this._sessionsSubject.next(e),this._logger.info("DeviceSession added",{data:{deviceSession:e}}),this)}removeDeviceSession(e){const i=this._sessions.find(s=>s.id===e);return i?(i.close(),this._sessions=this._sessions.filter(s=>s.id!==e),this._logger.info("DeviceSession removed",{data:{sessionId:e}}),this):(this._logger.warn("DeviceSession not found",{data:{sessionId:e}}),this)}getDeviceSessionById(e){return a.Maybe.fromNullable(this._sessions.find(s=>s.id===e)).toEither(new h.DeviceSessionNotFound)}getDeviceSessionByDeviceId(e){return a.Maybe.fromNullable(this._sessions.find(s=>s.connectedDevice.id===e)).toEither(new h.DeviceSessionNotFound)}getDeviceSessions(){return this._sessions}};r=l([(0,c.injectable)(),u(0,(0,c.inject)(b.loggerTypes.LoggerPublisherServiceFactory))],r);0&&(module.exports={DefaultDeviceSessionService});
1
+ "use strict";var n=Object.defineProperty;var h=Object.getOwnPropertyDescriptor;var m=Object.getOwnPropertyNames;var f=Object.prototype.hasOwnProperty;var _=(o,e)=>{for(var i in e)n(o,i,{get:e[i],enumerable:!0})},p=(o,e,i,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of m(e))!f.call(o,t)&&t!==i&&n(o,t,{get:()=>e[t],enumerable:!(s=h(e,t))||s.enumerable});return o};var D=o=>p(n({},"__esModule",{value:!0}),o),l=(o,e,i,s)=>{for(var t=s>1?void 0:s?h(e,i):e,g=o.length-1,d;g>=0;g--)(d=o[g])&&(t=(s?d(e,i,t):d(t))||t);return s&&t&&n(e,i,t),t},u=(o,e)=>(i,s)=>e(i,s,o);var y={};_(y,{DefaultDeviceSessionService:()=>r});module.exports=D(y);var c=require("inversify"),v=require("purify-ts"),S=require("rxjs"),a=require("../../device-session/model/Errors"),b=require("../../logger-publisher/di/loggerTypes");let r=class{_sessions;_logger;_sessionsSubject;constructor(e){this._sessions=[],this._sessionsSubject=new S.ReplaySubject,this._logger=e("DeviceSessionService")}get sessionsObs(){return this._sessionsSubject.asObservable()}addDeviceSession(e){return this._sessions.find(s=>s.id===e.id)?(this._logger.warn("DeviceSession already exists",{data:{deviceSession:e}}),this):(this._sessions.push(e),this._sessionsSubject.next(e),this._logger.info("DeviceSession added",{data:{sessionId:e.id}}),this)}removeDeviceSession(e){const i=this._sessions.find(s=>s.id===e);return i?(i.close(),this._sessions=this._sessions.filter(s=>s.id!==e),this._logger.info("DeviceSession removed",{data:{sessionId:e}}),this):(this._logger.warn("DeviceSession not found",{data:{sessionId:e}}),this)}getDeviceSessionById(e){return v.Maybe.fromNullable(this._sessions.find(s=>s.id===e)).toEither(new a.DeviceSessionNotFound)}getDeviceSessionByDeviceId(e){return v.Maybe.fromNullable(this._sessions.find(s=>s.connectedDevice.id===e)).toEither(new a.DeviceSessionNotFound)}getDeviceSessions(){return this._sessions}};r=l([(0,c.injectable)(),u(0,(0,c.inject)(b.loggerTypes.LoggerPublisherServiceFactory))],r);0&&(module.exports={DefaultDeviceSessionService});
2
2
  //# sourceMappingURL=DefaultDeviceSessionService.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/internal/device-session/service/DefaultDeviceSessionService.ts"],
4
- "sourcesContent": ["import { inject, injectable } from \"inversify\";\nimport { Maybe } from \"purify-ts\";\nimport { Observable, ReplaySubject } from \"rxjs\";\n\nimport { LoggerPublisherService } from \"@api/logger-publisher/service/LoggerPublisherService\";\nimport { DeviceSession } from \"@internal/device-session/model/DeviceSession\";\nimport { DeviceSessionNotFound } from \"@internal/device-session/model/Errors\";\nimport { DeviceSessionService } from \"@internal/device-session/service/DeviceSessionService\";\nimport { loggerTypes } from \"@internal/logger-publisher/di/loggerTypes\";\n\n@injectable()\nexport class DefaultDeviceSessionService implements DeviceSessionService {\n private _sessions: DeviceSession[];\n private readonly _logger: LoggerPublisherService;\n private _sessionsSubject: ReplaySubject<DeviceSession>;\n\n constructor(\n @inject(loggerTypes.LoggerPublisherServiceFactory)\n loggerModuleFactory: (tag: string) => LoggerPublisherService,\n ) {\n this._sessions = [];\n this._sessionsSubject = new ReplaySubject();\n this._logger = loggerModuleFactory(\"DeviceSessionService\");\n }\n\n public get sessionsObs(): Observable<DeviceSession> {\n return this._sessionsSubject.asObservable();\n }\n\n addDeviceSession(deviceSession: DeviceSession) {\n const found = this._sessions.find((s) => s.id === deviceSession.id);\n if (found) {\n this._logger.warn(\"DeviceSession already exists\", {\n data: { deviceSession },\n });\n return this;\n }\n\n this._sessions.push(deviceSession);\n this._sessionsSubject.next(deviceSession);\n this._logger.info(\"DeviceSession added\", { data: { deviceSession } });\n return this;\n }\n\n removeDeviceSession(sessionId: string) {\n const found = this._sessions.find((s) => s.id === sessionId);\n if (found) {\n found.close();\n this._sessions = this._sessions.filter((s) => s.id !== sessionId);\n this._logger.info(\"DeviceSession removed\", { data: { sessionId } });\n return this;\n }\n\n this._logger.warn(\"DeviceSession not found\", { data: { sessionId } });\n return this;\n }\n\n getDeviceSessionById(sessionId: string) {\n const deviceSession = Maybe.fromNullable(\n this._sessions.find((s) => s.id === sessionId),\n );\n\n return deviceSession.toEither(new DeviceSessionNotFound());\n }\n\n getDeviceSessionByDeviceId(deviceId: string) {\n const deviceSession = Maybe.fromNullable(\n this._sessions.find((s) => s.connectedDevice.id === deviceId),\n );\n\n return deviceSession.toEither(new DeviceSessionNotFound());\n }\n\n getDeviceSessions() {\n return this._sessions;\n }\n}\n"],
5
- "mappings": "okBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,iCAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAAmC,qBACnCC,EAAsB,qBACtBC,EAA0C,gBAI1CC,EAAsC,iDAEtCC,EAA4B,qDAGrB,IAAMC,EAAN,KAAkE,CAC/D,UACS,QACT,iBAER,YAEEC,EACA,CACA,KAAK,UAAY,CAAC,EAClB,KAAK,iBAAmB,IAAI,gBAC5B,KAAK,QAAUA,EAAoB,sBAAsB,CAC3D,CAEA,IAAW,aAAyC,CAClD,OAAO,KAAK,iBAAiB,aAAa,CAC5C,CAEA,iBAAiBC,EAA8B,CAE7C,OADc,KAAK,UAAU,KAAM,GAAM,EAAE,KAAOA,EAAc,EAAE,GAEhE,KAAK,QAAQ,KAAK,+BAAgC,CAChD,KAAM,CAAE,cAAAA,CAAc,CACxB,CAAC,EACM,OAGT,KAAK,UAAU,KAAKA,CAAa,EACjC,KAAK,iBAAiB,KAAKA,CAAa,EACxC,KAAK,QAAQ,KAAK,sBAAuB,CAAE,KAAM,CAAE,cAAAA,CAAc,CAAE,CAAC,EAC7D,KACT,CAEA,oBAAoBC,EAAmB,CACrC,MAAMC,EAAQ,KAAK,UAAU,KAAM,GAAM,EAAE,KAAOD,CAAS,EAC3D,OAAIC,GACFA,EAAM,MAAM,EACZ,KAAK,UAAY,KAAK,UAAU,OAAQ,GAAM,EAAE,KAAOD,CAAS,EAChE,KAAK,QAAQ,KAAK,wBAAyB,CAAE,KAAM,CAAE,UAAAA,CAAU,CAAE,CAAC,EAC3D,OAGT,KAAK,QAAQ,KAAK,0BAA2B,CAAE,KAAM,CAAE,UAAAA,CAAU,CAAE,CAAC,EAC7D,KACT,CAEA,qBAAqBA,EAAmB,CAKtC,OAJsB,QAAM,aAC1B,KAAK,UAAU,KAAM,GAAM,EAAE,KAAOA,CAAS,CAC/C,EAEqB,SAAS,IAAI,uBAAuB,CAC3D,CAEA,2BAA2BE,EAAkB,CAK3C,OAJsB,QAAM,aAC1B,KAAK,UAAU,KAAM,GAAM,EAAE,gBAAgB,KAAOA,CAAQ,CAC9D,EAEqB,SAAS,IAAI,uBAAuB,CAC3D,CAEA,mBAAoB,CAClB,OAAO,KAAK,SACd,CACF,EAjEaL,EAANM,EAAA,IADN,cAAW,EAOPC,EAAA,eAAO,cAAY,6BAA6B,IANxCP",
4
+ "sourcesContent": ["import { inject, injectable } from \"inversify\";\nimport { Maybe } from \"purify-ts\";\nimport { Observable, ReplaySubject } from \"rxjs\";\n\nimport { LoggerPublisherService } from \"@api/logger-publisher/service/LoggerPublisherService\";\nimport { DeviceSession } from \"@internal/device-session/model/DeviceSession\";\nimport { DeviceSessionNotFound } from \"@internal/device-session/model/Errors\";\nimport { DeviceSessionService } from \"@internal/device-session/service/DeviceSessionService\";\nimport { loggerTypes } from \"@internal/logger-publisher/di/loggerTypes\";\n\n@injectable()\nexport class DefaultDeviceSessionService implements DeviceSessionService {\n private _sessions: DeviceSession[];\n private readonly _logger: LoggerPublisherService;\n private _sessionsSubject: ReplaySubject<DeviceSession>;\n\n constructor(\n @inject(loggerTypes.LoggerPublisherServiceFactory)\n loggerModuleFactory: (tag: string) => LoggerPublisherService,\n ) {\n this._sessions = [];\n this._sessionsSubject = new ReplaySubject();\n this._logger = loggerModuleFactory(\"DeviceSessionService\");\n }\n\n public get sessionsObs(): Observable<DeviceSession> {\n return this._sessionsSubject.asObservable();\n }\n\n addDeviceSession(deviceSession: DeviceSession) {\n const found = this._sessions.find((s) => s.id === deviceSession.id);\n if (found) {\n this._logger.warn(\"DeviceSession already exists\", {\n data: { deviceSession },\n });\n return this;\n }\n\n this._sessions.push(deviceSession);\n this._sessionsSubject.next(deviceSession);\n this._logger.info(\"DeviceSession added\", {\n data: { sessionId: deviceSession.id },\n });\n return this;\n }\n\n removeDeviceSession(sessionId: string) {\n const found = this._sessions.find((s) => s.id === sessionId);\n if (found) {\n found.close();\n this._sessions = this._sessions.filter((s) => s.id !== sessionId);\n this._logger.info(\"DeviceSession removed\", { data: { sessionId } });\n return this;\n }\n\n this._logger.warn(\"DeviceSession not found\", { data: { sessionId } });\n return this;\n }\n\n getDeviceSessionById(sessionId: string) {\n const deviceSession = Maybe.fromNullable(\n this._sessions.find((s) => s.id === sessionId),\n );\n\n return deviceSession.toEither(new DeviceSessionNotFound());\n }\n\n getDeviceSessionByDeviceId(deviceId: string) {\n const deviceSession = Maybe.fromNullable(\n this._sessions.find((s) => s.connectedDevice.id === deviceId),\n );\n\n return deviceSession.toEither(new DeviceSessionNotFound());\n }\n\n getDeviceSessions() {\n return this._sessions;\n }\n}\n"],
5
+ "mappings": "okBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,iCAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAAmC,qBACnCC,EAAsB,qBACtBC,EAA0C,gBAI1CC,EAAsC,iDAEtCC,EAA4B,qDAGrB,IAAMC,EAAN,KAAkE,CAC/D,UACS,QACT,iBAER,YAEEC,EACA,CACA,KAAK,UAAY,CAAC,EAClB,KAAK,iBAAmB,IAAI,gBAC5B,KAAK,QAAUA,EAAoB,sBAAsB,CAC3D,CAEA,IAAW,aAAyC,CAClD,OAAO,KAAK,iBAAiB,aAAa,CAC5C,CAEA,iBAAiBC,EAA8B,CAE7C,OADc,KAAK,UAAU,KAAM,GAAM,EAAE,KAAOA,EAAc,EAAE,GAEhE,KAAK,QAAQ,KAAK,+BAAgC,CAChD,KAAM,CAAE,cAAAA,CAAc,CACxB,CAAC,EACM,OAGT,KAAK,UAAU,KAAKA,CAAa,EACjC,KAAK,iBAAiB,KAAKA,CAAa,EACxC,KAAK,QAAQ,KAAK,sBAAuB,CACvC,KAAM,CAAE,UAAWA,EAAc,EAAG,CACtC,CAAC,EACM,KACT,CAEA,oBAAoBC,EAAmB,CACrC,MAAMC,EAAQ,KAAK,UAAU,KAAM,GAAM,EAAE,KAAOD,CAAS,EAC3D,OAAIC,GACFA,EAAM,MAAM,EACZ,KAAK,UAAY,KAAK,UAAU,OAAQ,GAAM,EAAE,KAAOD,CAAS,EAChE,KAAK,QAAQ,KAAK,wBAAyB,CAAE,KAAM,CAAE,UAAAA,CAAU,CAAE,CAAC,EAC3D,OAGT,KAAK,QAAQ,KAAK,0BAA2B,CAAE,KAAM,CAAE,UAAAA,CAAU,CAAE,CAAC,EAC7D,KACT,CAEA,qBAAqBA,EAAmB,CAKtC,OAJsB,QAAM,aAC1B,KAAK,UAAU,KAAM,GAAM,EAAE,KAAOA,CAAS,CAC/C,EAEqB,SAAS,IAAI,uBAAuB,CAC3D,CAEA,2BAA2BE,EAAkB,CAK3C,OAJsB,QAAM,aAC1B,KAAK,UAAU,KAAM,GAAM,EAAE,gBAAgB,KAAOA,CAAQ,CAC9D,EAEqB,SAAS,IAAI,uBAAuB,CAC3D,CAEA,mBAAoB,CAClB,OAAO,KAAK,SACd,CACF,EAnEaL,EAANM,EAAA,IADN,cAAW,EAOPC,EAAA,eAAO,cAAY,6BAA6B,IANxCP",
6
6
  "names": ["DefaultDeviceSessionService_exports", "__export", "DefaultDeviceSessionService", "__toCommonJS", "import_inversify", "import_purify_ts", "import_rxjs", "import_Errors", "import_loggerTypes", "DefaultDeviceSessionService", "loggerModuleFactory", "deviceSession", "sessionId", "found", "deviceId", "__decorateClass", "__decorateParam"]
7
7
  }
@@ -1,2 +1,2 @@
1
- var p=(o=>(o.None="none",o.UnlockDevice="unlock-device",o.AllowSecureConnection="allow-secure-connection",o.ConfirmOpenApp="confirm-open-app",o.SignTransaction="sign-transaction",o.SignTypedData="sign-typed-data",o.AllowListApps="allow-list-apps",o.VerifyAddress="verify-address",o.SignPersonalMessage="sign-personal-message",o.SignDelegationAuthorization="sign-delegation-authorization",o.Web3ChecksOptIn="web3-checks-opt-in",o))(p||{});export{p as UserInteractionRequired};
1
+ var s=(p=>(p.None="none",p.UnlockDevice="unlock-device",p.AllowSecureConnection="allow-secure-connection",p.ConfirmOpenApp="confirm-open-app",p.SignTransaction="sign-transaction",p.SignTypedData="sign-typed-data",p.AllowListApps="allow-list-apps",p.VerifyAddress="verify-address",p.SignPersonalMessage="sign-personal-message",p.SignDelegationAuthorization="sign-delegation-authorization",p.Web3ChecksOptIn="web3-checks-opt-in",p.VerifySafeAddress="verify-safe-address",p))(s||{});export{s as UserInteractionRequired};
2
2
  //# sourceMappingURL=UserInteractionRequired.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/api/device-action/model/UserInteractionRequired.ts"],
4
- "sourcesContent": ["/**\n * The user interaction required on the device to move further in a device action.\n * This is used to inform the users about the action they need to take on the device.\n */\nexport enum UserInteractionRequired {\n None = \"none\",\n UnlockDevice = \"unlock-device\",\n AllowSecureConnection = \"allow-secure-connection\",\n ConfirmOpenApp = \"confirm-open-app\",\n SignTransaction = \"sign-transaction\",\n SignTypedData = \"sign-typed-data\",\n AllowListApps = \"allow-list-apps\",\n VerifyAddress = \"verify-address\",\n SignPersonalMessage = \"sign-personal-message\",\n SignDelegationAuthorization = \"sign-delegation-authorization\",\n Web3ChecksOptIn = \"web3-checks-opt-in\",\n}\n"],
5
- "mappings": "AAIO,IAAKA,OACVA,EAAA,KAAO,OACPA,EAAA,aAAe,gBACfA,EAAA,sBAAwB,0BACxBA,EAAA,eAAiB,mBACjBA,EAAA,gBAAkB,mBAClBA,EAAA,cAAgB,kBAChBA,EAAA,cAAgB,kBAChBA,EAAA,cAAgB,iBAChBA,EAAA,oBAAsB,wBACtBA,EAAA,4BAA8B,gCAC9BA,EAAA,gBAAkB,qBAXRA,OAAA",
4
+ "sourcesContent": ["/**\n * The user interaction required on the device to move further in a device action.\n * This is used to inform the users about the action they need to take on the device.\n */\nexport enum UserInteractionRequired {\n None = \"none\",\n UnlockDevice = \"unlock-device\",\n AllowSecureConnection = \"allow-secure-connection\",\n ConfirmOpenApp = \"confirm-open-app\",\n SignTransaction = \"sign-transaction\",\n SignTypedData = \"sign-typed-data\",\n AllowListApps = \"allow-list-apps\",\n VerifyAddress = \"verify-address\",\n SignPersonalMessage = \"sign-personal-message\",\n SignDelegationAuthorization = \"sign-delegation-authorization\",\n Web3ChecksOptIn = \"web3-checks-opt-in\",\n VerifySafeAddress = \"verify-safe-address\",\n}\n"],
5
+ "mappings": "AAIO,IAAKA,OACVA,EAAA,KAAO,OACPA,EAAA,aAAe,gBACfA,EAAA,sBAAwB,0BACxBA,EAAA,eAAiB,mBACjBA,EAAA,gBAAkB,mBAClBA,EAAA,cAAgB,kBAChBA,EAAA,cAAgB,kBAChBA,EAAA,cAAgB,iBAChBA,EAAA,oBAAsB,wBACtBA,EAAA,4BAA8B,gCAC9BA,EAAA,gBAAkB,qBAClBA,EAAA,kBAAoB,sBAZVA,OAAA",
6
6
  "names": ["UserInteractionRequired"]
7
7
  }
@@ -1,2 +1,2 @@
1
- import{LogLevel as e}from"../../logger-subscriber/model/LogLevel";class c{maxLevel;constructor(l=e.Debug){this.maxLevel=l}log(l,a,r){const o=`[${r.tag}]`;switch(l){case e.Info:{this.maxLevel>=e.Info&&console.info(o,a,r.data);break}case e.Warning:{this.maxLevel>=e.Warning&&console.warn(o,a,r.data);break}case e.Debug:{this.maxLevel>=e.Debug&&console.debug(o,a,r.data);break}case e.Error:{this.maxLevel>=e.Error&&console.error(o,a,r.data);break}case e.Fatal:{this.maxLevel>=e.Fatal&&console.error(o,a,r.data);break}default:console.log(o,a,r.data)}}}export{c as ConsoleLogger};
1
+ import{LogLevel as e}from"../../logger-subscriber/model/LogLevel";class g{maxLevel;constructor(t=e.Debug){this.maxLevel=t}log(t,a,r){const i=`[${r.tag}]`;switch(t){case e.Info:{this.maxLevel>=e.Info&&this.logWithData(i,console.info,a,r);break}case e.Warning:{this.maxLevel>=e.Warning&&this.logWithData(i,console.warn,a,r);break}case e.Debug:{this.maxLevel>=e.Debug&&this.logWithData(i,console.debug,a,r);break}case e.Error:{this.maxLevel>=e.Error&&this.logWithData(i,console.error,a,r);break}case e.Fatal:{this.maxLevel>=e.Fatal&&this.logWithData(i,console.error,a,r);break}default:this.logWithData(i,console.log,a,r)}}logWithData(t,a,r,i){i.data?a(t,r,i.data):a(t,r)}}export{g as ConsoleLogger};
2
2
  //# sourceMappingURL=ConsoleLogger.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/api/logger-subscriber/service/ConsoleLogger.ts"],
4
- "sourcesContent": ["import { LogLevel } from \"@api/logger-subscriber/model/LogLevel\";\nimport { type LogSubscriberOptions } from \"@api/logger-subscriber/model/LogSubscriberOptions\";\nimport { type LoggerSubscriberService } from \"@api/logger-subscriber/service/LoggerSubscriberService\";\n\nexport class ConsoleLogger implements LoggerSubscriberService {\n private readonly maxLevel: LogLevel;\n\n constructor(level: LogLevel = LogLevel.Debug) {\n this.maxLevel = level;\n }\n\n log(\n level: LogLevel | null,\n message: string,\n options: LogSubscriberOptions,\n ): void {\n const tag = `[${options.tag}]`;\n\n switch (level) {\n case LogLevel.Info: {\n if (this.maxLevel >= LogLevel.Info) {\n console.info(tag, message, options.data);\n }\n break;\n }\n case LogLevel.Warning: {\n if (this.maxLevel >= LogLevel.Warning) {\n console.warn(tag, message, options.data);\n }\n break;\n }\n case LogLevel.Debug: {\n if (this.maxLevel >= LogLevel.Debug) {\n console.debug(tag, message, options.data);\n }\n break;\n }\n case LogLevel.Error: {\n if (this.maxLevel >= LogLevel.Error) {\n console.error(tag, message, options.data);\n }\n break;\n }\n case LogLevel.Fatal: {\n if (this.maxLevel >= LogLevel.Fatal) {\n console.error(tag, message, options.data);\n }\n break;\n }\n default:\n console.log(tag, message, options.data);\n }\n }\n}\n"],
5
- "mappings": "AAAA,OAAS,YAAAA,MAAgB,wCAIlB,MAAMC,CAAiD,CAC3C,SAEjB,YAAYC,EAAkBF,EAAS,MAAO,CAC5C,KAAK,SAAWE,CAClB,CAEA,IACEA,EACAC,EACAC,EACM,CACN,MAAMC,EAAM,IAAID,EAAQ,GAAG,IAE3B,OAAQF,EAAO,CACb,KAAKF,EAAS,KAAM,CACd,KAAK,UAAYA,EAAS,MAC5B,QAAQ,KAAKK,EAAKF,EAASC,EAAQ,IAAI,EAEzC,KACF,CACA,KAAKJ,EAAS,QAAS,CACjB,KAAK,UAAYA,EAAS,SAC5B,QAAQ,KAAKK,EAAKF,EAASC,EAAQ,IAAI,EAEzC,KACF,CACA,KAAKJ,EAAS,MAAO,CACf,KAAK,UAAYA,EAAS,OAC5B,QAAQ,MAAMK,EAAKF,EAASC,EAAQ,IAAI,EAE1C,KACF,CACA,KAAKJ,EAAS,MAAO,CACf,KAAK,UAAYA,EAAS,OAC5B,QAAQ,MAAMK,EAAKF,EAASC,EAAQ,IAAI,EAE1C,KACF,CACA,KAAKJ,EAAS,MAAO,CACf,KAAK,UAAYA,EAAS,OAC5B,QAAQ,MAAMK,EAAKF,EAASC,EAAQ,IAAI,EAE1C,KACF,CACA,QACE,QAAQ,IAAIC,EAAKF,EAASC,EAAQ,IAAI,CAC1C,CACF,CACF",
6
- "names": ["LogLevel", "ConsoleLogger", "level", "message", "options", "tag"]
4
+ "sourcesContent": ["import { LogLevel } from \"@api/logger-subscriber/model/LogLevel\";\nimport { type LogSubscriberOptions } from \"@api/logger-subscriber/model/LogSubscriberOptions\";\nimport { type LoggerSubscriberService } from \"@api/logger-subscriber/service/LoggerSubscriberService\";\n\nexport class ConsoleLogger implements LoggerSubscriberService {\n private readonly maxLevel: LogLevel;\n\n constructor(level: LogLevel = LogLevel.Debug) {\n this.maxLevel = level;\n }\n\n log(\n level: LogLevel | null,\n message: string,\n options: LogSubscriberOptions,\n ): void {\n const tag = `[${options.tag}]`;\n\n switch (level) {\n case LogLevel.Info: {\n if (this.maxLevel >= LogLevel.Info) {\n this.logWithData(tag, console.info, message, options);\n }\n break;\n }\n case LogLevel.Warning: {\n if (this.maxLevel >= LogLevel.Warning) {\n this.logWithData(tag, console.warn, message, options);\n }\n break;\n }\n case LogLevel.Debug: {\n if (this.maxLevel >= LogLevel.Debug) {\n this.logWithData(tag, console.debug, message, options);\n }\n break;\n }\n case LogLevel.Error: {\n if (this.maxLevel >= LogLevel.Error) {\n this.logWithData(tag, console.error, message, options);\n }\n break;\n }\n case LogLevel.Fatal: {\n if (this.maxLevel >= LogLevel.Fatal) {\n this.logWithData(tag, console.error, message, options);\n }\n break;\n }\n default:\n this.logWithData(tag, console.log, message, options);\n }\n }\n\n private logWithData(\n tag: string,\n logFunction: (...args: unknown[]) => void,\n message: string,\n options: LogSubscriberOptions,\n ): void {\n if (options.data) {\n logFunction(tag, message, options.data);\n } else {\n logFunction(tag, message);\n }\n }\n}\n"],
5
+ "mappings": "AAAA,OAAS,YAAAA,MAAgB,wCAIlB,MAAMC,CAAiD,CAC3C,SAEjB,YAAYC,EAAkBF,EAAS,MAAO,CAC5C,KAAK,SAAWE,CAClB,CAEA,IACEA,EACAC,EACAC,EACM,CACN,MAAMC,EAAM,IAAID,EAAQ,GAAG,IAE3B,OAAQF,EAAO,CACb,KAAKF,EAAS,KAAM,CACd,KAAK,UAAYA,EAAS,MAC5B,KAAK,YAAYK,EAAK,QAAQ,KAAMF,EAASC,CAAO,EAEtD,KACF,CACA,KAAKJ,EAAS,QAAS,CACjB,KAAK,UAAYA,EAAS,SAC5B,KAAK,YAAYK,EAAK,QAAQ,KAAMF,EAASC,CAAO,EAEtD,KACF,CACA,KAAKJ,EAAS,MAAO,CACf,KAAK,UAAYA,EAAS,OAC5B,KAAK,YAAYK,EAAK,QAAQ,MAAOF,EAASC,CAAO,EAEvD,KACF,CACA,KAAKJ,EAAS,MAAO,CACf,KAAK,UAAYA,EAAS,OAC5B,KAAK,YAAYK,EAAK,QAAQ,MAAOF,EAASC,CAAO,EAEvD,KACF,CACA,KAAKJ,EAAS,MAAO,CACf,KAAK,UAAYA,EAAS,OAC5B,KAAK,YAAYK,EAAK,QAAQ,MAAOF,EAASC,CAAO,EAEvD,KACF,CACA,QACE,KAAK,YAAYC,EAAK,QAAQ,IAAKF,EAASC,CAAO,CACvD,CACF,CAEQ,YACNC,EACAC,EACAH,EACAC,EACM,CACFA,EAAQ,KACVE,EAAYD,EAAKF,EAASC,EAAQ,IAAI,EAEtCE,EAAYD,EAAKF,CAAO,CAE5B,CACF",
6
+ "names": ["LogLevel", "ConsoleLogger", "level", "message", "options", "tag", "logFunction"]
7
7
  }
@@ -1,2 +1,2 @@
1
- import k from"isomorphic-ws";import{Observable as x}from"rxjs";import{CommandUtils as m}from"../../command/utils/CommandUtils";import{InMessageQueryEnum as p,OutMessageResponseEnum as w,SecureChannelEventType as a}from"../../secure-channel/task/types";import{willRequestPermission as M}from"../../secure-channel/utils";import{bufferToHexaString as _,hexaStringToBuffer as A}from"../../utils/HexaString";import{SecureChannelError as t,SecureChannelErrorType as E}from"../../../internal/secure-channel/model/Errors";class L{constructor(n,l){this._api=n;this._args=l;if(this._args.connection.isRight())this._connection=this._args.connection.extract();else throw new t(`Invalid WebSocket connection: ${String(this._args.connection.extract())}`)}_connection;run(){const n=this._api.disableRefresher("connectToSecureChannel");return new x(e=>{let S=!1,u=!1,C=!1;const c=d=>{e.next({type:a.Error,error:d}),e.complete(),u=!0};return this._connection.onopen=()=>{e.next({type:a.Opened})},this._connection.onerror=d=>{u||(e.next({type:a.Error,error:new t({url:this._connection.url,errorMessage:d.message})}),e.complete())},this._connection.onclose=()=>{u||(C?e.next({type:a.Closed}):e.next({type:a.Error,error:new t({url:this._connection.url,errorMessage:"Connection closed unexpectedly"})}),e.complete())},this._connection.onmessage=async d=>{if(S)return;let o;try{const s=JSON.parse(String(d.data));if(this.isInMessageType(s))o=s;else throw new Error("Data does not match InMessageType")}catch{c(new t({url:this._connection.url,errorMessage:`Invalid message received: ${String(d.data)}`}));return}switch(o.query){case p.EXCHANGE:{const{nonce:s,data:h}=o;if(typeof h!="string"){c(new t(`${p.EXCHANGE} data type should be an APDU`));return}const r=A(h);if(r===null||r.length<5){c(new t(`Received invalid APDU data: ${h}`));return}e.next({type:a.PreExchange,payload:{nonce:s,apdu:r}});let f=!1;M(r)&&!this.isSecureConnectionAllowed()&&(f=!0,e.next({type:a.PermissionRequested}));const g=await this._api.sendApdu(r);if(S)return;g.caseOf({Left:i=>{c(new t(i))},Right:i=>{let y;const v=this.mapDeviceError(i);v===null?(y=w.SUCCESS,e.next({type:a.Exchange,payload:{nonce:s,apdu:r,data:i.data,status:i.statusCode}}),f&&e.next({type:a.PermissionGranted})):(y=w.ERROR,c(v));const T={nonce:s,response:y,data:_(i.data,!1)};this._connection.send(JSON.stringify(T))}});break}case p.BULK:{u=!0,this._connection.close();const s=Date.now();if(console.log("[ConnectToSecureChannelTask] BULK started"),!Array.isArray(o.data)||o.data.length===0||!o.data.every(r=>typeof r=="string")){c(new t("Invalid bulk data received"));return}for(let r=0,f=o.data.length;r<f;r++){const g=A(o.data[r]);if(g===null||g.length<5){c(new t(`Received invalid APDU bulk data: ${o.data[r]}`));return}const i=await this._api.sendApdu(g);if(S)return;if(i.isLeft()){c(new t(i.extract()));return}else if(i.isRight()){const y=this.mapDeviceError(i.extract());if(y===null)e.next({type:a.Progress,payload:{progress:+Number((r+1)/f).toFixed(2),index:r,total:f}});else{c(y);return}}}const h=Date.now();console.log("[ConnectToSecureChannelTask] BULK finished in",h-s,"ms"),C=!0,e.complete();break}case p.SUCCESS:{if(u)break;const s=o.result??o.data;s&&e.next({type:a.Result,payload:s??""}),C=!0,e.complete();break}case p.WARNING:{if(u)break;e.next({type:a.Warning,payload:{message:String(o.data)}});break}case p.ERROR:{if(u)break;c(new t({url:this._connection.url,errorMessage:String(o.data)}))}}},()=>{n(),S=!0,this._connection.readyState===k.OPEN&&this._connection.close()}})}isSecureConnectionAllowed(){const n=this._api.getDeviceSessionState();return"isSecureConnectionAllowed"in n&&n.isSecureConnectionAllowed}isInMessageType(n){if(typeof n!="object"||!n)return!1;const l=n;return typeof l.uuid=="string"&&typeof l.session=="string"&&typeof l.query=="string"&&Object.values(p).includes(l.query)&&typeof l.nonce=="number"}mapDeviceError(n){return m.isSuccessResponse(n)?null:m.isLockedDeviceResponse(n)?new t({url:this._connection.url,errorMessage:"Device is locked"},E.DeviceLocked):m.isRefusedByUser(n)?new t({url:this._connection.url,errorMessage:"User refused on the device"},E.RefusedByUser):m.isAppAlreadyInstalled(n)?new t({url:this._connection.url,errorMessage:"App already installed"},E.AppAlreadyInstalled):m.isOutOfMemory(n)?new t({url:this._connection.url,errorMessage:"Out of memory"},E.OutOfMemory):new t({url:this._connection.url,errorMessage:`Invalid status code: ${_(n.statusCode)}`})}}export{L as ConnectToSecureChannelTask};
1
+ import M from"isomorphic-ws";import{Observable as k}from"rxjs";import{CommandUtils as h}from"../../command/utils/CommandUtils";import{InMessageQueryEnum as d,OutMessageResponseEnum as w,SecureChannelEventType as s}from"../../secure-channel/task/types";import{willRequestPermission as R}from"../../secure-channel/utils";import{bufferToHexaString as _,hexaStringToBuffer as A}from"../../utils/HexaString";import{SecureChannelError as r,SecureChannelErrorType as S}from"../../../internal/secure-channel/model/Errors";class q{constructor(t,c){this._api=t;this._args=c;if(this._args.connection.isRight())this._connection=this._args.connection.extract();else throw new r(`Invalid WebSocket connection: ${String(this._args.connection.extract())}`)}_connection;run(){const t=this._api.disableRefresher("connectToSecureChannel");return new k(n=>{let g=!1,l=!1,E=!1;const i=f=>{n.next({type:s.Error,error:f}),n.complete(),l=!0};return this._connection.onopen=()=>{n.next({type:s.Opened})},this._connection.onerror=f=>{l||(n.next({type:s.Error,error:new r({url:this._connection.url,errorMessage:f.message})}),n.complete())},this._connection.onclose=()=>{l||(E?n.next({type:s.Closed}):n.next({type:s.Error,error:new r({url:this._connection.url,errorMessage:"Connection closed unexpectedly"})}),n.complete())},this._connection.onmessage=async f=>{if(g)return;let o;try{const e=JSON.parse(String(f.data));if(this.isInMessageType(e))o=e;else throw new Error("Data does not match InMessageType")}catch{i(new r({url:this._connection.url,errorMessage:`Invalid message received: ${String(f.data)}`}));return}switch(o.query){case d.EXCHANGE:{const{nonce:e,data:u}=o;if(typeof u!="string"){i(new r(`${d.EXCHANGE} data type should be an APDU`));return}const a=A(u);if(a===null||a.length<5){i(new r(`Received invalid APDU data: ${u}`));return}n.next({type:s.PreExchange,payload:{nonce:e,apdu:a}});let p=!1;R(a)&&!this.isSecureConnectionAllowed()&&(p=!0,n.next({type:s.PermissionRequested}));const m=await this._api.sendApdu(a);if(g)return;m.caseOf({Left:y=>{i(new r(y))},Right:y=>{let v;const C=this.mapDeviceError(y);C===null?(v=w.SUCCESS,n.next({type:s.Exchange,payload:{nonce:e,apdu:a,data:y.data,status:y.statusCode}}),p&&n.next({type:s.PermissionGranted})):(v=w.ERROR,i(C));const x={nonce:e,response:v,data:_(y.data,!1)};this._connection.send(JSON.stringify(x))}});break}case d.BULK:{if(l=!0,this._connection.close(),!Array.isArray(o.data)||o.data.length===0||!o.data.every(e=>typeof e=="string")){i(new r("Invalid bulk data received"));return}for(let e=0,u=o.data.length;e<u;e++){const a=A(o.data[e]);if(a===null||a.length<5){i(new r(`Received invalid APDU bulk data: ${o.data[e]}`));return}const p=await this._api.sendApdu(a);if(g)return;if(p.isLeft()){i(new r(p.extract()));return}else if(p.isRight()){const m=this.mapDeviceError(p.extract());if(m===null)n.next({type:s.Progress,payload:{progress:+Number((e+1)/u).toFixed(2),index:e,total:u}});else{i(m);return}}}E=!0,n.complete();break}case d.SUCCESS:{if(l)break;const e=o.result??o.data;e&&n.next({type:s.Result,payload:e??""}),E=!0,n.complete();break}case d.WARNING:{if(l)break;n.next({type:s.Warning,payload:{message:String(o.data)}});break}case d.ERROR:{if(l)break;i(new r({url:this._connection.url,errorMessage:String(o.data)}))}}},()=>{t(),g=!0,this._connection.readyState===M.OPEN&&this._connection.close()}})}isSecureConnectionAllowed(){const t=this._api.getDeviceSessionState();return"isSecureConnectionAllowed"in t&&t.isSecureConnectionAllowed}isInMessageType(t){if(typeof t!="object"||!t)return!1;const c=t;return typeof c.uuid=="string"&&typeof c.session=="string"&&typeof c.query=="string"&&Object.values(d).includes(c.query)&&typeof c.nonce=="number"}mapDeviceError(t){return h.isSuccessResponse(t)?null:h.isLockedDeviceResponse(t)?new r({url:this._connection.url,errorMessage:"Device is locked"},S.DeviceLocked):h.isRefusedByUser(t)?new r({url:this._connection.url,errorMessage:"User refused on the device"},S.RefusedByUser):h.isAppAlreadyInstalled(t)?new r({url:this._connection.url,errorMessage:"App already installed"},S.AppAlreadyInstalled):h.isOutOfMemory(t)?new r({url:this._connection.url,errorMessage:"Out of memory"},S.OutOfMemory):new r({url:this._connection.url,errorMessage:`Invalid status code: ${_(t.statusCode)}`})}}export{q as ConnectToSecureChannelTask};
2
2
  //# sourceMappingURL=ConnectToSecureChannelTask.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/api/secure-channel/task/ConnectToSecureChannelTask.ts"],
4
- "sourcesContent": ["import WebSocket from \"isomorphic-ws\";\nimport { type Either } from \"purify-ts\";\nimport { Observable } from \"rxjs\";\n\nimport { CommandUtils } from \"@api/command/utils/CommandUtils\";\nimport { type InternalApi } from \"@api/device-action/DeviceAction\";\nimport { type ApduResponse } from \"@api/device-session/ApduResponse\";\nimport {\n InMessageQueryEnum,\n type InMessageType,\n OutMessageResponseEnum,\n type OutMessageType,\n type SecureChannelEvent,\n SecureChannelEventType,\n} from \"@api/secure-channel/task/types\";\nimport { willRequestPermission } from \"@api/secure-channel/utils\";\nimport { bufferToHexaString, hexaStringToBuffer } from \"@api/utils/HexaString\";\nimport {\n SecureChannelError,\n SecureChannelErrorType,\n type WebSocketConnectionError,\n} from \"@internal/secure-channel/model/Errors\";\n\nexport type ConnectToSecureChannelTaskArgs = {\n connection: Either<WebSocketConnectionError, WebSocket>;\n};\n\nexport class ConnectToSecureChannelTask {\n private readonly _connection: WebSocket;\n constructor(\n private readonly _api: InternalApi,\n private readonly _args: ConnectToSecureChannelTaskArgs,\n ) {\n if (this._args.connection.isRight()) {\n this._connection = this._args.connection.extract();\n } else {\n throw new SecureChannelError(\n `Invalid WebSocket connection: ${String(this._args.connection.extract())}`,\n );\n }\n }\n\n run(): Observable<SecureChannelEvent> {\n const reenableRefresher = this._api.disableRefresher(\n \"connectToSecureChannel\",\n );\n\n const obs = new Observable<SecureChannelEvent>((subscriber) => {\n let unsubscribed: boolean = false;\n let ignoreNetworkEvents = false;\n let communicationFinished = false;\n\n const notifyError = (error: SecureChannelError) => {\n subscriber.next({\n type: SecureChannelEventType.Error,\n error,\n });\n subscriber.complete();\n\n // Netowrks events can be ignored once the obervable has been completed\n ignoreNetworkEvents = true;\n };\n\n this._connection.onopen = () => {\n subscriber.next({\n type: SecureChannelEventType.Opened,\n });\n };\n\n this._connection.onerror = (error) => {\n if (ignoreNetworkEvents) {\n return;\n }\n\n subscriber.next({\n type: SecureChannelEventType.Error,\n error: new SecureChannelError({\n url: this._connection.url,\n errorMessage: error.message,\n }),\n });\n subscriber.complete();\n };\n\n this._connection.onclose = () => {\n if (ignoreNetworkEvents) {\n return;\n }\n\n if (communicationFinished) {\n subscriber.next({\n type: SecureChannelEventType.Closed,\n });\n } else {\n subscriber.next({\n type: SecureChannelEventType.Error,\n error: new SecureChannelError({\n url: this._connection.url,\n errorMessage: \"Connection closed unexpectedly\",\n }),\n });\n }\n subscriber.complete();\n };\n\n this._connection.onmessage = async (event) => {\n // When unsubscribed, ignore the message\n if (unsubscribed) {\n return;\n }\n\n // Parse input message\n let input: InMessageType;\n try {\n const jsonData = JSON.parse(String(event.data));\n if (this.isInMessageType(jsonData)) {\n input = jsonData;\n } else {\n throw new Error(\"Data does not match InMessageType\");\n }\n } catch (_) {\n notifyError(\n new SecureChannelError({\n url: this._connection.url,\n errorMessage: `Invalid message received: ${String(event.data)}`,\n }),\n );\n return;\n }\n\n // Execute message query\n switch (input.query) {\n case InMessageQueryEnum.EXCHANGE: {\n const { nonce, data } = input;\n\n // Exchange query should contain a single APDU\n if (typeof data !== \"string\") {\n notifyError(\n new SecureChannelError(\n `${InMessageQueryEnum.EXCHANGE} data type should be an APDU`,\n ),\n );\n return;\n }\n\n // APDU should be a valid hex string\n const apdu = hexaStringToBuffer(data);\n if (apdu === null || apdu.length < 5) {\n notifyError(\n new SecureChannelError(`Received invalid APDU data: ${data}`),\n );\n return;\n }\n subscriber.next({\n type: SecureChannelEventType.PreExchange,\n payload: { nonce, apdu },\n });\n\n // Notify permission requested\n let permissionRequested = false;\n if (\n willRequestPermission(apdu) &&\n !this.isSecureConnectionAllowed()\n ) {\n permissionRequested = true;\n subscriber.next({\n type: SecureChannelEventType.PermissionRequested,\n });\n }\n\n // Send APDU to the device\n const response = await this._api.sendApdu(apdu);\n if (unsubscribed) {\n return;\n }\n\n // Map device response\n response.caseOf({\n Left: (error) => {\n notifyError(new SecureChannelError(error));\n },\n Right: (apduResponse: ApduResponse) => {\n let outMessageResponse: OutMessageResponseEnum;\n const deviceError = this.mapDeviceError(apduResponse);\n if (deviceError === null) {\n outMessageResponse = OutMessageResponseEnum.SUCCESS;\n\n // Emit event for the exchange\n subscriber.next({\n type: SecureChannelEventType.Exchange,\n payload: {\n nonce,\n apdu,\n data: apduResponse.data,\n status: apduResponse.statusCode,\n },\n });\n\n // If manager consent was requested, notify the \"granted\" event\n if (permissionRequested) {\n subscriber.next({\n type: SecureChannelEventType.PermissionGranted,\n });\n }\n } else {\n outMessageResponse = OutMessageResponseEnum.ERROR;\n notifyError(deviceError);\n }\n\n // Send the message back to the server\n const message: OutMessageType = {\n nonce,\n response: outMessageResponse,\n data: bufferToHexaString(apduResponse.data, false),\n };\n this._connection.send(JSON.stringify(message));\n },\n });\n break;\n }\n case InMessageQueryEnum.BULK: {\n // Network not needed anymore during bulk APDUs sending\n ignoreNetworkEvents = true;\n this._connection.close();\n\n const startTime = Date.now();\n console.log(\"[ConnectToSecureChannelTask] BULK started\");\n\n // A valid array of APDUs is required in a bulk query\n if (\n !Array.isArray(input.data) ||\n input.data.length === 0 ||\n !input.data.every((data) => typeof data === \"string\")\n ) {\n notifyError(new SecureChannelError(\"Invalid bulk data received\"));\n return;\n }\n\n for (let i = 0, len = input.data.length; i < len; i++) {\n // APDU should be a valid hex string\n const apdu = hexaStringToBuffer(input.data[i]!);\n if (apdu === null || apdu.length < 5) {\n notifyError(\n new SecureChannelError(\n `Received invalid APDU bulk data: ${input.data[i]}`,\n ),\n );\n return;\n }\n\n // Send APDU to the device\n const response = await this._api.sendApdu(apdu);\n if (unsubscribed) {\n return;\n }\n\n // Map device response\n if (response.isLeft()) {\n notifyError(new SecureChannelError(response.extract()));\n return;\n } else if (response.isRight()) {\n const deviceError = this.mapDeviceError(response.extract());\n if (deviceError === null) {\n // Notify the progress\n subscriber.next({\n type: SecureChannelEventType.Progress,\n payload: {\n progress: +Number((i + 1) / len).toFixed(2),\n index: i,\n total: len,\n },\n });\n } else {\n notifyError(deviceError);\n return;\n }\n }\n }\n\n const endTime = Date.now();\n console.log(\n \"[ConnectToSecureChannelTask] BULK finished in\",\n endTime - startTime,\n \"ms\",\n );\n communicationFinished = true;\n subscriber.complete();\n break;\n }\n case InMessageQueryEnum.SUCCESS: {\n if (ignoreNetworkEvents) {\n break;\n }\n // Emit the result if there is any\n const payload = input.result ?? input.data;\n if (payload) {\n subscriber.next({\n type: SecureChannelEventType.Result,\n payload: payload ?? \"\",\n });\n }\n communicationFinished = true;\n subscriber.complete();\n break;\n }\n case InMessageQueryEnum.WARNING: {\n if (ignoreNetworkEvents) {\n break;\n }\n subscriber.next({\n type: SecureChannelEventType.Warning,\n payload: { message: String(input.data) },\n });\n break;\n }\n case InMessageQueryEnum.ERROR: {\n if (ignoreNetworkEvents) {\n break;\n }\n notifyError(\n new SecureChannelError({\n url: this._connection.url,\n errorMessage: String(input.data),\n }),\n );\n }\n }\n };\n\n return () => {\n reenableRefresher();\n unsubscribed = true;\n // Close the connection if it is open when unsubscribing\n if (this._connection.readyState === WebSocket.OPEN) {\n this._connection.close();\n }\n };\n });\n\n return obs;\n }\n\n /**\n * Determines if a secure connection is already allowed based on the current device session state.\n *\n * @returns {boolean} `true` if a secure connection is allowed, otherwise `false`.\n */\n isSecureConnectionAllowed(): boolean {\n const deviceSessionState = this._api.getDeviceSessionState();\n return (\n \"isSecureConnectionAllowed\" in deviceSessionState &&\n deviceSessionState.isSecureConnectionAllowed\n );\n }\n\n isInMessageType(data: unknown): data is InMessageType {\n if (typeof data !== \"object\" || !data) {\n return false;\n }\n\n const message = data as InMessageType;\n return (\n typeof message.uuid === \"string\" &&\n typeof message.session === \"string\" &&\n typeof message.query === \"string\" &&\n Object.values(InMessageQueryEnum).includes(message.query) &&\n typeof message.nonce === \"number\"\n );\n }\n\n mapDeviceError(apduResponse: ApduResponse): SecureChannelError | null {\n if (CommandUtils.isSuccessResponse(apduResponse)) {\n return null;\n }\n\n // Device is locked\n if (CommandUtils.isLockedDeviceResponse(apduResponse)) {\n return new SecureChannelError(\n {\n url: this._connection.url,\n errorMessage: `Device is locked`,\n },\n SecureChannelErrorType.DeviceLocked,\n );\n }\n\n // User refused the permission\n if (CommandUtils.isRefusedByUser(apduResponse)) {\n return new SecureChannelError(\n {\n url: this._connection.url,\n errorMessage: \"User refused on the device\",\n },\n SecureChannelErrorType.RefusedByUser,\n );\n }\n\n // App already installed\n if (CommandUtils.isAppAlreadyInstalled(apduResponse)) {\n return new SecureChannelError(\n {\n url: this._connection.url,\n errorMessage: \"App already installed\",\n },\n SecureChannelErrorType.AppAlreadyInstalled,\n );\n }\n\n // Out of memory\n if (CommandUtils.isOutOfMemory(apduResponse)) {\n return new SecureChannelError(\n {\n url: this._connection.url,\n errorMessage: \"Out of memory\",\n },\n SecureChannelErrorType.OutOfMemory,\n );\n }\n\n return new SecureChannelError({\n url: this._connection.url,\n errorMessage: `Invalid status code: ${bufferToHexaString(\n apduResponse.statusCode,\n )}`,\n });\n }\n}\n"],
5
- "mappings": "AAAA,OAAOA,MAAe,gBAEtB,OAAS,cAAAC,MAAkB,OAE3B,OAAS,gBAAAC,MAAoB,kCAG7B,OACE,sBAAAC,EAEA,0BAAAC,EAGA,0BAAAC,MACK,iCACP,OAAS,yBAAAC,MAA6B,4BACtC,OAAS,sBAAAC,EAAoB,sBAAAC,MAA0B,wBACvD,OACE,sBAAAC,EACA,0BAAAC,MAEK,wCAMA,MAAMC,CAA2B,CAEtC,YACmBC,EACAC,EACjB,CAFiB,UAAAD,EACA,WAAAC,EAEjB,GAAI,KAAK,MAAM,WAAW,QAAQ,EAChC,KAAK,YAAc,KAAK,MAAM,WAAW,QAAQ,MAEjD,OAAM,IAAIJ,EACR,iCAAiC,OAAO,KAAK,MAAM,WAAW,QAAQ,CAAC,CAAC,EAC1E,CAEJ,CAZiB,YAcjB,KAAsC,CACpC,MAAMK,EAAoB,KAAK,KAAK,iBAClC,wBACF,EAsSA,OApSY,IAAIb,EAAgCc,GAAe,CAC7D,IAAIC,EAAwB,GACxBC,EAAsB,GACtBC,EAAwB,GAE5B,MAAMC,EAAeC,GAA8B,CACjDL,EAAW,KAAK,CACd,KAAMV,EAAuB,MAC7B,MAAAe,CACF,CAAC,EACDL,EAAW,SAAS,EAGpBE,EAAsB,EACxB,EAEA,YAAK,YAAY,OAAS,IAAM,CAC9BF,EAAW,KAAK,CACd,KAAMV,EAAuB,MAC/B,CAAC,CACH,EAEA,KAAK,YAAY,QAAWe,GAAU,CAChCH,IAIJF,EAAW,KAAK,CACd,KAAMV,EAAuB,MAC7B,MAAO,IAAII,EAAmB,CAC5B,IAAK,KAAK,YAAY,IACtB,aAAcW,EAAM,OACtB,CAAC,CACH,CAAC,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,CAGH,CAOA,2BAAqC,CACnC,MAAMsC,EAAqB,KAAK,KAAK,sBAAsB,EAC3D,MACE,8BAA+BA,GAC/BA,EAAmB,yBAEvB,CAEA,gBAAgBb,EAAsC,CACpD,GAAI,OAAOA,GAAS,UAAY,CAACA,EAC/B,MAAO,GAGT,MAAMO,EAAUP,EAChB,OACE,OAAOO,EAAQ,MAAS,UACxB,OAAOA,EAAQ,SAAY,UAC3B,OAAOA,EAAQ,OAAU,UACzB,OAAO,OAAO7B,CAAkB,EAAE,SAAS6B,EAAQ,KAAK,GACxD,OAAOA,EAAQ,OAAU,QAE7B,CAEA,eAAeH,EAAuD,CACpE,OAAI3B,EAAa,kBAAkB2B,CAAY,EACtC,KAIL3B,EAAa,uBAAuB2B,CAAY,EAC3C,IAAIpB,EACT,CACE,IAAK,KAAK,YAAY,IACtB,aAAc,kBAChB,EACAC,EAAuB,YACzB,EAIER,EAAa,gBAAgB2B,CAAY,EACpC,IAAIpB,EACT,CACE,IAAK,KAAK,YAAY,IACtB,aAAc,4BAChB,EACAC,EAAuB,aACzB,EAIER,EAAa,sBAAsB2B,CAAY,EAC1C,IAAIpB,EACT,CACE,IAAK,KAAK,YAAY,IACtB,aAAc,uBAChB,EACAC,EAAuB,mBACzB,EAIER,EAAa,cAAc2B,CAAY,EAClC,IAAIpB,EACT,CACE,IAAK,KAAK,YAAY,IACtB,aAAc,eAChB,EACAC,EAAuB,WACzB,EAGK,IAAID,EAAmB,CAC5B,IAAK,KAAK,YAAY,IACtB,aAAc,wBAAwBF,EACpCsB,EAAa,UACf,CAAC,EACH,CAAC,CACH,CACF",
6
- "names": ["WebSocket", "Observable", "CommandUtils", "InMessageQueryEnum", "OutMessageResponseEnum", "SecureChannelEventType", "willRequestPermission", "bufferToHexaString", "hexaStringToBuffer", "SecureChannelError", "SecureChannelErrorType", "ConnectToSecureChannelTask", "_api", "_args", "reenableRefresher", "subscriber", "unsubscribed", "ignoreNetworkEvents", "communicationFinished", "notifyError", "error", "event", "input", "jsonData", "nonce", "data", "apdu", "permissionRequested", "response", "apduResponse", "outMessageResponse", "deviceError", "message", "startTime", "i", "len", "endTime", "payload", "deviceSessionState"]
4
+ "sourcesContent": ["import WebSocket from \"isomorphic-ws\";\nimport { type Either } from \"purify-ts\";\nimport { Observable } from \"rxjs\";\n\nimport { CommandUtils } from \"@api/command/utils/CommandUtils\";\nimport { type InternalApi } from \"@api/device-action/DeviceAction\";\nimport { type ApduResponse } from \"@api/device-session/ApduResponse\";\nimport {\n InMessageQueryEnum,\n type InMessageType,\n OutMessageResponseEnum,\n type OutMessageType,\n type SecureChannelEvent,\n SecureChannelEventType,\n} from \"@api/secure-channel/task/types\";\nimport { willRequestPermission } from \"@api/secure-channel/utils\";\nimport { bufferToHexaString, hexaStringToBuffer } from \"@api/utils/HexaString\";\nimport {\n SecureChannelError,\n SecureChannelErrorType,\n type WebSocketConnectionError,\n} from \"@internal/secure-channel/model/Errors\";\n\nexport type ConnectToSecureChannelTaskArgs = {\n connection: Either<WebSocketConnectionError, WebSocket>;\n};\n\nexport class ConnectToSecureChannelTask {\n private readonly _connection: WebSocket;\n constructor(\n private readonly _api: InternalApi,\n private readonly _args: ConnectToSecureChannelTaskArgs,\n ) {\n if (this._args.connection.isRight()) {\n this._connection = this._args.connection.extract();\n } else {\n throw new SecureChannelError(\n `Invalid WebSocket connection: ${String(this._args.connection.extract())}`,\n );\n }\n }\n\n run(): Observable<SecureChannelEvent> {\n const reenableRefresher = this._api.disableRefresher(\n \"connectToSecureChannel\",\n );\n\n const obs = new Observable<SecureChannelEvent>((subscriber) => {\n let unsubscribed: boolean = false;\n let ignoreNetworkEvents = false;\n let communicationFinished = false;\n\n const notifyError = (error: SecureChannelError) => {\n subscriber.next({\n type: SecureChannelEventType.Error,\n error,\n });\n subscriber.complete();\n\n // Netowrks events can be ignored once the obervable has been completed\n ignoreNetworkEvents = true;\n };\n\n this._connection.onopen = () => {\n subscriber.next({\n type: SecureChannelEventType.Opened,\n });\n };\n\n this._connection.onerror = (error) => {\n if (ignoreNetworkEvents) {\n return;\n }\n\n subscriber.next({\n type: SecureChannelEventType.Error,\n error: new SecureChannelError({\n url: this._connection.url,\n errorMessage: error.message,\n }),\n });\n subscriber.complete();\n };\n\n this._connection.onclose = () => {\n if (ignoreNetworkEvents) {\n return;\n }\n\n if (communicationFinished) {\n subscriber.next({\n type: SecureChannelEventType.Closed,\n });\n } else {\n subscriber.next({\n type: SecureChannelEventType.Error,\n error: new SecureChannelError({\n url: this._connection.url,\n errorMessage: \"Connection closed unexpectedly\",\n }),\n });\n }\n subscriber.complete();\n };\n\n this._connection.onmessage = async (event) => {\n // When unsubscribed, ignore the message\n if (unsubscribed) {\n return;\n }\n\n // Parse input message\n let input: InMessageType;\n try {\n const jsonData = JSON.parse(String(event.data));\n if (this.isInMessageType(jsonData)) {\n input = jsonData;\n } else {\n throw new Error(\"Data does not match InMessageType\");\n }\n } catch (_) {\n notifyError(\n new SecureChannelError({\n url: this._connection.url,\n errorMessage: `Invalid message received: ${String(event.data)}`,\n }),\n );\n return;\n }\n\n // Execute message query\n switch (input.query) {\n case InMessageQueryEnum.EXCHANGE: {\n const { nonce, data } = input;\n\n // Exchange query should contain a single APDU\n if (typeof data !== \"string\") {\n notifyError(\n new SecureChannelError(\n `${InMessageQueryEnum.EXCHANGE} data type should be an APDU`,\n ),\n );\n return;\n }\n\n // APDU should be a valid hex string\n const apdu = hexaStringToBuffer(data);\n if (apdu === null || apdu.length < 5) {\n notifyError(\n new SecureChannelError(`Received invalid APDU data: ${data}`),\n );\n return;\n }\n subscriber.next({\n type: SecureChannelEventType.PreExchange,\n payload: { nonce, apdu },\n });\n\n // Notify permission requested\n let permissionRequested = false;\n if (\n willRequestPermission(apdu) &&\n !this.isSecureConnectionAllowed()\n ) {\n permissionRequested = true;\n subscriber.next({\n type: SecureChannelEventType.PermissionRequested,\n });\n }\n\n // Send APDU to the device\n const response = await this._api.sendApdu(apdu);\n if (unsubscribed) {\n return;\n }\n\n // Map device response\n response.caseOf({\n Left: (error) => {\n notifyError(new SecureChannelError(error));\n },\n Right: (apduResponse: ApduResponse) => {\n let outMessageResponse: OutMessageResponseEnum;\n const deviceError = this.mapDeviceError(apduResponse);\n if (deviceError === null) {\n outMessageResponse = OutMessageResponseEnum.SUCCESS;\n\n // Emit event for the exchange\n subscriber.next({\n type: SecureChannelEventType.Exchange,\n payload: {\n nonce,\n apdu,\n data: apduResponse.data,\n status: apduResponse.statusCode,\n },\n });\n\n // If manager consent was requested, notify the \"granted\" event\n if (permissionRequested) {\n subscriber.next({\n type: SecureChannelEventType.PermissionGranted,\n });\n }\n } else {\n outMessageResponse = OutMessageResponseEnum.ERROR;\n notifyError(deviceError);\n }\n\n // Send the message back to the server\n const message: OutMessageType = {\n nonce,\n response: outMessageResponse,\n data: bufferToHexaString(apduResponse.data, false),\n };\n this._connection.send(JSON.stringify(message));\n },\n });\n break;\n }\n case InMessageQueryEnum.BULK: {\n // Network not needed anymore during bulk APDUs sending\n ignoreNetworkEvents = true;\n this._connection.close();\n\n // A valid array of APDUs is required in a bulk query\n if (\n !Array.isArray(input.data) ||\n input.data.length === 0 ||\n !input.data.every((data) => typeof data === \"string\")\n ) {\n notifyError(new SecureChannelError(\"Invalid bulk data received\"));\n return;\n }\n\n for (let i = 0, len = input.data.length; i < len; i++) {\n // APDU should be a valid hex string\n const apdu = hexaStringToBuffer(input.data[i]!);\n if (apdu === null || apdu.length < 5) {\n notifyError(\n new SecureChannelError(\n `Received invalid APDU bulk data: ${input.data[i]}`,\n ),\n );\n return;\n }\n\n // Send APDU to the device\n const response = await this._api.sendApdu(apdu);\n if (unsubscribed) {\n return;\n }\n\n // Map device response\n if (response.isLeft()) {\n notifyError(new SecureChannelError(response.extract()));\n return;\n } else if (response.isRight()) {\n const deviceError = this.mapDeviceError(response.extract());\n if (deviceError === null) {\n // Notify the progress\n subscriber.next({\n type: SecureChannelEventType.Progress,\n payload: {\n progress: +Number((i + 1) / len).toFixed(2),\n index: i,\n total: len,\n },\n });\n } else {\n notifyError(deviceError);\n return;\n }\n }\n }\n communicationFinished = true;\n subscriber.complete();\n break;\n }\n case InMessageQueryEnum.SUCCESS: {\n if (ignoreNetworkEvents) {\n break;\n }\n // Emit the result if there is any\n const payload = input.result ?? input.data;\n if (payload) {\n subscriber.next({\n type: SecureChannelEventType.Result,\n payload: payload ?? \"\",\n });\n }\n communicationFinished = true;\n subscriber.complete();\n break;\n }\n case InMessageQueryEnum.WARNING: {\n if (ignoreNetworkEvents) {\n break;\n }\n subscriber.next({\n type: SecureChannelEventType.Warning,\n payload: { message: String(input.data) },\n });\n break;\n }\n case InMessageQueryEnum.ERROR: {\n if (ignoreNetworkEvents) {\n break;\n }\n notifyError(\n new SecureChannelError({\n url: this._connection.url,\n errorMessage: String(input.data),\n }),\n );\n }\n }\n };\n\n return () => {\n reenableRefresher();\n unsubscribed = true;\n // Close the connection if it is open when unsubscribing\n if (this._connection.readyState === WebSocket.OPEN) {\n this._connection.close();\n }\n };\n });\n\n return obs;\n }\n\n /**\n * Determines if a secure connection is already allowed based on the current device session state.\n *\n * @returns {boolean} `true` if a secure connection is allowed, otherwise `false`.\n */\n isSecureConnectionAllowed(): boolean {\n const deviceSessionState = this._api.getDeviceSessionState();\n return (\n \"isSecureConnectionAllowed\" in deviceSessionState &&\n deviceSessionState.isSecureConnectionAllowed\n );\n }\n\n isInMessageType(data: unknown): data is InMessageType {\n if (typeof data !== \"object\" || !data) {\n return false;\n }\n\n const message = data as InMessageType;\n return (\n typeof message.uuid === \"string\" &&\n typeof message.session === \"string\" &&\n typeof message.query === \"string\" &&\n Object.values(InMessageQueryEnum).includes(message.query) &&\n typeof message.nonce === \"number\"\n );\n }\n\n mapDeviceError(apduResponse: ApduResponse): SecureChannelError | null {\n if (CommandUtils.isSuccessResponse(apduResponse)) {\n return null;\n }\n\n // Device is locked\n if (CommandUtils.isLockedDeviceResponse(apduResponse)) {\n return new SecureChannelError(\n {\n url: this._connection.url,\n errorMessage: `Device is locked`,\n },\n SecureChannelErrorType.DeviceLocked,\n );\n }\n\n // User refused the permission\n if (CommandUtils.isRefusedByUser(apduResponse)) {\n return new SecureChannelError(\n {\n url: this._connection.url,\n errorMessage: \"User refused on the device\",\n },\n SecureChannelErrorType.RefusedByUser,\n );\n }\n\n // App already installed\n if (CommandUtils.isAppAlreadyInstalled(apduResponse)) {\n return new SecureChannelError(\n {\n url: this._connection.url,\n errorMessage: \"App already installed\",\n },\n SecureChannelErrorType.AppAlreadyInstalled,\n );\n }\n\n // Out of memory\n if (CommandUtils.isOutOfMemory(apduResponse)) {\n return new SecureChannelError(\n {\n url: this._connection.url,\n errorMessage: \"Out of memory\",\n },\n SecureChannelErrorType.OutOfMemory,\n );\n }\n\n return new SecureChannelError({\n url: this._connection.url,\n errorMessage: `Invalid status code: ${bufferToHexaString(\n apduResponse.statusCode,\n )}`,\n });\n }\n}\n"],
5
+ "mappings": "AAAA,OAAOA,MAAe,gBAEtB,OAAS,cAAAC,MAAkB,OAE3B,OAAS,gBAAAC,MAAoB,kCAG7B,OACE,sBAAAC,EAEA,0BAAAC,EAGA,0BAAAC,MACK,iCACP,OAAS,yBAAAC,MAA6B,4BACtC,OAAS,sBAAAC,EAAoB,sBAAAC,MAA0B,wBACvD,OACE,sBAAAC,EACA,0BAAAC,MAEK,wCAMA,MAAMC,CAA2B,CAEtC,YACmBC,EACAC,EACjB,CAFiB,UAAAD,EACA,WAAAC,EAEjB,GAAI,KAAK,MAAM,WAAW,QAAQ,EAChC,KAAK,YAAc,KAAK,MAAM,WAAW,QAAQ,MAEjD,OAAM,IAAIJ,EACR,iCAAiC,OAAO,KAAK,MAAM,WAAW,QAAQ,CAAC,CAAC,EAC1E,CAEJ,CAZiB,YAcjB,KAAsC,CACpC,MAAMK,EAAoB,KAAK,KAAK,iBAClC,wBACF,EA4RA,OA1RY,IAAIb,EAAgCc,GAAe,CAC7D,IAAIC,EAAwB,GACxBC,EAAsB,GACtBC,EAAwB,GAE5B,MAAMC,EAAeC,GAA8B,CACjDL,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Observable", "CommandUtils", "InMessageQueryEnum", "OutMessageResponseEnum", "SecureChannelEventType", "willRequestPermission", "bufferToHexaString", "hexaStringToBuffer", "SecureChannelError", "SecureChannelErrorType", "ConnectToSecureChannelTask", "_api", "_args", "reenableRefresher", "subscriber", "unsubscribed", "ignoreNetworkEvents", "communicationFinished", "notifyError", "error", "event", "input", "jsonData", "nonce", "data", "apdu", "permissionRequested", "response", "apduResponse", "outMessageResponse", "deviceError", "message", "i", "len", "payload", "deviceSessionState"]
7
7
  }