Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[PS-817] Add Generate Password Shortcut to MV3 #3575

Merged
merged 19 commits into from
Oct 18, 2022
Merged
Show file tree
Hide file tree
Changes from 17 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions apps/browser/src/background.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,25 @@
import MainBackground from "./background/main.background";
import { ClearClipboard } from "./listeners/clearClipboard";
import { onCommandListener } from "./listeners/onCommandListener";
import { onInstallListener } from "./listeners/onInstallListener";

type AlarmAction = (executionTime: Date, serviceCache: Record<string, unknown>) => void;

const AlarmActions: AlarmAction[] = [ClearClipboard.run];

const manifest = chrome.runtime.getManifest();

if (manifest.manifest_version === 3) {
chrome.commands.onCommand.addListener(onCommandListener);
chrome.runtime.onInstalled.addListener(onInstallListener);
chrome.alarms.onAlarm.addListener((_alarm) => {
const executionTime = new Date();
const serviceCache = {};

for (const alarmAction of AlarmActions) {
alarmAction(executionTime, serviceCache);
}
});
} else {
const bitwardenMain = ((window as any).bitwardenMain = new MainBackground());
bitwardenMain.bootstrap().then(() => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { CryptoService as AbstractCryptoService } from "@bitwarden/common/abstractions/crypto.service";
import { CryptoService } from "@bitwarden/common/services/crypto.service";

import { BrowserCryptoService } from "../../services/browserCrypto.service";

import {
cryptoFunctionServiceFactory,
Expand Down Expand Up @@ -32,7 +33,7 @@ export function cryptoServiceFactory(
"cryptoService",
opts,
async () =>
new CryptoService(
new BrowserCryptoService(
await cryptoFunctionServiceFactory(cache, opts),
await encryptServiceFactory(cache, opts),
await platformUtilsServiceFactory(cache, opts),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { PasswordGenerationService as AbstractPasswordGenerationService } from "@bitwarden/common/abstractions/passwordGeneration.service";
import { PasswordGenerationService } from "@bitwarden/common/services/passwordGeneration.service";

import { cryptoServiceFactory, CryptoServiceInitOptions } from "./crypto-service.factory";
import { CachedServices, factory, FactoryOptions } from "./factory-options";
import { policyServiceFactory, PolicyServiceInitOptions } from "./policy-service.factory";
import { stateServiceFactory, StateServiceInitOptions } from "./state-service.factory";

type PasswordGenerationServiceFactoryOptions = FactoryOptions;

export type PasswordGenerationServiceInitOptions = PasswordGenerationServiceFactoryOptions &
CryptoServiceInitOptions &
PolicyServiceInitOptions &
StateServiceInitOptions;

export function passwordGenerationServiceFactory(
cache: { passwordGenerationService?: AbstractPasswordGenerationService } & CachedServices,
opts: PasswordGenerationServiceInitOptions
): Promise<AbstractPasswordGenerationService> {
return factory(
cache,
"passwordGenerationService",
opts,
async () =>
new PasswordGenerationService(
await cryptoServiceFactory(cache, opts),
await policyServiceFactory(cache, opts),
await stateServiceFactory(cache, opts)
)
);
}
10 changes: 10 additions & 0 deletions apps/browser/src/browser/browserApi.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { TabMessage } from "../types/tab-messages";

export class BrowserApi {
static isWebExtensionsApi: boolean = typeof browser !== "undefined";
static isSafariApi: boolean =
Expand Down Expand Up @@ -80,6 +82,14 @@ export class BrowserApi {
});
}

static sendTabsMessage<T = never>(
tabId: number,
message: TabMessage,
responseCallback?: (response: T) => void
) {
chrome.tabs.sendMessage<TabMessage, T>(tabId, message, responseCallback);
}

justindbaur marked this conversation as resolved.
Show resolved Hide resolved
static async getPrivateModeWindows(): Promise<browser.windows.Window[]> {
return (await browser.windows.getAll()).filter((win) => win.incognito);
}
Expand Down
79 changes: 79 additions & 0 deletions apps/browser/src/clipboard/clearClipboard.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import { mock, MockProxy } from "jest-mock-extended";

import { BrowserApi } from "../browser/browserApi";
import { StateService } from "../services/abstractions/state.service";

import { ClearClipboard } from "./clearClipboard";
import { getClearClipboardTime, setClearClipboardTime } from "./clipboard-state";

jest.mock("./clipboard-state", () => {
return {
getClearClipboardTime: jest.fn(),
setClearClipboardTime: jest.fn(),
};
});

const getClearClipboardTimeMock = getClearClipboardTime as jest.Mock;
const setClearClipboardTimeMock = setClearClipboardTime as jest.Mock;

describe("clearClipboard", () => {
describe("run", () => {
let stateService: MockProxy<StateService>;
let serviceCache: Record<string, unknown>;

beforeEach(() => {
stateService = mock<StateService>();
serviceCache = {
stateService: stateService,
};
});

afterEach(() => {
jest.resetAllMocks();
});

it("has a clear time that is past execution time", async () => {
const executionTime = new Date(2022, 1, 1, 12);
const clearTime = new Date(2022, 1, 1, 12, 1);

jest.spyOn(BrowserApi, "getActiveTabs").mockResolvedValue([
{
id: 1,
},
] as any);

jest.spyOn(BrowserApi, "sendTabsMessage").mockReturnValue();

getClearClipboardTimeMock.mockResolvedValue(clearTime.getTime());

await ClearClipboard.run(executionTime, serviceCache);

expect(jest.spyOn(BrowserApi, "sendTabsMessage")).toHaveBeenCalledTimes(1);

expect(jest.spyOn(BrowserApi, "sendTabsMessage")).toHaveBeenCalledWith(1, {
command: "clearClipboard",
});
});

it("has a clear time before execution time", async () => {
const executionTime = new Date(2022, 1, 1, 12);
const clearTime = new Date(2022, 1, 1, 11);

setClearClipboardTimeMock.mockResolvedValue(clearTime.getTime());

await ClearClipboard.run(executionTime, serviceCache);

expect(jest.spyOn(BrowserApi, "getActiveTabs")).not.toHaveBeenCalled();
});

it("has an undefined clearTime", async () => {
const executionTime = new Date(2022, 1, 1);

getClearClipboardTimeMock.mockResolvedValue(undefined);

await ClearClipboard.run(executionTime, serviceCache);

expect(jest.spyOn(BrowserApi, "getActiveTabs")).not.toHaveBeenCalled();
});
});
});
50 changes: 50 additions & 0 deletions apps/browser/src/clipboard/clearClipboard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { StateFactory } from "@bitwarden/common/factories/stateFactory";
import { GlobalState } from "@bitwarden/common/models/domain/globalState";

import { stateServiceFactory } from "../background/service_factories/state-service.factory";
import { BrowserApi } from "../browser/browserApi";
import { Account } from "../models/account";

import { getClearClipboardTime } from "./clipboard-state";

export class ClearClipboard {
static async run(executionTime: Date, serviceCache: Record<string, unknown>) {
const stateFactory = new StateFactory(GlobalState, Account);
const stateService = await stateServiceFactory(serviceCache, {
cryptoFunctionServiceOptions: {
win: self,
},
encryptServiceOptions: {
logMacFailures: false,
},
logServiceOptions: {
isDev: false,
},
stateMigrationServiceOptions: {
stateFactory: stateFactory,
},
stateServiceOptions: {
stateFactory: stateFactory,
},
});

const clearClipboardTime = await getClearClipboardTime(stateService);

if (!clearClipboardTime) {
return;
}

if (clearClipboardTime < executionTime.getTime()) {
return;
}

const activeTabs = await BrowserApi.getActiveTabs();
if (!activeTabs || activeTabs.length === 0) {
return;
}

BrowserApi.sendTabsMessage(activeTabs[0].id, {
command: "clearClipboard",
});
}
}
10 changes: 10 additions & 0 deletions apps/browser/src/clipboard/clipboard-state.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { StateService } from "../services/abstractions/state.service";

const clearClipboardStorageKey = "clearClipboardTime";
export const getClearClipboardTime = async (stateService: StateService) => {
return await stateService.getFromSessionMemory<number>(clearClipboardStorageKey);
};

export const setClearClipboardTime = async (stateService: StateService, time: number) => {
await stateService.setInSessionMemory(clearClipboardStorageKey, time);
};
17 changes: 17 additions & 0 deletions apps/browser/src/clipboard/copy-to-clipboard-command.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { BrowserApi } from "../browser/browserApi";

/**
* Copies text to the clipboard in a MV3 safe way.
* @param tab - The tab that the text will be sent to so that it can be copied to the users clipboard this needs to be an active tab or the DOM won't be able to be used to do the action. The tab sent in here should be from a user started action or queried for active tabs.
* @param text - The text that you want added to the users clipboard.
*/
export const copyToClipboard = async (tab: chrome.tabs.Tab, text: string) => {
if (tab.id == null) {
throw new Error("Cannot copy text to clipboard with a tab that does not have an id.");
}

BrowserApi.sendTabsMessage(tab.id, {
command: "copyText",
text: text,
});
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import { mock, MockProxy } from "jest-mock-extended";

import { PasswordGenerationService } from "@bitwarden/common/abstractions/passwordGeneration.service";

import { BrowserApi } from "../browser/browserApi";
import { StateService } from "../services/abstractions/state.service";

import { setClearClipboardTime } from "./clipboard-state";
import { GeneratePasswordToClipboardCommand } from "./generate-password-to-clipboard-command";

jest.mock("./clipboard-state", () => {
return {
getClearClipboardTime: jest.fn(),
setClearClipboardTime: jest.fn(),
};
});

const setClearClipboardTimeMock = setClearClipboardTime as jest.Mock;

describe("GeneratePasswordToClipboardCommand", () => {
let passwordGenerationService: MockProxy<PasswordGenerationService>;
let stateService: MockProxy<StateService>;

let sut: GeneratePasswordToClipboardCommand;

beforeEach(() => {
passwordGenerationService = mock<PasswordGenerationService>();
stateService = mock<StateService>();

passwordGenerationService.getOptions.mockResolvedValue([{ length: 8 }, {} as any]);

passwordGenerationService.generatePassword.mockResolvedValue("PASSWORD");

jest.spyOn(BrowserApi, "sendTabsMessage").mockReturnValue();

sut = new GeneratePasswordToClipboardCommand(passwordGenerationService, stateService);
});

afterEach(() => {
jest.resetAllMocks();
});

describe("generatePasswordToClipboard", () => {
it("has clear clipboard value", async () => {
stateService.getClearClipboard.mockResolvedValue(5 * 60); // 5 minutes

await sut.generatePasswordToClipboard({ id: 1 } as any);

expect(jest.spyOn(BrowserApi, "sendTabsMessage")).toHaveBeenCalledTimes(1);

expect(jest.spyOn(BrowserApi, "sendTabsMessage")).toHaveBeenCalledWith(1, {
command: "copyText",
text: "PASSWORD",
});

expect(setClearClipboardTimeMock).toHaveBeenCalledTimes(1);

expect(setClearClipboardTimeMock).toHaveBeenCalledWith(stateService, expect.any(Number));
});

it("does not have clear clipboard value", async () => {
stateService.getClearClipboard.mockResolvedValue(null);

await sut.generatePasswordToClipboard({ id: 1 } as any);

expect(jest.spyOn(BrowserApi, "sendTabsMessage")).toHaveBeenCalledTimes(1);

expect(jest.spyOn(BrowserApi, "sendTabsMessage")).toHaveBeenCalledWith(1, {
command: "copyText",
text: "PASSWORD",
});

expect(setClearClipboardTimeMock).not.toHaveBeenCalled();
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { PasswordGenerationService } from "@bitwarden/common/abstractions/passwordGeneration.service";

import { StateService } from "../services/abstractions/state.service";

import { setClearClipboardTime } from "./clipboard-state";
import { copyToClipboard } from "./copy-to-clipboard-command";

export class GeneratePasswordToClipboardCommand {
constructor(
private passwordGenerationService: PasswordGenerationService,
private stateService: StateService
) {}

async generatePasswordToClipboard(tab: chrome.tabs.Tab) {
const [options] = await this.passwordGenerationService.getOptions();
const password = await this.passwordGenerationService.generatePassword(options);

copyToClipboard(tab, password);

const clearClipboard = await this.stateService.getClearClipboard();

if (clearClipboard != null) {
await setClearClipboardTime(this.stateService, Date.now() + clearClipboard * 1000);
}
}
}
3 changes: 3 additions & 0 deletions apps/browser/src/clipboard/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export * from "./clearClipboard";
export * from "./copy-to-clipboard-command";
export * from "./generate-password-to-clipboard-command";
23 changes: 23 additions & 0 deletions apps/browser/src/content/misc-utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { TabMessage } from "../types/tab-messages";

async function copyText(text: string) {
await window.navigator.clipboard.writeText(text);
}

async function onMessageListener(
msg: TabMessage,
sender: chrome.runtime.MessageSender,
responseCallback: (response: unknown) => void
) {
switch (msg.command) {
case "copyText":
justindbaur marked this conversation as resolved.
Show resolved Hide resolved
await copyText(msg.text);
break;
case "clearClipboard":
await copyText("\u0000");
break;
default:
}
}

chrome.runtime.onMessage.addListener(onMessageListener);
Loading