s-bit-agent
Version:
s.BitAgent is a simple Bitwarden CLI wrapper which provides a SSH2 Key Agent solution for Bitwarden.
173 lines • 8.13 kB
JavaScript
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AgentService = void 0;
const common_1 = require("@nestjs/common");
const log_service_1 = require("../shared/log.service");
const bitwarden_service_1 = require("../bitwarden/bitwarden.service");
const gui_service_1 = require("../gui/gui.service");
const session_service_1 = require("../bitwarden/session.service");
const cache_service_1 = require("../bitwarden/cache.service");
const cache_service_2 = require("../shared/cache.service");
const handler_1 = require("./types/handler");
const index_1 = require("./handler/index");
const node_ipc_1 = require("node-ipc");
const fs = require("fs");
const path = require("path");
const os = require("os");
const message_1 = require("./types/message");
let AgentService = class AgentService {
constructor(logService, bitService, guiService, sessionService, cacheService, keyCacheService) {
this.logService = logService;
this.bitService = bitService;
this.guiService = guiService;
this.sessionService = sessionService;
this.cacheService = cacheService;
this.keyCacheService = keyCacheService;
this.file = process.env.SSH_AUTH_SOCK || os.homedir() + '/.ssh/s-bit-agent.sock';
this.socketId = 'agentService';
this.client = null;
this.running = false;
this.timeout = 300000;
node_ipc_1.default.config.id = this.socketId;
node_ipc_1.default.config.retry = 1500;
node_ipc_1.default.config.silent = true;
node_ipc_1.default.config.rawBuffer = true;
node_ipc_1.default.config.encoding = 'hex';
node_ipc_1.default.config.writableAll = true;
node_ipc_1.default.config.readableAll = true;
['SIGINT', 'SIGTERM', 'SIGQUIT'].forEach((signal) => {
process.on(signal, () => this.stop());
});
}
async handle(data) {
const prefix = `[event@${Math.random().toString(36).substring(7)}] `;
const client = this.client;
if (!Buffer.isBuffer(data)) {
this.logService.error(prefix + 'Received non-buffer data:', data);
return;
}
else if (data.length < 5) {
this.logService.error(prefix + 'Received too short message:', data.toString('hex'));
return;
}
this.logService.info(prefix + 'Received message:', data.toString('hex'));
const messageLength = data.readUInt32BE(0);
const messageType = data.readInt8(4);
let timouted = false;
const timeoutT = setTimeout(() => {
timouted = true;
this.logService.error(prefix + 'Timeout while handling message:', messageType);
this.logService.error(prefix + 'Message:', data.toString('hex'));
node_ipc_1.default.server.emit(client, Buffer.from([0, 0, 0, 1, handler_1.IcpMessageType.SSH_AGENT_FAILURE]));
}, this.timeout);
try {
let token = null;
if (messageType == handler_1.IcpMessageType.S_BIT_AGENT_EXCHANGE) {
this.logService.info(prefix + 'Received', 'S_BIT_AGENT_EXCHANGE');
const json = JSON.parse(data.toString('utf-8', 5, messageLength + 4));
let response = new message_1.ResponseFailure('Unknown message');
for (const handler of index_1.IcpCustomHandlers) {
if (handler.messageType != json.type)
continue;
response = await handler.handle(json, prefix, this, client);
this.logService.info(prefix + 'Handled', json.type);
break;
}
const size = Buffer.alloc(4);
const mType = Buffer.from([handler_1.IcpMessageType.S_BIT_AGENT_EXCHANGE]);
const responseBuffer = Buffer.from(JSON.stringify(response), 'utf-8');
size.writeUInt32BE(responseBuffer.length + 1, 0);
node_ipc_1.default.server.emit(client, Buffer.concat([size, mType, responseBuffer]));
this.logService.info(prefix + 'Sent', response.type);
return;
}
else {
for (const handler of index_1.IcpHandlers) {
if (handler.messageType != messageType)
continue;
await handler.handle(data, prefix, this, client);
this.logService.info(prefix + 'Handled', messageType);
return;
}
}
throw new Error('Unknown message type: ' + messageType);
}
catch (e) {
this.logService.error(prefix + 'Error while handling message:', messageType);
this.logService.error(prefix + 'Error message:', e.message);
if (!node_ipc_1.default.config.silent)
console.error(e);
this.logService.info(prefix + 'Sending', 'SSH_AGENT_FAILURE');
node_ipc_1.default.server.emit(client, Buffer.from([0, 0, 0, 1, handler_1.IcpMessageType.SSH_AGENT_FAILURE]));
}
finally {
clearTimeout(timeoutT);
}
}
setLogging(val) {
if (node_ipc_1.default.server)
throw new Error('Cannot change logging while server is running');
node_ipc_1.default.config.silent = !val;
}
setTimeout(val) {
if (node_ipc_1.default.server)
throw new Error('Cannot change timeout while server is running');
this.timeout = val;
}
async start() {
if (this.running)
return;
this.running = true;
if (fs.existsSync(this.file))
this.logService.fatal('Socket file already exists:', this.file);
const dir = path.dirname(this.file);
if (!fs.existsSync(dir))
fs.mkdirSync(dir, { recursive: true });
node_ipc_1.default.serve(this.file, () => {
node_ipc_1.default.server.on('data', (buffer) => {
this.handle(buffer);
});
node_ipc_1.default.server.on('socket.disconnected', () => {
this.logService.info('Client disconnected');
});
node_ipc_1.default.server.on('connect', (socket) => {
this.client = socket;
this.logService.info('Client connected');
});
node_ipc_1.default.server.on('error', (err) => {
if (err.message === 'read ECONNRESET')
return;
this.logService.error('IPC server error:', err.message);
});
});
node_ipc_1.default.server.start();
this.logService.info('IPC Server started on', this.file);
}
async stop() {
if (!this.running)
return;
this.running = false;
node_ipc_1.default.server.stop();
this.logService.warn('IPC Server stopped');
}
};
exports.AgentService = AgentService;
exports.AgentService = AgentService = __decorate([
(0, common_1.Injectable)(),
__metadata("design:paramtypes", [log_service_1.LogService,
bitwarden_service_1.BitwardenService,
gui_service_1.GuiService,
session_service_1.SessionService,
cache_service_1.CacheService,
cache_service_2.CacheService])
], AgentService);
//# sourceMappingURL=agent.service.js.map