@trezor/transport
Version:
Low level library facilitating protocol buffers based communication with Trezor devices
61 lines (60 loc) • 1.58 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.validateProtocolMessage = validateProtocolMessage;
exports.createProtocolMessage = createProtocolMessage;
function validateProtocolMessage(body, withData = true) {
const isHex = s => /^[0-9A-Fa-f]+$/g.test(s);
const isValidProtocol = s => s === 'v1' || s === 'v2' || s === 'bridge';
if (typeof body === 'string') {
if (withData && isHex(body) || !withData && !body.length) {
return {
data: body
};
}
}
let json;
if (typeof body === 'object') {
json = body;
} else {
try {
json = JSON.parse(body);
} catch {}
}
if (!json) {
throw new Error('Invalid BridgeProtocolMessage body');
}
if (typeof json.protocol !== 'string' || !isValidProtocol(json.protocol)) {
throw new Error('Invalid BridgeProtocolMessage protocol');
}
if (withData && (typeof json.data !== 'string' || !isHex(json.data))) {
throw new Error('Invalid BridgeProtocolMessage data');
}
return {
protocol: json.protocol,
data: json.data,
thpState: json.thpState
};
}
function createProtocolMessage(body, protocol, thpState) {
let data;
if (Buffer.isBuffer(body)) {
data = body.toString('hex');
}
if (typeof body === 'string') {
data = body;
}
if (typeof data !== 'string') {
data = '';
}
if (!protocol) {
return data;
}
return JSON.stringify({
protocol: typeof protocol === 'string' ? protocol : protocol.name,
data,
thpState
});
}
//# sourceMappingURL=bridgeProtocolMessage.js.map