1
0
mirror of https://github.com/bitwarden/browser synced 2024-12-26 09:54:35 +01:00
bitwarden-estensione-browser/src/background/webRequest.background.ts

96 lines
2.7 KiB
TypeScript
Raw Normal View History

2021-12-21 15:43:35 +01:00
import { CipherService } from "jslib-common/abstractions/cipher.service";
import { PlatformUtilsService } from "jslib-common/abstractions/platformUtils.service";
import { VaultTimeoutService } from "jslib-common/abstractions/vaultTimeout.service";
import { UriMatchType } from "jslib-common/enums/uriMatchType";
export default class WebRequestBackground {
2021-12-21 15:43:35 +01:00
private pendingAuthRequests: any[] = [];
private webRequest: any;
private isFirefox: boolean;
2021-12-21 15:43:35 +01:00
constructor(
platformUtilsService: PlatformUtilsService,
private cipherService: CipherService,
private vaultTimeoutService: VaultTimeoutService
) {
this.webRequest = (window as any).chrome.webRequest;
this.isFirefox = platformUtilsService.isFirefox();
}
async init() {
if (!this.webRequest || !this.webRequest.onAuthRequired) {
return;
}
2021-12-21 15:43:35 +01:00
this.webRequest.onAuthRequired.addListener(
async (details: any, callback: any) => {
if (!details.url || this.pendingAuthRequests.indexOf(details.requestId) !== -1) {
if (callback) {
callback();
}
return;
}
2021-12-21 15:43:35 +01:00
this.pendingAuthRequests.push(details.requestId);
2021-12-21 15:43:35 +01:00
if (this.isFirefox) {
2022-02-24 18:14:04 +01:00
// eslint-disable-next-line
2021-12-21 15:43:35 +01:00
return new Promise(async (resolve, reject) => {
await this.resolveAuthCredentials(details.url, resolve, reject);
});
} else {
await this.resolveAuthCredentials(details.url, callback, callback);
}
},
{ urls: ["http://*/*", "https://*/*"] },
[this.isFirefox ? "blocking" : "asyncBlocking"]
);
2021-12-21 15:43:35 +01:00
this.webRequest.onCompleted.addListener((details: any) => this.completeAuthRequest(details), {
urls: ["http://*/*"],
});
this.webRequest.onErrorOccurred.addListener(
(details: any) => this.completeAuthRequest(details),
{
urls: ["http://*/*"],
}
);
}
2022-02-24 18:14:04 +01:00
// eslint-disable-next-line
2021-12-21 15:43:35 +01:00
private async resolveAuthCredentials(domain: string, success: Function, error: Function) {
if (await this.vaultTimeoutService.isLocked()) {
error();
return;
}
2021-12-21 15:43:35 +01:00
try {
const ciphers = await this.cipherService.getAllDecryptedForUrl(
domain,
null,
UriMatchType.Host
);
if (ciphers == null || ciphers.length !== 1) {
error();
return;
}
2021-12-21 15:43:35 +01:00
success({
authCredentials: {
username: ciphers[0].login.username,
password: ciphers[0].login.password,
},
});
} catch {
error();
}
2021-12-21 15:43:35 +01:00
}
2021-12-21 15:43:35 +01:00
private completeAuthRequest(details: any) {
const i = this.pendingAuthRequests.indexOf(details.requestId);
if (i > -1) {
this.pendingAuthRequests.splice(i, 1);
}
2021-12-21 15:43:35 +01:00
}
}