1
0
mirror of https://github.com/bitwarden/browser.git synced 2024-06-28 10:55:27 +02:00
bitwarden-browser/src/background/nativeMessaging.background.ts

85 lines
2.8 KiB
TypeScript
Raw Normal View History

2020-10-16 11:09:49 +02:00
import { CryptoService, LogService, VaultTimeoutService } from 'jslib/abstractions';
import { StorageService } from 'jslib/abstractions/storage.service';
import { ConstantsService } from 'jslib/services';
2020-10-11 20:45:25 +02:00
import { BrowserApi } from '../browser/browserApi';
import RuntimeBackground from './runtime.background';
2020-10-16 11:09:49 +02:00
const MessageValidTimeout = 10 * 1000;
export class NativeMessagingBackground {
private connected = false;
private port: browser.runtime.Port | chrome.runtime.Port;
private resolver: any = null;
constructor(private storageService: StorageService, private cryptoService: CryptoService,
private vaultTimeoutService: VaultTimeoutService, private runtimeBackground: RuntimeBackground) {}
connect() {
2020-10-11 20:45:25 +02:00
this.port = BrowserApi.connectNative('com.8bit.bitwarden');
this.connected = true;
this.port.onMessage.addListener((msg) => this.onMessage(msg));
2020-10-16 11:09:49 +02:00
this.port.onDisconnect.addListener(() => {
this.connected = false;
});
}
2020-10-12 21:18:47 +02:00
async send(message: any) {
// If not connected, try to connect
if (!this.connected) {
this.connect();
}
2020-10-12 21:18:47 +02:00
message.timestamp = Date.now();
const encrypted = await this.cryptoService.encrypt(JSON.stringify(message));
this.port.postMessage(encrypted);
}
await(): Promise<any> {
return new Promise((resolve, reject) => {
this.resolver = resolve;
});
}
2020-10-12 21:18:47 +02:00
private async onMessage(rawMessage: any) {
const message = JSON.parse(await this.cryptoService.decryptToUtf8(rawMessage));
2020-10-16 11:09:49 +02:00
if (Math.abs(message.timestamp - Date.now()) > MessageValidTimeout) {
// tslint:disable-next-line
console.error('NativeMessage is to old, ignoring.');
2020-10-12 21:18:47 +02:00
return;
}
2020-10-16 11:09:49 +02:00
switch (message.command) {
case 'biometricUnlock': {
await this.storageService.remove(ConstantsService.biometricAwaitingAcceptance);
const enabled = await this.storageService.get(ConstantsService.biometricUnlockKey);
if (enabled === null || enabled === false) {
2020-10-12 21:18:47 +02:00
if (message.response === 'unlocked') {
await this.storageService.save(ConstantsService.biometricUnlockKey, true);
}
2020-10-16 11:09:49 +02:00
await this.cryptoService.toggleKey();
}
if (this.vaultTimeoutService.biometricLocked) {
this.runtimeBackground.processMessage({command: 'unlocked'}, null, null);
this.vaultTimeoutService.biometricLocked = false;
}
}
2020-10-16 11:09:49 +02:00
default:
// tslint:disable-next-line
console.error('NativeMessage, got unknown command.');
}
if (this.resolver) {
2020-10-12 21:18:47 +02:00
this.resolver(message);
}
}
}