mirror of
https://github.com/bitwarden/clients.git
synced 2026-11-16 07:03:29 +00:00
Merge remote-tracking branch 'origin/main' into dirt/pm-44037/mar-access-reports
This commit is contained in:
1
.github/CODEOWNERS
vendored
1
.github/CODEOWNERS
vendored
@@ -103,6 +103,7 @@ libs/common/src/provider @bitwarden/team-provider-business-unit-portals-dev
|
||||
|
||||
## Secrets Manager team files ##
|
||||
bitwarden_license/bit-web/src/app/secrets-manager @bitwarden/team-secrets-manager-dev
|
||||
bitwarden_license/bit-sm @bitwarden/team-secrets-manager-dev
|
||||
|
||||
## Platform team files ##
|
||||
apps/browser/src/platform @bitwarden/team-platform-dev
|
||||
|
||||
8
.github/renovate.json5
vendored
8
.github/renovate.json5
vendored
@@ -52,6 +52,14 @@
|
||||
depNameTemplate: "electron",
|
||||
datasourceTemplate: "npm",
|
||||
},
|
||||
{
|
||||
// Keep electronVersion in electron-builder.beta.json in sync with the electron package.
|
||||
customType: "regex",
|
||||
fileMatch: ["apps/desktop/electron-builder.beta\\.json$"],
|
||||
matchStrings: ['"electronVersion":\\s*"(?<currentValue>[\\d.]+)"'],
|
||||
depNameTemplate: "electron",
|
||||
datasourceTemplate: "npm",
|
||||
},
|
||||
],
|
||||
packageRules: [
|
||||
// ==================== Repo-Wide Update Behavior Rules ====================
|
||||
|
||||
15
.github/workflows/sdlc-sdk-update-evaluate.yml
vendored
15
.github/workflows/sdlc-sdk-update-evaluate.yml
vendored
@@ -23,8 +23,9 @@ jobs:
|
||||
pull-requests: write # sticky comment
|
||||
|
||||
env:
|
||||
_BOT_NAME: "bw-ghapp[bot]"
|
||||
_BOT_EMAIL: "178206702+bw-ghapp[bot]@users.noreply.github.com"
|
||||
_AGENT_ID: "209825114"
|
||||
_AGENT_NAME: "claude[bot]"
|
||||
|
||||
steps:
|
||||
- name: Skip if this bump was already evaluated
|
||||
@@ -114,12 +115,14 @@ jobs:
|
||||
if: steps.gate.outputs.skip == 'false'
|
||||
run: npm ci
|
||||
|
||||
# Any commit the agent makes has to be bot-authored or the next bump run's author guard fails.
|
||||
# Agent commits use their own identity so sdk-update.yml's author guard freezes the branch until
|
||||
# the fix is reviewed and merged, the same way a human fix commit does. claude-code-action sets
|
||||
# the same identity from bot_id/bot_name; this covers it continuing past a failed git setup.
|
||||
- name: Configure git identity
|
||||
if: steps.gate.outputs.skip == 'false'
|
||||
run: |
|
||||
git config user.name "$_BOT_NAME"
|
||||
git config user.email "$_BOT_EMAIL"
|
||||
git config user.name "$_AGENT_NAME"
|
||||
git config user.email "${_AGENT_ID}+${_AGENT_NAME}@users.noreply.github.com"
|
||||
|
||||
- name: Run the baseline type check
|
||||
id: baseline
|
||||
@@ -150,8 +153,8 @@ jobs:
|
||||
with:
|
||||
anthropic_api_key: ${{ steps.get-kv-secrets.outputs.ANTHROPIC-RESPONSE-API-KEY }}
|
||||
allowed_bots: "bw-ghapp"
|
||||
bot_id: "178206702"
|
||||
bot_name: "bw-ghapp[bot]"
|
||||
bot_id: ${{ env._AGENT_ID }}
|
||||
bot_name: ${{ env._AGENT_NAME }}
|
||||
track_progress: true
|
||||
use_sticky_comment: true
|
||||
plugin_marketplaces: "https://github.com/bitwarden/ai-plugins.git"
|
||||
|
||||
@@ -36,6 +36,7 @@ const config: StorybookConfig = {
|
||||
"../bitwarden_license/bit-web/src/**/*.stories.@(js|jsx|ts|tsx)",
|
||||
"../bitwarden_license/bit-browser/src/**/*.mdx",
|
||||
"../bitwarden_license/bit-browser/src/**/*.stories.@(js|jsx|ts|tsx)",
|
||||
"../libs/angular/src/**/*.mdx",
|
||||
"../libs/angular/src/**/*.stories.@(js|jsx|ts|tsx)",
|
||||
],
|
||||
addons: [
|
||||
|
||||
@@ -6731,9 +6731,6 @@
|
||||
"copyAddress": {
|
||||
"message": "Copy address"
|
||||
},
|
||||
"myItems": {
|
||||
"message": "My Items"
|
||||
},
|
||||
"myItemsV2": {
|
||||
"message": "My items"
|
||||
},
|
||||
@@ -8470,8 +8467,8 @@
|
||||
"message": "This Send will automatically expire at the set deletion date",
|
||||
"description": "'Send' is a noun and the name of a feature called 'Bitwarden Send'. It should not be translated."
|
||||
},
|
||||
"errorImportingMyItemsMultiCollection": {
|
||||
"message": "You cannot import items into My Items that are part of multiple collections"
|
||||
"errorImportingMyItemsMultiCollectionV2": {
|
||||
"message": "You cannot import items into My items that are part of multiple collections"
|
||||
},
|
||||
"cannotSaveItemNoConfirmedOrgs": {
|
||||
"message": "Unable to save item. You must be confirmed to the organization to save items."
|
||||
|
||||
@@ -131,6 +131,9 @@ describe("NotificationBackground", () => {
|
||||
accountService.activeAccount$ = activeAccountSubject;
|
||||
const storedCipherPolicy = new DefaultFillCipherPolicy(cipherService);
|
||||
fillCipherPolicy.ciphers.mockImplementation((...args) => storedCipherPolicy.ciphers(...args));
|
||||
fillCipherPolicy.ciphersForIds.mockImplementation((...args) =>
|
||||
storedCipherPolicy.ciphersForIds(...args),
|
||||
);
|
||||
fillCipherPolicy.ciphersForUrl.mockImplementation((...args) =>
|
||||
storedCipherPolicy.ciphersForUrl(...args),
|
||||
);
|
||||
|
||||
@@ -290,18 +290,20 @@ export default class NotificationBackground {
|
||||
const {
|
||||
data: { cipherIds },
|
||||
} = cipherQueueMessage;
|
||||
const cipherViews = await this.fillCipherPolicy.ciphers(activeUserId, CipherUse.SavePrompt);
|
||||
return cipherViews
|
||||
.filter((cipher) => cipherIds.includes(cipher.id))
|
||||
.map((cipherView) => {
|
||||
const organizationType = getOrganizationType(cipherView.organizationId);
|
||||
return this.convertToNotificationCipherData(
|
||||
cipherView,
|
||||
iconsServerUrl,
|
||||
showFavicons,
|
||||
organizationType,
|
||||
);
|
||||
});
|
||||
const cipherViews = await this.fillCipherPolicy.ciphersForIds(
|
||||
activeUserId,
|
||||
cipherIds,
|
||||
CipherUse.SavePrompt,
|
||||
);
|
||||
return cipherViews.map((cipherView) => {
|
||||
const organizationType = getOrganizationType(cipherView.organizationId);
|
||||
return this.convertToNotificationCipherData(
|
||||
cipherView,
|
||||
iconsServerUrl,
|
||||
showFavicons,
|
||||
organizationType,
|
||||
);
|
||||
});
|
||||
} else {
|
||||
cipherView = this.convertAddLoginQueueMessageToCipherView(cipherQueueMessage);
|
||||
}
|
||||
|
||||
@@ -60,6 +60,12 @@ describe("ContextMenuClickedHandler", () => {
|
||||
};
|
||||
};
|
||||
|
||||
/** Serves `ciphers` to lookups by id, as the vault would. */
|
||||
const serveCiphers = (policy: MockProxy<FillCipherPolicy>, ciphers: CipherView[]) =>
|
||||
policy.ciphersForIds.mockImplementation(async (_userId, ids) =>
|
||||
ciphers.filter((cipher) => ids.includes(cipher.id)),
|
||||
);
|
||||
|
||||
const createCipher = (data?: {
|
||||
id?: CipherView["id"];
|
||||
username?: CipherView["login"]["username"];
|
||||
@@ -179,7 +185,7 @@ describe("ContextMenuClickedHandler", () => {
|
||||
extra: () => expect(totpService.getCode$).not.toHaveBeenCalled(),
|
||||
},
|
||||
])("breaks silently when cipher is missing for $label", async ({ parentId, extra }) => {
|
||||
fillCipherPolicy.ciphers.mockResolvedValue([]);
|
||||
serveCiphers(fillCipherPolicy, []);
|
||||
|
||||
await expect(runWithUrl(createData(`${parentId}_1`, parentId))).resolves.toBeUndefined();
|
||||
|
||||
@@ -209,7 +215,7 @@ describe("ContextMenuClickedHandler", () => {
|
||||
])("breaks silently when $label property is missing", async ({ parentId, unset, isTotp }) => {
|
||||
const cipher = createCipher();
|
||||
unset(cipher);
|
||||
fillCipherPolicy.ciphers.mockResolvedValue([cipher]);
|
||||
serveCiphers(fillCipherPolicy, [cipher]);
|
||||
|
||||
await expect(runWithUrl(createData(`${parentId}_1`, parentId))).resolves.toBeUndefined();
|
||||
|
||||
@@ -232,7 +238,7 @@ describe("ContextMenuClickedHandler", () => {
|
||||
|
||||
it("attempts to autofill the correct cipher", async () => {
|
||||
const cipher = createCipher();
|
||||
fillCipherPolicy.ciphers.mockResolvedValue([cipher]);
|
||||
serveCiphers(fillCipherPolicy, [cipher]);
|
||||
|
||||
await sut.run(createData(`${AUTOFILL_ID}_1`, AUTOFILL_ID), { id: 5 } as any);
|
||||
|
||||
@@ -242,15 +248,19 @@ describe("ContextMenuClickedHandler", () => {
|
||||
});
|
||||
|
||||
it("looks up the cipher the user picked by id as a user fill", async () => {
|
||||
fillCipherPolicy.ciphers.mockResolvedValue([createCipher()]);
|
||||
serveCiphers(fillCipherPolicy, [createCipher()]);
|
||||
|
||||
await sut.run(createData(`${AUTOFILL_ID}_1`, AUTOFILL_ID), { id: 5 } as any);
|
||||
|
||||
expect(fillCipherPolicy.ciphers).toHaveBeenCalledWith(mockUserId, CipherUse.UserFill);
|
||||
expect(fillCipherPolicy.ciphersForIds).toHaveBeenCalledWith(
|
||||
mockUserId,
|
||||
["1"],
|
||||
CipherUse.UserFill,
|
||||
);
|
||||
});
|
||||
|
||||
it("copies username to clipboard", async () => {
|
||||
fillCipherPolicy.ciphers.mockResolvedValue([createCipher({ username: "TEST_USERNAME" })]);
|
||||
serveCiphers(fillCipherPolicy, [createCipher({ username: "TEST_USERNAME" })]);
|
||||
|
||||
await sut.run(createData(`${COPY_USERNAME_ID}_1`, COPY_USERNAME_ID), {
|
||||
url: "https://test.com",
|
||||
@@ -265,7 +275,7 @@ describe("ContextMenuClickedHandler", () => {
|
||||
});
|
||||
|
||||
it("copies password to clipboard", async () => {
|
||||
fillCipherPolicy.ciphers.mockResolvedValue([createCipher({ password: "TEST_PASSWORD" })]);
|
||||
serveCiphers(fillCipherPolicy, [createCipher({ password: "TEST_PASSWORD" })]);
|
||||
|
||||
await sut.run(createData(`${COPY_PASSWORD_ID}_1`, COPY_PASSWORD_ID), {
|
||||
url: "https://test.com",
|
||||
@@ -280,7 +290,7 @@ describe("ContextMenuClickedHandler", () => {
|
||||
});
|
||||
|
||||
it("copies totp code to clipboard", async () => {
|
||||
fillCipherPolicy.ciphers.mockResolvedValue([createCipher({ totp: "TEST_TOTP_SEED" })]);
|
||||
serveCiphers(fillCipherPolicy, [createCipher({ totp: "TEST_TOTP_SEED" })]);
|
||||
|
||||
jest.spyOn(totpService, "getCode$").mockImplementation((seed: string) => {
|
||||
if (seed === "TEST_TOTP_SEED") {
|
||||
|
||||
@@ -211,8 +211,11 @@ export class ContextMenuClickedHandler {
|
||||
|
||||
cipher = ciphers[0];
|
||||
} else {
|
||||
const ciphers = await this.fillCipherPolicy.ciphers(activeUserId, CipherUse.UserFill);
|
||||
cipher = ciphers.find(({ id }) => id === menuItemId);
|
||||
[cipher] = await this.fillCipherPolicy.ciphersForIds(
|
||||
activeUserId,
|
||||
[menuItemId],
|
||||
CipherUse.UserFill,
|
||||
);
|
||||
}
|
||||
|
||||
if (!cipher && !isCreateCipherAction) {
|
||||
|
||||
@@ -8,6 +8,7 @@ import { DomElementVisibilityService } from "../services/abstractions/dom-elemen
|
||||
import { DomQueryService } from "../services/abstractions/dom-query.service";
|
||||
import { CollectAutofillContentService } from "../services/collect-autofill-content.service";
|
||||
import InsertAutofillContentService from "../services/insert-autofill-content.service";
|
||||
import { DefaultRuleQualificationService } from "../services/rule-qualification.service";
|
||||
import { AutofillTriageResponse } from "../types/autofill-triage";
|
||||
import { sendExtensionMessage } from "../utils";
|
||||
import { EventSecurity } from "../utils/event-security";
|
||||
@@ -62,6 +63,16 @@ class AutofillInit implements AutofillInitInterface {
|
||||
domQueryService,
|
||||
this.autofillOverlayContentService,
|
||||
);
|
||||
// Setter injection breaks the circular dependency. The rule qualification
|
||||
// service needs the collect service for its heuristic bypass. The collect
|
||||
// service needs the rule qualification service to qualify matched rules.
|
||||
this.collectAutofillContentService.setRuleQualificationService(
|
||||
new DefaultRuleQualificationService(
|
||||
this.collectAutofillContentService,
|
||||
domQueryService,
|
||||
domElementVisibilityService,
|
||||
),
|
||||
);
|
||||
this.insertAutofillContentService = new InsertAutofillContentService(
|
||||
domElementVisibilityService,
|
||||
this.collectAutofillContentService,
|
||||
|
||||
@@ -1,27 +1,63 @@
|
||||
import { serialize } from "v8";
|
||||
|
||||
import { WebauthnUtils } from "./webauthn-utils";
|
||||
|
||||
// jsdom does not expose structuredClone. Node's v8.serialize uses the same
|
||||
// structured-clone algorithm, so it throws DataCloneError on the same inputs.
|
||||
const assertStructuredCloneable = (value: unknown) => serialize(value);
|
||||
|
||||
const challenge = new Uint8Array([1, 2, 3, 4]).buffer;
|
||||
const credentialId = new Uint8Array([9, 9, 9]).buffer;
|
||||
const userId = new Uint8Array([5, 5, 5]).buffer;
|
||||
|
||||
// Reactive frameworks wrap caller inputs in a Proxy, which window.postMessage cannot clone.
|
||||
describe("WebauthnUtils", () => {
|
||||
describe("mapCredentialRequestOptions", () => {
|
||||
it("copies credential transports into a plain array", () => {
|
||||
const transports = new Proxy(["usb"] as AuthenticatorTransport[], {});
|
||||
it("produces a structured-cloneable result when transports is a Proxy", () => {
|
||||
const transportsProxy = new Proxy(["usb", "nfc"], {}) as AuthenticatorTransport[];
|
||||
|
||||
const options: CredentialRequestOptions = {
|
||||
publicKey: {
|
||||
challenge: new Uint8Array([1, 2, 3]),
|
||||
challenge,
|
||||
allowCredentials: [
|
||||
{
|
||||
id: new Uint8Array([4, 5, 6]),
|
||||
id: credentialId,
|
||||
type: "public-key",
|
||||
transports,
|
||||
transports: transportsProxy,
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
const result = WebauthnUtils.mapCredentialRequestOptions(options, true);
|
||||
const [allowedCredential] = result.allowedCredentials;
|
||||
const mapped = WebauthnUtils.mapCredentialRequestOptions(options, false);
|
||||
|
||||
expect(allowedCredential?.transports).toEqual(["usb"]);
|
||||
expect(allowedCredential?.transports).not.toBe(transports);
|
||||
expect(() => assertStructuredCloneable(mapped)).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("mapCredentialCreationOptions", () => {
|
||||
it("produces a structured-cloneable result when excludeCredentials transports is a Proxy", () => {
|
||||
const transportsProxy = new Proxy(["usb"], {}) as AuthenticatorTransport[];
|
||||
|
||||
const options: CredentialCreationOptions = {
|
||||
publicKey: {
|
||||
challenge,
|
||||
rp: { id: "example.com", name: "Example" },
|
||||
user: { id: userId, name: "jdoe", displayName: "J. Doe" },
|
||||
pubKeyCredParams: [{ type: "public-key", alg: -7 }],
|
||||
excludeCredentials: [
|
||||
{
|
||||
id: credentialId,
|
||||
type: "public-key",
|
||||
transports: transportsProxy,
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
const mapped = WebauthnUtils.mapCredentialCreationOptions(options, false);
|
||||
|
||||
expect(() => assertStructuredCloneable(mapped)).not.toThrow();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -32,7 +32,7 @@ export class WebauthnUtils {
|
||||
),
|
||||
excludeCredentials: keyOptions.excludeCredentials?.map((credential) => ({
|
||||
id: Fido2Utils.arrayToString(Fido2Utils.bufferSourceToUint8Array(credential.id)),
|
||||
transports: credential.transports,
|
||||
transports: Array.from(credential.transports ?? []),
|
||||
type: credential.type,
|
||||
})),
|
||||
extensions: {
|
||||
|
||||
@@ -4,6 +4,8 @@ import AutofillForm from "../../models/autofill-form";
|
||||
import AutofillPageDetails from "../../models/autofill-page-details";
|
||||
import { ElementWithOpId, FormFieldElement } from "../../types";
|
||||
|
||||
import { InScopeFormsDetection, RuleQualificationService } from "./rule-qualification.service";
|
||||
|
||||
type AutofillFormElements = Map<ElementWithOpId<HTMLFormElement>, AutofillForm>;
|
||||
|
||||
type AutofillFieldElements = Map<ElementWithOpId<FormFieldElement>, AutofillField>;
|
||||
@@ -24,6 +26,26 @@ interface CollectAutofillContentService extends AutofillMonitor {
|
||||
targetedFields: { selector: string; fieldType: string }[],
|
||||
): Promise<void>;
|
||||
clearCachedTargetingRules(): void;
|
||||
/**
|
||||
* Runs the heuristic collection path after clearing the field caches so the
|
||||
* pass starts fresh. Called by `RuleQualificationService` on the miss path.
|
||||
* When `cachedInScopeForms.detectedFields` is populated, the bypass reuses
|
||||
* those detections rather than scanning the same forms again.
|
||||
*/
|
||||
collectHeuristicPageDetailsBypass(
|
||||
cachedInScopeForms?: InScopeFormsDetection,
|
||||
): Promise<AutofillPageDetails>;
|
||||
/**
|
||||
* Setter wiring to break the circular dependency between this service and
|
||||
* the rule qualification service. Called once at DI setup.
|
||||
*/
|
||||
setRuleQualificationService(ruleQualificationService: RuleQualificationService): void;
|
||||
/**
|
||||
* Returns whether the element is a form field the heuristic collection pass
|
||||
* would consider fillable. Exposed so the rule qualification service can
|
||||
* apply the same filter when checking in-scope extras.
|
||||
*/
|
||||
isElementFormFieldElement(element: Element): boolean;
|
||||
}
|
||||
|
||||
export {
|
||||
|
||||
@@ -35,6 +35,8 @@ export abstract class FillCipherPolicy {
|
||||
/** Emits when a lookup result can change. A cached result must recompute. */
|
||||
abstract changed$(userId: UserId): Observable<void>;
|
||||
abstract ciphers(userId: UserId, use: CipherUse): Promise<CipherView[]>;
|
||||
/** The ciphers among `ids`. Decrypts only those, not the whole vault. */
|
||||
abstract ciphersForIds(userId: UserId, ids: string[], use: CipherUse): Promise<CipherView[]>;
|
||||
abstract ciphersForUrl(
|
||||
url: string,
|
||||
userId: UserId,
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { FormContent } from "@bitwarden/common/autofill/types";
|
||||
|
||||
import { FillAssistMissReason } from "../../background/fill-assist-event-receiver";
|
||||
import AutofillPageDetails from "../../models/autofill-page-details";
|
||||
import { FormFieldElement } from "../../types";
|
||||
|
||||
/**
|
||||
* Forms that hold at least one of a targeting rule's declared selectors.
|
||||
* Half 1 (`checkStructural`) populates `forms`. Half 2 (`checkInScopeExtras`)
|
||||
* runs heuristic field detection within those forms and stores the result in
|
||||
* `detectedFields` so the miss path can reuse it rather than detecting fields
|
||||
* in those forms again.
|
||||
*/
|
||||
export type InScopeFormsDetection = {
|
||||
forms: Set<HTMLFormElement>;
|
||||
detectedFields?: Map<HTMLFormElement, FormFieldElement[]>;
|
||||
};
|
||||
|
||||
export type QualificationResult =
|
||||
| { kind: "proceedTargeted" }
|
||||
| {
|
||||
kind: "fallback";
|
||||
missReason: FillAssistMissReason;
|
||||
pageDetails: AutofillPageDetails;
|
||||
};
|
||||
|
||||
/**
|
||||
* Decides whether a matched targeting rule can fill the current page. A rule
|
||||
* qualifies only when both halves pass:
|
||||
* - Half 1 (structural): every declared selector resolves to an eligible field.
|
||||
* - Half 2 (in-scope extras): no undeclared field exists in any form the rule
|
||||
* declares at least one selector in.
|
||||
* Either half failing triggers the miss path: heuristic collection with the
|
||||
* full security-check suite re-engaged. The field caches are cleared before
|
||||
* heuristic collection runs so the heuristic pass starts fresh.
|
||||
*/
|
||||
export interface RuleQualificationService {
|
||||
qualifyRule(url: string, matchedRule: FormContent[]): Promise<QualificationResult>;
|
||||
}
|
||||
@@ -459,6 +459,186 @@ describe("CollectAutofillContentService", () => {
|
||||
expect(collectAutofillContentService["buildAutofillFieldsData"]).toHaveBeenCalled();
|
||||
expect(collectAutofillContentService["noFieldsFound"]).toBe(true);
|
||||
});
|
||||
|
||||
describe("rule qualification branch", () => {
|
||||
const sampleRule = [{ category: "login", fields: {} }] as any;
|
||||
const fallbackPageDetails = { foo: "fallback" } as any;
|
||||
const targetedPageDetails = { foo: "targeted" } as any;
|
||||
let ruleQualificationService: {
|
||||
qualifyRule: jest.Mock;
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
ruleQualificationService = { qualifyRule: jest.fn() };
|
||||
collectAutofillContentService.setRuleQualificationService(ruleQualificationService as any);
|
||||
jest
|
||||
.spyOn(collectAutofillContentService as any, "getTargetedPageDetails")
|
||||
.mockResolvedValue(targetedPageDetails);
|
||||
});
|
||||
|
||||
it("does not run qualification when ruleFailureFallback is unset", async () => {
|
||||
collectAutofillContentService["pageTargetingRules"] = sampleRule;
|
||||
collectAutofillContentService["ruleFailureFallback"] = undefined;
|
||||
|
||||
await collectAutofillContentService.getPageDetails();
|
||||
|
||||
expect(ruleQualificationService.qualifyRule).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("runs qualification and returns targeted page details on proceedTargeted", async () => {
|
||||
collectAutofillContentService["pageTargetingRules"] = sampleRule;
|
||||
collectAutofillContentService["ruleFailureFallback"] = true;
|
||||
ruleQualificationService.qualifyRule.mockResolvedValue({ kind: "proceedTargeted" });
|
||||
|
||||
const result = await collectAutofillContentService.getPageDetails();
|
||||
|
||||
expect(ruleQualificationService.qualifyRule).toHaveBeenCalledWith(
|
||||
location.href,
|
||||
sampleRule,
|
||||
);
|
||||
expect(collectAutofillContentService["getTargetedPageDetails"]).toHaveBeenCalledWith(
|
||||
sampleRule,
|
||||
);
|
||||
expect(result).toBe(targetedPageDetails);
|
||||
});
|
||||
|
||||
it("pins pageTargetingRules to null and returns the fallback page details on miss", async () => {
|
||||
collectAutofillContentService["pageTargetingRules"] = sampleRule;
|
||||
collectAutofillContentService["ruleFailureFallback"] = true;
|
||||
ruleQualificationService.qualifyRule.mockResolvedValue({
|
||||
kind: "fallback",
|
||||
missReason: "structural",
|
||||
pageDetails: fallbackPageDetails,
|
||||
});
|
||||
|
||||
const result = await collectAutofillContentService.getPageDetails();
|
||||
|
||||
expect(result).toBe(fallbackPageDetails);
|
||||
expect(collectAutofillContentService["pageTargetingRules"]).toBeNull();
|
||||
});
|
||||
|
||||
it("reuses the cached qualification result on subsequent calls", async () => {
|
||||
collectAutofillContentService["pageTargetingRules"] = sampleRule;
|
||||
collectAutofillContentService["ruleFailureFallback"] = true;
|
||||
ruleQualificationService.qualifyRule.mockResolvedValue({ kind: "proceedTargeted" });
|
||||
|
||||
await collectAutofillContentService.getPageDetails();
|
||||
await collectAutofillContentService.getPageDetails();
|
||||
|
||||
expect(ruleQualificationService.qualifyRule).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("falls through to the heuristic path on subsequent calls after a miss", async () => {
|
||||
collectAutofillContentService["pageTargetingRules"] = sampleRule;
|
||||
collectAutofillContentService["ruleFailureFallback"] = true;
|
||||
ruleQualificationService.qualifyRule.mockResolvedValue({
|
||||
kind: "fallback",
|
||||
missReason: "structural",
|
||||
pageDetails: fallbackPageDetails,
|
||||
});
|
||||
|
||||
await collectAutofillContentService.getPageDetails();
|
||||
// pageTargetingRules is now null, so the second call should not re-enter the branch
|
||||
await collectAutofillContentService.getPageDetails();
|
||||
|
||||
expect(ruleQualificationService.qualifyRule).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("falls through to the targeted-fill path when the qualification service has not been wired", async () => {
|
||||
// Fresh instance without setRuleQualificationService call
|
||||
const freshService = new CollectAutofillContentService(
|
||||
mock<DomElementVisibilityService>(),
|
||||
mock<DomQueryService>(),
|
||||
mock<AutofillOverlayContentService>(),
|
||||
);
|
||||
jest.spyOn(freshService as any, "sendExtensionMessage").mockResolvedValue({ result: null });
|
||||
const targetedSpy = jest
|
||||
.spyOn(freshService as any, "getTargetedPageDetails")
|
||||
.mockResolvedValue(targetedPageDetails);
|
||||
freshService["pageTargetingRules"] = sampleRule;
|
||||
freshService["ruleFailureFallback"] = true;
|
||||
|
||||
const result = await freshService.getPageDetails();
|
||||
|
||||
expect(targetedSpy).toHaveBeenCalledWith(sampleRule);
|
||||
expect(result).toBe(targetedPageDetails);
|
||||
});
|
||||
});
|
||||
|
||||
describe("clearCachedTargetingRules", () => {
|
||||
it("resets all three URL-scoped caches", () => {
|
||||
collectAutofillContentService["pageTargetingRules"] = [] as any;
|
||||
collectAutofillContentService["ruleFailureFallback"] = true;
|
||||
collectAutofillContentService["ruleQualificationResult"] = {
|
||||
kind: "proceedTargeted",
|
||||
} as any;
|
||||
|
||||
collectAutofillContentService.clearCachedTargetingRules();
|
||||
|
||||
expect(collectAutofillContentService["pageTargetingRules"]).toBeUndefined();
|
||||
expect(collectAutofillContentService["ruleFailureFallback"]).toBeUndefined();
|
||||
expect(collectAutofillContentService["ruleQualificationResult"]).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("collectHeuristicPageDetailsBypass", () => {
|
||||
it("clears pageTargetingRules, autofillFieldElements, and autofillFieldsByOpid before running heuristic collection", async () => {
|
||||
const dummyField = document.createElement("input") as any;
|
||||
collectAutofillContentService["pageTargetingRules"] = [
|
||||
{ category: "login", fields: {} },
|
||||
] as any;
|
||||
collectAutofillContentService["autofillFieldElements"].set(dummyField, {} as any);
|
||||
collectAutofillContentService["autofillFieldsByOpid"].set("__opid__0", dummyField);
|
||||
|
||||
const runHeuristicSpy = jest
|
||||
.spyOn(collectAutofillContentService as any, "runHeuristicCollection")
|
||||
.mockImplementation(() => {
|
||||
expect(collectAutofillContentService["pageTargetingRules"]).toBeNull();
|
||||
expect(collectAutofillContentService["autofillFieldElements"].size).toBe(0);
|
||||
expect(collectAutofillContentService["autofillFieldsByOpid"].size).toBe(0);
|
||||
return Promise.resolve({} as any);
|
||||
});
|
||||
|
||||
await collectAutofillContentService.collectHeuristicPageDetailsBypass();
|
||||
|
||||
expect(runHeuristicSpy).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("envelope destructure", () => {
|
||||
it("populates pageTargetingRules and ruleFailureFallback from the envelope", async () => {
|
||||
const rules = [{ category: "login", fields: {} }] as any;
|
||||
jest
|
||||
.spyOn(collectAutofillContentService as any, "sendExtensionMessage")
|
||||
.mockImplementation((command: string) =>
|
||||
command === "getUrlAutofillTargetingRules"
|
||||
? Promise.resolve({
|
||||
result: { targetingRules: rules, ruleFailureFallback: true },
|
||||
})
|
||||
: Promise.resolve(undefined),
|
||||
);
|
||||
|
||||
await collectAutofillContentService.getPageDetails();
|
||||
|
||||
expect(collectAutofillContentService["pageTargetingRules"]).toBe(rules);
|
||||
expect(collectAutofillContentService["ruleFailureFallback"]).toBe(true);
|
||||
});
|
||||
|
||||
it("defaults to null rules and false fallback when the message returns no result", async () => {
|
||||
jest
|
||||
.spyOn(collectAutofillContentService as any, "sendExtensionMessage")
|
||||
.mockImplementation((command: string) =>
|
||||
command === "getUrlAutofillTargetingRules"
|
||||
? Promise.resolve({ result: null })
|
||||
: Promise.resolve(undefined),
|
||||
);
|
||||
|
||||
await collectAutofillContentService.getPageDetails();
|
||||
|
||||
expect(collectAutofillContentService["pageTargetingRules"]).toBeNull();
|
||||
expect(collectAutofillContentService["ruleFailureFallback"]).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("applyExternalTargetedFields", () => {
|
||||
@@ -513,13 +693,16 @@ describe("CollectAutofillContentService", () => {
|
||||
.mockImplementation((command: string) => {
|
||||
if (command === "getUrlAutofillTargetingRules") {
|
||||
return Promise.resolve({
|
||||
result: [
|
||||
{
|
||||
fields: {
|
||||
username: ["iframe#nonexistent >>> #username"],
|
||||
result: {
|
||||
targetingRules: [
|
||||
{
|
||||
fields: {
|
||||
username: ["iframe#nonexistent >>> #username"],
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
],
|
||||
ruleFailureFallback: false,
|
||||
},
|
||||
});
|
||||
}
|
||||
return Promise.resolve(undefined);
|
||||
@@ -543,7 +726,10 @@ describe("CollectAutofillContentService", () => {
|
||||
.mockImplementation((command: string) => {
|
||||
if (command === "getUrlAutofillTargetingRules") {
|
||||
return Promise.resolve({
|
||||
result: [{ fields: { username: ["iframe#nonexistent >>> #username"] } }],
|
||||
result: {
|
||||
targetingRules: [{ fields: { username: ["iframe#nonexistent >>> #username"] } }],
|
||||
ruleFailureFallback: false,
|
||||
},
|
||||
});
|
||||
}
|
||||
return Promise.resolve(undefined);
|
||||
@@ -565,12 +751,15 @@ describe("CollectAutofillContentService", () => {
|
||||
.mockImplementation((command: string) => {
|
||||
if (command === "getUrlAutofillTargetingRules") {
|
||||
return Promise.resolve({
|
||||
result: [
|
||||
{
|
||||
category: FormPurposeCategories.AccountLogin,
|
||||
fields: { email: ["#username"] },
|
||||
},
|
||||
],
|
||||
result: {
|
||||
targetingRules: [
|
||||
{
|
||||
category: FormPurposeCategories.AccountLogin,
|
||||
fields: { email: ["#username"] },
|
||||
},
|
||||
],
|
||||
ruleFailureFallback: false,
|
||||
},
|
||||
});
|
||||
}
|
||||
return Promise.resolve(undefined);
|
||||
@@ -591,7 +780,10 @@ describe("CollectAutofillContentService", () => {
|
||||
.mockImplementation((command: string) => {
|
||||
if (command === "getUrlAutofillTargetingRules") {
|
||||
return Promise.resolve({
|
||||
result: [{ fields: { username: [selector] } }],
|
||||
result: {
|
||||
targetingRules: [{ fields: { username: [selector] } }],
|
||||
ruleFailureFallback: false,
|
||||
},
|
||||
});
|
||||
}
|
||||
return Promise.resolve(undefined);
|
||||
@@ -675,12 +867,15 @@ describe("CollectAutofillContentService", () => {
|
||||
.mockImplementation((command: string) => {
|
||||
if (command === "getUrlAutofillTargetingRules") {
|
||||
return Promise.resolve({
|
||||
result: [
|
||||
{
|
||||
category: FormPurposeCategories.AccountLogin,
|
||||
fields: { username: ["iframe#login-form-container >>> #username"] },
|
||||
},
|
||||
],
|
||||
result: {
|
||||
targetingRules: [
|
||||
{
|
||||
category: FormPurposeCategories.AccountLogin,
|
||||
fields: { username: ["iframe#login-form-container >>> #username"] },
|
||||
},
|
||||
],
|
||||
ruleFailureFallback: false,
|
||||
},
|
||||
});
|
||||
}
|
||||
return Promise.resolve(undefined);
|
||||
|
||||
@@ -37,6 +37,11 @@ import {
|
||||
} from "./abstractions/collect-autofill-content.service";
|
||||
import { DomElementVisibilityService } from "./abstractions/dom-element-visibility.service";
|
||||
import { DomQueryService } from "./abstractions/dom-query.service";
|
||||
import {
|
||||
InScopeFormsDetection,
|
||||
QualificationResult,
|
||||
RuleQualificationService,
|
||||
} from "./abstractions/rule-qualification.service";
|
||||
import { AutoFillConstants } from "./autofill-constants";
|
||||
import { ShadowHostHydrationTracker } from "./shadow-host-hydration-tracker";
|
||||
|
||||
@@ -67,6 +72,12 @@ export class CollectAutofillContentService implements CollectAutofillContentServ
|
||||
* [] = blocklisted (suppress autofill), [...] = use targeted fill
|
||||
*/
|
||||
private pageTargetingRules: FormContent[] | null | undefined = undefined;
|
||||
// Populated alongside `pageTargetingRules` from the background envelope. Sibling
|
||||
// caches that short-circuit the per-call qualification cost (Half 1 + Half 2) on
|
||||
// subsequent `getPageDetails()` calls for the same page load.
|
||||
private ruleFailureFallback: boolean | undefined = undefined;
|
||||
private ruleQualificationResult: QualificationResult | undefined = undefined;
|
||||
private ruleQualificationService?: RuleQualificationService;
|
||||
private _autofillFormElements: AutofillFormElements = new Map();
|
||||
private autofillFieldElements: AutofillFieldElements = new Map();
|
||||
private autofillFieldsByOpid: Map<string, FormFieldElement> = new Map();
|
||||
@@ -281,11 +292,40 @@ export class CollectAutofillContentService implements CollectAutofillContentServ
|
||||
|
||||
// Check for targeting rules before running heuristic collection
|
||||
if (this.pageTargetingRules === undefined) {
|
||||
this.pageTargetingRules =
|
||||
(await this.sendExtensionMessage("getUrlAutofillTargetingRules")).result ?? null;
|
||||
const { result } = await this.sendExtensionMessage("getUrlAutofillTargetingRules");
|
||||
const envelope = result ?? { targetingRules: null, ruleFailureFallback: false };
|
||||
this.pageTargetingRules = envelope.targetingRules;
|
||||
this.ruleFailureFallback = envelope.ruleFailureFallback;
|
||||
}
|
||||
|
||||
const targetingRules = this.pageTargetingRules;
|
||||
|
||||
// Rule qualification branch. When the envelope's `ruleFailureFallback`
|
||||
// is set and a non-empty rule matches, run qualification once per page
|
||||
// load and route on the result. On miss, pin `pageTargetingRules = null`
|
||||
// so later calls on this document skip this branch and run the heuristic
|
||||
// path. The null check on `ruleQualificationService` guards against the
|
||||
// branch firing before the service is wired by content-script DI setup.
|
||||
if (
|
||||
this.ruleFailureFallback &&
|
||||
targetingRules != null &&
|
||||
targetingRules.length > 0 &&
|
||||
this.ruleQualificationService
|
||||
) {
|
||||
if (this.ruleQualificationResult === undefined) {
|
||||
this.ruleQualificationResult = await this.ruleQualificationService.qualifyRule(
|
||||
location.href,
|
||||
targetingRules,
|
||||
);
|
||||
}
|
||||
const qualification = this.ruleQualificationResult;
|
||||
if (qualification.kind === "proceedTargeted") {
|
||||
return this.getTargetedPageDetails(targetingRules);
|
||||
}
|
||||
this.pageTargetingRules = null;
|
||||
return qualification.pageDetails;
|
||||
}
|
||||
|
||||
if (targetingRules != null) {
|
||||
if (targetingRules.length === 0) {
|
||||
// Blocklisted; return empty page details, skip heuristics
|
||||
@@ -307,6 +347,15 @@ export class CollectAutofillContentService implements CollectAutofillContentServ
|
||||
);
|
||||
}
|
||||
|
||||
return this.runHeuristicCollection();
|
||||
}
|
||||
|
||||
/**
|
||||
* Walks the DOM for forms and fields, builds the page details, and sets up
|
||||
* overlay listeners. Shared by `getPageDetails` and
|
||||
* `collectHeuristicPageDetailsBypass`.
|
||||
*/
|
||||
private async runHeuristicCollection(): Promise<AutofillPageDetails> {
|
||||
const { formElements, formFieldElements } = this.queryAutofillFormAndFieldElements();
|
||||
const autofillFormsData: Record<string, AutofillForm> =
|
||||
this.buildAutofillFormsData(formElements);
|
||||
@@ -326,6 +375,29 @@ export class CollectAutofillContentService implements CollectAutofillContentServ
|
||||
return pageDetails;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the heuristic collection path on the miss path, after clearing any
|
||||
* targeted-rule state so the heuristic pass starts fresh. Called by
|
||||
* `RuleQualificationService` when a matched rule fails qualification.
|
||||
*
|
||||
* The `cachedInScopeForms` parameter is reserved for a later optimization
|
||||
* that reuses Half 2's field detection within the rule's in-scope forms
|
||||
* rather than detecting them again. Not consumed yet; the heuristic walk
|
||||
* runs over the full document.
|
||||
*/
|
||||
async collectHeuristicPageDetailsBypass(
|
||||
cachedInScopeForms?: InScopeFormsDetection,
|
||||
): Promise<AutofillPageDetails> {
|
||||
this.pageTargetingRules = null;
|
||||
this.autofillFieldElements.clear();
|
||||
this.autofillFieldsByOpid.clear();
|
||||
return this.runHeuristicCollection();
|
||||
}
|
||||
|
||||
setRuleQualificationService(ruleQualificationService: RuleQualificationService): void {
|
||||
this.ruleQualificationService = ruleQualificationService;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find an AutofillField element by its opid, will only return the first
|
||||
* element if there are multiple elements with the same opid. If no
|
||||
@@ -586,6 +658,8 @@ export class CollectAutofillContentService implements CollectAutofillContentServ
|
||||
*/
|
||||
clearCachedTargetingRules(): void {
|
||||
this.pageTargetingRules = undefined;
|
||||
this.ruleFailureFallback = undefined;
|
||||
this.ruleQualificationResult = undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1467,12 +1541,13 @@ export class CollectAutofillContentService implements CollectAutofillContentServ
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the passed node is a form field element.
|
||||
* @param {Element} element the element to check.
|
||||
* @returns {boolean} whether the element is a form field element.
|
||||
* @private
|
||||
* Checks if the passed node is a form field element. Mirrors the filter used
|
||||
* by the heuristic collection pass: excludes ignored input types and
|
||||
* `data-bwignore` elements.
|
||||
* @param element the element to check.
|
||||
* @returns whether the element is a form field element.
|
||||
*/
|
||||
private isElementFormFieldElement(element: Element): boolean {
|
||||
isElementFormFieldElement(element: Element): boolean {
|
||||
const nodeTagName = element.tagName.toLowerCase();
|
||||
|
||||
const nodeIsSpanElementWithAutofillAttribute =
|
||||
@@ -1613,6 +1688,8 @@ export class CollectAutofillContentService implements CollectAutofillContentServ
|
||||
// Targeting rules are URL-scoped and gated by user/feature state at fetch
|
||||
// time; the new URL must re-fetch to pick up rule and gate changes.
|
||||
this.pageTargetingRules = undefined;
|
||||
this.ruleFailureFallback = undefined;
|
||||
this.ruleQualificationResult = undefined;
|
||||
|
||||
this.clearFieldCache();
|
||||
|
||||
|
||||
@@ -25,17 +25,25 @@ describe("DefaultFillCipherPolicy", () => {
|
||||
});
|
||||
|
||||
it("emits changed$ after each decryption and not while decryption is in progress", async () => {
|
||||
const cipherViews$ = new Subject<CipherView[] | null>();
|
||||
cipherService.cipherViews$.mockReturnValue(cipherViews$);
|
||||
const listViews$ = new Subject<CipherView[] | null>();
|
||||
cipherService.cipherListViews$.mockReturnValue(listViews$);
|
||||
|
||||
const emitted = firstValueFrom(policy.changed$(userId).pipe(toArray()));
|
||||
cipherViews$.next([view("a")]);
|
||||
cipherViews$.next(null);
|
||||
cipherViews$.next([view("b")]);
|
||||
cipherViews$.complete();
|
||||
listViews$.next([view("a")]);
|
||||
listViews$.next(null);
|
||||
listViews$.next([view("b")]);
|
||||
listViews$.complete();
|
||||
|
||||
expect(await emitted).toEqual([undefined, undefined]);
|
||||
expect(cipherService.cipherViews$).toHaveBeenCalledWith(userId);
|
||||
expect(cipherService.cipherListViews$).toHaveBeenCalledWith(userId);
|
||||
});
|
||||
|
||||
it("watches list views for changed$, so the background never decrypts the whole vault", () => {
|
||||
cipherService.cipherListViews$.mockReturnValue(new Subject<CipherView[] | null>());
|
||||
|
||||
policy.changed$(userId).subscribe();
|
||||
|
||||
expect(cipherService.cipherViews$).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(Object.values(CipherUse))("returns the stored ciphers for %s", async (use) => {
|
||||
@@ -45,6 +53,15 @@ describe("DefaultFillCipherPolicy", () => {
|
||||
expect(await policy.ciphers(userId, use)).toBe(stored);
|
||||
});
|
||||
|
||||
it("decrypts only the requested ids", async () => {
|
||||
const stored = [view("a")];
|
||||
cipherService.getAllDecryptedForIds.mockResolvedValue(stored);
|
||||
|
||||
expect(await policy.ciphersForIds(userId, ["a"], CipherUse.UserFill)).toBe(stored);
|
||||
expect(cipherService.getAllDecryptedForIds).toHaveBeenCalledWith(userId, ["a"]);
|
||||
expect(cipherService.getAllDecrypted).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("passes the URL options to the stored lookup", async () => {
|
||||
const stored = [view("stored")];
|
||||
cipherService.getAllDecryptedForUrl.mockResolvedValue(stored);
|
||||
|
||||
@@ -12,9 +12,13 @@ import { CipherUse, FillCipherPolicy, SaveCandidate } from "./abstractions/fill-
|
||||
export class DefaultFillCipherPolicy implements FillCipherPolicy {
|
||||
constructor(protected readonly cipherService: CipherService) {}
|
||||
|
||||
/** Emits after each decryption, so a lookup that follows reads the new ciphers. */
|
||||
/**
|
||||
* Emits after each decryption, so a lookup that follows reads the new ciphers. Watches list
|
||||
* views: the background subscribes for as long as the vault is unlocked, and full views would
|
||||
* keep the whole vault decrypted in memory.
|
||||
*/
|
||||
changed$(userId: UserId): Observable<void> {
|
||||
return this.cipherService.cipherViews$(userId).pipe(
|
||||
return this.cipherService.cipherListViews$(userId).pipe(
|
||||
filter((views) => views != null),
|
||||
map((): void => undefined),
|
||||
);
|
||||
@@ -24,6 +28,10 @@ export class DefaultFillCipherPolicy implements FillCipherPolicy {
|
||||
return this.cipherService.getAllDecrypted(userId);
|
||||
}
|
||||
|
||||
ciphersForIds(userId: UserId, ids: string[], use: CipherUse): Promise<CipherView[]> {
|
||||
return this.cipherService.getAllDecryptedForIds(userId, ids);
|
||||
}
|
||||
|
||||
ciphersForUrl(
|
||||
url: string,
|
||||
userId: UserId,
|
||||
|
||||
@@ -0,0 +1,739 @@
|
||||
import { mock, MockProxy } from "jest-mock-extended";
|
||||
|
||||
import { FormContent, FormPurposeCategory } from "@bitwarden/common/autofill/types";
|
||||
|
||||
import AutofillPageDetails from "../models/autofill-page-details";
|
||||
|
||||
import { CollectAutofillContentService } from "./abstractions/collect-autofill-content.service";
|
||||
import { DomElementVisibilityService } from "./abstractions/dom-element-visibility.service";
|
||||
import { DomQueryService } from "./abstractions/dom-query.service";
|
||||
import { DefaultRuleQualificationService } from "./rule-qualification.service";
|
||||
|
||||
describe("DefaultRuleQualificationService", () => {
|
||||
let collectService: MockProxy<CollectAutofillContentService>;
|
||||
let domQueryService: MockProxy<DomQueryService>;
|
||||
let domElementVisibilityService: MockProxy<DomElementVisibilityService>;
|
||||
let service: DefaultRuleQualificationService;
|
||||
|
||||
const samplePageDetails = {} as AutofillPageDetails;
|
||||
|
||||
const buildLoginRule = (): FormContent[] => [
|
||||
{
|
||||
category: "login" as FormPurposeCategory,
|
||||
fields: {
|
||||
username: ["#user"],
|
||||
password: ["#pass"],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
// Mirrors the real `isElementFormFieldElement` filter on the collect service:
|
||||
// excludes ignored input types and `data-bwignore` elements.
|
||||
const IGNORED_INPUT_TYPES = new Set([
|
||||
"hidden",
|
||||
"submit",
|
||||
"reset",
|
||||
"button",
|
||||
"image",
|
||||
"file",
|
||||
"search",
|
||||
"url",
|
||||
"date",
|
||||
"time",
|
||||
"datetime",
|
||||
"datetime-local",
|
||||
"week",
|
||||
"color",
|
||||
"range",
|
||||
]);
|
||||
const realisticIsElementFormFieldElement = (element: Element): boolean => {
|
||||
const tagName = element.tagName.toLowerCase();
|
||||
if (element.hasAttribute("data-bwignore")) {
|
||||
return false;
|
||||
}
|
||||
if (tagName === "input") {
|
||||
return !IGNORED_INPUT_TYPES.has((element as HTMLInputElement).type);
|
||||
}
|
||||
return tagName === "textarea" || tagName === "select";
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
document.body.innerHTML = "";
|
||||
|
||||
collectService = mock<CollectAutofillContentService>();
|
||||
collectService.collectHeuristicPageDetailsBypass.mockResolvedValue(samplePageDetails);
|
||||
collectService.isElementFormFieldElement.mockImplementation(realisticIsElementFormFieldElement);
|
||||
|
||||
domQueryService = mock<DomQueryService>();
|
||||
// Default stub mimics a light-DOM walk of the form root. Tests that need
|
||||
// shadow-DOM-rooted or span[data-bwautofill] candidates override this.
|
||||
domQueryService.queryWithUnresolvedShadowHosts.mockImplementation((root, predicate) => {
|
||||
const elements: Element[] = [];
|
||||
(root as Element).querySelectorAll("*").forEach((element) => {
|
||||
if (predicate(element)) {
|
||||
elements.push(element);
|
||||
}
|
||||
});
|
||||
return { elements: elements as never[], unresolvedHosts: new Set<Element>() };
|
||||
});
|
||||
domElementVisibilityService = mock<DomElementVisibilityService>();
|
||||
domElementVisibilityService.isElementHiddenByCss.mockReturnValue(false);
|
||||
|
||||
service = new DefaultRuleQualificationService(
|
||||
collectService,
|
||||
domQueryService,
|
||||
domElementVisibilityService,
|
||||
);
|
||||
});
|
||||
|
||||
describe("qualifyRule — happy path", () => {
|
||||
it("returns proceedTargeted when every declared selector resolves inside a form with no extras", async () => {
|
||||
const form = document.createElement("form");
|
||||
const user = document.createElement("input");
|
||||
const pass = document.createElement("input");
|
||||
form.append(user, pass);
|
||||
document.body.append(form);
|
||||
|
||||
domQueryService.queryDeepSelector.mockImplementation((selector) =>
|
||||
selector === "#user" ? user : selector === "#pass" ? pass : null,
|
||||
);
|
||||
|
||||
const result = await service.qualifyRule("https://example.com", buildLoginRule());
|
||||
|
||||
expect(result).toEqual({ kind: "proceedTargeted" });
|
||||
expect(collectService.collectHeuristicPageDetailsBypass).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns proceedTargeted when extras exist in unrelated forms outside the in-scope set", async () => {
|
||||
const loginForm = document.createElement("form");
|
||||
const user = document.createElement("input");
|
||||
const pass = document.createElement("input");
|
||||
loginForm.append(user, pass);
|
||||
|
||||
const newsletterForm = document.createElement("form");
|
||||
const email = document.createElement("input");
|
||||
newsletterForm.append(email);
|
||||
|
||||
document.body.append(loginForm, newsletterForm);
|
||||
|
||||
domQueryService.queryDeepSelector.mockImplementation((selector) =>
|
||||
selector === "#user" ? user : selector === "#pass" ? pass : null,
|
||||
);
|
||||
|
||||
const result = await service.qualifyRule("https://example.com", buildLoginRule());
|
||||
|
||||
expect(result).toEqual({ kind: "proceedTargeted" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("qualifyRule — structural miss", () => {
|
||||
it("returns fallback with missReason structural when a declared selector does not resolve", async () => {
|
||||
domQueryService.queryDeepSelector.mockReturnValue(null);
|
||||
|
||||
const result = await service.qualifyRule("https://example.com", buildLoginRule());
|
||||
|
||||
expect(result).toEqual({
|
||||
kind: "fallback",
|
||||
missReason: "structural",
|
||||
pageDetails: samplePageDetails,
|
||||
});
|
||||
expect(collectService.collectHeuristicPageDetailsBypass).toHaveBeenCalledWith();
|
||||
});
|
||||
|
||||
it("returns fallback with missReason structural when a declared selector resolves to an input[type=hidden]", async () => {
|
||||
// Exercises the real `type="hidden"` check in Half 1. The visibility
|
||||
// service's `isElementHiddenByCss` only inspects CSS, so a hidden-type
|
||||
// input would silently qualify without the dedicated check.
|
||||
const form = document.createElement("form");
|
||||
const hidden = document.createElement("input");
|
||||
hidden.type = "hidden";
|
||||
form.append(hidden);
|
||||
document.body.append(form);
|
||||
|
||||
domQueryService.queryDeepSelector.mockReturnValue(hidden);
|
||||
|
||||
const result = await service.qualifyRule("https://example.com", buildLoginRule());
|
||||
|
||||
expect(result).toEqual({
|
||||
kind: "fallback",
|
||||
missReason: "structural",
|
||||
pageDetails: samplePageDetails,
|
||||
});
|
||||
});
|
||||
|
||||
it("returns fallback with missReason structural when a declared selector resolves but is CSS-hidden", async () => {
|
||||
const form = document.createElement("form");
|
||||
const field = document.createElement("input");
|
||||
form.append(field);
|
||||
document.body.append(form);
|
||||
|
||||
domQueryService.queryDeepSelector.mockReturnValue(field);
|
||||
domElementVisibilityService.isElementHiddenByCss.mockReturnValue(true);
|
||||
|
||||
const result = await service.qualifyRule("https://example.com", buildLoginRule());
|
||||
|
||||
expect(result).toEqual({
|
||||
kind: "fallback",
|
||||
missReason: "structural",
|
||||
pageDetails: samplePageDetails,
|
||||
});
|
||||
});
|
||||
|
||||
it("fails structural when any member of a DeepSelectorSequence does not resolve", async () => {
|
||||
const form = document.createElement("form");
|
||||
const d1 = document.createElement("input");
|
||||
const d2 = document.createElement("input");
|
||||
form.append(d1, d2);
|
||||
document.body.append(form);
|
||||
|
||||
const otpRule: FormContent[] = [
|
||||
{
|
||||
category: "login" as FormPurposeCategory,
|
||||
fields: {
|
||||
// Each entry here is a DeepSelectorSequence (string[]). The whole sequence
|
||||
// must resolve for the rule to qualify.
|
||||
oneTimeCode: [["#d1", "#d2", "#d3-missing"]],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
domQueryService.queryDeepSelector.mockImplementation((selector) =>
|
||||
selector === "#d1" ? d1 : selector === "#d2" ? d2 : null,
|
||||
);
|
||||
|
||||
const result = await service.qualifyRule("https://example.com", otpRule);
|
||||
|
||||
expect(result).toMatchObject({ kind: "fallback", missReason: "structural" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("qualifyRule — selector alternatives", () => {
|
||||
const buildAlternativesRule = (): FormContent[] => [
|
||||
{
|
||||
category: "login" as FormPurposeCategory,
|
||||
fields: {
|
||||
username: ["#email", "#login"],
|
||||
password: ["#pwd"],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
it("qualifies when only the first alternative resolves", async () => {
|
||||
const form = document.createElement("form");
|
||||
const email = document.createElement("input");
|
||||
const pwd = document.createElement("input");
|
||||
form.append(email, pwd);
|
||||
document.body.append(form);
|
||||
|
||||
domQueryService.queryDeepSelector.mockImplementation((selector) =>
|
||||
selector === "#email" ? email : selector === "#pwd" ? pwd : null,
|
||||
);
|
||||
|
||||
const result = await service.qualifyRule("https://example.com", buildAlternativesRule());
|
||||
|
||||
expect(result).toEqual({ kind: "proceedTargeted" });
|
||||
});
|
||||
|
||||
it("qualifies when only the second alternative resolves", async () => {
|
||||
const form = document.createElement("form");
|
||||
const login = document.createElement("input");
|
||||
const pwd = document.createElement("input");
|
||||
form.append(login, pwd);
|
||||
document.body.append(form);
|
||||
|
||||
domQueryService.queryDeepSelector.mockImplementation((selector) =>
|
||||
selector === "#login" ? login : selector === "#pwd" ? pwd : null,
|
||||
);
|
||||
|
||||
const result = await service.qualifyRule("https://example.com", buildAlternativesRule());
|
||||
|
||||
expect(result).toEqual({ kind: "proceedTargeted" });
|
||||
});
|
||||
|
||||
it("fails structural when no alternative resolves", async () => {
|
||||
const form = document.createElement("form");
|
||||
const pwd = document.createElement("input");
|
||||
form.append(pwd);
|
||||
document.body.append(form);
|
||||
|
||||
domQueryService.queryDeepSelector.mockImplementation((selector) =>
|
||||
selector === "#pwd" ? pwd : null,
|
||||
);
|
||||
|
||||
const result = await service.qualifyRule("https://example.com", buildAlternativesRule());
|
||||
|
||||
expect(result).toMatchObject({ kind: "fallback", missReason: "structural" });
|
||||
});
|
||||
|
||||
it("qualifies when a sequence alternative fully resolves even though the string alternative does not", async () => {
|
||||
// Rule: `password: ["#pwd", ["#pwd-a", "#pwd-b"]]`.
|
||||
// Page has `#pwd-a` and `#pwd-b` but not `#pwd`.
|
||||
const form = document.createElement("form");
|
||||
const user = document.createElement("input");
|
||||
const pwdA = document.createElement("input");
|
||||
const pwdB = document.createElement("input");
|
||||
form.append(user, pwdA, pwdB);
|
||||
document.body.append(form);
|
||||
|
||||
const rule: FormContent[] = [
|
||||
{
|
||||
category: "login" as FormPurposeCategory,
|
||||
fields: {
|
||||
username: ["#user"],
|
||||
password: ["#pwd", ["#pwd-a", "#pwd-b"]],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
domQueryService.queryDeepSelector.mockImplementation((selector) => {
|
||||
if (selector === "#user") {
|
||||
return user;
|
||||
}
|
||||
if (selector === "#pwd-a") {
|
||||
return pwdA;
|
||||
}
|
||||
if (selector === "#pwd-b") {
|
||||
return pwdB;
|
||||
}
|
||||
return null;
|
||||
});
|
||||
|
||||
const result = await service.qualifyRule("https://example.com", rule);
|
||||
|
||||
expect(result).toEqual({ kind: "proceedTargeted" });
|
||||
});
|
||||
|
||||
it("fails structural when a sequence alternative has one member missing and no other alternative qualifies", async () => {
|
||||
const form = document.createElement("form");
|
||||
const d1 = document.createElement("input");
|
||||
const d2 = document.createElement("input");
|
||||
form.append(d1, d2);
|
||||
document.body.append(form);
|
||||
|
||||
const rule: FormContent[] = [
|
||||
{
|
||||
category: "login" as FormPurposeCategory,
|
||||
fields: {
|
||||
oneTimeCode: [["#d1", "#d2", "#d3-missing"]],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
domQueryService.queryDeepSelector.mockImplementation((selector) =>
|
||||
selector === "#d1" ? d1 : selector === "#d2" ? d2 : null,
|
||||
);
|
||||
|
||||
const result = await service.qualifyRule("https://example.com", rule);
|
||||
|
||||
expect(result).toMatchObject({ kind: "fallback", missReason: "structural" });
|
||||
});
|
||||
|
||||
it("treats every alternative's resolved elements as declared for the extras check", async () => {
|
||||
// Both `#email` and `#login` are declared as alternatives for the
|
||||
// username and both exist on the page. Neither should be flagged as an
|
||||
// extra. A third input that no alternative covers should.
|
||||
const form = document.createElement("form");
|
||||
const email = document.createElement("input");
|
||||
const login = document.createElement("input");
|
||||
const pwd = document.createElement("input");
|
||||
const stray = document.createElement("input");
|
||||
form.append(email, login, pwd, stray);
|
||||
document.body.append(form);
|
||||
|
||||
domQueryService.queryDeepSelector.mockImplementation((selector) => {
|
||||
if (selector === "#email") {
|
||||
return email;
|
||||
}
|
||||
if (selector === "#login") {
|
||||
return login;
|
||||
}
|
||||
if (selector === "#pwd") {
|
||||
return pwd;
|
||||
}
|
||||
return null;
|
||||
});
|
||||
|
||||
const result = await service.qualifyRule("https://example.com", buildAlternativesRule());
|
||||
|
||||
expect(result).toMatchObject({ kind: "fallback", missReason: "in_scope_extras" });
|
||||
});
|
||||
|
||||
it("qualifies when only one of several container selectors resolves", async () => {
|
||||
// Container entries name the same element with different selectors.
|
||||
// Any one resolving is enough. Pins the any-of semantic for container.
|
||||
const form = document.createElement("form");
|
||||
const user = document.createElement("input");
|
||||
const pass = document.createElement("input");
|
||||
form.append(user, pass);
|
||||
document.body.append(form);
|
||||
|
||||
const rule: FormContent[] = [
|
||||
{
|
||||
category: "login" as FormPurposeCategory,
|
||||
container: ["#main-login", "#legacy-login"],
|
||||
fields: {
|
||||
username: ["#user"],
|
||||
password: ["#pass"],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
domQueryService.queryDeepSelector.mockImplementation((selector) => {
|
||||
if (selector === "#legacy-login") {
|
||||
return form;
|
||||
}
|
||||
if (selector === "#user") {
|
||||
return user;
|
||||
}
|
||||
if (selector === "#pass") {
|
||||
return pass;
|
||||
}
|
||||
return null;
|
||||
});
|
||||
|
||||
const result = await service.qualifyRule("https://example.com", rule);
|
||||
|
||||
expect(result).toEqual({ kind: "proceedTargeted" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("qualifyRule — in-scope extras miss", () => {
|
||||
it("returns fallback with missReason in_scope_extras when an in-scope form contains an undeclared field", async () => {
|
||||
const form = document.createElement("form");
|
||||
const user = document.createElement("input");
|
||||
const pass = document.createElement("input");
|
||||
const extra = document.createElement("input");
|
||||
form.append(user, pass, extra);
|
||||
document.body.append(form);
|
||||
|
||||
domQueryService.queryDeepSelector.mockImplementation((selector) =>
|
||||
selector === "#user" ? user : selector === "#pass" ? pass : null,
|
||||
);
|
||||
|
||||
const result = await service.qualifyRule("https://example.com", buildLoginRule());
|
||||
|
||||
expect(result).toEqual({
|
||||
kind: "fallback",
|
||||
missReason: "in_scope_extras",
|
||||
pageDetails: samplePageDetails,
|
||||
});
|
||||
});
|
||||
|
||||
it("passes the in-scope detection to the bypass when extras are found", async () => {
|
||||
const form = document.createElement("form");
|
||||
const user = document.createElement("input");
|
||||
const pass = document.createElement("input");
|
||||
const extra = document.createElement("input");
|
||||
form.append(user, pass, extra);
|
||||
document.body.append(form);
|
||||
|
||||
domQueryService.queryDeepSelector.mockImplementation((selector) =>
|
||||
selector === "#user" ? user : selector === "#pass" ? pass : null,
|
||||
);
|
||||
|
||||
await service.qualifyRule("https://example.com", buildLoginRule());
|
||||
|
||||
expect(collectService.collectHeuristicPageDetailsBypass).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
forms: expect.any(Set),
|
||||
detectedFields: expect.any(Map),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("flags a shadow-DOM-rooted field inside an in-scope form as in_scope_extras", async () => {
|
||||
// Regression guard. The extras check must cross shadow boundaries, or a
|
||||
// shadow-rooted field inside an in-scope form would be invisible and the
|
||||
// rule would qualify despite the extra.
|
||||
const form = document.createElement("form");
|
||||
const user = document.createElement("input");
|
||||
const customEl = document.createElement("my-input");
|
||||
form.append(user, customEl);
|
||||
document.body.append(form);
|
||||
|
||||
// Stand-in for a field inside customEl's shadow root. The test only
|
||||
// exercises what the deep-query mock returns, not the live DOM.
|
||||
const shadowPassword = document.createElement("input");
|
||||
shadowPassword.type = "password";
|
||||
|
||||
const usernameOnlyRule: FormContent[] = [
|
||||
{
|
||||
category: "login" as FormPurposeCategory,
|
||||
fields: { username: ["#user"] },
|
||||
},
|
||||
];
|
||||
|
||||
domQueryService.queryDeepSelector.mockImplementation((selector) =>
|
||||
selector === "#user" ? user : null,
|
||||
);
|
||||
domQueryService.queryWithUnresolvedShadowHosts.mockImplementation((root, predicate) => {
|
||||
if (root === form) {
|
||||
return {
|
||||
elements: [user, shadowPassword] as never[],
|
||||
unresolvedHosts: new Set<Element>(),
|
||||
};
|
||||
}
|
||||
const elements: Element[] = [];
|
||||
(root as Element).querySelectorAll("*").forEach((element) => {
|
||||
if (predicate(element)) {
|
||||
elements.push(element);
|
||||
}
|
||||
});
|
||||
return { elements: elements as never[], unresolvedHosts: new Set<Element>() };
|
||||
});
|
||||
|
||||
const result = await service.qualifyRule("https://example.com", usernameOnlyRule);
|
||||
|
||||
expect(result).toMatchObject({ kind: "fallback", missReason: "in_scope_extras" });
|
||||
});
|
||||
|
||||
it("flags a span[data-bwautofill] inside an in-scope form as in_scope_extras", async () => {
|
||||
// When honorBitwardenAutofillAttribute is on, the heuristic treats
|
||||
// span[data-bwautofill] as a fillable field. An undeclared one inside
|
||||
// an in-scope form must be flagged as an extra.
|
||||
const form = document.createElement("form");
|
||||
const user = document.createElement("input");
|
||||
const pass = document.createElement("input");
|
||||
pass.type = "password";
|
||||
const span = document.createElement("span");
|
||||
span.setAttribute("data-bwautofill", "");
|
||||
form.append(user, pass, span);
|
||||
document.body.append(form);
|
||||
|
||||
domQueryService.queryDeepSelector.mockImplementation((selector) =>
|
||||
selector === "#user" ? user : selector === "#pass" ? pass : null,
|
||||
);
|
||||
collectService.isElementFormFieldElement.mockImplementation((element) => {
|
||||
if (element.tagName.toLowerCase() === "span" && element.hasAttribute("data-bwautofill")) {
|
||||
return true;
|
||||
}
|
||||
return realisticIsElementFormFieldElement(element);
|
||||
});
|
||||
|
||||
const result = await service.qualifyRule("https://example.com", buildLoginRule());
|
||||
|
||||
expect(result).toMatchObject({ kind: "fallback", missReason: "in_scope_extras" });
|
||||
});
|
||||
|
||||
it("qualifies a realistic login form containing a submit button and hidden token", async () => {
|
||||
// Regression guard. Earlier the detector used a coarse filter that counted
|
||||
// every input/select/textarea as a fillable field, so a standard login
|
||||
// form with a CSRF hidden input and a submit button failed Half 2 on
|
||||
// every page load. The real heuristic filter excludes those types.
|
||||
const form = document.createElement("form");
|
||||
const user = document.createElement("input");
|
||||
user.id = "user";
|
||||
const pass = document.createElement("input");
|
||||
pass.id = "pass";
|
||||
pass.type = "password";
|
||||
const csrf = document.createElement("input");
|
||||
csrf.type = "hidden";
|
||||
csrf.name = "csrf_token";
|
||||
const submit = document.createElement("input");
|
||||
submit.type = "submit";
|
||||
form.append(user, pass, csrf, submit);
|
||||
document.body.append(form);
|
||||
|
||||
domQueryService.queryDeepSelector.mockImplementation((selector) =>
|
||||
selector === "#user" ? user : selector === "#pass" ? pass : null,
|
||||
);
|
||||
|
||||
const result = await service.qualifyRule("https://example.com", buildLoginRule());
|
||||
|
||||
expect(result).toEqual({ kind: "proceedTargeted" });
|
||||
});
|
||||
|
||||
it("qualifies a login form with a Remember Me checkbox", async () => {
|
||||
// Checkbox and radio are not rule types and the autofill engine does
|
||||
// not fill them, so Half 2 must not flag them as extras.
|
||||
const form = document.createElement("form");
|
||||
const user = document.createElement("input");
|
||||
const pass = document.createElement("input");
|
||||
pass.type = "password";
|
||||
const remember = document.createElement("input");
|
||||
remember.type = "checkbox";
|
||||
form.append(user, pass, remember);
|
||||
document.body.append(form);
|
||||
|
||||
domQueryService.queryDeepSelector.mockImplementation((selector) =>
|
||||
selector === "#user" ? user : selector === "#pass" ? pass : null,
|
||||
);
|
||||
|
||||
const result = await service.qualifyRule("https://example.com", buildLoginRule());
|
||||
|
||||
expect(result).toEqual({ kind: "proceedTargeted" });
|
||||
});
|
||||
|
||||
it("ignores a CSS-hidden input when checking for extras", async () => {
|
||||
// Honeypot inputs are rendered off-screen or display:none. Treating
|
||||
// them as extras would cause misses on forms that use them.
|
||||
const form = document.createElement("form");
|
||||
const user = document.createElement("input");
|
||||
const pass = document.createElement("input");
|
||||
pass.type = "password";
|
||||
const honeypot = document.createElement("input");
|
||||
form.append(user, pass, honeypot);
|
||||
document.body.append(form);
|
||||
|
||||
domQueryService.queryDeepSelector.mockImplementation((selector) =>
|
||||
selector === "#user" ? user : selector === "#pass" ? pass : null,
|
||||
);
|
||||
domElementVisibilityService.isElementHiddenByCss.mockImplementation(
|
||||
(element) => element === honeypot,
|
||||
);
|
||||
|
||||
const result = await service.qualifyRule("https://example.com", buildLoginRule());
|
||||
|
||||
expect(result).toEqual({ kind: "proceedTargeted" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("qualifyRule — formless pages (known limitation)", () => {
|
||||
it("returns proceedTargeted when every selector resolves outside any form, even if page has other fields", async () => {
|
||||
// Fields rendered as plain divs, not inside <form>. closest("form") returns
|
||||
// null for the resolved elements, so the in-scope form set is empty and
|
||||
// the extras check passes without inspecting the page's other fields.
|
||||
const user = document.createElement("input");
|
||||
const pass = document.createElement("input");
|
||||
const unrelated = document.createElement("input");
|
||||
document.body.append(user, pass, unrelated);
|
||||
|
||||
domQueryService.queryDeepSelector.mockImplementation((selector) =>
|
||||
selector === "#user" ? user : selector === "#pass" ? pass : null,
|
||||
);
|
||||
|
||||
const result = await service.qualifyRule("https://example.com", buildLoginRule());
|
||||
|
||||
expect(result).toEqual({ kind: "proceedTargeted" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("qualifyRule — iframe >>> selectors", () => {
|
||||
it("passes structural when the first-hop iframe exists in the parent's DOM", async () => {
|
||||
const rule: FormContent[] = [
|
||||
{
|
||||
category: "login" as FormPurposeCategory,
|
||||
fields: { username: ["iframe#login >>> #user"] },
|
||||
},
|
||||
];
|
||||
const iframe = document.createElement("iframe");
|
||||
domQueryService.findIframeCrossing.mockReturnValue({
|
||||
iframeElement: iframe,
|
||||
innerSelector: "#user",
|
||||
});
|
||||
|
||||
const result = await service.qualifyRule("https://example.com", rule);
|
||||
|
||||
expect(result).toEqual({ kind: "proceedTargeted" });
|
||||
expect(domQueryService.queryDeepSelector).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("fails structural when the first-hop iframe is missing (findIframeCrossing returns null)", async () => {
|
||||
const rule: FormContent[] = [
|
||||
{
|
||||
category: "login" as FormPurposeCategory,
|
||||
fields: { username: ["iframe#missing >>> #user"] },
|
||||
},
|
||||
];
|
||||
domQueryService.findIframeCrossing.mockReturnValue(null);
|
||||
domQueryService.queryDeepSelector.mockReturnValue(null);
|
||||
|
||||
const result = await service.qualifyRule("https://example.com", rule);
|
||||
|
||||
expect(result).toMatchObject({ kind: "fallback", missReason: "structural" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("qualifyRule — shadow DOM >>> selectors", () => {
|
||||
it("passes structural when a shadow DOM >>> chain resolves to an eligible element", async () => {
|
||||
const rule: FormContent[] = [
|
||||
{
|
||||
category: "login" as FormPurposeCategory,
|
||||
fields: { username: ["gi-login.hydrated >>> input#user"] },
|
||||
},
|
||||
];
|
||||
const input = document.createElement("input");
|
||||
// findIframeCrossing returns null for chains without an iframe boundary.
|
||||
domQueryService.findIframeCrossing.mockReturnValue(null);
|
||||
domQueryService.queryDeepSelector.mockReturnValue(input);
|
||||
|
||||
const result = await service.qualifyRule("https://example.com", rule);
|
||||
|
||||
expect(result).toEqual({ kind: "proceedTargeted" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("qualifyRule — debug logging", () => {
|
||||
let debugSpy: jest.SpyInstance;
|
||||
|
||||
beforeEach(() => {
|
||||
debugSpy = jest.spyOn(console, "debug").mockImplementation(() => {});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
debugSpy.mockRestore();
|
||||
});
|
||||
|
||||
it("logs the proceedTargeted outcome with domain, duration, and in-scope form count", async () => {
|
||||
const form = document.createElement("form");
|
||||
const user = document.createElement("input");
|
||||
const pass = document.createElement("input");
|
||||
form.append(user, pass);
|
||||
document.body.append(form);
|
||||
|
||||
domQueryService.queryDeepSelector.mockImplementation((selector) =>
|
||||
selector === "#user" ? user : selector === "#pass" ? pass : null,
|
||||
);
|
||||
|
||||
await service.qualifyRule("https://example.com/login?token=secret", buildLoginRule());
|
||||
|
||||
expect(debugSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining("proceedTargeted"),
|
||||
expect.objectContaining({
|
||||
domain: "example.com",
|
||||
durationMs: expect.any(Number),
|
||||
inScopeForms: expect.any(Number),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("logs the structural miss outcome with domain, duration, and in-scope form count", async () => {
|
||||
domQueryService.queryDeepSelector.mockReturnValue(null);
|
||||
|
||||
await service.qualifyRule("https://example.com/login?token=secret", buildLoginRule());
|
||||
|
||||
expect(debugSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining("structural miss"),
|
||||
expect.objectContaining({
|
||||
domain: "example.com",
|
||||
durationMs: expect.any(Number),
|
||||
inScopeForms: expect.any(Number),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("logs the in_scope_extras miss outcome with domain, duration, and in-scope form count", async () => {
|
||||
const form = document.createElement("form");
|
||||
const user = document.createElement("input");
|
||||
const pass = document.createElement("input");
|
||||
const extra = document.createElement("input");
|
||||
form.append(user, pass, extra);
|
||||
document.body.append(form);
|
||||
|
||||
domQueryService.queryDeepSelector.mockImplementation((selector) =>
|
||||
selector === "#user" ? user : selector === "#pass" ? pass : null,
|
||||
);
|
||||
|
||||
await service.qualifyRule("https://example.com/login?token=secret", buildLoginRule());
|
||||
|
||||
expect(debugSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining("in_scope_extras miss"),
|
||||
expect.objectContaining({
|
||||
domain: "example.com",
|
||||
durationMs: expect.any(Number),
|
||||
inScopeForms: expect.any(Number),
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
263
apps/browser/src/autofill/services/rule-qualification.service.ts
Normal file
263
apps/browser/src/autofill/services/rule-qualification.service.ts
Normal file
@@ -0,0 +1,263 @@
|
||||
import { FormContent } from "@bitwarden/common/autofill/types";
|
||||
|
||||
import { FormFieldElement } from "../types";
|
||||
|
||||
import { CollectAutofillContentService } from "./abstractions/collect-autofill-content.service";
|
||||
import { DomElementVisibilityService } from "./abstractions/dom-element-visibility.service";
|
||||
import { DomQueryService } from "./abstractions/dom-query.service";
|
||||
import {
|
||||
InScopeFormsDetection,
|
||||
QualificationResult,
|
||||
RuleQualificationService,
|
||||
} from "./abstractions/rule-qualification.service";
|
||||
import { AutoFillConstants } from "./autofill-constants";
|
||||
|
||||
export class DefaultRuleQualificationService implements RuleQualificationService {
|
||||
constructor(
|
||||
private collectAutofillContentService: CollectAutofillContentService,
|
||||
private domQueryService: DomQueryService,
|
||||
private domElementVisibilityService: DomElementVisibilityService,
|
||||
) {}
|
||||
|
||||
async qualifyRule(url: string, matchedRule: FormContent[]): Promise<QualificationResult> {
|
||||
const startTime = performance.now();
|
||||
// Hostname only. URL paths and queries can carry sensitive values.
|
||||
const domain = new URL(url).hostname;
|
||||
const structural = await this.checkStructural(matchedRule);
|
||||
if (!structural.ok) {
|
||||
const pageDetails =
|
||||
await this.collectAutofillContentService.collectHeuristicPageDetailsBypass();
|
||||
// eslint-disable-next-line no-console -- this is running in a content-script; `LogService` is unavailable
|
||||
console.debug("[RuleQualificationService] structural miss", {
|
||||
domain,
|
||||
durationMs: performance.now() - startTime,
|
||||
inScopeForms: structural.inScopeForms.forms.size,
|
||||
});
|
||||
return { kind: "fallback", missReason: "structural", pageDetails };
|
||||
}
|
||||
|
||||
const extras = await this.checkInScopeExtras(matchedRule, structural.inScopeForms);
|
||||
if (!extras.ok) {
|
||||
const pageDetails =
|
||||
await this.collectAutofillContentService.collectHeuristicPageDetailsBypass(
|
||||
structural.inScopeForms,
|
||||
);
|
||||
// eslint-disable-next-line no-console -- this is running in a content-script; `LogService` is unavailable
|
||||
console.debug("[RuleQualificationService] in_scope_extras miss", {
|
||||
domain,
|
||||
durationMs: performance.now() - startTime,
|
||||
inScopeForms: structural.inScopeForms.forms.size,
|
||||
});
|
||||
return { kind: "fallback", missReason: "in_scope_extras", pageDetails };
|
||||
}
|
||||
|
||||
// eslint-disable-next-line no-console -- this is running in a content-script; `LogService` is unavailable
|
||||
console.debug("[RuleQualificationService] proceedTargeted", {
|
||||
domain,
|
||||
durationMs: performance.now() - startTime,
|
||||
inScopeForms: structural.inScopeForms.forms.size,
|
||||
});
|
||||
return { kind: "proceedTargeted" };
|
||||
}
|
||||
|
||||
/**
|
||||
* Half 1: for each declared field, at least one alternative qualifies.
|
||||
* Side-effect free. Collects enclosing `<form>` elements along the way so
|
||||
* Half 2 knows which forms to detect fields within.
|
||||
*/
|
||||
private async checkStructural(
|
||||
rule: FormContent[],
|
||||
): Promise<{ ok: boolean; inScopeForms: InScopeFormsDetection }> {
|
||||
const inScopeForms = new Set<HTMLFormElement>();
|
||||
|
||||
for (const form of rule) {
|
||||
for (const alternatives of this.extractAlternativeGroups(form)) {
|
||||
const winningElements = this.firstQualifyingAlternative(alternatives);
|
||||
if (winningElements === null) {
|
||||
return { ok: false, inScopeForms: { forms: inScopeForms } };
|
||||
}
|
||||
for (const element of winningElements) {
|
||||
const enclosingForm = element.closest("form");
|
||||
if (enclosingForm) {
|
||||
inScopeForms.add(enclosingForm);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { ok: true, inScopeForms: { forms: inScopeForms } };
|
||||
}
|
||||
|
||||
/**
|
||||
* Half 2: no undeclared field exists in any in-scope form. Populates
|
||||
* `inScopeForms.detectedFields` with the detection result so the miss path
|
||||
* can reuse it rather than detecting fields in those forms again.
|
||||
*
|
||||
* The declared set includes elements for every alternative that resolves,
|
||||
* not just the one Half 1 picked. If a rule declares `username: ["#email",
|
||||
* "#login"]` and both exist on the page, neither counts as an extra.
|
||||
*
|
||||
* Note on formless pages: when every resolved declared selector sits outside
|
||||
* a `<form>`, `inScopeForms.forms` is empty and this method returns `ok: true`
|
||||
* without finding any extras. The check asks "is there an extra inside any
|
||||
* in-scope form?" and with zero in-scope forms the answer is no. This matches
|
||||
* the known limitation that formless pages are not covered by the extras check.
|
||||
*/
|
||||
private async checkInScopeExtras(
|
||||
rule: FormContent[],
|
||||
inScopeForms: InScopeFormsDetection,
|
||||
): Promise<{ ok: boolean }> {
|
||||
const declaredElements = new Set<Element>();
|
||||
for (const selector of this.flattenDeclaredSelectors(rule)) {
|
||||
if (selector.includes(">>>") && this.domQueryService.findIframeCrossing(selector)) {
|
||||
continue;
|
||||
}
|
||||
const element = this.domQueryService.queryDeepSelector(selector);
|
||||
if (element) {
|
||||
declaredElements.add(element);
|
||||
}
|
||||
}
|
||||
|
||||
const detectedFields = new Map<HTMLFormElement, FormFieldElement[]>();
|
||||
for (const form of inScopeForms.forms) {
|
||||
const fields = this.detectHeuristicFieldsInForm(form);
|
||||
detectedFields.set(form, fields);
|
||||
for (const field of fields) {
|
||||
if (!declaredElements.has(field as Element)) {
|
||||
inScopeForms.detectedFields = detectedFields;
|
||||
return { ok: false };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
inScopeForms.detectedFields = detectedFields;
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns one list of alternatives per declared field, plus the container
|
||||
* if present. A field qualifies when any one alternative qualifies. An
|
||||
* alternative is a list of selectors that must all resolve together. A
|
||||
* string entry becomes a one-member list. A `DeepSelectorSequence` entry
|
||||
* carries all its members.
|
||||
*
|
||||
* Container selectors are grouped the same way: multiple entries name the
|
||||
* same container element, so any one that resolves qualifies.
|
||||
*/
|
||||
private extractAlternativeGroups(form: FormContent): string[][][] {
|
||||
const groups: string[][][] = [];
|
||||
|
||||
if (form.container) {
|
||||
groups.push(form.container.map((selector) => [selector]));
|
||||
}
|
||||
|
||||
for (const typeSelectors of Object.values(form.fields)) {
|
||||
if (!typeSelectors) {
|
||||
continue;
|
||||
}
|
||||
groups.push(typeSelectors.map((entry) => (typeof entry === "string" ? [entry] : entry)));
|
||||
}
|
||||
|
||||
return groups;
|
||||
}
|
||||
|
||||
/**
|
||||
* Flattens every declared selector from a rule into one list. The extras
|
||||
* check only needs element identity, not alternative grouping, so a flat
|
||||
* walk keeps the caller free of deep nesting.
|
||||
*/
|
||||
private flattenDeclaredSelectors(rule: FormContent[]): string[] {
|
||||
const selectors: string[] = [];
|
||||
for (const form of rule) {
|
||||
for (const alternatives of this.extractAlternativeGroups(form)) {
|
||||
for (const members of alternatives) {
|
||||
selectors.push(...members);
|
||||
}
|
||||
}
|
||||
}
|
||||
return selectors;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the resolved elements of the first alternative that fully
|
||||
* qualifies, or null if none do. An iframe `>>>` selector with a resolved
|
||||
* first-hop iframe counts as qualifying without contributing a local
|
||||
* element. Later segments live in child frames and are not checked here.
|
||||
*/
|
||||
private firstQualifyingAlternative(alternatives: string[][]): HTMLElement[] | null {
|
||||
for (const members of alternatives) {
|
||||
const resolved: HTMLElement[] = [];
|
||||
let allResolve = true;
|
||||
for (const selector of members) {
|
||||
if (selector.includes(">>>") && this.domQueryService.findIframeCrossing(selector)) {
|
||||
continue;
|
||||
}
|
||||
const element = this.domQueryService.queryDeepSelector(selector) as HTMLElement | null;
|
||||
if (!element || this.isElementIneligible(element)) {
|
||||
allResolve = false;
|
||||
break;
|
||||
}
|
||||
resolved.push(element);
|
||||
}
|
||||
if (allResolve) {
|
||||
return resolved;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Treats `input type="hidden"` and CSS-hidden elements (display, visibility,
|
||||
* opacity, clip-path) as unresolved, matching the eligibility probe.
|
||||
*/
|
||||
private isElementIneligible(element: HTMLElement): boolean {
|
||||
const isHiddenInput = element instanceof HTMLInputElement && element.type === "hidden";
|
||||
return isHiddenInput || this.domElementVisibilityService.isElementHiddenByCss(element);
|
||||
}
|
||||
|
||||
/**
|
||||
* Detects heuristic-eligible fields within a single form container. Scoped,
|
||||
* side-effect-free equivalent of the field detection in
|
||||
* `buildAutofillFieldsData`.
|
||||
*
|
||||
* We chose a scoped reimplementation over making `buildAutofillFieldsData`
|
||||
* cache-optional because the shared method populates the collect service's
|
||||
* field caches as a side effect, and those caches must stay empty on the
|
||||
* heuristic bypass path. Adding a `skipCaching` branch to the shared path
|
||||
* would clutter it for just one caller.
|
||||
*
|
||||
* Uses the same `queryWithUnresolvedShadowHosts` call the full heuristic
|
||||
* scan uses, so shadow-rooted fields and `span[data-bwautofill]` surface
|
||||
* the same way. The predicate narrows further via `isFillableField`.
|
||||
* Unresolved shadow hosts are discarded. The collect service handles
|
||||
* shadow tracker reconciliation on its own full scan.
|
||||
*/
|
||||
private detectHeuristicFieldsInForm(form: HTMLFormElement): FormFieldElement[] {
|
||||
const { elements } = this.domQueryService.queryWithUnresolvedShadowHosts<FormFieldElement>(
|
||||
form,
|
||||
(element) => this.isFillableField(element),
|
||||
);
|
||||
return elements;
|
||||
}
|
||||
|
||||
/**
|
||||
* Narrows the collect service's form-field filter to elements the autofill
|
||||
* engine can actually fill. Rules have no field type for checkbox or radio
|
||||
* and the autofill engine does not fill them, so counting them as extras
|
||||
* would misfire on common login forms (e.g. a Remember Me checkbox).
|
||||
* CSS-hidden elements are also skipped so honeypot inputs do not trip the
|
||||
* extras check.
|
||||
*/
|
||||
private isFillableField(element: Element): boolean {
|
||||
if (!this.collectAutofillContentService.isElementFormFieldElement(element)) {
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
element instanceof HTMLInputElement &&
|
||||
AutoFillConstants.ExcludedAutofillTypes.includes(element.type)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
return !this.domElementVisibilityService.isElementHiddenByCss(element as HTMLElement);
|
||||
}
|
||||
}
|
||||
@@ -424,6 +424,7 @@ import {
|
||||
isNotificationsSupported,
|
||||
} from "../platform/system-notifications/browser-system-notification.service";
|
||||
import { fromChromeRuntimeMessaging } from "../platform/utils/from-chrome-runtime-messaging";
|
||||
import { ListViewsAnnouncerService } from "../vault/background/list-views-announcer.service";
|
||||
import { AtRiskCipherBadgeUpdaterService } from "../vault/services/at-risk-cipher-badge-updater.service";
|
||||
|
||||
import CommandsBackground from "./commands.background";
|
||||
@@ -1043,7 +1044,6 @@ export default class MainBackground {
|
||||
this.collectionEncryptionService = new DefaultCollectionEncryptionService(
|
||||
this.sdkService,
|
||||
this.logService,
|
||||
this.configService,
|
||||
);
|
||||
|
||||
this.collectionService = new DefaultCollectionService(
|
||||
@@ -2416,6 +2416,11 @@ export default class MainBackground {
|
||||
await this.autofillBadgeUpdaterService.init();
|
||||
await this.clipboardNotificationBadgeUpdaterService.init();
|
||||
await this.atRiskCipherUpdaterService.init();
|
||||
new ListViewsAnnouncerService(
|
||||
this.accountService,
|
||||
this.cipherService,
|
||||
this.messagingService,
|
||||
).init();
|
||||
}
|
||||
|
||||
generatePasswordToClipboard = () => {
|
||||
|
||||
@@ -5,6 +5,7 @@ import { AccountService } from "@bitwarden/common/auth/abstractions/account.serv
|
||||
import { LogoutReason } from "@bitwarden/common/auth/logout";
|
||||
import { ExtensionCommand } from "@bitwarden/common/autofill/constants";
|
||||
import { DomainSettingsService } from "@bitwarden/common/autofill/services/domain-settings.service";
|
||||
import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service";
|
||||
import {
|
||||
Environment,
|
||||
Region,
|
||||
@@ -67,6 +68,7 @@ type RuntimeBackgroundOverrides = {
|
||||
autofillOrchestrator?: MockProxy<AutofillOrchestrator>;
|
||||
intraprocessMessageSender?: MockProxy<IntraprocessMessageSender>;
|
||||
fillAssistEventReceiver?: MockProxy<FillAssistEventReceiver>;
|
||||
configService?: MockProxy<ConfigService>;
|
||||
};
|
||||
|
||||
function createRuntimeBackground({
|
||||
@@ -79,6 +81,7 @@ function createRuntimeBackground({
|
||||
autofillOrchestrator = mock<AutofillOrchestrator>(),
|
||||
intraprocessMessageSender = mock<IntraprocessMessageSender>(),
|
||||
fillAssistEventReceiver = mock<FillAssistEventReceiver>(),
|
||||
configService = mock<ConfigService>(),
|
||||
}: RuntimeBackgroundOverrides = {}) {
|
||||
// The `undefined` slots are collaborators no covered path reaches.
|
||||
// Give one a mock as soon as a test needs it.
|
||||
@@ -90,7 +93,7 @@ function createRuntimeBackground({
|
||||
environmentService as any,
|
||||
messagingService as any,
|
||||
logService,
|
||||
undefined as any, // configService
|
||||
configService,
|
||||
undefined as any, // messageListener
|
||||
accountService,
|
||||
undefined as any, // lockService
|
||||
@@ -213,6 +216,12 @@ describe("RuntimeBackground collection dispatch", () => {
|
||||
});
|
||||
});
|
||||
|
||||
/** Serves `ciphers` to lookups by id, as the vault would. */
|
||||
const serveCiphers = (policy: MockProxy<FillCipherPolicy>, ciphers: CipherView[]) =>
|
||||
policy.ciphersForIds.mockImplementation(async (_userId, ids) =>
|
||||
ciphers.filter((cipher) => ids.includes(cipher.id)),
|
||||
);
|
||||
|
||||
describe("fillCipherForPopup", () => {
|
||||
const cipher = Object.assign(new CipherView(), { id: "cipher-1" });
|
||||
let fillCipherPolicy: MockProxy<FillCipherPolicy>;
|
||||
@@ -220,7 +229,7 @@ describe("RuntimeBackground collection dispatch", () => {
|
||||
beforeEach(() => {
|
||||
jest.spyOn(BrowserApi, "getTab").mockResolvedValue(tab);
|
||||
fillCipherPolicy = mock<FillCipherPolicy>();
|
||||
fillCipherPolicy.ciphers.mockResolvedValue([cipher]);
|
||||
serveCiphers(fillCipherPolicy, [cipher]);
|
||||
(main as any).fillCipherPolicy = fillCipherPolicy;
|
||||
autofillOrchestrator.unsafeAutofillTabWithCipher.mockResolvedValue({
|
||||
outcome: AutofillOutcome.Filled,
|
||||
@@ -244,7 +253,11 @@ describe("RuntimeBackground collection dispatch", () => {
|
||||
popupSender,
|
||||
);
|
||||
|
||||
expect(fillCipherPolicy.ciphers).toHaveBeenCalledWith("user-1", CipherUse.UserFill);
|
||||
expect(fillCipherPolicy.ciphersForIds).toHaveBeenCalledWith(
|
||||
"user-1",
|
||||
["cipher-1"],
|
||||
CipherUse.UserFill,
|
||||
);
|
||||
});
|
||||
|
||||
it("security: rejects a content-script sender without fetching or filling", async () => {
|
||||
@@ -261,7 +274,7 @@ describe("RuntimeBackground collection dispatch", () => {
|
||||
// Logging the rejection is part of the security requirement: the warning is the
|
||||
// observable record that the boundary fired on this sender.
|
||||
expect(logService.warning).toHaveBeenCalled();
|
||||
expect(fillCipherPolicy.ciphers).not.toHaveBeenCalled();
|
||||
expect(fillCipherPolicy.ciphersForIds).not.toHaveBeenCalled();
|
||||
expect(autofillOrchestrator.unsafeAutofillTabWithCipher).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -475,6 +488,7 @@ describe("RuntimeBackground getUrlAutofillTargetingRules", () => {
|
||||
let runtimeBackground: RuntimeBackground;
|
||||
let mainBackground: MockProxy<MainBackground>;
|
||||
let domainSettingsService: MockProxy<DomainSettingsService>;
|
||||
let configService: MockProxy<ConfigService>;
|
||||
|
||||
const message = { command: "getUrlAutofillTargetingRules" };
|
||||
|
||||
@@ -491,8 +505,10 @@ describe("RuntimeBackground getUrlAutofillTargetingRules", () => {
|
||||
domainSettingsService = mock<DomainSettingsService>();
|
||||
mainBackground = mock<MainBackground>();
|
||||
(mainBackground as any).domainSettingsService = domainSettingsService;
|
||||
configService = mock<ConfigService>();
|
||||
configService.getFeatureFlag.mockResolvedValue(false as any);
|
||||
|
||||
runtimeBackground = createRuntimeBackground({ main: mainBackground });
|
||||
runtimeBackground = createRuntimeBackground({ main: mainBackground, configService });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
@@ -564,7 +580,7 @@ describe("RuntimeBackground getUrlAutofillTargetingRules", () => {
|
||||
expect(domainSettingsService.getTargetingRulesForUrl).toHaveBeenCalledWith(committedUrl);
|
||||
});
|
||||
|
||||
it("returns the resolved rules to the caller", async () => {
|
||||
it("returns the resolved rules in the envelope under `targetingRules`", async () => {
|
||||
const rules = [{ category: "account-login", fields: {} }] as any;
|
||||
mockFrameLookup(routedUrl);
|
||||
domainSettingsService.getTargetingRulesForUrl.mockResolvedValue(rules);
|
||||
@@ -576,7 +592,23 @@ describe("RuntimeBackground getUrlAutofillTargetingRules", () => {
|
||||
|
||||
const result = await runtimeBackground.processMessageWithSender(message, sender);
|
||||
|
||||
expect(result).toBe(rules);
|
||||
expect(result).toEqual({ targetingRules: rules, ruleFailureFallback: false });
|
||||
});
|
||||
|
||||
it("sets ruleFailureFallback=true in the envelope when the fallback flag is on", async () => {
|
||||
const rules = [{ category: "account-login", fields: {} }] as any;
|
||||
mockFrameLookup(routedUrl);
|
||||
domainSettingsService.getTargetingRulesForUrl.mockResolvedValue(rules);
|
||||
configService.getFeatureFlag.mockResolvedValue(true as any);
|
||||
const sender = {
|
||||
frameId: 0,
|
||||
url: committedUrl,
|
||||
tab: createChromeTabMock({ id: 1, url: routedUrl }),
|
||||
} as chrome.runtime.MessageSender;
|
||||
|
||||
const result = await runtimeBackground.processMessageWithSender(message, sender);
|
||||
|
||||
expect(result).toEqual({ targetingRules: rules, ruleFailureFallback: true });
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
// FIXME: Update this file to be type safe and remove this and next line
|
||||
// @ts-strict-ignore
|
||||
import { firstValueFrom, map, mergeMap } from "rxjs";
|
||||
import { filter, firstValueFrom, map, mergeMap } from "rxjs";
|
||||
|
||||
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
|
||||
import { AutofillOverlayVisibility, ExtensionCommand } from "@bitwarden/common/autofill/constants";
|
||||
import { AutofillSettingsServiceAbstraction } from "@bitwarden/common/autofill/services/autofill-settings.service";
|
||||
import { BillingAccountProfileStateService } from "@bitwarden/common/billing/abstractions/account/billing-account-profile-state.service";
|
||||
import { FeatureFlag } from "@bitwarden/common/enums/feature-flag.enum";
|
||||
import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service";
|
||||
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
|
||||
import { MessagingService } from "@bitwarden/common/platform/abstractions/messaging.service";
|
||||
@@ -55,6 +56,7 @@ import BrowserInitialInstallService from "../platform/services/browser-initial-i
|
||||
import { BrowserPlatformUtilsService } from "../platform/services/platform-utils/browser-platform-utils.service";
|
||||
import { isValidVaultReferrer } from "../platform/utils/valid-vault-referrer";
|
||||
import { getWebExtSender } from "../platform/utils/web-ext-sender";
|
||||
import { GET_CIPHER_LIST_VIEWS } from "../vault/services/foreground-cipher.service";
|
||||
|
||||
import MainBackground from "./main.background";
|
||||
|
||||
@@ -124,6 +126,7 @@ export default class RuntimeBackground {
|
||||
"fillCipherForPopup",
|
||||
"getBitwardenAutofillAttributeSettings",
|
||||
VaultMessages.checkBwInstalled,
|
||||
GET_CIPHER_LIST_VIEWS,
|
||||
];
|
||||
|
||||
if (messagesWithResponse.includes(msg.command)) {
|
||||
@@ -180,6 +183,17 @@ export default class RuntimeBackground {
|
||||
}
|
||||
return await this.autofillOrchestrator.collectPageDetails(targetTab);
|
||||
}
|
||||
case GET_CIPHER_LIST_VIEWS: {
|
||||
// The list views are decrypted vault data, so only extension pages get them.
|
||||
if (!BrowserApi.senderIsInternal(sender, this.logService)) {
|
||||
return [];
|
||||
}
|
||||
return await firstValueFrom(
|
||||
this.main.cipherService
|
||||
.cipherListViewsIncludingRestricted$(msg.userId)
|
||||
.pipe(filter((views) => views != null)),
|
||||
);
|
||||
}
|
||||
case "fillCipherForPopup": {
|
||||
// The popup keeps the reprompt and TOTP copy in the foreground but dispatches the fill here.
|
||||
// The cipher is referenced by id and re-fetched below so decrypted vault data never crosses
|
||||
@@ -198,8 +212,11 @@ export default class RuntimeBackground {
|
||||
if (activeUserId == null) {
|
||||
return AUTOFILL_DENIED;
|
||||
}
|
||||
const ciphers = await this.main.fillCipherPolicy.ciphers(activeUserId, CipherUse.UserFill);
|
||||
const cipher = ciphers.find((candidate) => candidate.id === msg.cipherId);
|
||||
const [cipher] = await this.main.fillCipherPolicy.ciphersForIds(
|
||||
activeUserId,
|
||||
[msg.cipherId],
|
||||
CipherUse.UserFill,
|
||||
);
|
||||
if (cipher == null) {
|
||||
return AUTOFILL_DENIED;
|
||||
}
|
||||
@@ -277,10 +294,13 @@ export default class RuntimeBackground {
|
||||
// Rules are matched against the sender frame's URL rather than the tab's to minimize
|
||||
// selector collisions between frames with similar in-frame markup.
|
||||
const senderURL = await BrowserApi.getSenderFrameUrl(sender);
|
||||
const targetingRulesForUrl =
|
||||
const targetingRules =
|
||||
await this.main.domainSettingsService.getTargetingRulesForUrl(senderURL);
|
||||
const ruleFailureFallback = await this.configService.getFeatureFlag(
|
||||
FeatureFlag.FillAssistRuleFallback,
|
||||
);
|
||||
|
||||
return targetingRulesForUrl;
|
||||
return { targetingRules, ruleFailureFallback };
|
||||
}
|
||||
case "getBitwardenAutofillAttributeSettings": {
|
||||
const [honorBitwardenIgnoreAttribute, honorBitwardenAutofillAttribute] = await Promise.all([
|
||||
|
||||
@@ -7,6 +7,9 @@ import { FakeStorageService, makeEncString, makeSymmetricCryptoKey } from "@bitw
|
||||
import { EncryptService, KeyGenerationService, SymmetricCryptoKey } from "@bitwarden/legacy-crypto";
|
||||
import { StorageService } from "@bitwarden/storage-core";
|
||||
|
||||
import { BrowserApi } from "../browser/browser-api";
|
||||
import { portName } from "../storage/port-name";
|
||||
|
||||
import BrowserLocalStorageService from "./browser-local-storage.service";
|
||||
import {
|
||||
LocalBackedSessionStorageService,
|
||||
@@ -113,6 +116,44 @@ describe("LocalBackedSessionStorage", () => {
|
||||
);
|
||||
});
|
||||
|
||||
describe("port connections", () => {
|
||||
it("stops broadcasting updates to a port once it disconnects", async () => {
|
||||
jest.spyOn(BrowserApi, "senderIsInternal").mockReturnValue(true);
|
||||
let onConnect!: (port: chrome.runtime.Port) => void;
|
||||
jest
|
||||
.spyOn(BrowserApi, "addListener")
|
||||
.mockImplementation((_event, callback) => (onConnect = callback as typeof onConnect));
|
||||
const connectedSut = new LocalBackedSessionStorageService(
|
||||
memoryStorage,
|
||||
localStorage,
|
||||
keyGenerationService,
|
||||
encryptService,
|
||||
platformUtilsService,
|
||||
logService,
|
||||
);
|
||||
let disconnect!: () => void;
|
||||
const port = {
|
||||
name: portName(chrome.storage.session),
|
||||
sender: {},
|
||||
postMessage: jest.fn(),
|
||||
onMessage: { addListener: jest.fn(), removeListener: jest.fn() },
|
||||
onDisconnect: { addListener: jest.fn((cb: () => void) => (disconnect = cb)) },
|
||||
} as unknown as chrome.runtime.Port;
|
||||
onConnect(port);
|
||||
encryptService.encryptString.mockResolvedValue(makeEncString("encrypted"));
|
||||
|
||||
const broadcast = jest.spyOn(
|
||||
connectedSut as unknown as { broadcastMessage: () => void },
|
||||
"broadcastMessage",
|
||||
);
|
||||
|
||||
disconnect();
|
||||
await connectedSut.save("key", "value");
|
||||
|
||||
expect(broadcast).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("get", () => {
|
||||
const encString = makeEncString("encrypted");
|
||||
|
||||
|
||||
@@ -115,7 +115,15 @@ export class LocalBackedSessionStorageService
|
||||
this.ports.add(port);
|
||||
|
||||
const listenerCallback = this.onMessageFromForeground.bind(this);
|
||||
// One per port, dropped on disconnect so each popup open doesn't leave a listener behind.
|
||||
const updatesSubscription = this.updates$.subscribe((update) => {
|
||||
this.broadcastMessage({
|
||||
action: "subject_update",
|
||||
data: update,
|
||||
});
|
||||
});
|
||||
port.onDisconnect.addListener(() => {
|
||||
updatesSubscription.unsubscribe();
|
||||
this.ports.delete(port);
|
||||
port.onMessage.removeListener(listenerCallback);
|
||||
});
|
||||
@@ -125,12 +133,6 @@ export class LocalBackedSessionStorageService
|
||||
action: "initialization",
|
||||
data: Array.from(Object.keys(this.cache)),
|
||||
});
|
||||
this.updates$.subscribe((update) => {
|
||||
this.broadcastMessage({
|
||||
action: "subject_update",
|
||||
data: update,
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -17,6 +17,12 @@ import {
|
||||
import { LoginViaWebAuthnComponent } from "@bitwarden/angular/auth/login-via-webauthn/login-via-webauthn.component";
|
||||
import { ChangePasswordComponent } from "@bitwarden/angular/auth/password-management/change-password";
|
||||
import { SetInitialPasswordComponent } from "@bitwarden/angular/auth/password-management/set-initial-password/set-initial-password.component";
|
||||
import {
|
||||
RegistrationFinishComponent,
|
||||
RegistrationStartComponent,
|
||||
RegistrationStartSecondaryComponent,
|
||||
RegistrationStartSecondaryComponentData,
|
||||
} from "@bitwarden/angular/auth/registration";
|
||||
import { canAccessFeature } from "@bitwarden/angular/platform/guard/feature-flag.guard";
|
||||
import { featureFlaggedRoute } from "@bitwarden/angular/platform/utils/feature-flagged-route";
|
||||
import {
|
||||
@@ -35,10 +41,6 @@ import {
|
||||
LoginViaAuthRequestComponent,
|
||||
NewDeviceVerificationComponent,
|
||||
PasswordHintComponent,
|
||||
RegistrationFinishComponent,
|
||||
RegistrationStartComponent,
|
||||
RegistrationStartSecondaryComponent,
|
||||
RegistrationStartSecondaryComponentData,
|
||||
SsoComponent,
|
||||
TwoFactorAuthComponent,
|
||||
TwoFactorAuthGuard,
|
||||
|
||||
@@ -144,7 +144,10 @@ import { UnsupportedSystemNotificationsService } from "@bitwarden/common/platfor
|
||||
import { SendApiService } from "@bitwarden/common/tools/send/services/send-api.service.abstraction";
|
||||
import { InternalSendService } from "@bitwarden/common/tools/send/services/send.service.abstraction";
|
||||
import { CipherArchiveService } from "@bitwarden/common/vault/abstractions/cipher-archive.service";
|
||||
import { CipherEncryptionService } from "@bitwarden/common/vault/abstractions/cipher-encryption.service";
|
||||
import { CipherSdkService } from "@bitwarden/common/vault/abstractions/cipher-sdk.service";
|
||||
import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service";
|
||||
import { CipherFileUploadService } from "@bitwarden/common/vault/abstractions/file-upload/cipher-file-upload.service";
|
||||
import { FolderApiServiceAbstraction } from "@bitwarden/common/vault/abstractions/folder/folder-api.service.abstraction";
|
||||
import { InternalFolderService } from "@bitwarden/common/vault/abstractions/folder/folder.service.abstraction";
|
||||
import { TotpService as TotpServiceAbstraction } from "@bitwarden/common/vault/abstractions/totp.service";
|
||||
@@ -260,6 +263,7 @@ import {
|
||||
import { fromChromeRuntimeMessaging } from "../../platform/utils/from-chrome-runtime-messaging";
|
||||
import { BrowserAutofillNudgeService } from "../../vault/popup/services/browser-autofill-nudge.service";
|
||||
import { Fido2UserVerificationService } from "../../vault/services/fido2-user-verification.service";
|
||||
import { ForegroundCipherService } from "../../vault/services/foreground-cipher.service";
|
||||
import { ExtensionAnonLayoutWrapperDataService } from "../components/extension-anon-layout-wrapper/extension-anon-layout-wrapper-data.service";
|
||||
|
||||
import { DebounceNavigationService } from "./debounce-navigation.service";
|
||||
@@ -281,6 +285,27 @@ const DISK_BACKUP_LOCAL_STORAGE = new SafeInjectionToken<
|
||||
*/
|
||||
const safeProviders: SafeProvider[] = [
|
||||
safeProvider(InitService),
|
||||
safeProvider({
|
||||
provide: CipherService,
|
||||
useClass: ForegroundCipherService,
|
||||
deps: [
|
||||
MessageListener,
|
||||
KeyService,
|
||||
LegacyCompatKeyService,
|
||||
DomainSettingsService,
|
||||
ApiService,
|
||||
I18nServiceAbstraction,
|
||||
AutofillSettingsServiceAbstraction,
|
||||
EncryptService,
|
||||
CipherFileUploadService,
|
||||
ConfigService,
|
||||
StateProvider,
|
||||
AccountServiceAbstraction,
|
||||
LogService,
|
||||
CipherEncryptionService,
|
||||
CipherSdkService,
|
||||
],
|
||||
}),
|
||||
safeProvider(DebounceNavigationService),
|
||||
safeProvider(DialogService),
|
||||
safeProvider(PopupCloseWarningService),
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import { mock, MockProxy } from "jest-mock-extended";
|
||||
import { BehaviorSubject, Subject } from "rxjs";
|
||||
|
||||
import { Account, AccountService } from "@bitwarden/common/auth/abstractions/account.service";
|
||||
import { MessageSender } from "@bitwarden/common/platform/messaging";
|
||||
import { UserId } from "@bitwarden/common/types/guid";
|
||||
import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service";
|
||||
import { CipherListView } from "@bitwarden/sdk-internal";
|
||||
|
||||
import { CIPHER_LIST_VIEWS_CHANGED } from "../services/foreground-cipher.service";
|
||||
|
||||
import { ListViewsAnnouncerService } from "./list-views-announcer.service";
|
||||
|
||||
describe("ListViewsAnnouncerService", () => {
|
||||
const userId = "user-id" as UserId;
|
||||
|
||||
let activeAccount$: BehaviorSubject<Account | null>;
|
||||
let listViews$: Subject<CipherListView[] | null>;
|
||||
let cipherService: MockProxy<CipherService>;
|
||||
let messageSender: MockProxy<MessageSender>;
|
||||
|
||||
beforeEach(() => {
|
||||
activeAccount$ = new BehaviorSubject<Account | null>({ id: userId } as Account);
|
||||
listViews$ = new Subject();
|
||||
cipherService = mock<CipherService>();
|
||||
cipherService.cipherListViewsIncludingRestricted$.mockReturnValue(listViews$);
|
||||
messageSender = mock<MessageSender>();
|
||||
|
||||
const accountService = mock<AccountService>();
|
||||
accountService.activeAccount$ = activeAccount$;
|
||||
new ListViewsAnnouncerService(accountService, cipherService, messageSender).init();
|
||||
});
|
||||
|
||||
it("announces each list-view change, so an open popup fetches them again", () => {
|
||||
listViews$.next([]);
|
||||
listViews$.next([]);
|
||||
|
||||
expect(cipherService.cipherListViewsIncludingRestricted$).toHaveBeenCalledWith(userId);
|
||||
expect(messageSender.send).toHaveBeenCalledTimes(2);
|
||||
expect(messageSender.send).toHaveBeenCalledWith(CIPHER_LIST_VIEWS_CHANGED);
|
||||
});
|
||||
|
||||
it("stays quiet while list views are cleared or decrypting", () => {
|
||||
listViews$.next(null);
|
||||
|
||||
expect(messageSender.send).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("stays quiet without an active account", () => {
|
||||
activeAccount$.next(null);
|
||||
listViews$.next([]);
|
||||
|
||||
expect(messageSender.send).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
import { EMPTY, filter, switchMap } from "rxjs";
|
||||
|
||||
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
|
||||
import { MessageSender } from "@bitwarden/common/platform/messaging";
|
||||
import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service";
|
||||
|
||||
import { CIPHER_LIST_VIEWS_CHANGED } from "../services/foreground-cipher.service";
|
||||
|
||||
/**
|
||||
* Tells an open popup each time the background's list views change, after an edit, sync or
|
||||
* `localData` update, so the popup fetches them again. The popup holds no decrypted vault of its
|
||||
* own and cannot see these changes otherwise.
|
||||
*
|
||||
* background popup
|
||||
* cipherListViewsIncludingRestricted$ ──▶ CIPHER_LIST_VIEWS_CHANGED
|
||||
* ◀── GET_CIPHER_LIST_VIEWS
|
||||
*/
|
||||
export class ListViewsAnnouncerService {
|
||||
constructor(
|
||||
private readonly accountService: AccountService,
|
||||
private readonly cipherService: CipherService,
|
||||
private readonly messageSender: MessageSender,
|
||||
) {}
|
||||
|
||||
init(): void {
|
||||
this.accountService.activeAccount$
|
||||
.pipe(
|
||||
switchMap((account) =>
|
||||
account == null
|
||||
? EMPTY
|
||||
: this.cipherService.cipherListViewsIncludingRestricted$(account.id),
|
||||
),
|
||||
// Null means cleared or still decrypting: nothing new to fetch yet.
|
||||
filter((views) => views != null),
|
||||
)
|
||||
.subscribe(() => this.messageSender.send(CIPHER_LIST_VIEWS_CHANGED));
|
||||
}
|
||||
}
|
||||
@@ -379,7 +379,7 @@ const buildNotificationPolicies = (args: StoryArgs) => {
|
||||
/**
|
||||
* Tasks backing `vault-at-risk-password-callout`. `pendingTasks$` joins each task to a cipher by
|
||||
* `cipherId` and keeps only the editable, password-visible ones, so tasks have to point at ciphers
|
||||
* the story provides and `CipherService.cipherViews$` has to return them.
|
||||
* the story provides and `CipherService.cipherListViews$` has to return them.
|
||||
*/
|
||||
const buildAtRiskTask = (
|
||||
cipherId: PopupCipherViewLike["id"],
|
||||
@@ -558,6 +558,8 @@ const buildProviders = (args: StoryArgs) => {
|
||||
// No decryption failures, so the failure dialog never opens during a snapshot.
|
||||
failedToDecryptCiphers$: () => of([]),
|
||||
cipherViews$: () => of(atRiskCiphers),
|
||||
// The at-risk password callout matches tasks to list views.
|
||||
cipherListViews$: () => of(atRiskCiphers),
|
||||
ciphers$: () => of({}),
|
||||
},
|
||||
},
|
||||
|
||||
@@ -24,8 +24,6 @@ import { RevealedCipherService } from "@bitwarden/common/vault/abstractions/reve
|
||||
import { SearchService } from "@bitwarden/common/vault/abstractions/search.service";
|
||||
import { VaultSettingsService } from "@bitwarden/common/vault/abstractions/vault-settings/vault-settings.service";
|
||||
import { CipherType } from "@bitwarden/common/vault/enums";
|
||||
import { CipherData } from "@bitwarden/common/vault/models/data/cipher.data";
|
||||
import { LocalData } from "@bitwarden/common/vault/models/data/local.data";
|
||||
import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view";
|
||||
import {
|
||||
RestrictedCipherType,
|
||||
@@ -61,8 +59,7 @@ describe("VaultPopupItemsService", () => {
|
||||
mockSignal: WritableSignal<string | null>;
|
||||
};
|
||||
|
||||
let ciphersSubject: BehaviorSubject<Record<CipherId, CipherData>>;
|
||||
let localDataSubject: BehaviorSubject<Record<CipherId, LocalData>>;
|
||||
let cipherList$: BehaviorSubject<CipherView[]>;
|
||||
let failedToDecryptCiphersSubject: BehaviorSubject<CipherView[]>;
|
||||
|
||||
const cipherServiceMock = mock<CipherService>();
|
||||
@@ -109,22 +106,14 @@ describe("VaultPopupItemsService", () => {
|
||||
cipherList[2].favorite = true;
|
||||
cipherList[3].favorite = true;
|
||||
|
||||
const cipherList$ = new BehaviorSubject<CipherView[]>(cipherList);
|
||||
cipherList$ = new BehaviorSubject<CipherView[]>(cipherList);
|
||||
|
||||
cipherServiceMock.cipherListViewsIncludingRestricted$.mockReturnValue(
|
||||
cipherList$.asObservable(),
|
||||
);
|
||||
|
||||
ciphersSubject = new BehaviorSubject<Record<CipherId, CipherData>>({});
|
||||
localDataSubject = new BehaviorSubject<Record<CipherId, LocalData>>({});
|
||||
failedToDecryptCiphersSubject = new BehaviorSubject<CipherView[]>([]);
|
||||
|
||||
cipherServiceMock.ciphers$.mockImplementation((userId: UserId) =>
|
||||
ciphersSubject.asObservable(),
|
||||
);
|
||||
cipherServiceMock.localData$.mockImplementation((userId: UserId) =>
|
||||
localDataSubject.asObservable(),
|
||||
);
|
||||
cipherServiceMock.failedToDecryptCiphers$.mockImplementation((userId: UserId) =>
|
||||
failedToDecryptCiphersSubject.asObservable(),
|
||||
);
|
||||
@@ -239,26 +228,12 @@ describe("VaultPopupItemsService", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("should update cipher list when cipherService.ciphers$ emits", async () => {
|
||||
it("should update cipher list when cipherService.cipherListViewsIncludingRestricted$ emits", async () => {
|
||||
const tracker = new ObservableTracker(service.autoFillCiphers$);
|
||||
|
||||
await tracker.expectEmission();
|
||||
|
||||
ciphersSubject.next({});
|
||||
|
||||
await tracker.expectEmission();
|
||||
|
||||
// Should only emit twice
|
||||
expect(tracker.emissions.length).toBe(2);
|
||||
await expect(tracker.pauseUntilReceived(3)).rejects.toThrow("Timeout exceeded");
|
||||
});
|
||||
|
||||
it("should update cipher list when cipherService.localData$ emits", async () => {
|
||||
const tracker = new ObservableTracker(service.autoFillCiphers$);
|
||||
|
||||
await tracker.expectEmission();
|
||||
|
||||
localDataSubject.next({});
|
||||
cipherList$.next(cipherList$.value);
|
||||
|
||||
await tracker.expectEmission();
|
||||
|
||||
@@ -383,7 +358,6 @@ describe("VaultPopupItemsService", () => {
|
||||
|
||||
it("lists restricted ciphers", async () => {
|
||||
cipherServiceMock.cipherListViewsIncludingRestricted$.mockReturnValue(of([restrictedRow()]));
|
||||
ciphersSubject.next({});
|
||||
|
||||
const ciphers = await firstValueFrom(service.filteredCiphers$);
|
||||
|
||||
@@ -397,7 +371,6 @@ describe("VaultPopupItemsService", () => {
|
||||
const revealed = Object.assign(new CipherView(), { id: "restricted" as CipherId });
|
||||
cipherServiceMock.cipherListViewsIncludingRestricted$.mockReturnValue(of([row]));
|
||||
revealed$.next(new Map([["restricted" as CipherId, revealed]]));
|
||||
ciphersSubject.next({});
|
||||
|
||||
const [shown] = await firstValueFrom(service.filteredCiphers$);
|
||||
|
||||
@@ -411,7 +384,6 @@ describe("VaultPopupItemsService", () => {
|
||||
cipherServiceMock.cipherListViewsIncludingRestricted$.mockReturnValue(
|
||||
of([deletedRow, deleted]),
|
||||
);
|
||||
ciphersSubject.next({});
|
||||
|
||||
const deletedCiphers = await firstValueFrom(service.deletedCiphers$);
|
||||
|
||||
@@ -507,7 +479,6 @@ describe("VaultPopupItemsService", () => {
|
||||
const ciphers = [new CipherView(), new CipherView(), new CipherView(), deletedCipher];
|
||||
|
||||
cipherServiceMock.cipherListViewsIncludingRestricted$.mockReturnValue(of(ciphers));
|
||||
ciphersSubject.next({});
|
||||
|
||||
const deletedCiphers = await firstValueFrom(service.deletedCiphers$);
|
||||
expect(deletedCiphers.length).toBe(1);
|
||||
@@ -526,7 +497,6 @@ describe("VaultPopupItemsService", () => {
|
||||
cipherServiceMock.cipherListViewsIncludingRestricted$.mockReturnValue(
|
||||
of([personalCipher, memberOrgCipher, revokedOrgCipher]),
|
||||
);
|
||||
ciphersSubject.next({});
|
||||
|
||||
const deletedCiphers = await firstValueFrom(service.deletedCiphers$);
|
||||
expect(deletedCiphers.map((c) => c.organizationId)).toEqual([undefined, "org1"]);
|
||||
@@ -657,11 +627,11 @@ describe("VaultPopupItemsService", () => {
|
||||
expect(tracked.emissions[1]).toBe(false);
|
||||
});
|
||||
|
||||
it("should cycle when cipherService.ciphers$ emits", async () => {
|
||||
it("should cycle when cipherService.cipherListViewsIncludingRestricted$ emits", async () => {
|
||||
await trackedCiphers.expectEmission();
|
||||
// Restart tracking
|
||||
tracked = new ObservableTracker(service.loading$);
|
||||
ciphersSubject.next({});
|
||||
cipherList$.next(cipherList$.value);
|
||||
|
||||
await trackedCiphers.pauseUntilReceived(2);
|
||||
|
||||
|
||||
@@ -136,16 +136,15 @@ export class VaultPopupItemsService {
|
||||
map((a) => a?.id),
|
||||
filter((userId): userId is UserId => userId != null),
|
||||
switchMap((userId) =>
|
||||
merge(this.cipherService.ciphers$(userId), this.cipherService.localData$(userId)).pipe(
|
||||
this.cipherService.cipherListViewsIncludingRestricted$(userId).pipe(
|
||||
filter((ciphers) => ciphers != null),
|
||||
debounceTime(0),
|
||||
runInsideAngular(this.ngZone),
|
||||
tap(() => this._ciphersLoading$.next()),
|
||||
waitUntilSync(this.syncService),
|
||||
switchMap(() =>
|
||||
switchMap((ciphers) =>
|
||||
combineLatest([
|
||||
this.cipherService
|
||||
.cipherListViewsIncludingRestricted$(userId)
|
||||
.pipe(filter((ciphers) => ciphers != null)),
|
||||
of(ciphers),
|
||||
this.cipherService.failedToDecryptCiphers$(userId).pipe(startWith([])),
|
||||
this.restrictedItemTypesService.restricted$,
|
||||
]),
|
||||
|
||||
@@ -41,7 +41,7 @@ describe("AtRiskCipherBadgeUpdaterService", () => {
|
||||
service = new AtRiskCipherBadgeUpdaterService(
|
||||
{ setState } as unknown as BadgeService,
|
||||
{ activeAccount$ } as unknown as AccountService,
|
||||
{ cipherViews$: () => cipherViews$, getAllDecryptedForUrl } as unknown as CipherService,
|
||||
{ cipherListViews$: () => cipherViews$, getAllDecryptedForUrl } as unknown as CipherService,
|
||||
{ pendingTasks$: () => pendingTasks$ } as unknown as TaskService,
|
||||
);
|
||||
|
||||
|
||||
@@ -23,7 +23,8 @@ export class AtRiskCipherBadgeUpdaterService {
|
||||
.pipe(
|
||||
map((tasks) => tasks.filter((t) => t.type === SecurityTaskType.UpdateAtRiskCredential)),
|
||||
),
|
||||
this.cipherService.cipherViews$(user.id).pipe(filterOutNullish()),
|
||||
// A change trigger only: list views, so the vault is not fully decrypted for it.
|
||||
this.cipherService.cipherListViews$(user.id).pipe(filterOutNullish()),
|
||||
]),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
import { mock } from "jest-mock-extended";
|
||||
import { firstValueFrom, Subject } from "rxjs";
|
||||
|
||||
import { Message, MessageListener } from "@bitwarden/common/platform/messaging";
|
||||
import { UserId } from "@bitwarden/common/types/guid";
|
||||
import { CipherService } from "@bitwarden/common/vault/services/cipher.service";
|
||||
import { CipherListView } from "@bitwarden/sdk-internal";
|
||||
|
||||
import { BrowserApi } from "../../platform/browser/browser-api";
|
||||
|
||||
import {
|
||||
CIPHER_LIST_VIEWS_CHANGED,
|
||||
ForegroundCipherService,
|
||||
GET_CIPHER_LIST_VIEWS,
|
||||
} from "./foreground-cipher.service";
|
||||
|
||||
describe("ForegroundCipherService", () => {
|
||||
const userId = "user-id" as UserId;
|
||||
let messages$: Subject<Message<Record<string, unknown>>>;
|
||||
let sendMessageWithResponse: jest.SpyInstance;
|
||||
let service: ForegroundCipherService;
|
||||
|
||||
const listViews = (name: string) => [{ id: "cipher-id", name }] as unknown as CipherListView[];
|
||||
|
||||
beforeEach(() => {
|
||||
messages$ = new Subject();
|
||||
sendMessageWithResponse = jest
|
||||
.spyOn(BrowserApi, "sendMessageWithResponse")
|
||||
.mockResolvedValue({ result: listViews("first") });
|
||||
|
||||
// Only the list-view stream is under test; the inherited dependencies stay mocks.
|
||||
const cipherServiceDeps = Array.from({ length: 14 }, () =>
|
||||
mock<any>(),
|
||||
) as ConstructorParameters<typeof CipherService>;
|
||||
service = new ForegroundCipherService(new MessageListener(messages$), ...cipherServiceDeps);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("takes the list views from the background instead of decrypting them", async () => {
|
||||
const views = await firstValueFrom(service.cipherListViewsIncludingRestricted$(userId));
|
||||
|
||||
expect(views).toEqual(listViews("first"));
|
||||
expect(sendMessageWithResponse).toHaveBeenCalledWith(GET_CIPHER_LIST_VIEWS, { userId });
|
||||
});
|
||||
|
||||
it("fetches again when the background announces new list views", async () => {
|
||||
const emitted: (CipherListView[] | null)[] = [];
|
||||
service.cipherListViewsIncludingRestricted$(userId).subscribe((views) => emitted.push(views));
|
||||
await Promise.resolve();
|
||||
|
||||
sendMessageWithResponse.mockResolvedValue({ result: listViews("second") });
|
||||
messages$.next({ command: CIPHER_LIST_VIEWS_CHANGED });
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
|
||||
expect(emitted.at(-1)).toEqual(listViews("second"));
|
||||
expect(sendMessageWithResponse).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("ignores the overlay's updateOverlayCiphers, which nothing sends anymore", async () => {
|
||||
service.cipherListViewsIncludingRestricted$(userId).subscribe();
|
||||
await Promise.resolve();
|
||||
|
||||
messages$.next({ command: "updateOverlayCiphers" });
|
||||
await Promise.resolve();
|
||||
|
||||
expect(sendMessageWithResponse).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("waits for the background's announcement when the background did not answer", async () => {
|
||||
// Chrome calls back without a response when no listener is registered yet.
|
||||
sendMessageWithResponse.mockResolvedValueOnce(undefined);
|
||||
const emitted: (CipherListView[] | null)[] = [];
|
||||
service.cipherListViewsIncludingRestricted$(userId).subscribe((views) => emitted.push(views));
|
||||
await Promise.resolve();
|
||||
expect(emitted).toEqual([null]);
|
||||
|
||||
messages$.next({ command: CIPHER_LIST_VIEWS_CHANGED });
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
|
||||
expect(emitted.at(-1)).toEqual(listViews("first"));
|
||||
});
|
||||
|
||||
it("drops its copy of the list views when the cache is cleared", async () => {
|
||||
const emitted: (CipherListView[] | null)[] = [];
|
||||
service.cipherListViewsIncludingRestricted$(userId).subscribe((views) => emitted.push(views));
|
||||
await Promise.resolve();
|
||||
|
||||
jest.spyOn(Object.getPrototypeOf(ForegroundCipherService.prototype), "clearCache");
|
||||
Object.getPrototypeOf(ForegroundCipherService.prototype).clearCache.mockResolvedValue(
|
||||
undefined,
|
||||
);
|
||||
await service.clearCache(userId);
|
||||
|
||||
expect(emitted.at(-1)).toBeNull();
|
||||
});
|
||||
});
|
||||
54
apps/browser/src/vault/services/foreground-cipher.service.ts
Normal file
54
apps/browser/src/vault/services/foreground-cipher.service.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import { filter, map, startWith, Subject, switchMap } from "rxjs";
|
||||
|
||||
import { MessageListener } from "@bitwarden/common/platform/messaging";
|
||||
import { UserId } from "@bitwarden/common/types/guid";
|
||||
import { CipherService } from "@bitwarden/common/vault/services/cipher.service";
|
||||
import { perUserCache$ } from "@bitwarden/common/vault/utils/observable-utilities";
|
||||
import { CipherListView } from "@bitwarden/sdk-internal";
|
||||
|
||||
import { BrowserApi } from "../../platform/browser/browser-api";
|
||||
|
||||
export const GET_CIPHER_LIST_VIEWS = "getCipherListViews";
|
||||
|
||||
/** What the background's `ListViewsAnnouncerService` sends each time its list views change. */
|
||||
export const CIPHER_LIST_VIEWS_CHANGED = "cipherListViewsChanged";
|
||||
|
||||
/**
|
||||
* The popup's cipher service. Takes the list views from the background, which already
|
||||
* decrypted them, instead of decrypting the whole vault again on every popup open.
|
||||
*/
|
||||
export class ForegroundCipherService extends CipherService {
|
||||
private readonly clearListViews$ = new Subject<UserId | null>();
|
||||
|
||||
constructor(
|
||||
private readonly messageListener: MessageListener,
|
||||
...cipherServiceArgs: ConstructorParameters<typeof CipherService>
|
||||
) {
|
||||
super(...cipherServiceArgs);
|
||||
}
|
||||
|
||||
// Fetches when opened and whenever the background announces new list views, so the popup
|
||||
// never asks before the background caught up with a change.
|
||||
override cipherListViewsIncludingRestricted$ = perUserCache$(
|
||||
(userId: UserId) =>
|
||||
this.messageListener.allMessages$.pipe(
|
||||
filter((message) => message.command === CIPHER_LIST_VIEWS_CHANGED),
|
||||
startWith(null),
|
||||
switchMap(() =>
|
||||
BrowserApi.sendMessageWithResponse<{ result: CipherListView[] }>(GET_CIPHER_LIST_VIEWS, {
|
||||
userId,
|
||||
}),
|
||||
),
|
||||
// No answer, e.g. from a background still starting after a restart, is not ready yet;
|
||||
// the background announces its list views once it has decrypted them.
|
||||
map((response) => response?.result ?? null),
|
||||
),
|
||||
this.clearListViews$,
|
||||
);
|
||||
|
||||
/** Drops the popup's copy of the list views too, e.g. on lock. */
|
||||
override async clearCache(userId?: UserId): Promise<void> {
|
||||
await super.clearCache(userId);
|
||||
this.clearListViews$.next(userId ?? null);
|
||||
}
|
||||
}
|
||||
@@ -70,7 +70,7 @@
|
||||
"browser-hrtime": "1.1.8",
|
||||
"chalk": "4.1.2",
|
||||
"commander": "14.0.0",
|
||||
"core-js": "3.50.0",
|
||||
"core-js": "3.51.0",
|
||||
"form-data": "4.0.6",
|
||||
"https-proxy-agent": "9.1.0",
|
||||
"inquirer": "8.2.6",
|
||||
|
||||
@@ -94,7 +94,7 @@ export class ConfirmCommand {
|
||||
}
|
||||
|
||||
private async getEncryptedDefaultUserCollectionName(orgKey: OrgKey): Promise<EncString> {
|
||||
const defaultCollectionName = this.i18nService.t("myItems");
|
||||
const defaultCollectionName = this.i18nService.t("myItemsV2");
|
||||
const encrypted = await this.encryptService.encryptString(defaultCollectionName, orgKey);
|
||||
if (encrypted.encryptedString == null) {
|
||||
throw new Error("Failed to encrypt default user collection name.");
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
// @ts-strict-ignore
|
||||
import { mock } from "jest-mock-extended";
|
||||
import { Observable, of } from "rxjs";
|
||||
|
||||
import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view";
|
||||
|
||||
import { GetCommand } from "./get.command";
|
||||
|
||||
@@ -26,4 +29,54 @@ describe("GetCommand", () => {
|
||||
expect(actual.data).toEqual(expected.data);
|
||||
});
|
||||
});
|
||||
|
||||
describe("item lookup by search term", () => {
|
||||
const listViews = [
|
||||
{ id: "c1", name: "Alpha", type: { login: {} } },
|
||||
{ id: "c2", name: "Beta", type: { login: {} } },
|
||||
{ id: "c3", name: "Alpha trashed", type: { login: {} }, deletedDate: "2024-01-01" },
|
||||
];
|
||||
|
||||
function build(listViews$: Observable<unknown>) {
|
||||
const alpha = Object.assign(new CipherView(), { id: "c1", name: "Alpha" });
|
||||
const cipherService = {
|
||||
cipherListViews$: jest.fn().mockReturnValue(listViews$),
|
||||
getAllDecrypted: jest.fn().mockResolvedValue([alpha]),
|
||||
getAllDecryptedForIds: jest.fn().mockResolvedValue([alpha]),
|
||||
};
|
||||
const searchService = {
|
||||
searchCiphersBasic: jest
|
||||
.fn()
|
||||
.mockImplementation((ciphers: any[], query: string) =>
|
||||
ciphers.filter((c) => c.name.toLowerCase().includes(query)),
|
||||
),
|
||||
};
|
||||
const args: any[] = new Array(16).fill(null).map(() => mock());
|
||||
args[0] = cipherService;
|
||||
args[8] = searchService;
|
||||
const getCommand = new (GetCommand as any)(...args);
|
||||
|
||||
return { cipherService, getCommand };
|
||||
}
|
||||
|
||||
it("decrypts only the matching ciphers", async () => {
|
||||
const { cipherService, getCommand } = build(of(listViews));
|
||||
|
||||
await getCommand["getCipherView"]("alpha", "user-1");
|
||||
|
||||
expect(cipherService.getAllDecrypted).not.toHaveBeenCalled();
|
||||
expect(cipherService.getAllDecryptedForIds).toHaveBeenCalledWith("user-1", ["c1"]);
|
||||
});
|
||||
|
||||
// A failed write clears the stream and nothing re-emits it, so waiting would hang.
|
||||
it("decrypts directly when the list views were cleared", async () => {
|
||||
const { cipherService, getCommand } = build(of(null));
|
||||
|
||||
const result = await getCommand["getCipherView"]("alpha", "user-1");
|
||||
|
||||
expect(cipherService.getAllDecrypted).toHaveBeenCalledWith("user-1");
|
||||
expect(cipherService.getAllDecryptedForIds).not.toHaveBeenCalled();
|
||||
expect(result.id).toBe("c1");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -29,6 +29,7 @@ import { PassportExport } from "@bitwarden/common/models/export/passport.export"
|
||||
import { SecureNoteExport } from "@bitwarden/common/models/export/secure-note.export";
|
||||
import { ErrorResponse } from "@bitwarden/common/models/response/error.response";
|
||||
import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service";
|
||||
import { uuidAsString } from "@bitwarden/common/platform/abstractions/sdk/sdk.service";
|
||||
import { getById } from "@bitwarden/common/platform/misc";
|
||||
import { Utils } from "@bitwarden/common/platform/misc/utils";
|
||||
import { CipherId, OrganizationId, UserId } from "@bitwarden/common/types/guid";
|
||||
@@ -39,6 +40,10 @@ import { TotpService } from "@bitwarden/common/vault/abstractions/totp.service";
|
||||
import { CipherType } from "@bitwarden/common/vault/enums";
|
||||
import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view";
|
||||
import { FolderView } from "@bitwarden/common/vault/models/view/folder.view";
|
||||
import {
|
||||
CipherViewLike,
|
||||
CipherViewLikeUtils,
|
||||
} from "@bitwarden/common/vault/utils/cipher-view-like-utils";
|
||||
import { KeyService } from "@bitwarden/key-management";
|
||||
// eslint-disable-next-line no-restricted-imports
|
||||
import { EncryptService, LegacyCompatKeyService } from "@bitwarden/legacy-crypto";
|
||||
@@ -132,9 +137,7 @@ export class GetCommand extends DownloadCommand {
|
||||
decCipher = await this.cipherService.decrypt(cipher, userId);
|
||||
}
|
||||
} else if (id.trim() !== "") {
|
||||
let ciphers = await this.cipherService.getAllDecrypted(userId);
|
||||
ciphers = ciphers.filter((c) => !c.isDeleted && !c.isArchived);
|
||||
ciphers = this.searchService.searchCiphersBasic(ciphers, id);
|
||||
const ciphers = await this.searchCiphers(id, userId);
|
||||
if (ciphers.length > 1) {
|
||||
return ciphers;
|
||||
}
|
||||
@@ -146,6 +149,30 @@ export class GetCommand extends DownloadCommand {
|
||||
return decCipher;
|
||||
}
|
||||
|
||||
/**
|
||||
* Searches the list views and decrypts only the matches, so a lookup does not decrypt the vault.
|
||||
* Falls back to decrypting directly when the views were cleared by a write that failed: nothing
|
||||
* re-emits them, so waiting would hang `bw serve`.
|
||||
*/
|
||||
private async searchCiphers(query: string, userId: UserId): Promise<CipherView[]> {
|
||||
const listViews = await firstValueFrom(this.cipherService.cipherListViews$(userId));
|
||||
|
||||
if (listViews == null) {
|
||||
const all = await this.cipherService.getAllDecrypted(userId);
|
||||
return this.searchService.searchCiphersBasic(all.filter(this.isActive), query);
|
||||
}
|
||||
|
||||
const matches = this.searchService.searchCiphersBasic(listViews.filter(this.isActive), query);
|
||||
|
||||
return await this.cipherService.getAllDecryptedForIds(
|
||||
userId,
|
||||
matches.map((v) => uuidAsString(v.id)),
|
||||
);
|
||||
}
|
||||
|
||||
private isActive = (c: CipherViewLike): boolean =>
|
||||
!CipherViewLikeUtils.isDeleted(c) && !CipherViewLikeUtils.isArchived(c);
|
||||
|
||||
private async getCipher(id: string, filter?: (c: CipherView) => boolean) {
|
||||
const activeUserId = await firstValueFrom(this.accountService.activeAccount$.pipe(getUserId));
|
||||
|
||||
|
||||
99
apps/cli/src/commands/list.command.spec.ts
Normal file
99
apps/cli/src/commands/list.command.spec.ts
Normal file
@@ -0,0 +1,99 @@
|
||||
// @ts-strict-ignore
|
||||
import { of } from "rxjs";
|
||||
|
||||
import { CipherType } from "@bitwarden/common/vault/enums";
|
||||
import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view";
|
||||
import { SecureNoteView } from "@bitwarden/common/vault/models/view/secure-note.view";
|
||||
|
||||
import { ListCommand } from "./list.command";
|
||||
|
||||
function fullView(id: string, name: string, extra: Partial<CipherView> = {}): CipherView {
|
||||
const view = new CipherView();
|
||||
view.id = id;
|
||||
view.name = name;
|
||||
view.type = CipherType.SecureNote;
|
||||
view.secureNote = new SecureNoteView();
|
||||
return Object.assign(view, extra);
|
||||
}
|
||||
|
||||
describe("ListCommand items", () => {
|
||||
let command: ListCommand;
|
||||
let cipherService: any;
|
||||
|
||||
beforeEach(() => {
|
||||
cipherService = {
|
||||
cipherViews$: jest
|
||||
.fn()
|
||||
.mockReturnValue(
|
||||
of([
|
||||
fullView("c1", "Alpha"),
|
||||
fullView("c2", "Beta"),
|
||||
fullView("c3", "Trashed", { deletedDate: new Date() }),
|
||||
]),
|
||||
),
|
||||
getAllDecrypted: jest.fn(),
|
||||
getAllDecryptedForUrl: jest.fn().mockResolvedValue([fullView("c9", "Url match")]),
|
||||
};
|
||||
const searchService = {
|
||||
searchCiphersBasic: jest
|
||||
.fn()
|
||||
.mockImplementation((ciphers: CipherView[], query: string) =>
|
||||
ciphers.filter((c) => c.name.toLowerCase().includes(query.toLowerCase())),
|
||||
),
|
||||
};
|
||||
|
||||
command = new ListCommand(
|
||||
cipherService,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
searchService as any,
|
||||
null,
|
||||
null,
|
||||
{ collectMany: jest.fn() } as any,
|
||||
{ activeAccount$: of({ id: "user-1" }) } as any,
|
||||
null,
|
||||
{ filterRestrictedCiphers: jest.fn().mockImplementation(async (c) => c) } as any,
|
||||
{ userCanArchive$: jest.fn().mockReturnValue(of(false)) } as any,
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
const listedIds = (response: any): string[] => response.data.data.map((i: any) => i.id);
|
||||
|
||||
it("reads the cached stream instead of decrypting the vault", async () => {
|
||||
const response = await command.run("items", {});
|
||||
|
||||
expect(cipherService.getAllDecrypted).not.toHaveBeenCalled();
|
||||
expect(listedIds(response)).toEqual(["c1", "c2"]);
|
||||
});
|
||||
|
||||
it("filters by search", async () => {
|
||||
const response = await command.run("items", { search: "beta" });
|
||||
|
||||
expect(listedIds(response)).toEqual(["c2"]);
|
||||
});
|
||||
|
||||
it("lists the trash on request", async () => {
|
||||
const response = await command.run("items", { trash: true });
|
||||
|
||||
expect(listedIds(response)).toEqual(["c3"]);
|
||||
});
|
||||
|
||||
it("matches a URL without the cached stream", async () => {
|
||||
const response = await command.run("items", { url: "https://example.com" });
|
||||
|
||||
expect(cipherService.cipherViews$).not.toHaveBeenCalled();
|
||||
expect(listedIds(response)).toEqual(["c9"]);
|
||||
});
|
||||
|
||||
// A failed write clears the stream and nothing re-emits it, so waiting would hang.
|
||||
it("decrypts directly when the cached stream was cleared", async () => {
|
||||
cipherService.cipherViews$.mockReturnValue(of(null));
|
||||
cipherService.getAllDecrypted.mockResolvedValue([fullView("c1", "Alpha")]);
|
||||
|
||||
const response = await command.run("items", {});
|
||||
|
||||
expect(listedIds(response)).toEqual(["c1"]);
|
||||
});
|
||||
});
|
||||
@@ -87,7 +87,11 @@ export class ListCommand {
|
||||
if (options.url != null && options.url.trim() !== "") {
|
||||
ciphers = await this.cipherService.getAllDecryptedForUrl(options.url, activeUserId);
|
||||
} else {
|
||||
ciphers = await this.cipherService.getAllDecrypted(activeUserId);
|
||||
// The cached stream, so repeated requests (`bw serve`) do not decrypt the vault each time.
|
||||
// Null once a write failed after clearing it: nothing re-emits, so decrypt directly.
|
||||
ciphers =
|
||||
(await firstValueFrom(this.cipherService.cipherViews$(activeUserId))) ??
|
||||
(await this.cipherService.getAllDecrypted(activeUserId));
|
||||
}
|
||||
|
||||
if (
|
||||
|
||||
@@ -273,8 +273,8 @@
|
||||
"youHaveBeenLoggedOut": {
|
||||
"message": "You have been logged out."
|
||||
},
|
||||
"myItems": {
|
||||
"message": "My Items"
|
||||
"myItemsV2": {
|
||||
"message": "My items"
|
||||
},
|
||||
"organizationUsingKeyConnectorConfirmLoggedOut": {
|
||||
"message": "An organization you are a member of is using Key Connector. In order to access the vault, you must confirm the Key Connector domain now via the web vault. You have been logged out."
|
||||
|
||||
@@ -787,7 +787,6 @@ export class ServiceContainer {
|
||||
this.collectionEncryptionService = new DefaultCollectionEncryptionService(
|
||||
this.sdkService,
|
||||
this.logService,
|
||||
this.configService,
|
||||
);
|
||||
|
||||
this.collectionService = new DefaultCollectionService(
|
||||
|
||||
@@ -38,6 +38,8 @@
|
||||
<string>/Library/Application Support/Vivaldi/NativeMessagingHosts/</string>
|
||||
<string>/Library/Application Support/Zen/NativeMessagingHosts/</string>
|
||||
<string>/Library/Application Support/net.imput.helium/NativeMessagingHosts/</string>
|
||||
<string>/Library/Application Support/Arbalete/NativeMessagingHosts/</string>
|
||||
<string>/Library/Application Support/Arbalete Dev/NativeMessagingHosts/</string>
|
||||
<string>/Library/Application Support/BraveSoftware/Brave-Browser/NativeMessagingHosts/</string>
|
||||
<string>/Library/Application Support/BraveSoftware/Brave-Browser-Beta/NativeMessagingHosts/</string>
|
||||
<string>/Library/Application Support/BraveSoftware/Brave-Browser-Nightly/NativeMessagingHosts/</string>
|
||||
|
||||
@@ -8,7 +8,10 @@ import { BehaviorSubject, EMPTY, firstValueFrom, from, fromEvent } from "rxjs";
|
||||
import { catchError, concatMap, map, switchMap, timeout } from "rxjs/operators";
|
||||
|
||||
import { PremiumBadgeComponent } from "@bitwarden/angular/billing/components/premium-badge";
|
||||
import { AutotypeShortcutComponent } from "@bitwarden/angular/desktop-native/components/autotype-shortcut.component";
|
||||
import {
|
||||
AutotypeShortcutComponent,
|
||||
formatAutotypeShortcut,
|
||||
} from "@bitwarden/angular/desktop-native/components/autotype-shortcut.component";
|
||||
import { PolicyService } from "@bitwarden/common/admin-console/abstractions/policy/policy.service.abstraction";
|
||||
import { PolicyType } from "@bitwarden/common/admin-console/enums";
|
||||
import { getFirstPolicy } from "@bitwarden/common/admin-console/services/policy/default-policy.service";
|
||||
@@ -843,7 +846,7 @@ export class SettingsDialogComponent implements OnInit {
|
||||
}
|
||||
|
||||
private getFormattedAutotypeShortcutText(shortcut: string[]) {
|
||||
return shortcut ? shortcut.join("+").replace("Super", "Win") : null;
|
||||
return shortcut ? formatAutotypeShortcut(shortcut) : null;
|
||||
}
|
||||
|
||||
static open(dialogService: DialogService) {
|
||||
|
||||
@@ -15,6 +15,12 @@ import {
|
||||
} from "@bitwarden/angular/auth/guards";
|
||||
import { ChangePasswordComponent } from "@bitwarden/angular/auth/password-management/change-password";
|
||||
import { SetInitialPasswordComponent } from "@bitwarden/angular/auth/password-management/set-initial-password/set-initial-password.component";
|
||||
import {
|
||||
RegistrationFinishComponent,
|
||||
RegistrationStartComponent,
|
||||
RegistrationStartSecondaryComponent,
|
||||
RegistrationStartSecondaryComponentData,
|
||||
} from "@bitwarden/angular/auth/registration";
|
||||
import { canAccessFeature } from "@bitwarden/angular/platform/guard/feature-flag.guard";
|
||||
import { featureFlaggedRoute } from "@bitwarden/angular/platform/utils/feature-flagged-route";
|
||||
import {
|
||||
@@ -32,10 +38,6 @@ import {
|
||||
LoginSecondaryContentComponent,
|
||||
LoginViaAuthRequestComponent,
|
||||
PasswordHintComponent,
|
||||
RegistrationFinishComponent,
|
||||
RegistrationStartComponent,
|
||||
RegistrationStartSecondaryComponent,
|
||||
RegistrationStartSecondaryComponentData,
|
||||
LoginDecryptionOptionsComponent,
|
||||
SsoComponent,
|
||||
TwoFactorAuthComponent,
|
||||
|
||||
@@ -532,6 +532,7 @@ const safeProviders: SafeProvider[] = [
|
||||
DesktopFido2UserVerificationService,
|
||||
PasswordRepromptService,
|
||||
DomainSettingsService,
|
||||
MessageListener,
|
||||
],
|
||||
}),
|
||||
safeProvider({
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<bit-dialog [title]="'share' | i18n" dialogSize="large">
|
||||
<bit-dialog [title]="'share' | i18n">
|
||||
<ng-container bitDialogContent>
|
||||
<app-share-item-form [cipher]="data.cipher"></app-share-item-form>
|
||||
</ng-container>
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import {
|
||||
DEFAULT_AUTOTYPE_GA_KEYBOARD_SHORTCUT,
|
||||
isAutotypeGaShortcut,
|
||||
} from "@bitwarden/common/desktop-native/models/autotype-ga-policy.data";
|
||||
|
||||
/**
|
||||
Electron's representation of modifier keys
|
||||
<https://www.electronjs.org/docs/latest/tutorial/keyboard-shortcuts#cross-platform-modifiers>
|
||||
*/
|
||||
export const CONTROL_KEY_STR = "Control";
|
||||
export const ALT_KEY_STR = "Alt";
|
||||
export const SUPER_KEY_STR = "Super";
|
||||
|
||||
export const VALID_SHORTCUT_MODIFIER_KEYS: string[] = [CONTROL_KEY_STR, ALT_KEY_STR, SUPER_KEY_STR];
|
||||
|
||||
export const DEFAULT_KEYBOARD_SHORTCUT: string[] = [CONTROL_KEY_STR, ALT_KEY_STR, "B"];
|
||||
// Shared with the web Autotype GA policy, which shows this as its Default option
|
||||
export const DEFAULT_KEYBOARD_SHORTCUT: string[] = [...DEFAULT_AUTOTYPE_GA_KEYBOARD_SHORTCUT];
|
||||
|
||||
/*
|
||||
This class provides the following:
|
||||
@@ -30,8 +30,8 @@ export class AutotypeKeyboardShortcut {
|
||||
Returns a boolean value indicating if the autotypeKeyboardShortcut
|
||||
was valid and set or not.
|
||||
*/
|
||||
set(newAutotypeKeyboardShortcut: string[]) {
|
||||
if (!this.#keyboardShortcutIsValid(newAutotypeKeyboardShortcut)) {
|
||||
set(newAutotypeKeyboardShortcut: string[]): boolean {
|
||||
if (!isAutotypeGaShortcut(newAutotypeKeyboardShortcut)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -56,55 +56,4 @@ export class AutotypeKeyboardShortcut {
|
||||
getElectronFormat() {
|
||||
return this.autotypeKeyboardShortcut.join("+");
|
||||
}
|
||||
|
||||
/*
|
||||
This private function validates the strArray input to make sure the array contains
|
||||
valid, currently accepted shortcut keys for Windows.
|
||||
|
||||
Valid shortcut keys: Control, Alt, Super, letters A - Z
|
||||
Platform specifics:
|
||||
- On Windows, Super maps to the Windows key.
|
||||
- On MacOS, Super maps to the Command key.
|
||||
- On MacOS, Alt maps to the Option key.
|
||||
|
||||
See Electron keyboard shortcut docs for more info:
|
||||
https://www.electronjs.org/docs/latest/tutorial/keyboard-shortcuts
|
||||
*/
|
||||
#keyboardShortcutIsValid(strArray: string[]) {
|
||||
const UNICODE_LOWER_BOUND = 65; // unicode 'A'
|
||||
const UNICODE_UPPER_BOUND = 90; // unicode 'Z'
|
||||
const MIN_LENGTH: number = 2;
|
||||
const MAX_LENGTH: number = 3;
|
||||
|
||||
// Ensure strArray is a string array of valid length
|
||||
if (
|
||||
strArray === undefined ||
|
||||
strArray === null ||
|
||||
strArray.length < MIN_LENGTH ||
|
||||
strArray.length > MAX_LENGTH
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Ensure strArray is all modifier keys, and that the last key is a letter
|
||||
for (let i = 0; i < strArray.length; i++) {
|
||||
if (i < strArray.length - 1) {
|
||||
if (!VALID_SHORTCUT_MODIFIER_KEYS.includes(strArray[i])) {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
const unicodeValue: number = strArray[i].charCodeAt(0);
|
||||
|
||||
if (
|
||||
Number.isNaN(unicodeValue) ||
|
||||
unicodeValue < UNICODE_LOWER_BOUND ||
|
||||
unicodeValue > UNICODE_UPPER_BOUND
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import { BehaviorSubject, firstValueFrom, take } from "rxjs";
|
||||
|
||||
import { PolicyService } from "@bitwarden/common/admin-console/abstractions/policy/policy.service.abstraction";
|
||||
import { PolicyType } from "@bitwarden/common/admin-console/enums";
|
||||
import { Policy } from "@bitwarden/common/admin-console/models/domain/policy";
|
||||
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
|
||||
import { AuthService } from "@bitwarden/common/auth/abstractions/auth.service";
|
||||
import { AuthenticationStatus } from "@bitwarden/common/auth/enums/authentication-status";
|
||||
@@ -30,6 +31,7 @@ describe("DesktopAutotypeGaPolicyService", () => {
|
||||
let featureFlagSubject: BehaviorSubject<AutotypeFeatureFlagState>;
|
||||
let mockAuthStatusSubject: BehaviorSubject<AuthenticationStatus>;
|
||||
let mockPolicyAppliesSubject: BehaviorSubject<boolean>;
|
||||
let mockPoliciesSubject: BehaviorSubject<Policy[]>;
|
||||
|
||||
const mockUserId = "user-123" as UserId;
|
||||
|
||||
@@ -46,6 +48,7 @@ describe("DesktopAutotypeGaPolicyService", () => {
|
||||
AuthenticationStatus.Unlocked,
|
||||
);
|
||||
mockPolicyAppliesSubject = new BehaviorSubject<boolean>(false);
|
||||
mockPoliciesSubject = new BehaviorSubject<Policy[]>([]);
|
||||
|
||||
accountService = mock<AccountService>();
|
||||
authService = mock<AuthService>();
|
||||
@@ -60,6 +63,7 @@ describe("DesktopAutotypeGaPolicyService", () => {
|
||||
policyService.policyAppliesToUser$ = jest
|
||||
.fn()
|
||||
.mockReturnValue(mockPolicyAppliesSubject.asObservable());
|
||||
policyService.policiesByType$ = jest.fn().mockReturnValue(mockPoliciesSubject.asObservable());
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
@@ -80,6 +84,7 @@ describe("DesktopAutotypeGaPolicyService", () => {
|
||||
featureFlagSubject.complete();
|
||||
mockAuthStatusSubject.complete();
|
||||
mockPolicyAppliesSubject.complete();
|
||||
mockPoliciesSubject.complete();
|
||||
});
|
||||
|
||||
describe("autotypeGaDefaultSetting$", () => {
|
||||
@@ -246,4 +251,99 @@ describe("DesktopAutotypeGaPolicyService", () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("autotypeGaDefaultKeyboardShortcut$", () => {
|
||||
const policyWith = (data: unknown, enabled = true, organizationId = "org-1") =>
|
||||
({ enabled, data, organizationId }) as Policy;
|
||||
|
||||
const custom = (defaultKeyboardShortcut: unknown, organizationId = "org-1", enabled = true) =>
|
||||
policyWith({ shortcutOption: "custom", defaultKeyboardShortcut }, enabled, organizationId);
|
||||
|
||||
const latest = () => firstValueFrom(service.autotypeGaDefaultKeyboardShortcut$.pipe(take(1)));
|
||||
|
||||
const record = () => {
|
||||
const emissions: (string[] | null)[] = [];
|
||||
const subscription = service.autotypeGaDefaultKeyboardShortcut$.subscribe((value) =>
|
||||
emissions.push(value),
|
||||
);
|
||||
return { emissions, subscription };
|
||||
};
|
||||
|
||||
it("emits the enabled custom shortcut for the active user", async () => {
|
||||
mockPoliciesSubject.next([custom(["Super", "K"])]);
|
||||
|
||||
expect(await latest()).toEqual(["Super", "K"]);
|
||||
expect(policyService.policiesByType$).toHaveBeenCalledWith(
|
||||
PolicyType.AutotypeGaPolicy,
|
||||
mockUserId,
|
||||
);
|
||||
});
|
||||
|
||||
it("skips policies that do not yield a registerable custom shortcut", () => {
|
||||
const { emissions, subscription } = record();
|
||||
|
||||
for (const policies of [
|
||||
[],
|
||||
[custom(["Super", "K"], "org-1", false)],
|
||||
[policyWith(null)],
|
||||
[
|
||||
policyWith({
|
||||
shortcutOption: "default",
|
||||
defaultKeyboardShortcut: ["Control", "Alt", "B"],
|
||||
}),
|
||||
],
|
||||
[custom(["Shift", "1"])],
|
||||
[custom(["Control", "Bogus"])],
|
||||
[custom(["Alt", "Alt", "K"])],
|
||||
[custom(["Control", 5])],
|
||||
]) {
|
||||
mockPoliciesSubject.next(policies);
|
||||
}
|
||||
|
||||
mockPoliciesSubject.next([custom(["Super", "K"])]);
|
||||
mockPoliciesSubject.next([custom(["Super", "K"])]);
|
||||
mockPoliciesSubject.next([custom(["Alt", "Q"])]);
|
||||
|
||||
expect(emissions).toEqual([null, ["Super", "K"], ["Alt", "Q"]]);
|
||||
subscription.unsubscribe();
|
||||
});
|
||||
|
||||
it("uses the custom shortcut from the organization with the lowest id", async () => {
|
||||
mockPoliciesSubject.next([
|
||||
custom(["Alt", "Q"], "org-b"),
|
||||
custom(["Control", "L"], "org-0", false),
|
||||
policyWith(
|
||||
{ shortcutOption: "default", defaultKeyboardShortcut: ["Control", "Alt", "B"] },
|
||||
true,
|
||||
"org-1",
|
||||
),
|
||||
custom(["Super", "K"], "org-a"),
|
||||
]);
|
||||
|
||||
expect(await latest()).toEqual(["Super", "K"]);
|
||||
});
|
||||
|
||||
it("emits null unless the GA flag is on for an unlocked account", async () => {
|
||||
mockPoliciesSubject.next([custom(["Super", "K"])]);
|
||||
featureFlagSubject.next(AutotypeFeatureFlagState.Mvp);
|
||||
|
||||
expect(await latest()).toBeNull();
|
||||
expect(policyService.policiesByType$).not.toHaveBeenCalled();
|
||||
|
||||
featureFlagSubject.next(AutotypeFeatureFlagState.Ga);
|
||||
mockAuthStatusSubject.next(AuthenticationStatus.Locked);
|
||||
expect(await latest()).toBeNull();
|
||||
});
|
||||
|
||||
it("emits null while locked and the shortcut again after unlock", () => {
|
||||
mockPoliciesSubject.next([custom(["Super", "K"])]);
|
||||
const { emissions, subscription } = record();
|
||||
|
||||
mockAuthStatusSubject.next(AuthenticationStatus.Locked);
|
||||
mockAuthStatusSubject.next(AuthenticationStatus.Unlocked);
|
||||
|
||||
expect(emissions).toEqual([["Super", "K"], null, ["Super", "K"]]);
|
||||
subscription.unsubscribe();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,13 +4,20 @@ import { distinctUntilChanged, filter, map, shareReplay, switchMap } from "rxjs/
|
||||
|
||||
import { PolicyService } from "@bitwarden/common/admin-console/abstractions/policy/policy.service.abstraction";
|
||||
import { PolicyType } from "@bitwarden/common/admin-console/enums";
|
||||
import { Policy } from "@bitwarden/common/admin-console/models/domain/policy";
|
||||
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
|
||||
import { AuthService } from "@bitwarden/common/auth/abstractions/auth.service";
|
||||
import { AuthenticationStatus } from "@bitwarden/common/auth/enums/authentication-status";
|
||||
import { getUserId } from "@bitwarden/common/auth/services/account.service";
|
||||
import { AutotypeFeatureFlagState } from "@bitwarden/common/desktop-native/enums/autotype-feature-flag-state.enum";
|
||||
import {
|
||||
AutotypeGaPolicyData,
|
||||
AutotypeShortcutOption,
|
||||
isAutotypeGaShortcut,
|
||||
} from "@bitwarden/common/desktop-native/models/autotype-ga-policy.data";
|
||||
import { autotypeFeatureFlagState$ } from "@bitwarden/common/desktop-native/services/autotype-feature-flags";
|
||||
import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service";
|
||||
import { UserId } from "@bitwarden/common/types/guid";
|
||||
|
||||
@Injectable({ providedIn: "root" })
|
||||
export class DesktopAutotypeGaPolicyService {
|
||||
@@ -21,35 +28,68 @@ export class DesktopAutotypeGaPolicyService {
|
||||
private readonly configService: ConfigService,
|
||||
) {}
|
||||
|
||||
readonly autotypeGaDefaultSetting$: Observable<boolean | null> = autotypeFeatureFlagState$(
|
||||
this.configService,
|
||||
).pipe(
|
||||
switchMap((autotypeFeatureFlagState) => {
|
||||
if (autotypeFeatureFlagState !== AutotypeFeatureFlagState.Ga) {
|
||||
return of(null);
|
||||
}
|
||||
|
||||
return this.accountService.activeAccount$.pipe(
|
||||
filter((account) => account != null && account.id != null),
|
||||
getUserId,
|
||||
readonly autotypeGaDefaultSetting$: Observable<boolean | null> = this.whenGaAndUnlocked$(
|
||||
(userId) =>
|
||||
this.policyService.policyAppliesToUser$(PolicyType.AutotypeGaPolicy, userId).pipe(
|
||||
map((applies) => (applies ? true : null)),
|
||||
distinctUntilChanged(),
|
||||
switchMap((userId) => {
|
||||
const isUnlocked$ = this.authService.authStatusFor$(userId).pipe(
|
||||
map((status) => status === AuthenticationStatus.Unlocked),
|
||||
distinctUntilChanged(),
|
||||
);
|
||||
),
|
||||
);
|
||||
|
||||
const policy$ = this.policyService
|
||||
.policyAppliesToUser$(PolicyType.AutotypeGaPolicy, userId)
|
||||
.pipe(
|
||||
map((applies) => (applies ? true : null)),
|
||||
// The custom shortcut from the Autotype GA policy, or null when there is none.
|
||||
readonly autotypeGaDefaultKeyboardShortcut$: Observable<string[] | null> =
|
||||
this.whenGaAndUnlocked$((userId) =>
|
||||
this.policyService.policiesByType$(PolicyType.AutotypeGaPolicy, userId).pipe(
|
||||
map((policies) => this.shortcutFromPolicies(policies)),
|
||||
distinctUntilChanged((a, b) => a?.join("+") === b?.join("+")),
|
||||
),
|
||||
);
|
||||
|
||||
/** Lowest organization id. Default and invalid shortcuts are skipped, so sync order does not matter. */
|
||||
private shortcutFromPolicies(policies: Policy[]): string[] | null {
|
||||
return (
|
||||
policies
|
||||
.filter((policy) => policy.enabled)
|
||||
.sort((a, b) => a.organizationId.localeCompare(b.organizationId))
|
||||
.map((policy) => this.shortcutFromPolicy(policy.data))
|
||||
.find((shortcut) => shortcut != null) ?? null
|
||||
);
|
||||
}
|
||||
|
||||
private shortcutFromPolicy(data: Partial<AutotypeGaPolicyData> | undefined): string[] | null {
|
||||
const keys = data?.defaultKeyboardShortcut;
|
||||
return data?.shortcutOption === AutotypeShortcutOption.Custom && isAutotypeGaShortcut(keys)
|
||||
? keys
|
||||
: null;
|
||||
}
|
||||
|
||||
/** Emits the active user's policy value while the GA flag is on and the vault is unlocked, otherwise null. */
|
||||
private whenGaAndUnlocked$<T>(
|
||||
userPolicy$: (userId: UserId) => Observable<T | null>,
|
||||
): Observable<T | null> {
|
||||
return autotypeFeatureFlagState$(this.configService).pipe(
|
||||
switchMap((autotypeFeatureFlagState) => {
|
||||
if (autotypeFeatureFlagState !== AutotypeFeatureFlagState.Ga) {
|
||||
return of(null);
|
||||
}
|
||||
|
||||
return this.accountService.activeAccount$.pipe(
|
||||
filter((account) => account != null && account.id != null),
|
||||
getUserId,
|
||||
distinctUntilChanged(),
|
||||
switchMap((userId) => {
|
||||
const isUnlocked$ = this.authService.authStatusFor$(userId).pipe(
|
||||
map((status) => status === AuthenticationStatus.Unlocked),
|
||||
distinctUntilChanged(),
|
||||
);
|
||||
|
||||
return isUnlocked$.pipe(switchMap((unlocked) => (unlocked ? policy$ : of(null))));
|
||||
}),
|
||||
);
|
||||
}),
|
||||
shareReplay({ bufferSize: 1, refCount: true }),
|
||||
);
|
||||
return isUnlocked$.pipe(
|
||||
switchMap((unlocked) => (unlocked ? userPolicy$(userId) : of(null))),
|
||||
);
|
||||
}),
|
||||
);
|
||||
}),
|
||||
shareReplay({ bufferSize: 1, refCount: true }),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,6 +15,8 @@ import { UserId } from "@bitwarden/common/types/guid";
|
||||
import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service";
|
||||
import { LogService } from "@bitwarden/logging";
|
||||
|
||||
import { DEFAULT_KEYBOARD_SHORTCUT } from "../models/main-autotype-keyboard-shortcut";
|
||||
|
||||
import { DesktopAutotypeGaPolicyService } from "./desktop-autotype-ga-policy.service";
|
||||
import { DesktopAutotypeService } from "./desktop-autotype.service";
|
||||
|
||||
@@ -38,8 +40,9 @@ describe("DesktopAutotypeService", () => {
|
||||
let mockAutotypeKeyboardShortcutState: FakeGlobalState<string[]>;
|
||||
|
||||
let autotypeEnabledSubject: BehaviorSubject<boolean | null>;
|
||||
let autotypeKeyboardShortcutSubject: BehaviorSubject<string[]>;
|
||||
let autotypeKeyboardShortcutSubject: BehaviorSubject<string[] | null>;
|
||||
let autotypeGaPolicySubject: BehaviorSubject<boolean | null>;
|
||||
let autotypeGaPolicyShortcutSubject: BehaviorSubject<string[] | null>;
|
||||
let activeAccountSubject: BehaviorSubject<Account | null>;
|
||||
let activeAccountStatusSubject: BehaviorSubject<AuthenticationStatus>;
|
||||
let hasPremiumSubject: BehaviorSubject<boolean>;
|
||||
@@ -62,8 +65,9 @@ describe("DesktopAutotypeService", () => {
|
||||
|
||||
beforeEach(() => {
|
||||
autotypeEnabledSubject = new BehaviorSubject<boolean | null>(null);
|
||||
autotypeKeyboardShortcutSubject = new BehaviorSubject<string[]>(["Control", "Alt", "B"]);
|
||||
autotypeKeyboardShortcutSubject = new BehaviorSubject<string[] | null>(["Control", "Alt", "B"]);
|
||||
autotypeGaPolicySubject = new BehaviorSubject<boolean | null>(null);
|
||||
autotypeGaPolicyShortcutSubject = new BehaviorSubject<string[] | null>(null);
|
||||
activeAccountSubject = new BehaviorSubject<Account | null>({
|
||||
id: "user-123" as UserId,
|
||||
email: "user@bitwarden.com",
|
||||
@@ -143,7 +147,10 @@ describe("DesktopAutotypeService", () => {
|
||||
},
|
||||
{
|
||||
provide: DesktopAutotypeGaPolicyService,
|
||||
useValue: { autotypeGaDefaultSetting$: autotypeGaPolicySubject.asObservable() },
|
||||
useValue: {
|
||||
autotypeGaDefaultSetting$: autotypeGaPolicySubject.asObservable(),
|
||||
autotypeGaDefaultKeyboardShortcut$: autotypeGaPolicyShortcutSubject.asObservable(),
|
||||
},
|
||||
},
|
||||
{ provide: LogService, useValue: mock<LogService>() },
|
||||
],
|
||||
@@ -236,6 +243,55 @@ describe("DesktopAutotypeService", () => {
|
||||
|
||||
expect(autotypeEnabledSubject.value).toBe(false);
|
||||
});
|
||||
|
||||
it("stores the policy shortcut when the local shortcut has never been set", async () => {
|
||||
autotypeKeyboardShortcutSubject.next(null);
|
||||
autotypeGaPolicyShortcutSubject.next(["Super", "K"]);
|
||||
|
||||
await service.init();
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
expect(autotypeKeyboardShortcutSubject.value).toEqual(["Super", "K"]);
|
||||
expect(await firstValueFrom(service.autotypeKeyboardShortcut$)).toEqual(["Super", "K"]);
|
||||
});
|
||||
|
||||
it("does not overwrite a stored shortcut when the policy shortcut changes", async () => {
|
||||
autotypeKeyboardShortcutSubject.next(null);
|
||||
autotypeGaPolicyShortcutSubject.next(["Super", "K"]);
|
||||
|
||||
await service.init();
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
autotypeGaPolicyShortcutSubject.next(["Alt", "Q"]);
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
expect(mockAutotypeKeyboardShortcutState.update).toHaveBeenCalledTimes(1);
|
||||
expect(autotypeKeyboardShortcutSubject.value).toEqual(["Super", "K"]);
|
||||
});
|
||||
|
||||
it("does not overwrite a local keyboard shortcut the user already chose", async () => {
|
||||
autotypeKeyboardShortcutSubject.next(["Control", "Alt", "A"]);
|
||||
autotypeGaPolicyShortcutSubject.next(["Super", "K"]);
|
||||
|
||||
await service.init();
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
expect(mockAutotypeKeyboardShortcutState.update).not.toHaveBeenCalled();
|
||||
expect(autotypeKeyboardShortcutSubject.value).toEqual(["Control", "Alt", "A"]);
|
||||
});
|
||||
|
||||
it("uses the built-in shortcut when there is no local shortcut and no policy shortcut", async () => {
|
||||
autotypeKeyboardShortcutSubject.next(null);
|
||||
|
||||
await service.init();
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
expect(await firstValueFrom(service.autotypeKeyboardShortcut$)).toEqual(
|
||||
DEFAULT_KEYBOARD_SHORTCUT,
|
||||
);
|
||||
expect(mockAutotypeKeyboardShortcutState.update).not.toHaveBeenCalled();
|
||||
expect(autotypeKeyboardShortcutSubject.value).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("setAutotypeEnabledState", () => {
|
||||
|
||||
@@ -139,6 +139,24 @@ export class DesktopAutotypeService implements OnDestroy {
|
||||
)
|
||||
.subscribe();
|
||||
|
||||
combineLatest([
|
||||
this.autotypeKeyboardShortcutState.state$,
|
||||
this.desktopAutotypeGaPolicyService.autotypeGaDefaultKeyboardShortcut$,
|
||||
])
|
||||
.pipe(
|
||||
concatMap(async ([keyboardShortcutState, policyKeyboardShortcut]) => {
|
||||
try {
|
||||
if (policyKeyboardShortcut != null && keyboardShortcutState == null) {
|
||||
await this.setAutotypeKeyboardShortcutState(policyKeyboardShortcut);
|
||||
}
|
||||
} catch {
|
||||
this.logService.error("Failed to set Autotype keyboard shortcut.");
|
||||
}
|
||||
}),
|
||||
takeUntil(this.destroy$),
|
||||
)
|
||||
.subscribe();
|
||||
|
||||
// Listen for changes in keyboard shortcut settings
|
||||
this.autotypeKeyboardShortcut$
|
||||
.pipe(
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Router } from "@angular/router";
|
||||
import { mock, MockProxy } from "jest-mock-extended";
|
||||
import { BehaviorSubject, of } from "rxjs";
|
||||
import { BehaviorSubject, of, Subject } from "rxjs";
|
||||
|
||||
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
|
||||
import { AuthService } from "@bitwarden/common/auth/abstractions/auth.service";
|
||||
@@ -8,6 +8,7 @@ import { AuthenticationStatus } from "@bitwarden/common/auth/enums/authenticatio
|
||||
import { DomainSettingsService } from "@bitwarden/common/autofill/services/domain-settings.service";
|
||||
import { Fido2AuthenticatorErrorCode } from "@bitwarden/common/platform/abstractions/fido2/fido2-authenticator.service.abstraction";
|
||||
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
|
||||
import { MessageListener } from "@bitwarden/common/platform/messaging";
|
||||
import { Fido2Utils } from "@bitwarden/common/platform/services/fido2/fido2-utils";
|
||||
import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service";
|
||||
import { CipherRepromptType, CipherType } from "@bitwarden/common/vault/enums";
|
||||
@@ -75,6 +76,7 @@ describe("DesktopFido2UserInterfaceSession", () => {
|
||||
let userVerificationService: MockProxy<DesktopFido2UserVerificationService>;
|
||||
let passwordRepromptService: MockProxy<PasswordRepromptService>;
|
||||
let domainSettingsService: MockProxy<DomainSettingsService>;
|
||||
let messages$: Subject<{ command: string }>;
|
||||
|
||||
let activeAccountStatus$: BehaviorSubject<AuthenticationStatus>;
|
||||
let abortController: AbortController;
|
||||
@@ -109,6 +111,8 @@ describe("DesktopFido2UserInterfaceSession", () => {
|
||||
domainSettingsService = mock<DomainSettingsService>();
|
||||
domainSettingsService.getUrlEquivalentDomains.mockReturnValue(of(new Set<string>()));
|
||||
|
||||
messages$ = new Subject();
|
||||
|
||||
activeAccountStatus$ = new BehaviorSubject<AuthenticationStatus>(AuthenticationStatus.Unlocked);
|
||||
authService.activeAccountStatus$ = activeAccountStatus$;
|
||||
accountService.activeAccount$ = new BehaviorSubject({ id: "user-1" } as any);
|
||||
@@ -171,6 +175,7 @@ describe("DesktopFido2UserInterfaceSession", () => {
|
||||
userVerificationService,
|
||||
passwordRepromptService,
|
||||
domainSettingsService,
|
||||
new MessageListener(messages$),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -537,6 +542,40 @@ describe("DesktopFido2UserInterfaceSession", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("closing the window", () => {
|
||||
const closeWindow = () => messages$.next({ command: "modalWindowClosed" });
|
||||
|
||||
it("cancels a ceremony waiting on the lock screen", async () => {
|
||||
activeAccountStatus$.next(AuthenticationStatus.Locked);
|
||||
|
||||
const result = session.ensureUnlockedVault();
|
||||
await tick();
|
||||
closeWindow();
|
||||
|
||||
await expect(result).rejects.toThrow("Could not retrieve vault unlock status");
|
||||
expect(desktopSettingsService.setModalMode).toHaveBeenCalledWith(false);
|
||||
});
|
||||
|
||||
it("does not cancel a ceremony that is not showing UI", async () => {
|
||||
closeWindow();
|
||||
|
||||
expect(abortController.signal.aborted).toBe(false);
|
||||
});
|
||||
|
||||
it("does not cancel once the ceremony has hidden its UI", async () => {
|
||||
activeAccountStatus$.next(AuthenticationStatus.Locked);
|
||||
const result = session.ensureUnlockedVault();
|
||||
await tick();
|
||||
activeAccountStatus$.next(AuthenticationStatus.Unlocked);
|
||||
await result;
|
||||
await session.hideUi();
|
||||
|
||||
closeWindow();
|
||||
|
||||
expect(abortController.signal.aborted).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("informExcludedCredential", () => {
|
||||
it("shows the excluded credentials UI and waits for the user to dismiss it", async () => {
|
||||
const result = session.informExcludedCredential(["cipher-1"]);
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
switchMap,
|
||||
throwError,
|
||||
MonoTypeOperatorFunction,
|
||||
Subscription,
|
||||
} from "rxjs";
|
||||
|
||||
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
|
||||
@@ -29,6 +30,7 @@ import {
|
||||
} from "@bitwarden/common/platform/abstractions/fido2/fido2-user-interface.service.abstraction";
|
||||
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
|
||||
import { MessagingService } from "@bitwarden/common/platform/abstractions/messaging.service";
|
||||
import { CommandDefinition, MessageListener } from "@bitwarden/common/platform/messaging";
|
||||
import { Fido2Utils } from "@bitwarden/common/platform/services/fido2/fido2-utils";
|
||||
import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service";
|
||||
import { CipherRepromptType, CipherType, SecureNoteType } from "@bitwarden/common/vault/enums";
|
||||
@@ -91,6 +93,12 @@ export type NativeWindowObject = {
|
||||
userHandle?: number[];
|
||||
};
|
||||
|
||||
/**
|
||||
* Sent by the main process when the user closes the app window while it is in
|
||||
* modal mode, i.e. while a ceremony is showing its UI in it.
|
||||
*/
|
||||
const MODAL_WINDOW_CLOSED = new CommandDefinition("modalWindowClosed");
|
||||
|
||||
/** A ceremony that can be refused because of its RP ID. */
|
||||
export type RpIdNotAllowedOperation = "registration" | "assertion";
|
||||
|
||||
@@ -152,6 +160,7 @@ export class DesktopFido2UserInterfaceService implements Fido2UserInterfaceServi
|
||||
private userVerificationService: DesktopFido2UserVerificationService,
|
||||
private passwordRepromptService: PasswordRepromptService,
|
||||
private domainSettingsService: DomainSettingsService,
|
||||
private messageListener: MessageListener,
|
||||
) {}
|
||||
private currentSession: any;
|
||||
|
||||
@@ -184,6 +193,7 @@ export class DesktopFido2UserInterfaceService implements Fido2UserInterfaceServi
|
||||
this.userVerificationService,
|
||||
this.passwordRepromptService,
|
||||
this.domainSettingsService,
|
||||
this.messageListener,
|
||||
);
|
||||
|
||||
this.currentSession = session;
|
||||
@@ -204,6 +214,7 @@ export class DesktopFido2UserInterfaceSession implements Fido2UserInterfaceSessi
|
||||
private userVerificationService: DesktopFido2UserVerificationService,
|
||||
private passwordRepromptService: PasswordRepromptService,
|
||||
private domainSettingsService: DomainSettingsService,
|
||||
private messageListener: MessageListener,
|
||||
) {}
|
||||
|
||||
private confirmCredentialSubject = new Subject<boolean>();
|
||||
@@ -235,6 +246,11 @@ export class DesktopFido2UserInterfaceSession implements Fido2UserInterfaceSessi
|
||||
*/
|
||||
private uiShown = false;
|
||||
|
||||
/**
|
||||
* Cancels the ceremony if the user closes the window while it shows our UI.
|
||||
*/
|
||||
private windowClosedSubscription: Subscription | undefined;
|
||||
|
||||
// Method implementation
|
||||
async pickCredential(
|
||||
params: PickCredentialParams,
|
||||
@@ -610,6 +626,9 @@ export class DesktopFido2UserInterfaceSession implements Fido2UserInterfaceSessi
|
||||
* own `finally`. Safe to call more than once.
|
||||
*/
|
||||
async hideUi(): Promise<void> {
|
||||
this.windowClosedSubscription?.unsubscribe();
|
||||
this.windowClosedSubscription = undefined;
|
||||
|
||||
// Always clear modal mode so the app can never get stuck in it. The main
|
||||
// process only restyles the window on the modal -> standard transition, so
|
||||
// this is inert when the ceremony never entered modal mode.
|
||||
@@ -633,6 +652,17 @@ export class DesktopFido2UserInterfaceSession implements Fido2UserInterfaceSessi
|
||||
showTrafficButtons: boolean = false,
|
||||
disableRedirect?: boolean,
|
||||
): Promise<void> {
|
||||
this.windowClosedSubscription ??= this.messageListener
|
||||
.messages$(MODAL_WINDOW_CLOSED)
|
||||
.pipe(take(1))
|
||||
.subscribe(() => {
|
||||
this.logService.info(
|
||||
"[DesktopFido2UserInterfaceSession]",
|
||||
"Window closed while showing UI. Aborting the request.",
|
||||
);
|
||||
this.abortController.abort("Operation cancelled");
|
||||
});
|
||||
|
||||
// Load the UI:
|
||||
await this.desktopSettingsService.setModalMode(true, showTrafficButtons, position);
|
||||
await this.accountService.setShowHeader(showTrafficButtons);
|
||||
|
||||
@@ -2438,6 +2438,10 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"itemSingular": {
|
||||
"message": "1 item",
|
||||
"description": "Count of exactly one item, e.g. on a folder card holding a single item."
|
||||
},
|
||||
"all": {
|
||||
"message": "All"
|
||||
},
|
||||
@@ -7379,8 +7383,8 @@
|
||||
"makeACopy": {
|
||||
"message": "Make a copy"
|
||||
},
|
||||
"errorImportingMyItemsMultiCollection": {
|
||||
"message": "You cannot import items into My Items that are part of multiple collections"
|
||||
"errorImportingMyItemsMultiCollectionV2": {
|
||||
"message": "You cannot import items into My items that are part of multiple collections"
|
||||
},
|
||||
"driversLicenseDetails": {
|
||||
"message": "License details"
|
||||
|
||||
@@ -501,6 +501,8 @@ export class NativeMessagingMain {
|
||||
Vivaldi: `${this.homedir()}/Library/Application\ Support/Vivaldi/`,
|
||||
Zen: `${this.homedir()}/Library/Application\ Support/Zen/`,
|
||||
Helium: `${this.homedir()}/Library/Application\ Support/net.imput.helium/`,
|
||||
Arbalete: `${this.homedir()}/Library/Application\ Support/Arbalete/`,
|
||||
"Arbalete Dev": `${this.homedir()}/Library/Application\ Support/Arbalete\ Dev/`,
|
||||
Brave: `${this.homedir()}/Library/Application\ Support/BraveSoftware/Brave-Browser/`,
|
||||
"Brave Beta": `${this.homedir()}/Library/Application\ Support/BraveSoftware/Brave-Browser-Beta/`,
|
||||
"Brave Nightly": `${this.homedir()}/Library/Application\ Support/BraveSoftware/Brave-Browser-Nightly/`,
|
||||
|
||||
@@ -5,13 +5,14 @@ import * as path from "path";
|
||||
|
||||
import { app, BrowserWindow, ipcMain, session } from "electron";
|
||||
import { mock, MockProxy } from "jest-mock-extended";
|
||||
import { NEVER, of } from "rxjs";
|
||||
import { BehaviorSubject, NEVER, of } from "rxjs";
|
||||
|
||||
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
|
||||
import { AbstractStorageService } from "@bitwarden/common/platform/abstractions/storage.service";
|
||||
import { BiometricStateService } from "@bitwarden/key-management";
|
||||
|
||||
import { SafeShell } from "../platform/main/safe-shell.main";
|
||||
import { ModalModeState } from "../platform/models/domain/window-state";
|
||||
import { DesktopSettingsService } from "../platform/services/desktop-settings.service";
|
||||
|
||||
// window.main.ts registers a privileged scheme at module load time, which
|
||||
@@ -272,6 +273,7 @@ describe("WindowMain", () => {
|
||||
|
||||
describe("createWindow", () => {
|
||||
let sut: WindowMain;
|
||||
let modalMode$: BehaviorSubject<ModalModeState>;
|
||||
|
||||
const fakeWindow = () =>
|
||||
Object.assign(new EventEmitter(), {
|
||||
@@ -294,9 +296,11 @@ describe("WindowMain", () => {
|
||||
(global as any).BIT_ENVIRONMENT = "production";
|
||||
|
||||
const desktopSettingsService = mock<DesktopSettingsService>();
|
||||
modalMode$ = new BehaviorSubject<ModalModeState>({ isModalModeActive: false });
|
||||
Object.assign(desktopSettingsService, {
|
||||
alwaysOnTop$: of(false),
|
||||
preventScreenshots$: of(false),
|
||||
modalMode$,
|
||||
});
|
||||
|
||||
sut = new WindowMain(
|
||||
@@ -349,6 +353,33 @@ describe("WindowMain", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("tells the renderer when the user closes the window in modal mode", async () => {
|
||||
const win = fakeWindow();
|
||||
jest.mocked(BrowserWindow).mockImplementationOnce(() => win as any);
|
||||
await sut.createWindow();
|
||||
modalMode$.next({ isModalModeActive: true });
|
||||
|
||||
win.emit("close");
|
||||
await new Promise(process.nextTick);
|
||||
|
||||
expect(win.webContents.send).toHaveBeenCalledWith("messagingService", {
|
||||
command: "modalWindowClosed",
|
||||
});
|
||||
});
|
||||
|
||||
it("does not tell the renderer when the user closes the window outside modal mode", async () => {
|
||||
const win = fakeWindow();
|
||||
jest.mocked(BrowserWindow).mockImplementationOnce(() => win as any);
|
||||
await sut.createWindow();
|
||||
|
||||
win.emit("close");
|
||||
await new Promise(process.nextTick);
|
||||
|
||||
expect(win.webContents.send).not.toHaveBeenCalledWith("messagingService", {
|
||||
command: "modalWindowClosed",
|
||||
});
|
||||
});
|
||||
|
||||
it("clears the window reference when the current window closes", async () => {
|
||||
const win = fakeWindow();
|
||||
jest.mocked(BrowserWindow).mockImplementationOnce(() => win as any);
|
||||
|
||||
@@ -567,6 +567,7 @@ export class WindowMain {
|
||||
|
||||
win.on("close", async () => {
|
||||
this.isClosing = true;
|
||||
await this.notifyIfModalWindowClosed(win);
|
||||
await this.updateWindowState(mainWindowSizeKey, win);
|
||||
});
|
||||
|
||||
@@ -677,6 +678,18 @@ export class WindowMain {
|
||||
return fn(this.win);
|
||||
}
|
||||
|
||||
/**
|
||||
* Notifies the renderer that the user closed the window while the modal was
|
||||
* active, e.g. during a passkey ceremony.
|
||||
*/
|
||||
private async notifyIfModalWindowClosed(win: BrowserWindow) {
|
||||
const modalMode = await firstValueFrom(this.desktopSettingsService.modalMode$);
|
||||
if (!modalMode?.isModalModeActive || win.isDestroyed()) {
|
||||
return;
|
||||
}
|
||||
win.webContents.send("messagingService", { command: "modalWindowClosed" });
|
||||
}
|
||||
|
||||
private windowStateChangeHandler(configKey: string, win: BrowserWindow) {
|
||||
global.clearTimeout(this.windowStateChangeTimer);
|
||||
this.windowStateChangeTimer = global.setTimeout(async () => {
|
||||
|
||||
@@ -64,6 +64,7 @@
|
||||
class="tw-block tw-shrink-0 tw-px-8"
|
||||
[collections]="scopedCollections"
|
||||
[folders]="folders()"
|
||||
[ciphers]="allCiphers"
|
||||
[scope]="vaultScope()"
|
||||
></vault-card-grid>
|
||||
<!-- Remounted per scope: the table reads its filters from the URL once, at mount. -->
|
||||
|
||||
@@ -539,6 +539,8 @@ export class VaultComponent<C extends CipherViewLike> implements OnInit, OnDestr
|
||||
this.i18nService.t(this.calculateSearchBarLocalizationString(this.activeFilter())),
|
||||
);
|
||||
protected ciphers: C[] = [];
|
||||
/** Every allowed item, unfiltered by the page, for the card grid's item counts. */
|
||||
protected allCiphers: CipherViewLike[] = [];
|
||||
protected isEmpty: boolean;
|
||||
protected currentSearchText$: Observable<string> = this.route.queryParams.pipe(
|
||||
map((queryParams) => queryParams.search),
|
||||
@@ -843,12 +845,21 @@ export class VaultComponent<C extends CipherViewLike> implements OnInit, OnDestr
|
||||
collections$,
|
||||
this.vfo1Foundation$,
|
||||
this.vaultScope$,
|
||||
allowedCiphers$,
|
||||
]),
|
||||
),
|
||||
takeUntil(this.destroy$),
|
||||
)
|
||||
.subscribe(
|
||||
([allCollections, allOrganizations, ciphers, collections, vfo1Foundation, scope]) => {
|
||||
([
|
||||
allCollections,
|
||||
allOrganizations,
|
||||
ciphers,
|
||||
collections,
|
||||
vfo1Foundation,
|
||||
scope,
|
||||
allowedCiphers,
|
||||
]) => {
|
||||
this.allCollections = allCollections;
|
||||
this.allOrganizations = allOrganizations;
|
||||
this.scopedCollections = vfo1Foundation
|
||||
@@ -861,6 +872,7 @@ export class VaultComponent<C extends CipherViewLike> implements OnInit, OnDestr
|
||||
? allOrganizations.filter((organization) => organizationInScope(organization, scope))
|
||||
: allOrganizations;
|
||||
this.ciphers = ciphers;
|
||||
this.allCiphers = allowedCiphers;
|
||||
this.collectionsToDisplay = collections;
|
||||
this.isEmpty = collections?.length === 0 && ciphers?.length === 0;
|
||||
const initialLoad = this.performingInitialLoad;
|
||||
|
||||
@@ -33,7 +33,7 @@ RUN npm run ${NPM_COMMAND}
|
||||
###############################################
|
||||
# Build stage 2 #
|
||||
###############################################
|
||||
FROM --platform=$BUILDPLATFORM mcr.microsoft.com/dotnet/sdk:10.0-alpine3.23 AS build
|
||||
FROM --platform=$BUILDPLATFORM mcr.microsoft.com/dotnet/sdk:10.0-alpine3.24 AS build
|
||||
|
||||
# Docker buildx supplies the value for this arg
|
||||
ARG TARGETPLATFORM
|
||||
@@ -73,7 +73,7 @@ WORKDIR /app
|
||||
###############################################
|
||||
# App stage #
|
||||
###############################################
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:10.0-alpine3.23
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:10.0-alpine3.24
|
||||
|
||||
ARG TARGETPLATFORM
|
||||
LABEL com.bitwarden.product="bitwarden"
|
||||
|
||||
@@ -41,11 +41,11 @@ export type MemberFilters = {
|
||||
policies?: PolicyOption[];
|
||||
};
|
||||
|
||||
/** The roles offered in the Role filter, in display order. */
|
||||
/** The roles offered in the Role filter, in display order. Also the Role column sort order. */
|
||||
export const ROLE_OPTIONS: readonly { value: OrganizationUserType; labelKey: string }[] = [
|
||||
{ value: OrganizationUserType.Owner, labelKey: "owner" },
|
||||
{ value: OrganizationUserType.Admin, labelKey: "admin" },
|
||||
{ value: OrganizationUserType.User, labelKey: "user" },
|
||||
{ value: OrganizationUserType.Admin, labelKey: "admin" },
|
||||
{ value: OrganizationUserType.Owner, labelKey: "owner" },
|
||||
{ value: OrganizationUserType.Custom, labelKey: "custom" },
|
||||
];
|
||||
|
||||
|
||||
@@ -207,22 +207,15 @@
|
||||
</bit-column>
|
||||
|
||||
<!-- Role -->
|
||||
<bit-column sortable width="minmax(120px, 1fr)">
|
||||
<bit-column sortable [sortFn]="sortByRole" width="minmax(120px, 1fr)">
|
||||
<bit-header-cell>{{ "role" | i18n }}</bit-header-cell>
|
||||
<bit-cell *bitCellDef="table.columns.type; let row">
|
||||
@if (canManage && organization) {
|
||||
<button
|
||||
type="button"
|
||||
bitLink
|
||||
linkType="secondary"
|
||||
[attr.id]="'members-v2_button_edit-role-' + row.id"
|
||||
(click)="edit(row, organization, memberTab.Details)"
|
||||
>
|
||||
{{ row.type | userType }}
|
||||
</button>
|
||||
} @else {
|
||||
{{ row.type | userType }}
|
||||
}
|
||||
<!-- Matches v1: clicking the role cell opens the member dialog on the role tab. -->
|
||||
<bit-cell
|
||||
*bitCellDef="table.columns.type; let row"
|
||||
[class.tw-cursor-pointer]="canManage && organization"
|
||||
(click)="canManage && organization && edit(row, organization, memberTab.Details)"
|
||||
>
|
||||
{{ row.type | userType }}
|
||||
</bit-cell>
|
||||
</bit-column>
|
||||
|
||||
@@ -256,8 +249,7 @@
|
||||
<span class="tw-w-full tw-text-end">{{ "options" | i18n }}</span>
|
||||
</bit-header-cell>
|
||||
<bit-cell *bitCellDef="table.columns.options; let row">
|
||||
<!-- Without manage users permission, the menu only holds Recover account. -->
|
||||
@if (organization && (canManage || allowResetPassword(row, organization))) {
|
||||
@if (organization && canManage) {
|
||||
<div slot="end">
|
||||
<button
|
||||
type="button"
|
||||
@@ -268,88 +260,85 @@
|
||||
[bitMenuTriggerFor]="rowMenu"
|
||||
></button>
|
||||
<bit-menu #rowMenu>
|
||||
@if (canManage) {
|
||||
@if (row.canSendInvite) {
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
[attr.id]="'members-v2_menu-item_send-invite-' + row.id"
|
||||
(click)="isProcessing() ? null : sendInvite(row, organization)"
|
||||
>
|
||||
<bit-icon slot="start" fixedWidth name="bwi-envelope" />
|
||||
{{ "sendInvite" | i18n }}
|
||||
</button>
|
||||
}
|
||||
@if (row.canReinvite) {
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
[attr.id]="'members-v2_menu-item_resend-invitation-' + row.id"
|
||||
(click)="isProcessing() ? null : reinvite(row, organization)"
|
||||
>
|
||||
<bit-icon slot="start" fixedWidth name="bwi-envelope" />
|
||||
{{ "resendInvitation" | i18n }}
|
||||
</button>
|
||||
}
|
||||
@if (row.canConfirm) {
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
[attr.id]="'members-v2_menu-item_confirm-' + row.id"
|
||||
(click)="isProcessing() ? null : confirm(row, organization)"
|
||||
>
|
||||
<span class="tw-text-success">
|
||||
<bit-icon slot="start" fixedWidth name="bwi-check" />
|
||||
{{ "confirm" | i18n }}
|
||||
</span>
|
||||
</button>
|
||||
}
|
||||
@if (row.canConfirm || row.canReinvite || row.canSendInvite) {
|
||||
<bit-menu-divider></bit-menu-divider>
|
||||
}
|
||||
@if (row.canSendInvite) {
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
[attr.id]="'members-v2_menu-item_member-role-' + row.id"
|
||||
(click)="isProcessing() ? null : edit(row, organization, memberTab.Details)"
|
||||
[attr.id]="'members-v2_menu-item_send-invite-' + row.id"
|
||||
(click)="isProcessing() ? null : sendInvite(row, organization)"
|
||||
>
|
||||
<bit-icon slot="start" fixedWidth name="bwi-user" />
|
||||
{{ "memberRole" | i18n }}
|
||||
<bit-icon slot="start" fixedWidth name="bwi-envelope" />
|
||||
{{ "sendInvite" | i18n }}
|
||||
</button>
|
||||
}
|
||||
@if (row.canReinvite) {
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
[attr.id]="'members-v2_menu-item_resend-invitation-' + row.id"
|
||||
(click)="isProcessing() ? null : reinvite(row, organization)"
|
||||
>
|
||||
<bit-icon slot="start" fixedWidth name="bwi-envelope" />
|
||||
{{ "resendInvitation" | i18n }}
|
||||
</button>
|
||||
}
|
||||
@if (row.canConfirm) {
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
[attr.id]="'members-v2_menu-item_confirm-' + row.id"
|
||||
(click)="isProcessing() ? null : confirm(row, organization)"
|
||||
>
|
||||
<span class="tw-text-success">
|
||||
<bit-icon slot="start" fixedWidth name="bwi-check" />
|
||||
{{ "confirm" | i18n }}
|
||||
</span>
|
||||
</button>
|
||||
}
|
||||
@if (row.canConfirm || row.canReinvite || row.canSendInvite) {
|
||||
<bit-menu-divider></bit-menu-divider>
|
||||
}
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
[attr.id]="'members-v2_menu-item_member-role-' + row.id"
|
||||
(click)="isProcessing() ? null : edit(row, organization, memberTab.Details)"
|
||||
>
|
||||
<bit-icon slot="start" fixedWidth name="bwi-user" />
|
||||
{{ "memberRole" | i18n }}
|
||||
</button>
|
||||
@if (organization.useGroups) {
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
[attr.id]="'members-v2_menu-item_groups-' + row.id"
|
||||
(click)="isProcessing() ? null : edit(row, organization, memberTab.Groups)"
|
||||
>
|
||||
<bit-icon slot="start" fixedWidth name="bwi-users" />
|
||||
{{ "groups" | i18n }}
|
||||
</button>
|
||||
}
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
[attr.id]="'members-v2_menu-item_collections-' + row.id"
|
||||
(click)="isProcessing() ? null : edit(row, organization, memberTab.Collections)"
|
||||
>
|
||||
<bit-icon slot="start" fixedWidth [name]="'bwi-collection-shared' | vfo1Icon" />
|
||||
{{ "collections" | vfo1I18n: "sharedFolders" }}
|
||||
</button>
|
||||
<bit-menu-divider></bit-menu-divider>
|
||||
@if (organization.useEvents && row.status === userStatusType.Confirmed) {
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
[attr.id]="'members-v2_menu-item_event-logs-' + row.id"
|
||||
(click)="isProcessing() ? null : openEventsDialog(row, organization)"
|
||||
>
|
||||
<bit-icon slot="start" fixedWidth name="bwi-file-text" />
|
||||
{{ "eventLogs" | i18n }}
|
||||
</button>
|
||||
@if (organization.useGroups) {
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
[attr.id]="'members-v2_menu-item_groups-' + row.id"
|
||||
(click)="isProcessing() ? null : edit(row, organization, memberTab.Groups)"
|
||||
>
|
||||
<bit-icon slot="start" fixedWidth name="bwi-users" />
|
||||
{{ "groups" | i18n }}
|
||||
</button>
|
||||
}
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
[attr.id]="'members-v2_menu-item_collections-' + row.id"
|
||||
(click)="isProcessing() ? null : edit(row, organization, memberTab.Collections)"
|
||||
>
|
||||
<bit-icon slot="start" fixedWidth [name]="'bwi-collection-shared' | vfo1Icon" />
|
||||
{{ "collections" | vfo1I18n: "sharedFolders" }}
|
||||
</button>
|
||||
<bit-menu-divider></bit-menu-divider>
|
||||
@if (organization.useEvents && row.status === userStatusType.Confirmed) {
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
[attr.id]="'members-v2_menu-item_event-logs-' + row.id"
|
||||
(click)="isProcessing() ? null : openEventsDialog(row, organization)"
|
||||
>
|
||||
<bit-icon slot="start" fixedWidth name="bwi-file-text" />
|
||||
{{ "eventLogs" | i18n }}
|
||||
</button>
|
||||
}
|
||||
}
|
||||
<!-- Account recovery is available to all users with the appropriate permissions. -->
|
||||
@if (allowResetPassword(row, organization)) {
|
||||
<button
|
||||
type="button"
|
||||
@@ -361,56 +350,73 @@
|
||||
{{ "recoverAccount" | i18n }}
|
||||
</button>
|
||||
}
|
||||
@if (canManage) {
|
||||
@if (row.canRestore) {
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
[attr.id]="'members-v2_menu-item_restore-' + row.id"
|
||||
(click)="isProcessing() ? null : restore(row, organization)"
|
||||
>
|
||||
<bit-icon slot="start" fixedWidth name="bwi-plus-circle" />
|
||||
{{ "restoreAccess" | i18n }}
|
||||
</button>
|
||||
}
|
||||
@if (row.canRevoke) {
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
[attr.id]="'members-v2_menu-item_revoke-' + row.id"
|
||||
(click)="isProcessing() ? null : revoke(row, organization)"
|
||||
>
|
||||
<bit-icon slot="start" fixedWidth name="bwi-minus-circle" />
|
||||
{{ "revokeAccess" | i18n }}
|
||||
</button>
|
||||
}
|
||||
<!-- Claimed members can't be removed, only deleted. -->
|
||||
@if (row.canRemove) {
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
variant="danger"
|
||||
[attr.id]="'members-v2_menu-item_remove-' + row.id"
|
||||
(click)="isProcessing() ? null : remove(row, organization)"
|
||||
>
|
||||
<bit-icon slot="start" fixedWidth name="bwi-close" />
|
||||
{{ "remove" | i18n }}
|
||||
</button>
|
||||
} @else {
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
variant="danger"
|
||||
[attr.id]="'members-v2_menu-item_delete-' + row.id"
|
||||
(click)="isProcessing() ? null : deleteUser(row, organization)"
|
||||
>
|
||||
<bit-icon slot="start" fixedWidth name="bwi-trash" />
|
||||
{{ "delete" | i18n }}
|
||||
</button>
|
||||
}
|
||||
@if (row.canRestore) {
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
[attr.id]="'members-v2_menu-item_restore-' + row.id"
|
||||
(click)="isProcessing() ? null : restore(row, organization)"
|
||||
>
|
||||
<bit-icon slot="start" fixedWidth name="bwi-plus-circle" />
|
||||
{{ "restoreAccess" | i18n }}
|
||||
</button>
|
||||
}
|
||||
@if (row.canRevoke) {
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
[attr.id]="'members-v2_menu-item_revoke-' + row.id"
|
||||
(click)="isProcessing() ? null : revoke(row, organization)"
|
||||
>
|
||||
<bit-icon slot="start" fixedWidth name="bwi-minus-circle" />
|
||||
{{ "revokeAccess" | i18n }}
|
||||
</button>
|
||||
}
|
||||
<!-- Claimed members can't be removed, only deleted. -->
|
||||
@if (row.canRemove) {
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
variant="danger"
|
||||
[attr.id]="'members-v2_menu-item_remove-' + row.id"
|
||||
(click)="isProcessing() ? null : remove(row, organization)"
|
||||
>
|
||||
<bit-icon slot="start" fixedWidth name="bwi-close" />
|
||||
{{ "remove" | i18n }}
|
||||
</button>
|
||||
} @else {
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
variant="danger"
|
||||
[attr.id]="'members-v2_menu-item_delete-' + row.id"
|
||||
(click)="isProcessing() ? null : deleteUser(row, organization)"
|
||||
>
|
||||
<bit-icon slot="start" fixedWidth name="bwi-trash" />
|
||||
{{ "delete" | i18n }}
|
||||
</button>
|
||||
}
|
||||
</bit-menu>
|
||||
</div>
|
||||
} @else if (organization && allowResetPassword(row, organization)) {
|
||||
<!-- Without manage users permission, Recover account is the only action, so it's a button. -->
|
||||
<button
|
||||
type="button"
|
||||
bitButton
|
||||
buttonType="secondary"
|
||||
size="small"
|
||||
slot="end"
|
||||
[attr.id]="'members-v2_button_recover-account-' + row.id"
|
||||
[attr.aria-label]="'recoverAccountForMember' | i18n: row.name ?? row.email"
|
||||
(click)="isProcessing() ? null : resetPassword(row, organization)"
|
||||
>
|
||||
{{ "recover" | i18n }}
|
||||
</button>
|
||||
} @else {
|
||||
<div slot="end">
|
||||
<span class="tw-text-muted" aria-hidden="true">—</span>
|
||||
<span class="tw-sr-only">{{ "noActionsForMember" | i18n: row.name ?? row.email }}</span>
|
||||
</div>
|
||||
}
|
||||
</bit-cell>
|
||||
</bit-column>
|
||||
|
||||
@@ -27,6 +27,7 @@ import { BillingConstraintService } from "@bitwarden/web-vault/app/billing/membe
|
||||
|
||||
import { MaxCheckedCount } from "../../../common/people-table-data-source";
|
||||
import { OrganizationUserView } from "../../core/views/organization-user.view";
|
||||
import { AccountRecoveryDialogResultType } from "../components/account-recovery";
|
||||
import { MemberDialogResult, MemberDialogTab } from "../components/member-dialog";
|
||||
import {
|
||||
MemberDialogManagerService,
|
||||
@@ -271,6 +272,22 @@ describe("MembersV2Component", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("sorts by role in filter order", () => {
|
||||
const rows = [
|
||||
OrganizationUserType.Custom,
|
||||
OrganizationUserType.Owner,
|
||||
OrganizationUserType.Admin,
|
||||
OrganizationUserType.User,
|
||||
].map((type) => member({ type }));
|
||||
|
||||
expect(rows.sort(component.sortByRole).map((r) => r.type)).toEqual([
|
||||
OrganizationUserType.User,
|
||||
OrganizationUserType.Admin,
|
||||
OrganizationUserType.Owner,
|
||||
OrganizationUserType.Custom,
|
||||
]);
|
||||
});
|
||||
|
||||
it("sorts groups by the first group, then by how many there are", () => {
|
||||
const rows = [
|
||||
member({ id: "b" as Guid, groupNames: ["Sales"] }),
|
||||
@@ -878,4 +895,63 @@ describe("MembersV2Component", () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("read-only admin who can recover accounts", () => {
|
||||
const enrolled = member({ id: "enrolled" as Guid, resetPasswordEnrolled: true });
|
||||
const notEnrolled = member({ id: "not-enrolled" as Guid, resetPasswordEnrolled: false });
|
||||
let organization: Organization;
|
||||
|
||||
beforeEach(async () => {
|
||||
await setup(
|
||||
{ canManageUsers: false, canManageUsersPassword: true, useResetPassword: true },
|
||||
[enrolled, notEnrolled],
|
||||
{},
|
||||
{ resetPasswordPolicyEnabled: true },
|
||||
);
|
||||
organization = component.organization();
|
||||
memberActionsService.allowResetPassword.mockImplementation(
|
||||
(user) => user.resetPasswordEnrolled,
|
||||
);
|
||||
memberService.loadMembers.mockClear();
|
||||
});
|
||||
|
||||
it("allows recovering a member who's enrolled in account recovery", () => {
|
||||
expect(component.allowResetPassword(enrolled, organization)).toBe(true);
|
||||
expect(memberActionsService.allowResetPassword).toHaveBeenCalledWith(
|
||||
enrolled,
|
||||
organization,
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("doesn't allow recovering a member who isn't enrolled, so their row shows no action", () => {
|
||||
expect(component.allowResetPassword(notEnrolled, organization)).toBe(false);
|
||||
});
|
||||
|
||||
it("has no selection, so no checkbox column", () => {
|
||||
expect(component.selection()).toBeUndefined();
|
||||
});
|
||||
|
||||
it("opens the account recovery dialog and reloads when it succeeds", async () => {
|
||||
memberDialogManager.openAccountRecoveryDialog.mockResolvedValue(
|
||||
AccountRecoveryDialogResultType.Ok,
|
||||
);
|
||||
|
||||
await component.resetPassword(enrolled, organization);
|
||||
|
||||
expect(memberDialogManager.openAccountRecoveryDialog).toHaveBeenCalledWith(
|
||||
enrolled,
|
||||
organization,
|
||||
);
|
||||
expect(memberService.loadMembers).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("doesn't reload when the account recovery dialog is dismissed", async () => {
|
||||
memberDialogManager.openAccountRecoveryDialog.mockResolvedValue(undefined);
|
||||
|
||||
await component.resetPassword(enrolled, organization);
|
||||
|
||||
expect(memberService.loadMembers).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -555,12 +555,19 @@ export const RowActions: Story = {
|
||||
};
|
||||
|
||||
/**
|
||||
* An admin who can't manage users gets search, but no Export or Invite member button, no checkbox
|
||||
* column, no Options column and no clickable cells.
|
||||
* An admin who can't manage users but can recover accounts, like a custom role with only Manage
|
||||
* account recovery. They get search, filters, the count and pagination, but no Export or Invite
|
||||
* member button, no checkbox column and no clickable cells. Recover account is their only action,
|
||||
* so instead of the Options menu, members who can be recovered get a Recover button and the rest
|
||||
* get an em dash: Alice Smith, enrolled in account recovery, has the button, and Bob Jones, not
|
||||
* enrolled, doesn't.
|
||||
*/
|
||||
export const ReadOnly: Story = {
|
||||
name: "Read only",
|
||||
render: makeRender(mockMembers, mockOrganization({ canManageUsers: false })),
|
||||
render: makeRender(
|
||||
mockMembers,
|
||||
mockOrganization({ canManageUsers: false, canManageUsersPassword: true }),
|
||||
),
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -27,7 +27,7 @@ import { RegistrationUserAddIcon, SearchFolder } from "@bitwarden/assets/svg";
|
||||
import { OrganizationService } from "@bitwarden/common/admin-console/abstractions/organization/organization.service.abstraction";
|
||||
import { PolicyApiServiceAbstraction } from "@bitwarden/common/admin-console/abstractions/policy/policy-api.service.abstraction";
|
||||
import { PolicyService } from "@bitwarden/common/admin-console/abstractions/policy/policy.service.abstraction";
|
||||
import { PolicyType } from "@bitwarden/common/admin-console/enums";
|
||||
import { OrganizationUserType, PolicyType } from "@bitwarden/common/admin-console/enums";
|
||||
import { Organization } from "@bitwarden/common/admin-console/models/domain/organization";
|
||||
import { Policy } from "@bitwarden/common/admin-console/models/domain/policy";
|
||||
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
|
||||
@@ -604,6 +604,9 @@ export class MembersV2Component {
|
||||
protected readonly sortByStatus = (a: OrganizationUserView, b: OrganizationUserView) =>
|
||||
statusOrder(a.status) - statusOrder(b.status);
|
||||
|
||||
protected readonly sortByRole = (a: OrganizationUserView, b: OrganizationUserView) =>
|
||||
roleOrder(a.type) - roleOrder(b.type);
|
||||
|
||||
/** Orders by the first name shown in the badge, then by how many more there are. */
|
||||
protected readonly sortByFirstName = (a: string[], b: string[]) =>
|
||||
this.compareText(a[0] ?? "", b[0] ?? "") || a.length - b.length;
|
||||
@@ -645,3 +648,8 @@ function statusOrder(status: OrganizationUserStatusType): number {
|
||||
const index = STATUS_BADGES.findIndex((badge) => badge.status === status);
|
||||
return index === -1 ? STATUS_BADGES.length : index;
|
||||
}
|
||||
|
||||
function roleOrder(type: OrganizationUserType): number {
|
||||
const index = ROLE_OPTIONS.findIndex((role) => role.value === type);
|
||||
return index === -1 ? ROLE_OPTIONS.length : index;
|
||||
}
|
||||
|
||||
@@ -7,7 +7,6 @@ import { Organization } from "@bitwarden/common/admin-console/models/domain/orga
|
||||
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
|
||||
import { OrganizationMetadataServiceAbstraction } from "@bitwarden/common/billing/abstractions/organization-metadata.service.abstraction";
|
||||
import { OrganizationBillingMetadataResponse } from "@bitwarden/common/billing/models/response/organization-billing-metadata.response";
|
||||
import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service";
|
||||
import { Utils } from "@bitwarden/common/platform/misc/utils";
|
||||
import { StateProvider } from "@bitwarden/common/platform/state";
|
||||
import {
|
||||
@@ -35,7 +34,6 @@ describe("InviteLinkCalloutService", () => {
|
||||
const userId = Utils.newGuid() as UserId;
|
||||
let accountService: FakeAccountService;
|
||||
let stateProvider: FakeStateProvider;
|
||||
let configService: MockProxy<ConfigService>;
|
||||
let memberDialogManager: MockProxy<MemberDialogManagerService>;
|
||||
let organizationMembersService: MockProxy<OrganizationMembersService>;
|
||||
let organizationMetadataService: MockProxy<OrganizationMetadataServiceAbstraction>;
|
||||
@@ -64,8 +62,6 @@ describe("InviteLinkCalloutService", () => {
|
||||
beforeEach(() => {
|
||||
accountService = mockAccountServiceWith(userId);
|
||||
stateProvider = new FakeStateProvider(accountService);
|
||||
configService = mock<ConfigService>();
|
||||
configService.getFeatureFlag.mockResolvedValue(true);
|
||||
memberDialogManager = mock<MemberDialogManagerService>();
|
||||
memberDialogManager.openInviteDialog.mockResolvedValue(MemberDialogResult.Saved);
|
||||
organizationMembersService = mock<OrganizationMembersService>();
|
||||
@@ -85,7 +81,6 @@ describe("InviteLinkCalloutService", () => {
|
||||
InviteLinkCalloutService,
|
||||
{ provide: AccountService, useValue: accountService },
|
||||
{ provide: StateProvider, useValue: stateProvider },
|
||||
{ provide: ConfigService, useValue: configService },
|
||||
{ provide: MemberDialogManagerService, useValue: memberDialogManager },
|
||||
{ provide: OrganizationMembersService, useValue: organizationMembersService },
|
||||
{ provide: OrganizationMetadataServiceAbstraction, useValue: organizationMetadataService },
|
||||
@@ -145,15 +140,6 @@ describe("InviteLinkCalloutService", () => {
|
||||
expect(dialogService.open).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("showIfEligible() returns early without opening a dialog when the feature flag is disabled", async () => {
|
||||
configService.getFeatureFlag.mockResolvedValue(false);
|
||||
const organization = createOrganization();
|
||||
|
||||
await service.showIfEligible(organization);
|
||||
|
||||
expect(dialogService.open).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("showIfEligible() opens the dialog and calls dismiss() when the user clicks Skip", async () => {
|
||||
const organization = createOrganization();
|
||||
stubDialogClosed("skip");
|
||||
|
||||
@@ -6,8 +6,6 @@ import { Organization } from "@bitwarden/common/admin-console/models/domain/orga
|
||||
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
|
||||
import { getUserId } from "@bitwarden/common/auth/services/account.service";
|
||||
import { OrganizationMetadataServiceAbstraction } from "@bitwarden/common/billing/abstractions/organization-metadata.service.abstraction";
|
||||
import { FeatureFlag } from "@bitwarden/common/enums/feature-flag.enum";
|
||||
import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service";
|
||||
import {
|
||||
INVITE_LINK_CALLOUT_DISK,
|
||||
StateProvider,
|
||||
@@ -36,7 +34,6 @@ export const INVITE_LINK_CALLOUT_DISMISSED_KEY = new UserKeyDefinition<Organizat
|
||||
@Injectable({ providedIn: "root" })
|
||||
export class InviteLinkCalloutService {
|
||||
private accountService = inject(AccountService);
|
||||
private configService = inject(ConfigService);
|
||||
private stateProvider = inject(StateProvider);
|
||||
private memberDialogManager = inject(MemberDialogManagerService);
|
||||
private organizationMembersService = inject(OrganizationMembersService);
|
||||
@@ -90,10 +87,6 @@ export class InviteLinkCalloutService {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!(await this.configService.getFeatureFlag(FeatureFlag.InviteLinkNotification))) {
|
||||
return;
|
||||
}
|
||||
|
||||
const dismissed = await firstValueFrom(this.isDismissed$(organization.id));
|
||||
if (dismissed) {
|
||||
return;
|
||||
|
||||
@@ -31,7 +31,8 @@ import { PolicyEditDialogData, PolicyEditDrawerComponent } from "./policy-edit-d
|
||||
|
||||
const ORG_ID = "test-org-id";
|
||||
|
||||
export type PolicyDialogStoryArgs = { enabled: boolean; isCloud?: boolean };
|
||||
/** `data` is the saved policy data the drawer loads, omit it for a policy that was never saved. */
|
||||
export type PolicyDialogStoryArgs = { enabled: boolean; isCloud?: boolean; data?: object };
|
||||
|
||||
/** @deprecated Use {@link PolicyDialogStoryArgs}. Kept as an alias for existing story files. */
|
||||
export type PolicyDrawerStoryArgs = PolicyDialogStoryArgs;
|
||||
@@ -166,7 +167,7 @@ export function policyDrawerMeta(
|
||||
new PolicyStatusResponse({
|
||||
OrganizationId: ORG_ID,
|
||||
Type: policy.type,
|
||||
Data: null,
|
||||
Data: args.data ?? null,
|
||||
Enabled: args.enabled,
|
||||
CanToggleState: true,
|
||||
}),
|
||||
|
||||
@@ -1,11 +1,25 @@
|
||||
import { NO_ERRORS_SCHEMA } from "@angular/core";
|
||||
import { ComponentFixture, TestBed } from "@angular/core/testing";
|
||||
import { mock, MockProxy } from "jest-mock-extended";
|
||||
import { firstValueFrom, of } from "rxjs";
|
||||
|
||||
import { OrganizationService } from "@bitwarden/common/admin-console/abstractions/organization/organization.service.abstraction";
|
||||
import { PolicyApiServiceAbstraction } from "@bitwarden/common/admin-console/abstractions/policy/policy-api.service.abstraction";
|
||||
import { PolicyType } from "@bitwarden/common/admin-console/enums";
|
||||
import { Organization } from "@bitwarden/common/admin-console/models/domain/organization";
|
||||
import { PolicyStatusResponse } from "@bitwarden/common/admin-console/models/response/policy-status.response";
|
||||
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
|
||||
import { AutotypeFeatureFlagState } from "@bitwarden/common/desktop-native/enums/autotype-feature-flag-state.enum";
|
||||
import {
|
||||
AutotypeShortcutOption,
|
||||
DEFAULT_AUTOTYPE_GA_KEYBOARD_SHORTCUT,
|
||||
} from "@bitwarden/common/desktop-native/models/autotype-ga-policy.data";
|
||||
import { autotypeFeatureFlagState$ } from "@bitwarden/common/desktop-native/services/autotype-feature-flags";
|
||||
import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service";
|
||||
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
|
||||
import { mockAccountServiceWith } from "@bitwarden/common/spec";
|
||||
import { OrganizationId, UserId } from "@bitwarden/common/types/guid";
|
||||
import { KeyService } from "@bitwarden/key-management";
|
||||
|
||||
import {
|
||||
DesktopAutotypeGaPolicy,
|
||||
@@ -62,3 +76,187 @@ describe("DesktopAutotypeGaPolicy", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("DesktopAutotypeGaPolicyComponent", () => {
|
||||
let component: DesktopAutotypeGaPolicyComponent;
|
||||
let fixture: ComponentFixture<DesktopAutotypeGaPolicyComponent>;
|
||||
|
||||
const makePolicyResponse = (data: object | null, enabled = true) =>
|
||||
new PolicyStatusResponse({
|
||||
OrganizationId: "org1" as OrganizationId,
|
||||
Type: PolicyType.AutotypeGaPolicy,
|
||||
Enabled: enabled,
|
||||
Data: data,
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
await TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{ provide: OrganizationService, useValue: { organizations$: () => of([]) } },
|
||||
{ provide: AccountService, useValue: mockAccountServiceWith("user1" as UserId) },
|
||||
{ provide: KeyService, useValue: mock<KeyService>() },
|
||||
{ provide: PolicyApiServiceAbstraction, useValue: mock<PolicyApiServiceAbstraction>() },
|
||||
{ provide: I18nService, useValue: { t: jest.fn((key: string) => key) } },
|
||||
],
|
||||
schemas: [NO_ERRORS_SCHEMA],
|
||||
}).compileComponents();
|
||||
|
||||
fixture = TestBed.createComponent(DesktopAutotypeGaPolicyComponent);
|
||||
fixture.componentRef.setInput("policy", new DesktopAutotypeGaPolicy());
|
||||
component = fixture.componentInstance;
|
||||
});
|
||||
|
||||
const requestData = async () => (await component.buildRequest()).policy.data;
|
||||
|
||||
it("saves the built-in shortcut when Default is selected", async () => {
|
||||
component.ngOnInit();
|
||||
component.enabled.setValue(true);
|
||||
|
||||
expect(component["shortcutOption"].value).toBe(AutotypeShortcutOption.Default);
|
||||
expect(component["customShortcut"]()).toBeNull();
|
||||
expect(component.data.valid).toBe(true);
|
||||
expect(await requestData()).toEqual({
|
||||
shortcutOption: AutotypeShortcutOption.Default,
|
||||
defaultKeyboardShortcut: DEFAULT_AUTOTYPE_GA_KEYBOARD_SHORTCUT,
|
||||
});
|
||||
});
|
||||
|
||||
it("leaves an unsaved policy on Default with no shortcut", () => {
|
||||
fixture.componentRef.setInput("policyResponse", makePolicyResponse(null, false));
|
||||
component.ngOnInit();
|
||||
const loaded = component.data.getRawValue();
|
||||
|
||||
expect(loaded).toEqual({
|
||||
shortcutOption: AutotypeShortcutOption.Default,
|
||||
defaultKeyboardShortcut: null,
|
||||
});
|
||||
|
||||
component["shortcutOption"].setValue(AutotypeShortcutOption.Custom);
|
||||
component["shortcutOption"].setValue(AutotypeShortcutOption.Default);
|
||||
|
||||
expect(component.data.getRawValue()).toEqual(loaded);
|
||||
});
|
||||
|
||||
it("loads older or invalid saved data without changing it or throwing", () => {
|
||||
const response = makePolicyResponse({});
|
||||
fixture.componentRef.setInput("policyResponse", response);
|
||||
component.ngOnInit();
|
||||
|
||||
expect(component["shortcutOption"].value).toBe(AutotypeShortcutOption.Default);
|
||||
expect(component.data.valid).toBe(true);
|
||||
expect(response.data).toEqual({});
|
||||
|
||||
fixture.componentRef.setInput(
|
||||
"policyResponse",
|
||||
makePolicyResponse({
|
||||
shortcutOption: AutotypeShortcutOption.Custom,
|
||||
defaultKeyboardShortcut: "Ctrl+K",
|
||||
}),
|
||||
);
|
||||
|
||||
expect(() => {
|
||||
component.ngOnInit();
|
||||
fixture.detectChanges();
|
||||
}).not.toThrow();
|
||||
expect(component["shortcutOption"].value).toBe(AutotypeShortcutOption.Custom);
|
||||
expect(component["defaultKeyboardShortcut"].value).toBeNull();
|
||||
});
|
||||
|
||||
it("loads a saved custom shortcut and marks the form dirty only when it changes", async () => {
|
||||
fixture.componentRef.setInput(
|
||||
"policyResponse",
|
||||
makePolicyResponse({
|
||||
shortcutOption: AutotypeShortcutOption.Custom,
|
||||
defaultKeyboardShortcut: ["Control", "Super", "K"],
|
||||
}),
|
||||
);
|
||||
|
||||
component.ngOnInit();
|
||||
|
||||
expect(component["shortcutOption"].value).toBe(AutotypeShortcutOption.Custom);
|
||||
expect(component["customShortcut"]()).toEqual(["Control", "Super", "K"]);
|
||||
expect(component.data.dirty).toBe(false);
|
||||
expect(await requestData()).toEqual({
|
||||
shortcutOption: AutotypeShortcutOption.Custom,
|
||||
defaultKeyboardShortcut: ["Control", "Super", "K"],
|
||||
});
|
||||
|
||||
component["onCustomShortcut"](["Alt", "Q"]);
|
||||
|
||||
expect(component.data.dirty).toBe(true);
|
||||
});
|
||||
|
||||
it("saves a custom shortcut and keeps it when switching back to Default", async () => {
|
||||
component.ngOnInit();
|
||||
component.enabled.setValue(true);
|
||||
component["shortcutOption"].setValue(AutotypeShortcutOption.Custom);
|
||||
expect(component.data.valid).toBe(false);
|
||||
|
||||
component["onCustomShortcut"](["Alt", "Q"]);
|
||||
|
||||
expect(component.data.valid).toBe(true);
|
||||
expect(await requestData()).toEqual({
|
||||
shortcutOption: AutotypeShortcutOption.Custom,
|
||||
defaultKeyboardShortcut: ["Alt", "Q"],
|
||||
});
|
||||
|
||||
component["shortcutOption"].setValue(AutotypeShortcutOption.Default);
|
||||
|
||||
expect(await requestData()).toEqual({
|
||||
shortcutOption: AutotypeShortcutOption.Default,
|
||||
defaultKeyboardShortcut: DEFAULT_AUTOTYPE_GA_KEYBOARD_SHORTCUT,
|
||||
});
|
||||
|
||||
component["shortcutOption"].setValue(AutotypeShortcutOption.Custom);
|
||||
|
||||
expect(component["customShortcut"]()).toEqual(["Alt", "Q"]);
|
||||
expect(component.data.valid).toBe(true);
|
||||
|
||||
component["onCustomShortcut"](["Control", "Alt", "Super", "K"]);
|
||||
|
||||
expect(component.data.valid).toBe(false);
|
||||
});
|
||||
|
||||
it("saves Custom with no shortcut when the policy is turned off", async () => {
|
||||
fixture.componentRef.setInput(
|
||||
"policyResponse",
|
||||
makePolicyResponse(
|
||||
{
|
||||
shortcutOption: AutotypeShortcutOption.Default,
|
||||
defaultKeyboardShortcut: null,
|
||||
},
|
||||
true,
|
||||
),
|
||||
);
|
||||
|
||||
component.ngOnInit();
|
||||
component["shortcutOption"].setValue(AutotypeShortcutOption.Custom);
|
||||
|
||||
expect(component["customShortcut"]()).toBeNull();
|
||||
expect(component.data.valid).toBe(false);
|
||||
|
||||
component.enabled.setValue(false);
|
||||
|
||||
expect(component.data.valid).toBe(true);
|
||||
expect(await requestData()).toEqual({
|
||||
shortcutOption: AutotypeShortcutOption.Custom,
|
||||
defaultKeyboardShortcut: null,
|
||||
});
|
||||
|
||||
fixture.componentRef.setInput(
|
||||
"policyResponse",
|
||||
makePolicyResponse(
|
||||
{
|
||||
shortcutOption: AutotypeShortcutOption.Custom,
|
||||
defaultKeyboardShortcut: null,
|
||||
},
|
||||
false,
|
||||
),
|
||||
);
|
||||
component.ngOnInit();
|
||||
|
||||
expect(component["shortcutOption"].value).toBe(AutotypeShortcutOption.Custom);
|
||||
expect(component["customShortcut"]()).toBeNull();
|
||||
expect(component.enabled.value).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import { StoryObj } from "@storybook/angular";
|
||||
|
||||
import {
|
||||
AutotypeGaPolicyData,
|
||||
AutotypeShortcutOption,
|
||||
DEFAULT_AUTOTYPE_GA_KEYBOARD_SHORTCUT,
|
||||
} from "@bitwarden/common/desktop-native/models/autotype-ga-policy.data";
|
||||
|
||||
import { PolicyDialogStoryArgs, policyDrawerMeta } from "../policy-drawer-story.helper";
|
||||
|
||||
import { DesktopAutotypeGaPolicy } from "./autotype-ga-policy.component";
|
||||
@@ -16,3 +22,23 @@ export const PolicyOff: Story = {};
|
||||
export const PolicyOn: Story = {
|
||||
args: { enabled: true },
|
||||
};
|
||||
|
||||
export const DefaultShortcut: Story = {
|
||||
args: {
|
||||
enabled: true,
|
||||
data: {
|
||||
shortcutOption: AutotypeShortcutOption.Default,
|
||||
defaultKeyboardShortcut: [...DEFAULT_AUTOTYPE_GA_KEYBOARD_SHORTCUT],
|
||||
} satisfies AutotypeGaPolicyData,
|
||||
},
|
||||
};
|
||||
|
||||
export const CustomShortcut: Story = {
|
||||
args: {
|
||||
enabled: true,
|
||||
data: {
|
||||
shortcutOption: AutotypeShortcutOption.Custom,
|
||||
defaultKeyboardShortcut: ["Control", "Super", "K"],
|
||||
} satisfies AutotypeGaPolicyData,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1,15 +1,27 @@
|
||||
import { ChangeDetectionStrategy, Component } from "@angular/core";
|
||||
import { ReactiveFormsModule } from "@angular/forms";
|
||||
import { takeUntilDestroyed, toSignal } from "@angular/core/rxjs-interop";
|
||||
import { FormControl, FormGroup, ReactiveFormsModule } from "@angular/forms";
|
||||
import { merge } from "rxjs";
|
||||
import { map } from "rxjs/operators";
|
||||
|
||||
import {
|
||||
AutotypeShortcutComponent,
|
||||
formatAutotypeShortcut,
|
||||
} from "@bitwarden/angular/desktop-native/components/autotype-shortcut.component";
|
||||
import { PolicyType } from "@bitwarden/common/admin-console/enums";
|
||||
import { Organization } from "@bitwarden/common/admin-console/models/domain/organization";
|
||||
import { AutotypeFeatureFlagState } from "@bitwarden/common/desktop-native/enums/autotype-feature-flag-state.enum";
|
||||
import {
|
||||
AutotypeGaPolicyData,
|
||||
AutotypeShortcutOption,
|
||||
DEFAULT_AUTOTYPE_GA_KEYBOARD_SHORTCUT,
|
||||
isAutotypeGaShortcut,
|
||||
} from "@bitwarden/common/desktop-native/models/autotype-ga-policy.data";
|
||||
import { autotypeFeatureFlagState$ } from "@bitwarden/common/desktop-native/services/autotype-feature-flags";
|
||||
import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service";
|
||||
import {
|
||||
FormControlModule,
|
||||
LinkComponent,
|
||||
RadioButtonModule,
|
||||
SwitchComponent,
|
||||
TypographyModule,
|
||||
} from "@bitwarden/components";
|
||||
@@ -52,15 +64,140 @@ export class DesktopAutotypeGaPolicy extends BasePolicyEditDefinition {
|
||||
<bit-switch [formControl]="enabled"></bit-switch>
|
||||
<bit-label>{{ "enablePolicy" | i18n }}</bit-label>
|
||||
</bit-form-control>
|
||||
<div [formGroup]="data">
|
||||
<bit-form-control-group formControlName="shortcutOption" [block]="true">
|
||||
<bit-label>
|
||||
<span class="tw-flex tw-flex-col">
|
||||
<span>{{ "appAutofillShortcut" | i18n }}</span>
|
||||
<span bitTypography="body2" class="tw-text-muted tw-font-normal">
|
||||
{{ "appAutofillShortcutDesc" | i18n }}
|
||||
</span>
|
||||
</span>
|
||||
</bit-label>
|
||||
<bit-form-control disableMargin>
|
||||
<input
|
||||
type="radio"
|
||||
bitRadio
|
||||
[value]="shortcutOptions.Default"
|
||||
id="autotype-ga-policy_input_shortcut-default"
|
||||
/>
|
||||
<bit-label>{{ "default" | i18n }}</bit-label>
|
||||
<bit-hint>{{ "autotypeDefaultShortcutDesc" | i18n: defaultShortcutText }}</bit-hint>
|
||||
</bit-form-control>
|
||||
<bit-form-control disableMargin>
|
||||
<input
|
||||
type="radio"
|
||||
bitRadio
|
||||
[value]="shortcutOptions.Custom"
|
||||
id="autotype-ga-policy_input_shortcut-custom"
|
||||
/>
|
||||
<bit-label>{{ "custom" | i18n }}</bit-label>
|
||||
<bit-hint>{{ "autotypeCustomShortcutDesc" | i18n }}</bit-hint>
|
||||
</bit-form-control>
|
||||
</bit-form-control-group>
|
||||
@if (selectedShortcutOption() === shortcutOptions.Custom) {
|
||||
<app-autotype-shortcut
|
||||
class="tw-block"
|
||||
[inline]="true"
|
||||
[shortcut]="customShortcut()"
|
||||
(shortcutChange)="onCustomShortcut($event)"
|
||||
/>
|
||||
}
|
||||
</div>
|
||||
`,
|
||||
imports: [
|
||||
ReactiveFormsModule,
|
||||
FormControlModule,
|
||||
AutotypeShortcutComponent,
|
||||
LinkComponent,
|
||||
RadioButtonModule,
|
||||
SwitchComponent,
|
||||
TypographyModule,
|
||||
I18nPipe,
|
||||
],
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
})
|
||||
export class DesktopAutotypeGaPolicyComponent extends BasePolicyEditComponent {}
|
||||
export class DesktopAutotypeGaPolicyComponent extends BasePolicyEditComponent {
|
||||
protected readonly shortcutOptions = AutotypeShortcutOption;
|
||||
protected readonly defaultShortcutText = formatAutotypeShortcut(
|
||||
DEFAULT_AUTOTYPE_GA_KEYBOARD_SHORTCUT,
|
||||
);
|
||||
|
||||
private readonly shortcutOption = new FormControl<AutotypeShortcutOption>(
|
||||
AutotypeShortcutOption.Default,
|
||||
{ nonNullable: true },
|
||||
);
|
||||
|
||||
/**
|
||||
* The custom shortcut. Kept while Default is selected so switching back restores it.
|
||||
* Required only while Custom is selected and the policy is on.
|
||||
*/
|
||||
private readonly defaultKeyboardShortcut = new FormControl<string[] | null>(null, {
|
||||
validators: (control) => {
|
||||
if (control.value != null && !isAutotypeGaShortcut(control.value)) {
|
||||
return { invalidShortcut: true };
|
||||
}
|
||||
|
||||
return control.value == null &&
|
||||
this.shortcutOption.value === AutotypeShortcutOption.Custom &&
|
||||
this.enabled.value === true
|
||||
? { required: true }
|
||||
: null;
|
||||
},
|
||||
});
|
||||
|
||||
protected readonly customShortcut = toSignal(this.defaultKeyboardShortcut.valueChanges, {
|
||||
initialValue: this.defaultKeyboardShortcut.value,
|
||||
});
|
||||
|
||||
protected readonly selectedShortcutOption = toSignal(this.shortcutOption.valueChanges, {
|
||||
initialValue: this.shortcutOption.value,
|
||||
});
|
||||
|
||||
readonly data = new FormGroup({
|
||||
shortcutOption: this.shortcutOption,
|
||||
defaultKeyboardShortcut: this.defaultKeyboardShortcut,
|
||||
});
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
|
||||
// The shortcut's required check depends on the option and the policy toggle.
|
||||
merge(this.shortcutOption.valueChanges, this.enabled.valueChanges)
|
||||
.pipe(takeUntilDestroyed())
|
||||
.subscribe(() => {
|
||||
this.defaultKeyboardShortcut.updateValueAndValidity();
|
||||
});
|
||||
}
|
||||
|
||||
protected onCustomShortcut(keys: string[] | null): void {
|
||||
this.defaultKeyboardShortcut.setValue(keys);
|
||||
this.data.markAsDirty();
|
||||
}
|
||||
|
||||
/** Saved data without the Custom option, including data from before this setting existed, loads as Default. */
|
||||
protected override loadData() {
|
||||
const data = this.policyResponse()?.data as Partial<AutotypeGaPolicyData> | null;
|
||||
const custom = data?.shortcutOption === AutotypeShortcutOption.Custom;
|
||||
const storedShortcut = data?.defaultKeyboardShortcut;
|
||||
const stored = isAutotypeGaShortcut(storedShortcut) ? storedShortcut : null;
|
||||
|
||||
this.defaultKeyboardShortcut.setValue(custom ? stored : null);
|
||||
this.shortcutOption.setValue(
|
||||
custom ? AutotypeShortcutOption.Custom : AutotypeShortcutOption.Default,
|
||||
);
|
||||
}
|
||||
|
||||
protected override buildRequestData(): AutotypeGaPolicyData {
|
||||
if (this.shortcutOption.value === AutotypeShortcutOption.Custom) {
|
||||
return {
|
||||
shortcutOption: AutotypeShortcutOption.Custom,
|
||||
defaultKeyboardShortcut: this.defaultKeyboardShortcut.value,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
shortcutOption: AutotypeShortcutOption.Default,
|
||||
defaultKeyboardShortcut: [...DEFAULT_AUTOTYPE_GA_KEYBOARD_SHORTCUT],
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -129,7 +129,7 @@ export class OrganizationDataOwnershipPolicyComponent
|
||||
}
|
||||
|
||||
private async getEncryptedDefaultUserCollectionName(orgKey: OrgKey): Promise<EncString> {
|
||||
const defaultCollectionName = this.i18nService.t("myItems");
|
||||
const defaultCollectionName = this.i18nService.t("myItemsV2");
|
||||
const encrypted = await this.encryptService.encryptString(defaultCollectionName, orgKey);
|
||||
|
||||
if (!encrypted.encryptedString) {
|
||||
|
||||
@@ -541,7 +541,7 @@ export class CollectionDialogComponent implements OnInit {
|
||||
? "editedSharedFolderId"
|
||||
: "editedCollectionId"
|
||||
: vfo1Enabled
|
||||
? "createdSharedFolderId"
|
||||
? "addedSharedFolderId"
|
||||
: "createdCollectionId";
|
||||
this.toastService.showToast({
|
||||
variant: "success",
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
// @ts-strict-ignore
|
||||
import {
|
||||
DefaultRegistrationFinishService,
|
||||
PasswordInputResult,
|
||||
RegistrationFinishService,
|
||||
} from "@bitwarden/auth/angular";
|
||||
} from "@bitwarden/angular/auth/registration";
|
||||
import { PasswordInputResult } from "@bitwarden/auth/angular";
|
||||
import { AccountApiService } from "@bitwarden/common/auth/abstractions/account-api.service";
|
||||
import { OpenOrgInviteRequest } from "@bitwarden/common/auth/models/request/registration/open-org-invite.request";
|
||||
import { RegisterFinishRequest } from "@bitwarden/common/auth/models/request/registration/register-finish.request";
|
||||
|
||||
@@ -159,6 +159,31 @@ describe("OrganizationBillingClient", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("purchasePrivilegedControls", () => {
|
||||
it("calls the purchase route with the request body", async () => {
|
||||
mockApiService.send.mockResolvedValue(undefined);
|
||||
|
||||
await sut.purchasePrivilegedControls(orgId, { seats: 10, maxAutoscaleSeats: 20 });
|
||||
|
||||
expect(mockApiService.send).toHaveBeenCalledWith(
|
||||
"POST",
|
||||
`/organizations/${orgId}/billing/subscription/privileged-controls/purchase`,
|
||||
{ seats: 10, maxAutoscaleSeats: 20 },
|
||||
true,
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it("propagates errors from the API", async () => {
|
||||
const serverError = new ErrorResponse(null, 400);
|
||||
mockApiService.send.mockRejectedValue(serverError);
|
||||
|
||||
await expect(
|
||||
sut.purchasePrivilegedControls(orgId, { seats: 10, maxAutoscaleSeats: null }),
|
||||
).rejects.toBe(serverError);
|
||||
});
|
||||
});
|
||||
|
||||
describe("updatePrivilegedControlsSubscription", () => {
|
||||
it("sends the seat adjustment and limit to the correct route", async () => {
|
||||
mockApiService.send.mockResolvedValue(undefined);
|
||||
|
||||
@@ -7,6 +7,11 @@ import { OrganizationWarningsResponse } from "@bitwarden/web-vault/app/billing/o
|
||||
|
||||
type ChurnMitigationOfferDuration = "once" | "repeating";
|
||||
|
||||
export type PurchasePrivilegedControlsRequest = {
|
||||
seats: number;
|
||||
maxAutoscaleSeats: number | null;
|
||||
};
|
||||
|
||||
export type UpdatePrivilegedControlsSubscriptionRequest = {
|
||||
seatAdjustment: number;
|
||||
maxAutoscaleSeats: number | null;
|
||||
@@ -106,6 +111,19 @@ export class OrganizationBillingClient {
|
||||
);
|
||||
};
|
||||
|
||||
purchasePrivilegedControls = async (
|
||||
organizationId: OrganizationId,
|
||||
request: PurchasePrivilegedControlsRequest,
|
||||
): Promise<void> => {
|
||||
await this.apiService.send(
|
||||
"POST",
|
||||
`/organizations/${organizationId}/billing/subscription/privileged-controls/purchase`,
|
||||
request,
|
||||
true,
|
||||
false,
|
||||
);
|
||||
};
|
||||
|
||||
updatePrivilegedControlsSubscription = async (
|
||||
organizationId: OrganizationId,
|
||||
request: UpdatePrivilegedControlsSubscriptionRequest,
|
||||
|
||||
@@ -1 +1,5 @@
|
||||
/** Default trial length for in-product signups and premium upgrades. */
|
||||
export const DEFAULT_TRIAL_LENGTH_DAYS = 7;
|
||||
|
||||
/** Trial length for sales-initiated and marketing trials, used when the trial link omits an explicit length. */
|
||||
export const MARKETING_SALES_TRIAL_LENGTH_DAYS = 14;
|
||||
|
||||
@@ -89,6 +89,22 @@
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (showPrivilegedControlsPurchase() && orgSub && org) {
|
||||
<div class="tw-mt-7">
|
||||
@if (!showSecretsManagerSubscribe()) {
|
||||
<h3 bitTypography="h3">{{ "moreFromBitwarden" | i18n }}</h3>
|
||||
}
|
||||
<billing-privileged-controls-purchase
|
||||
[plan]="orgSub.plan"
|
||||
[organizationId]="org.id"
|
||||
[customerDiscount]="customerDiscount()"
|
||||
[passwordManagerSeats]="orgSub.seats"
|
||||
[passwordManagerMaxAutoscaleSeats]="orgSub.maxAutoscaleSeats"
|
||||
(purchased)="subscriptionAdjusted()"
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (showPrivilegedControlsContactSalesToAdd()) {
|
||||
<div class="tw-mt-7" id="privileged-controls-contact-sales-to-add">
|
||||
<h2 bitTypography="h2">{{ "privilegedControls" | i18n }}</h2>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { DatePipe } from "@angular/common";
|
||||
import { ChangeDetectionStrategy, Component, input, output } from "@angular/core";
|
||||
import { ComponentFixture, TestBed } from "@angular/core/testing";
|
||||
import { By } from "@angular/platform-browser";
|
||||
import { ActivatedRoute, convertToParamMap, ParamMap, Router } from "@angular/router";
|
||||
import { mock } from "jest-mock-extended";
|
||||
import { BehaviorSubject, Observable, of, Subject, throwError } from "rxjs";
|
||||
@@ -34,6 +35,7 @@ import {
|
||||
import { OrganizationSubscriptionCloudComponent } from "./organization-subscription-cloud.component";
|
||||
import { OrganizationSubscriptionDataService } from "./organization-subscription-data.service";
|
||||
import { PrivilegedControlsAdjustSubscriptionComponent } from "./privileged-controls-adjust-subscription.component";
|
||||
import { PrivilegedControlsPurchaseComponent } from "./privileged-controls-purchase.component";
|
||||
import * as restartSubscriptionDialog from "./restart-subscription-dialog.component";
|
||||
import { RestartSubscriptionDialogResultType } from "./restart-subscription-dialog.component";
|
||||
import { SecretsManagerAdjustSubscriptionComponent } from "./sm-adjust-subscription.component";
|
||||
@@ -79,6 +81,20 @@ class MockSmSubscribeStandaloneComponent {
|
||||
readonly onSubscribe = output<void>();
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: "billing-privileged-controls-purchase",
|
||||
template: "",
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
})
|
||||
class MockPrivilegedControlsPurchaseComponent {
|
||||
readonly plan = input<unknown>();
|
||||
readonly organizationId = input<unknown>();
|
||||
readonly customerDiscount = input<unknown>();
|
||||
readonly passwordManagerSeats = input<unknown>();
|
||||
readonly passwordManagerMaxAutoscaleSeats = input<unknown>();
|
||||
readonly purchased = output<void>();
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: "app-sm-adjust-subscription",
|
||||
template: "",
|
||||
@@ -287,6 +303,7 @@ describe("OrganizationSubscriptionCloudComponent", () => {
|
||||
SecretsManagerAdjustSubscriptionComponent,
|
||||
PrivilegedControlsAdjustSubscriptionComponent,
|
||||
OrganizationScheduledPriceIncreaseWarningComponent,
|
||||
PrivilegedControlsPurchaseComponent,
|
||||
],
|
||||
},
|
||||
add: {
|
||||
@@ -297,6 +314,7 @@ describe("OrganizationSubscriptionCloudComponent", () => {
|
||||
MockSmAdjustSubscriptionComponent,
|
||||
MockPrivilegedControlsAdjustSubscriptionComponent,
|
||||
MockScheduledPriceIncreaseWarningComponent,
|
||||
MockPrivilegedControlsPurchaseComponent,
|
||||
],
|
||||
},
|
||||
});
|
||||
@@ -1047,6 +1065,166 @@ describe("OrganizationSubscriptionCloudComponent", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("privileged controls purchase gating", () => {
|
||||
const buildEligibleOrganization = (overrides: Partial<Organization> = {}) =>
|
||||
buildOrganization({
|
||||
canEditSubscription: true,
|
||||
usePam: false,
|
||||
productTierType: ProductTierType.Enterprise,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const buildEnterpriseSubscription = (
|
||||
planOverrides: Record<string, unknown> = {},
|
||||
overrides: Partial<OrganizationSubscriptionResponse> = {},
|
||||
) => {
|
||||
const base = buildSubscriptionResponse();
|
||||
return buildSubscriptionResponse({
|
||||
planType: PlanType.EnterpriseAnnually,
|
||||
plan: {
|
||||
...base.plan,
|
||||
productTier: ProductTierType.Enterprise,
|
||||
PrivilegedControls: { seatPrice: 120 },
|
||||
...planOverrides,
|
||||
} as OrganizationSubscriptionResponse["plan"],
|
||||
...overrides,
|
||||
});
|
||||
};
|
||||
|
||||
const mockFlags = (billing: boolean, pam: boolean) =>
|
||||
configService.getFeatureFlag$.mockImplementation(
|
||||
(flag) =>
|
||||
of(
|
||||
(flag === FeatureFlag.PamBillingSupport && billing) ||
|
||||
(flag === FeatureFlag.Pam && pam),
|
||||
) as any,
|
||||
);
|
||||
|
||||
beforeEach(() => mockFlags(true, true));
|
||||
|
||||
/** Renders and waits for the subscription resource so each gate is evaluated on loaded data. */
|
||||
const render = async (options: {
|
||||
organization: Organization;
|
||||
subscription: OrganizationSubscriptionResponse;
|
||||
}) => {
|
||||
createComponent({ ...options, detectChanges: true });
|
||||
await fixture.whenStable();
|
||||
expect(component.organizationSubscription()).not.toBeNull();
|
||||
};
|
||||
|
||||
it("shows the purchase block for an eligible Enterprise organization", async () => {
|
||||
await render({
|
||||
organization: buildEligibleOrganization(),
|
||||
subscription: buildEnterpriseSubscription(),
|
||||
});
|
||||
expect(component.showPrivilegedControlsPurchase()).toBe(true);
|
||||
});
|
||||
|
||||
it("hides it when the billing flag is off", async () => {
|
||||
mockFlags(false, true);
|
||||
await render({
|
||||
organization: buildEligibleOrganization(),
|
||||
subscription: buildEnterpriseSubscription(),
|
||||
});
|
||||
expect(component.showPrivilegedControlsPurchase()).toBe(false);
|
||||
});
|
||||
|
||||
it("hides it when the PAM product flag is off", async () => {
|
||||
mockFlags(true, false);
|
||||
await render({
|
||||
organization: buildEligibleOrganization(),
|
||||
subscription: buildEnterpriseSubscription(),
|
||||
});
|
||||
expect(component.showPrivilegedControlsPurchase()).toBe(false);
|
||||
});
|
||||
|
||||
it("hides it when the organization already has Privileged Controls", async () => {
|
||||
await render({
|
||||
organization: buildEligibleOrganization({ usePam: true }),
|
||||
subscription: buildEnterpriseSubscription({}, { usePam: true }),
|
||||
});
|
||||
expect(component.showPrivilegedControlsPurchase()).toBe(false);
|
||||
});
|
||||
|
||||
it("hides it when the server reports Privileged Controls before the local organization syncs", async () => {
|
||||
await render({
|
||||
organization: buildEligibleOrganization({ usePam: false }),
|
||||
subscription: buildEnterpriseSubscription({}, { usePam: true }),
|
||||
});
|
||||
expect(component.showPrivilegedControlsPurchase()).toBe(false);
|
||||
});
|
||||
|
||||
it("hides it for a non-Enterprise plan", async () => {
|
||||
await render({
|
||||
organization: buildEligibleOrganization(),
|
||||
subscription: buildEnterpriseSubscription({ productTier: ProductTierType.Teams }),
|
||||
});
|
||||
expect(component.showPrivilegedControlsPurchase()).toBe(false);
|
||||
});
|
||||
|
||||
it("hides it when the plan has no Privileged Controls pricing", async () => {
|
||||
await render({
|
||||
organization: buildEligibleOrganization(),
|
||||
subscription: buildEnterpriseSubscription({ PrivilegedControls: null }),
|
||||
});
|
||||
expect(component.showPrivilegedControlsPurchase()).toBe(false);
|
||||
});
|
||||
|
||||
it("hides it when the subscription is cancelled", async () => {
|
||||
await render({
|
||||
organization: buildEligibleOrganization(),
|
||||
subscription: buildEnterpriseSubscription({}, { subscription: { cancelled: true } as any }),
|
||||
});
|
||||
expect(component.showPrivilegedControlsPurchase()).toBe(false);
|
||||
});
|
||||
|
||||
it("hides it when the organization has a provider", async () => {
|
||||
await render({
|
||||
organization: buildEligibleOrganization({ hasProvider: true }),
|
||||
subscription: buildEnterpriseSubscription(),
|
||||
});
|
||||
expect(component.showPrivilegedControlsPurchase()).toBe(false);
|
||||
});
|
||||
|
||||
it("passes the Password Manager seats and seat limit to the purchase block", async () => {
|
||||
await render({
|
||||
organization: buildEligibleOrganization(),
|
||||
subscription: buildEnterpriseSubscription({}, { seats: 25, maxAutoscaleSeats: 40 }),
|
||||
});
|
||||
fixture.detectChanges();
|
||||
|
||||
const block: MockPrivilegedControlsPurchaseComponent = fixture.debugElement.query(
|
||||
By.directive(MockPrivilegedControlsPurchaseComponent),
|
||||
).componentInstance;
|
||||
expect(block.passwordManagerSeats()).toBe(25);
|
||||
expect(block.passwordManagerMaxAutoscaleSeats()).toBe(40);
|
||||
});
|
||||
|
||||
const moreFromBitwardenHeadings = (): HTMLElement[] =>
|
||||
Array.from<HTMLElement>(fixture.nativeElement.querySelectorAll("h3")).filter(
|
||||
(heading) => heading.textContent?.trim() === "moreFromBitwarden",
|
||||
);
|
||||
|
||||
it("shows its own More from Bitwarden heading when Secrets Manager subscribe is hidden", async () => {
|
||||
await render({
|
||||
organization: buildEligibleOrganization({ useSecretsManager: true }),
|
||||
subscription: buildEnterpriseSubscription(),
|
||||
});
|
||||
fixture.detectChanges();
|
||||
expect(moreFromBitwardenHeadings().length).toBe(1);
|
||||
});
|
||||
|
||||
it("leaves the More from Bitwarden heading to Secrets Manager subscribe when it is shown", async () => {
|
||||
await render({
|
||||
organization: buildEligibleOrganization({ useSecretsManager: false }),
|
||||
subscription: buildEnterpriseSubscription(),
|
||||
});
|
||||
fixture.detectChanges();
|
||||
expect(component.showSecretsManagerSubscribe()).toBe(true);
|
||||
expect(moreFromBitwardenHeadings().length).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("privileged controls adjust gating", () => {
|
||||
const enablePamBillingSupport = () =>
|
||||
configService.getFeatureFlag$.mockImplementation(
|
||||
|
||||
@@ -61,6 +61,7 @@ import {
|
||||
PrivilegedControlsAdjustSubscriptionComponent,
|
||||
PrivilegedControlsSubscriptionOptions,
|
||||
} from "./privileged-controls-adjust-subscription.component";
|
||||
import { PrivilegedControlsPurchaseComponent } from "./privileged-controls-purchase.component";
|
||||
import { resolveOrgSubscriptionAccess } from "./resolve-org-subscription-access";
|
||||
import {
|
||||
openRestartSubscriptionDialog,
|
||||
@@ -116,6 +117,7 @@ const SubscriptionStatusLabels: Record<string, string> = {
|
||||
AdjustSubscription,
|
||||
SecretsManagerSubscribeStandaloneComponent,
|
||||
SecretsManagerAdjustSubscriptionComponent,
|
||||
PrivilegedControlsPurchaseComponent,
|
||||
PrivilegedControlsAdjustSubscriptionComponent,
|
||||
ErrorCardComponent,
|
||||
CalloutComponent,
|
||||
@@ -329,6 +331,38 @@ export class OrganizationSubscriptionCloudComponent {
|
||||
);
|
||||
});
|
||||
|
||||
private readonly pamBillingSupportEnabled = toSignal(
|
||||
this.configService.getFeatureFlag$(FeatureFlag.PamBillingSupport),
|
||||
{ initialValue: false },
|
||||
);
|
||||
|
||||
/** Privileged Controls itself; without it the product is reachable nowhere, so no Contact sales call to action. */
|
||||
private readonly pamEnabled = toSignal(this.configService.getFeatureFlag$(FeatureFlag.Pam), {
|
||||
initialValue: false,
|
||||
});
|
||||
|
||||
/**
|
||||
* Determines if the "Privileged Controls purchase" section should be shown.
|
||||
* @returns True if the section should be displayed, false otherwise.
|
||||
*/
|
||||
readonly showPrivilegedControlsPurchase = computed(() => {
|
||||
const org = this.organization();
|
||||
const subscription = this.organizationSubscription();
|
||||
const plan = subscription?.plan;
|
||||
if (org == null || subscription == null || plan == null) {
|
||||
return false;
|
||||
}
|
||||
return (
|
||||
!org.hasProvider &&
|
||||
this.pamBillingSupportEnabled() &&
|
||||
this.pamEnabled() &&
|
||||
!subscription.usePam &&
|
||||
plan.productTier === ProductTierType.Enterprise &&
|
||||
plan.PrivilegedControls != null &&
|
||||
!this.isSubscriptionCanceledOrPendingCancellation()
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* Determines if the "Adjust Secrets Manager" section should be shown.
|
||||
* @returns True if the section should be displayed, false otherwise.
|
||||
@@ -348,16 +382,6 @@ export class OrganizationSubscriptionCloudComponent {
|
||||
);
|
||||
});
|
||||
|
||||
private readonly pamBillingSupportEnabled = toSignal(
|
||||
this.configService.getFeatureFlag$(FeatureFlag.PamBillingSupport),
|
||||
{ initialValue: false },
|
||||
);
|
||||
|
||||
/** Privileged Controls itself; without it the product is reachable nowhere, so no Contact sales call to action. */
|
||||
private readonly pamEnabled = toSignal(this.configService.getFeatureFlag$(FeatureFlag.Pam), {
|
||||
initialValue: false,
|
||||
});
|
||||
|
||||
/** Self-serve Privileged Controls: seat and limit adjustment, shown only while PAM billing support is on. */
|
||||
readonly showAdjustPrivilegedControls = computed(() => {
|
||||
const org = this.organization();
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
<form [formGroup]="formGroup" [bitSubmit]="submit">
|
||||
<bit-accordion
|
||||
[title]="'privilegedControls' | i18n"
|
||||
startIcon="bwi-bitwarden-shield"
|
||||
height="auto"
|
||||
[open]="true"
|
||||
>
|
||||
<div class="tw-text-fg-body">
|
||||
{{ "privilegedControlsPurchaseDesc" | i18n }}
|
||||
<p class="tw-mb-0 tw-mt-3 tw-font-medium tw-text-fg-heading">{{ "whatsIncluded" | i18n }}</p>
|
||||
<ul class="tw-space-y-2">
|
||||
<li>{{ "privilegedControlsFeatureCredentialLeasing" | i18n }}</li>
|
||||
<li>{{ "privilegedControlsFeatureAccessRules" | i18n }}</li>
|
||||
<li>{{ "privilegedControlsFeatureRotation" | i18n }}</li>
|
||||
<li>{{ "privilegedControlsFeatureAuditLog" | i18n }}</li>
|
||||
<li>{{ "privilegedControlsFeatureGovernanceDashboard" | i18n }}</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="tw-mb-5 tw-text-fg-body">
|
||||
{{ "pricePerMember" | i18n: (monthlyCostPerSeat() | currency: "$") }} / {{ "month" | i18n }}
|
||||
</div>
|
||||
|
||||
<bit-form-control>
|
||||
<input
|
||||
id="privileged-controls-purchase_input_enabled"
|
||||
type="checkbox"
|
||||
bitCheckbox
|
||||
[formControl]="enabledControl"
|
||||
/>
|
||||
<bit-label>{{ "addPrivilegedControls" | i18n }}</bit-label>
|
||||
</bit-form-control>
|
||||
|
||||
@if (enabled()) {
|
||||
<div class="tw-w-1/2">
|
||||
<bit-form-field>
|
||||
<bit-label>{{ "seats" | i18n }}</bit-label>
|
||||
<input
|
||||
id="privileged-controls-purchase_input_seats"
|
||||
bitInput
|
||||
formControlName="seats"
|
||||
type="number"
|
||||
min="1"
|
||||
[max]="passwordManagerSeats()"
|
||||
step="1"
|
||||
/>
|
||||
</bit-form-field>
|
||||
</div>
|
||||
<bit-form-control>
|
||||
<input
|
||||
id="privileged-controls-purchase_input_limit-subscription"
|
||||
type="checkbox"
|
||||
bitCheckbox
|
||||
[formControl]="limitSubscriptionControl"
|
||||
/>
|
||||
<bit-label>{{ "limitSubscription" | i18n }}</bit-label>
|
||||
<bit-hint>{{ "privilegedControlsSeatLimitDesc" | i18n }}</bit-hint>
|
||||
</bit-form-control>
|
||||
@if (limitSubscription()) {
|
||||
<div class="tw-w-1/2">
|
||||
<bit-form-field>
|
||||
<bit-label>{{ "seatLimit" | i18n }}</bit-label>
|
||||
<input
|
||||
id="privileged-controls-purchase_input_seat-limit"
|
||||
bitInput
|
||||
formControlName="maxAutoscaleSeats"
|
||||
type="number"
|
||||
[min]="(seats() ?? 0) + 1"
|
||||
[max]="maxAutoscaleSeatsCap()"
|
||||
step="1"
|
||||
/>
|
||||
<bit-hint>
|
||||
<strong>{{ "maxSeatCost" | i18n }}:</strong>
|
||||
{{ maxAutoscaleSeats() || 0 }} × {{ seatPrice() | currency: "$" }} =
|
||||
{{ maxSeatTotal() | currency: "$" }} / {{ interval() | i18n }}
|
||||
</bit-hint>
|
||||
</bit-form-field>
|
||||
</div>
|
||||
}
|
||||
|
||||
<button
|
||||
id="privileged-controls-purchase_button_save"
|
||||
type="submit"
|
||||
bitButton
|
||||
buttonType="primary"
|
||||
bitFormButton
|
||||
>
|
||||
{{ "save" | i18n }}
|
||||
</button>
|
||||
}
|
||||
</bit-accordion>
|
||||
</form>
|
||||
@@ -0,0 +1,426 @@
|
||||
import { ComponentFixture, TestBed } from "@angular/core/testing";
|
||||
import { mock } from "jest-mock-extended";
|
||||
|
||||
import { BillingCustomerDiscount } from "@bitwarden/common/billing/models/response/organization-subscription.response";
|
||||
import { PlanResponse } from "@bitwarden/common/billing/models/response/plan.response";
|
||||
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
|
||||
import { OrganizationId } from "@bitwarden/common/types/guid";
|
||||
import { SyncService } from "@bitwarden/common/vault/abstractions/sync/sync.service.abstraction";
|
||||
import { ToastService } from "@bitwarden/components";
|
||||
|
||||
import { OrganizationBillingClient } from "../clients/organization-billing.client";
|
||||
|
||||
import { PrivilegedControlsPurchaseComponent } from "./privileged-controls-purchase.component";
|
||||
|
||||
describe("PrivilegedControlsPurchaseComponent", () => {
|
||||
let fixture: ComponentFixture<PrivilegedControlsPurchaseComponent>;
|
||||
let component: PrivilegedControlsPurchaseComponent;
|
||||
let billingClient: jest.Mocked<OrganizationBillingClient>;
|
||||
let syncService: jest.Mocked<SyncService>;
|
||||
let toastService: jest.Mocked<ToastService>;
|
||||
|
||||
const organizationId = "org-id" as OrganizationId;
|
||||
|
||||
const buildPlan = (overrides: { isAnnual?: boolean; seatPrice?: number } = {}): PlanResponse =>
|
||||
({
|
||||
isAnnual: overrides.isAnnual ?? true,
|
||||
PrivilegedControls: { seatPrice: overrides.seatPrice ?? 120 },
|
||||
}) as PlanResponse;
|
||||
|
||||
const createComponent = (options?: {
|
||||
plan?: PlanResponse;
|
||||
customerDiscount?: BillingCustomerDiscount | null;
|
||||
passwordManagerSeats?: number;
|
||||
passwordManagerMaxAutoscaleSeats?: number | null;
|
||||
}) => {
|
||||
fixture = TestBed.createComponent(PrivilegedControlsPurchaseComponent);
|
||||
component = fixture.componentInstance;
|
||||
fixture.componentRef.setInput("plan", options?.plan ?? buildPlan());
|
||||
fixture.componentRef.setInput("organizationId", organizationId);
|
||||
fixture.componentRef.setInput("customerDiscount", options?.customerDiscount ?? null);
|
||||
fixture.componentRef.setInput("passwordManagerSeats", options?.passwordManagerSeats ?? 50);
|
||||
fixture.componentRef.setInput(
|
||||
"passwordManagerMaxAutoscaleSeats",
|
||||
options?.passwordManagerMaxAutoscaleSeats ?? null,
|
||||
);
|
||||
fixture.detectChanges();
|
||||
};
|
||||
|
||||
const form = () => component["formGroup"];
|
||||
|
||||
const enableAndFill = (seats: number, maxAutoscaleSeats: number | null) => {
|
||||
component["enabledControl"].setValue(true);
|
||||
form().controls.seats.setValue(seats);
|
||||
form().controls.maxAutoscaleSeats.setValue(maxAutoscaleSeats);
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
billingClient = mock<OrganizationBillingClient>();
|
||||
syncService = mock<SyncService>();
|
||||
toastService = mock<ToastService>();
|
||||
const i18nService = mock<I18nService>();
|
||||
i18nService.t.mockImplementation((key: string) => key);
|
||||
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [PrivilegedControlsPurchaseComponent],
|
||||
providers: [
|
||||
{ provide: OrganizationBillingClient, useValue: billingClient },
|
||||
{ provide: SyncService, useValue: syncService },
|
||||
{ provide: ToastService, useValue: toastService },
|
||||
{ provide: I18nService, useValue: i18nService },
|
||||
],
|
||||
}).compileComponents();
|
||||
});
|
||||
|
||||
describe("price", () => {
|
||||
it("shows the monthly price for an annual plan", () => {
|
||||
createComponent();
|
||||
expect(component["monthlyCostPerSeat"]()).toBe(10);
|
||||
});
|
||||
|
||||
it("shows the plan price for a monthly plan", () => {
|
||||
createComponent({ plan: buildPlan({ isAnnual: false, seatPrice: 11 }) });
|
||||
expect(component["monthlyCostPerSeat"]()).toBe(11);
|
||||
});
|
||||
|
||||
it("applies an active percentage discount", () => {
|
||||
createComponent({
|
||||
customerDiscount: { active: true, percentOff: 20 } as BillingCustomerDiscount,
|
||||
});
|
||||
expect(component["monthlyCostPerSeat"]()).toBe(8);
|
||||
});
|
||||
|
||||
it("ignores an inactive discount", () => {
|
||||
createComponent({
|
||||
customerDiscount: { active: false, percentOff: 20 } as BillingCustomerDiscount,
|
||||
});
|
||||
expect(component["monthlyCostPerSeat"]()).toBe(10);
|
||||
});
|
||||
});
|
||||
|
||||
describe("form", () => {
|
||||
it("defaults seats to 1", () => {
|
||||
createComponent();
|
||||
expect(form().controls.seats.value).toBe(1);
|
||||
});
|
||||
|
||||
it("accepts 1 seat", () => {
|
||||
createComponent();
|
||||
enableAndFill(1, null);
|
||||
expect(form().controls.seats.valid).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects zero seats", () => {
|
||||
createComponent();
|
||||
enableAndFill(0, null);
|
||||
expect(form().controls.seats.hasError("min")).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts seats equal to the Password Manager seat count", () => {
|
||||
createComponent({ passwordManagerSeats: 50 });
|
||||
enableAndFill(50, null);
|
||||
expect(form().controls.seats.valid).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects seats above the Password Manager seat count", () => {
|
||||
createComponent({ passwordManagerSeats: 50 });
|
||||
enableAndFill(51, null);
|
||||
expect(form().controls.seats.getError("seatsAbovePasswordManagerSeats")).toEqual({
|
||||
message: "privilegedControlsSeatsAbovePasswordManagerSeats",
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects seats above 100,000", () => {
|
||||
createComponent();
|
||||
enableAndFill(100001, null);
|
||||
expect(form().controls.seats.hasError("max")).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects decimal seats", () => {
|
||||
createComponent();
|
||||
enableAndFill(10.5, null);
|
||||
expect(form().controls.seats.hasError("wholeNumber")).toBe(true);
|
||||
});
|
||||
|
||||
it("requires seats", () => {
|
||||
createComponent();
|
||||
enableAndFill(null, null);
|
||||
expect(form().controls.seats.hasError("required")).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts a seat limit above seats", () => {
|
||||
createComponent();
|
||||
enableAndFill(12, 13);
|
||||
expect(form().controls.maxAutoscaleSeats.hasError("maxAutoscaleSeatsNotAboveSeats")).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects a seat limit equal to seats", () => {
|
||||
createComponent();
|
||||
enableAndFill(12, 12);
|
||||
expect(form().controls.maxAutoscaleSeats.getError("maxAutoscaleSeatsNotAboveSeats")).toEqual({
|
||||
message: "privilegedControlsSeatLimitNotAboveSeats",
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects a negative seat limit", () => {
|
||||
createComponent();
|
||||
enableAndFill(12, -5);
|
||||
expect(form().controls.maxAutoscaleSeats.hasError("maxAutoscaleSeatsNotAboveSeats")).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects a decimal seat limit", () => {
|
||||
createComponent();
|
||||
enableAndFill(12, 20.5);
|
||||
expect(form().controls.maxAutoscaleSeats.hasError("wholeNumber")).toBe(true);
|
||||
});
|
||||
|
||||
it("caps the seat limit at the Password Manager seat limit when one is set", () => {
|
||||
createComponent({ passwordManagerSeats: 50, passwordManagerMaxAutoscaleSeats: 30 });
|
||||
enableAndFill(12, 30);
|
||||
expect(form().controls.maxAutoscaleSeats.valid).toBe(true);
|
||||
|
||||
form().controls.maxAutoscaleSeats.setValue(31);
|
||||
expect(
|
||||
form().controls.maxAutoscaleSeats.getError("maxAutoscaleSeatsAbovePasswordManager"),
|
||||
).toEqual({
|
||||
message: "privilegedControlsSeatLimitAbovePasswordManagerSeatLimit",
|
||||
});
|
||||
});
|
||||
|
||||
it("caps the seat limit at the Password Manager seat count when there is no Password Manager seat limit", () => {
|
||||
createComponent({ passwordManagerSeats: 50, passwordManagerMaxAutoscaleSeats: null });
|
||||
enableAndFill(12, 50);
|
||||
expect(form().controls.maxAutoscaleSeats.valid).toBe(true);
|
||||
|
||||
form().controls.maxAutoscaleSeats.setValue(51);
|
||||
expect(
|
||||
form().controls.maxAutoscaleSeats.getError("maxAutoscaleSeatsAbovePasswordManager"),
|
||||
).toEqual({
|
||||
message: "privilegedControlsSeatLimitAbovePasswordManagerSeats",
|
||||
});
|
||||
});
|
||||
|
||||
it("flags the seat limit when seats are raised to it", () => {
|
||||
createComponent();
|
||||
enableAndFill(12, 13);
|
||||
|
||||
form().controls.seats.setValue(13);
|
||||
expect(form().controls.maxAutoscaleSeats.hasError("maxAutoscaleSeatsNotAboveSeats")).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("clears the seat limit error when seats are lowered below it", () => {
|
||||
createComponent();
|
||||
enableAndFill(12, 12);
|
||||
|
||||
form().controls.seats.setValue(11);
|
||||
expect(form().controls.maxAutoscaleSeats.valid).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps the seat limit's own errors when the seats comparison passes", () => {
|
||||
createComponent({ passwordManagerSeats: 50 });
|
||||
enableAndFill(12, 51);
|
||||
|
||||
form().controls.seats.setValue(10);
|
||||
expect(
|
||||
form().controls.maxAutoscaleSeats.hasError("maxAutoscaleSeatsAbovePasswordManager"),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("hides the seat fields until Privileged Controls is checked", () => {
|
||||
createComponent();
|
||||
|
||||
expect(
|
||||
fixture.nativeElement.querySelector("#privileged-controls-purchase_input_seats"),
|
||||
).toBeNull();
|
||||
|
||||
fixture.nativeElement.querySelector("#privileged-controls-purchase_input_enabled").click();
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(
|
||||
fixture.nativeElement.querySelector("#privileged-controls-purchase_input_seats"),
|
||||
).not.toBeNull();
|
||||
});
|
||||
|
||||
it("hides the seat limit field until the subscription limit is checked", () => {
|
||||
createComponent();
|
||||
fixture.nativeElement.querySelector("#privileged-controls-purchase_input_enabled").click();
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(
|
||||
fixture.nativeElement.querySelector("#privileged-controls-purchase_input_seat-limit"),
|
||||
).toBeNull();
|
||||
|
||||
fixture.nativeElement
|
||||
.querySelector("#privileged-controls-purchase_input_limit-subscription")
|
||||
.click();
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(
|
||||
fixture.nativeElement.querySelector("#privileged-controls-purchase_input_seat-limit"),
|
||||
).not.toBeNull();
|
||||
});
|
||||
|
||||
it("shows the seat limit description under the subscription limit checkbox", () => {
|
||||
createComponent();
|
||||
fixture.nativeElement.querySelector("#privileged-controls-purchase_input_enabled").click();
|
||||
fixture.detectChanges();
|
||||
|
||||
const limitSubscriptionInput: HTMLElement = fixture.nativeElement.querySelector(
|
||||
"#privileged-controls-purchase_input_limit-subscription",
|
||||
);
|
||||
expect(limitSubscriptionInput.closest("bit-form-control")?.textContent).toContain(
|
||||
"privilegedControlsSeatLimitDesc",
|
||||
);
|
||||
});
|
||||
|
||||
it("clears the seat limit when the subscription limit is unchecked", () => {
|
||||
createComponent();
|
||||
component["limitSubscriptionControl"].setValue(true);
|
||||
enableAndFill(12, 20);
|
||||
|
||||
component["limitSubscriptionControl"].setValue(false);
|
||||
|
||||
expect(form().controls.maxAutoscaleSeats.value).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("max seat cost", () => {
|
||||
it("multiplies the seat limit by the plan seat price", () => {
|
||||
createComponent();
|
||||
enableAndFill(12, 20);
|
||||
expect(component["maxSeatTotal"]()).toBe(2400);
|
||||
});
|
||||
|
||||
it("applies an active percentage discount", () => {
|
||||
createComponent({
|
||||
customerDiscount: { active: true, percentOff: 20 } as BillingCustomerDiscount,
|
||||
});
|
||||
enableAndFill(12, 20);
|
||||
expect(component["maxSeatTotal"]()).toBe(1920);
|
||||
});
|
||||
|
||||
it("is zero when the seat limit is empty", () => {
|
||||
createComponent();
|
||||
enableAndFill(12, null);
|
||||
expect(component["maxSeatTotal"]()).toBe(0);
|
||||
});
|
||||
|
||||
it("uses the plan billing interval", () => {
|
||||
createComponent({ plan: buildPlan({ isAnnual: false, seatPrice: 11 }) });
|
||||
expect(component["interval"]()).toBe("month");
|
||||
});
|
||||
});
|
||||
|
||||
describe("submit", () => {
|
||||
it("sends the seats and seat limit on submit", async () => {
|
||||
createComponent();
|
||||
enableAndFill(15, 20);
|
||||
|
||||
await component["submit"]();
|
||||
|
||||
expect(billingClient.purchasePrivilegedControls).toHaveBeenCalledWith(organizationId, {
|
||||
seats: 15,
|
||||
maxAutoscaleSeats: 20,
|
||||
});
|
||||
});
|
||||
|
||||
it("sends a null seat limit when the subscription limit is unchecked", async () => {
|
||||
createComponent();
|
||||
component["limitSubscriptionControl"].setValue(true);
|
||||
enableAndFill(15, 20);
|
||||
component["limitSubscriptionControl"].setValue(false);
|
||||
|
||||
await component["submit"]();
|
||||
|
||||
expect(billingClient.purchasePrivilegedControls).toHaveBeenCalledWith(organizationId, {
|
||||
seats: 15,
|
||||
maxAutoscaleSeats: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("sends a null seat limit when the field is cleared", async () => {
|
||||
createComponent();
|
||||
enableAndFill(15, 20);
|
||||
form().controls.maxAutoscaleSeats.setValue(null);
|
||||
|
||||
await component["submit"]();
|
||||
|
||||
expect(billingClient.purchasePrivilegedControls).toHaveBeenCalledWith(organizationId, {
|
||||
seats: 15,
|
||||
maxAutoscaleSeats: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("does not purchase when seats are above the Password Manager seat count", async () => {
|
||||
createComponent({ passwordManagerSeats: 50 });
|
||||
enableAndFill(51, null);
|
||||
|
||||
await component["submit"]();
|
||||
|
||||
expect(billingClient.purchasePrivilegedControls).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not purchase when the seat limit is not above seats", async () => {
|
||||
createComponent();
|
||||
enableAndFill(12, 12);
|
||||
|
||||
await component["submit"]();
|
||||
|
||||
expect(billingClient.purchasePrivilegedControls).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not purchase when seats are a decimal", async () => {
|
||||
createComponent();
|
||||
enableAndFill(10.5, null);
|
||||
|
||||
await component["submit"]();
|
||||
|
||||
expect(billingClient.purchasePrivilegedControls).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not purchase when seats are empty", async () => {
|
||||
createComponent();
|
||||
enableAndFill(null, null);
|
||||
|
||||
await component["submit"]();
|
||||
|
||||
expect(billingClient.purchasePrivilegedControls).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("shows a toast, syncs, and emits after a successful purchase", async () => {
|
||||
createComponent();
|
||||
const emitted = jest.fn();
|
||||
component.purchased.subscribe(emitted);
|
||||
enableAndFill(15, null);
|
||||
|
||||
await component["submit"]();
|
||||
|
||||
expect(toastService.showToast).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ variant: "success", message: "privilegedControlsPurchased" }),
|
||||
);
|
||||
expect(syncService.fullSync).toHaveBeenCalledWith(true);
|
||||
expect(emitted).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("does not toast, sync, or emit when the purchase fails", async () => {
|
||||
createComponent();
|
||||
const emitted = jest.fn();
|
||||
component.purchased.subscribe(emitted);
|
||||
const error = new Error("Your card was declined.");
|
||||
billingClient.purchasePrivilegedControls.mockRejectedValue(error);
|
||||
enableAndFill(15, null);
|
||||
|
||||
await expect(component["submit"]()).rejects.toBe(error);
|
||||
|
||||
expect(toastService.showToast).not.toHaveBeenCalled();
|
||||
expect(syncService.fullSync).not.toHaveBeenCalled();
|
||||
expect(emitted).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,208 @@
|
||||
import {
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
computed,
|
||||
inject,
|
||||
input,
|
||||
OnInit,
|
||||
output,
|
||||
} from "@angular/core";
|
||||
import { takeUntilDestroyed, toSignal } from "@angular/core/rxjs-interop";
|
||||
import {
|
||||
AbstractControl,
|
||||
FormControl,
|
||||
FormGroup,
|
||||
ValidationErrors,
|
||||
Validators,
|
||||
} from "@angular/forms";
|
||||
|
||||
import { BillingCustomerDiscount } from "@bitwarden/common/billing/models/response/organization-subscription.response";
|
||||
import { PlanResponse } from "@bitwarden/common/billing/models/response/plan.response";
|
||||
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
|
||||
import { OrganizationId } from "@bitwarden/common/types/guid";
|
||||
import { SyncService } from "@bitwarden/common/vault/abstractions/sync/sync.service.abstraction";
|
||||
import { AccordionComponent, ToastService } from "@bitwarden/components";
|
||||
|
||||
import { SharedModule } from "../../shared";
|
||||
import { OrganizationBillingClient } from "../clients/organization-billing.client";
|
||||
|
||||
const MAX_PURCHASABLE_QUANTITY = 100000;
|
||||
|
||||
@Component({
|
||||
selector: "billing-privileged-controls-purchase",
|
||||
templateUrl: "privileged-controls-purchase.component.html",
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
imports: [SharedModule, AccordionComponent],
|
||||
})
|
||||
export class PrivilegedControlsPurchaseComponent implements OnInit {
|
||||
private readonly organizationBillingClient = inject(OrganizationBillingClient);
|
||||
private readonly syncService = inject(SyncService);
|
||||
private readonly toastService = inject(ToastService);
|
||||
private readonly i18nService = inject(I18nService);
|
||||
|
||||
readonly plan = input.required<PlanResponse>();
|
||||
readonly organizationId = input.required<OrganizationId>();
|
||||
readonly customerDiscount = input<BillingCustomerDiscount | null>(null);
|
||||
readonly passwordManagerSeats = input.required<number>();
|
||||
readonly passwordManagerMaxAutoscaleSeats = input<number | null>(null);
|
||||
|
||||
readonly purchased = output<void>();
|
||||
|
||||
protected readonly enabledControl = new FormControl(false, { nonNullable: true });
|
||||
|
||||
protected readonly enabled = toSignal(this.enabledControl.valueChanges, {
|
||||
initialValue: this.enabledControl.value,
|
||||
});
|
||||
|
||||
protected readonly limitSubscriptionControl = new FormControl(false, { nonNullable: true });
|
||||
|
||||
protected readonly limitSubscription = toSignal(this.limitSubscriptionControl.valueChanges, {
|
||||
initialValue: this.limitSubscriptionControl.value,
|
||||
});
|
||||
|
||||
protected readonly maxAutoscaleSeatsCap = computed(
|
||||
() => this.passwordManagerMaxAutoscaleSeats() ?? this.passwordManagerSeats(),
|
||||
);
|
||||
|
||||
protected readonly seatPrice = computed(() =>
|
||||
this.discountPrice(this.plan().PrivilegedControls.seatPrice),
|
||||
);
|
||||
|
||||
protected readonly monthlyCostPerSeat = computed(() =>
|
||||
this.plan().isAnnual ? this.seatPrice() / 12 : this.seatPrice(),
|
||||
);
|
||||
|
||||
protected readonly interval = computed(() => (this.plan().isAnnual ? "year" : "month"));
|
||||
|
||||
private readonly seatsControl = new FormControl<number | null>(null, [
|
||||
Validators.required,
|
||||
Validators.min(1),
|
||||
Validators.max(MAX_PURCHASABLE_QUANTITY),
|
||||
(control: AbstractControl) => this.validateWholeNumber(control),
|
||||
(control: AbstractControl) => this.validateSeatsWithinPasswordManagerSeats(control),
|
||||
]);
|
||||
|
||||
private readonly maxAutoscaleSeatsControl = new FormControl<number | null>(null, [
|
||||
Validators.max(MAX_PURCHASABLE_QUANTITY),
|
||||
(control: AbstractControl) => this.validateWholeNumber(control),
|
||||
(control: AbstractControl) => this.validateMaxAutoscaleSeatsAboveSeats(control),
|
||||
(control: AbstractControl) => this.validateMaxAutoscaleSeatsWithinCap(control),
|
||||
]);
|
||||
|
||||
protected readonly formGroup = new FormGroup({
|
||||
seats: this.seatsControl,
|
||||
maxAutoscaleSeats: this.maxAutoscaleSeatsControl,
|
||||
});
|
||||
|
||||
protected readonly seats = toSignal(this.seatsControl.valueChanges, {
|
||||
initialValue: this.seatsControl.value,
|
||||
});
|
||||
|
||||
protected readonly maxAutoscaleSeats = toSignal(this.maxAutoscaleSeatsControl.valueChanges, {
|
||||
initialValue: this.maxAutoscaleSeatsControl.value,
|
||||
});
|
||||
|
||||
protected readonly maxSeatTotal = computed(
|
||||
() => (this.maxAutoscaleSeats() ?? 0) * this.seatPrice(),
|
||||
);
|
||||
|
||||
constructor() {
|
||||
this.seatsControl.valueChanges
|
||||
.pipe(takeUntilDestroyed())
|
||||
.subscribe(() => this.maxAutoscaleSeatsControl.updateValueAndValidity());
|
||||
|
||||
this.limitSubscriptionControl.valueChanges
|
||||
.pipe(takeUntilDestroyed())
|
||||
.subscribe((limitSubscription) => {
|
||||
if (!limitSubscription) {
|
||||
this.maxAutoscaleSeatsControl.setValue(null);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
ngOnInit() {
|
||||
// Set after inputs are bound, since the seats validators read the required passwordManagerSeats input.
|
||||
this.seatsControl.setValue(1);
|
||||
}
|
||||
|
||||
protected readonly submit = async () => {
|
||||
this.formGroup.markAllAsTouched();
|
||||
const { seats, maxAutoscaleSeats } = this.formGroup.getRawValue();
|
||||
if (this.formGroup.invalid || seats == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
await this.organizationBillingClient.purchasePrivilegedControls(this.organizationId(), {
|
||||
seats,
|
||||
maxAutoscaleSeats: maxAutoscaleSeats ?? null,
|
||||
});
|
||||
|
||||
this.toastService.showToast({
|
||||
variant: "success",
|
||||
message: this.i18nService.t("privilegedControlsPurchased"),
|
||||
});
|
||||
|
||||
await this.syncService.fullSync(true);
|
||||
|
||||
this.purchased.emit();
|
||||
};
|
||||
|
||||
private discountPrice(price: number): number {
|
||||
const discount = this.customerDiscount();
|
||||
return discount?.active ? price - price * ((discount.percentOff ?? 0) / 100) : price;
|
||||
}
|
||||
|
||||
private validateWholeNumber(control: AbstractControl): ValidationErrors | null {
|
||||
if (control.value == null || Number.isInteger(control.value)) {
|
||||
return null;
|
||||
}
|
||||
return { wholeNumber: { message: this.i18nService.t("integerInputError") } };
|
||||
}
|
||||
|
||||
private validateSeatsWithinPasswordManagerSeats(
|
||||
control: AbstractControl,
|
||||
): ValidationErrors | null {
|
||||
if (control.value == null) {
|
||||
return null;
|
||||
}
|
||||
const passwordManagerSeats = this.passwordManagerSeats();
|
||||
return control.value > passwordManagerSeats
|
||||
? {
|
||||
seatsAbovePasswordManagerSeats: {
|
||||
message: this.i18nService.t(
|
||||
"privilegedControlsSeatsAbovePasswordManagerSeats",
|
||||
passwordManagerSeats,
|
||||
),
|
||||
},
|
||||
}
|
||||
: null;
|
||||
}
|
||||
|
||||
private validateMaxAutoscaleSeatsAboveSeats(control: AbstractControl): ValidationErrors | null {
|
||||
if (control.value == null || control.value > (this.seatsControl.value ?? 0)) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
maxAutoscaleSeatsNotAboveSeats: {
|
||||
message: this.i18nService.t("privilegedControlsSeatLimitNotAboveSeats"),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
private validateMaxAutoscaleSeatsWithinCap(control: AbstractControl): ValidationErrors | null {
|
||||
if (control.value == null) {
|
||||
return null;
|
||||
}
|
||||
const cap = this.maxAutoscaleSeatsCap();
|
||||
if (control.value <= cap) {
|
||||
return null;
|
||||
}
|
||||
const messageKey =
|
||||
this.passwordManagerMaxAutoscaleSeats() == null
|
||||
? "privilegedControlsSeatLimitAbovePasswordManagerSeats"
|
||||
: "privilegedControlsSeatLimitAbovePasswordManagerSeatLimit";
|
||||
return {
|
||||
maxAutoscaleSeatsAbovePasswordManager: { message: this.i18nService.t(messageKey, cap) },
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,11 @@
|
||||
import { NgModule } from "@angular/core";
|
||||
|
||||
import { BannerModule, FileUploadComponent, SpinnerComponent } from "@bitwarden/components";
|
||||
import {
|
||||
AccordionComponent,
|
||||
BannerModule,
|
||||
FileUploadComponent,
|
||||
SpinnerComponent,
|
||||
} from "@bitwarden/components";
|
||||
import { CartSummaryComponent, DiscountBadgeComponent } from "@bitwarden/pricing";
|
||||
import { Vfo1I18nPipe } from "@bitwarden/vault";
|
||||
import {
|
||||
@@ -24,6 +29,7 @@ import { UpdateLicenseComponent } from "./update-license.component";
|
||||
|
||||
@NgModule({
|
||||
imports: [
|
||||
AccordionComponent,
|
||||
BannerModule,
|
||||
CartSummaryComponent,
|
||||
DiscountBadgeComponent,
|
||||
|
||||
@@ -1,17 +1,15 @@
|
||||
<div *ngIf="formGroup && selectedPlan != null" [formGroup]="formGroup">
|
||||
<h3 bitTypography="h3">{{ "moreFromBitwarden" | i18n }}</h3>
|
||||
<div class="tw-rounded-t tw-bg-background-alt3 tw-p-5">
|
||||
<div class="tw-w-72">
|
||||
<bit-svg [content]="logo"></bit-svg>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
class="tw-rounded-b tw-border-x tw-border-b tw-border-t-0 tw-border-solid tw-border-secondary-300 tw-p-5"
|
||||
<bit-accordion
|
||||
[title]="'secretsManager' | i18n"
|
||||
startIcon="bwi-bitwarden-shield"
|
||||
height="auto"
|
||||
[open]="true"
|
||||
>
|
||||
<h4 bitTypography="h4">{{ "secretsManagerForPlan" | i18n: planName }}</h4>
|
||||
<div class="tw-text-muted">
|
||||
{{ "secretsManagerForPlanDesc" | i18n }}
|
||||
<ul>
|
||||
<div class="tw-text-fg-body">
|
||||
{{ "secretsManagerPurchaseDesc" | i18n }}
|
||||
<p class="tw-mb-0 tw-mt-3 tw-font-medium tw-text-fg-heading">{{ "whatsIncluded" | i18n }}</p>
|
||||
<ul class="tw-space-y-2">
|
||||
<li *ngIf="product == productTypes.Free">{{ "limitedUsers" | i18n: maxUsers }}</li>
|
||||
<li>{{ "unlimitedSecrets" | i18n }}</li>
|
||||
<li *ngIf="product == productTypes.Free; else unlimitedProjects">
|
||||
@@ -20,7 +18,7 @@
|
||||
<ng-template #unlimitedProjects>
|
||||
<li>{{ "unlimitedProjects" | i18n }}</li>
|
||||
</ng-template>
|
||||
<li>{{ "machineAccountsIncluded" | i18n: serviceAccountsIncluded }}</li>
|
||||
<li>{{ "includedMachineAccountsV2" | i18n: serviceAccountsIncluded }}</li>
|
||||
<li *ngIf="product != productTypes.Free">
|
||||
{{
|
||||
"additionalMachineAccountCost" | i18n: (monthlyCostPerServiceAccount | currency: "$")
|
||||
@@ -29,9 +27,9 @@
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="tw-mb-5">
|
||||
<div class="tw-mb-5 tw-text-fg-body">
|
||||
<span *ngIf="product != productTypes.Free; else freeForever">
|
||||
{{ "costPerUser" | i18n: (monthlyCostPerUser | currency: "$") }} /{{ "month" | i18n }}
|
||||
{{ "pricePerMember" | i18n: (monthlyCostPerUser | currency: "$") }} / {{ "month" | i18n }}
|
||||
</span>
|
||||
<ng-template #freeForever>
|
||||
<span>{{ "freeForever" | i18n }}</span>
|
||||
@@ -40,7 +38,7 @@
|
||||
|
||||
<bit-form-control>
|
||||
<input type="checkbox" bitCheckbox formControlName="enabled" />
|
||||
<bit-label>{{ "subscribeToSecretsManager" | i18n }}</bit-label>
|
||||
<bit-label>{{ "addSecretsManager" | i18n }}</bit-label>
|
||||
<bit-hint *ngIf="upgradeOrganization">{{ "addSecretsManagerUpgradeDesc" | i18n }}</bit-hint>
|
||||
</bit-form-control>
|
||||
|
||||
@@ -69,5 +67,5 @@
|
||||
{{ "save" | i18n }}
|
||||
</button>
|
||||
</ng-container>
|
||||
</div>
|
||||
</bit-accordion>
|
||||
</div>
|
||||
|
||||
@@ -1,17 +1,13 @@
|
||||
// FIXME: Update this file to be type safe and remove this and next line
|
||||
// @ts-strict-ignore
|
||||
import { Component, Input, OnDestroy, OnInit, inject } from "@angular/core";
|
||||
import { toSignal } from "@angular/core/rxjs-interop";
|
||||
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
|
||||
import { Subject, startWith, takeUntil } from "rxjs";
|
||||
|
||||
import { ControlsOf } from "@bitwarden/angular/types/controls-of";
|
||||
import { SecretsManagerAlt } from "@bitwarden/assets/svg";
|
||||
import { ProductTierType } from "@bitwarden/common/billing/enums";
|
||||
import { BillingCustomerDiscount } from "@bitwarden/common/billing/models/response/organization-subscription.response";
|
||||
import { PlanResponse } from "@bitwarden/common/billing/models/response/plan.response";
|
||||
import { FeatureFlag } from "@bitwarden/common/enums/feature-flag.enum";
|
||||
import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service";
|
||||
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
|
||||
|
||||
export interface SecretsManagerSubscription {
|
||||
@@ -41,7 +37,6 @@ export const secretsManagerSubscribeFormFactory = (
|
||||
})
|
||||
export class SecretsManagerSubscribeComponent implements OnInit, OnDestroy {
|
||||
private i18nService = inject(I18nService);
|
||||
private configService = inject(ConfigService);
|
||||
|
||||
// FIXME(https://bitwarden.atlassian.net/browse/CL-903): Migrate to Signals
|
||||
// eslint-disable-next-line @angular-eslint/prefer-signals
|
||||
@@ -59,16 +54,10 @@ export class SecretsManagerSubscribeComponent implements OnInit, OnDestroy {
|
||||
// eslint-disable-next-line @angular-eslint/prefer-signals
|
||||
@Input() customerDiscount: BillingCustomerDiscount;
|
||||
|
||||
logo = SecretsManagerAlt;
|
||||
productTypes = ProductTierType;
|
||||
|
||||
private destroy$ = new Subject<void>();
|
||||
|
||||
protected readonly vfo1Enabled = toSignal(
|
||||
this.configService.getFeatureFlag$(FeatureFlag.VFO1Foundation),
|
||||
{ initialValue: false },
|
||||
);
|
||||
|
||||
ngOnInit() {
|
||||
this.formGroup.controls.enabled.valueChanges
|
||||
.pipe(startWith(this.formGroup.value.enabled), takeUntil(this.destroy$))
|
||||
@@ -101,20 +90,6 @@ export class SecretsManagerSubscribeComponent implements OnInit, OnDestroy {
|
||||
return this.selectedPlan.productTier;
|
||||
}
|
||||
|
||||
get planName() {
|
||||
switch (this.product) {
|
||||
case ProductTierType.Free:
|
||||
return this.vfo1Enabled()
|
||||
? this.i18nService.t("freePlanWithSharedVault")
|
||||
: this.i18nService.t("free2PersonOrganization");
|
||||
case ProductTierType.Teams:
|
||||
case ProductTierType.TeamsStarter:
|
||||
return this.i18nService.t("planNameTeams");
|
||||
case ProductTierType.Enterprise:
|
||||
return this.i18nService.t("planNameEnterprise");
|
||||
}
|
||||
}
|
||||
|
||||
get serviceAccountsIncluded() {
|
||||
return this.selectedPlan.SecretsManager.baseServiceAccount;
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ import { ActivatedRoute, Router } from "@angular/router";
|
||||
import { mock, MockProxy } from "jest-mock-extended";
|
||||
import { BehaviorSubject, of } from "rxjs";
|
||||
|
||||
import { RegistrationFinishService } from "@bitwarden/auth/angular";
|
||||
import { RegistrationFinishService } from "@bitwarden/angular/auth/registration";
|
||||
import { LoginStrategyServiceAbstraction } from "@bitwarden/auth/common";
|
||||
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
|
||||
import { OrganizationBillingServiceAbstraction } from "@bitwarden/common/billing/abstractions/organization-billing.service";
|
||||
@@ -116,12 +116,12 @@ describe("CompleteTrialInitiationComponent", () => {
|
||||
expect(component.trialLength).toBe(7);
|
||||
});
|
||||
|
||||
it("should default trialLength to 7 when not provided", async () => {
|
||||
it("should default trialLength to 14 when not provided", async () => {
|
||||
mockActivatedRoute.queryParams.next({
|
||||
product: ProductType.PasswordManager,
|
||||
productTier: ProductTierType.Enterprise,
|
||||
});
|
||||
expect(component.trialLength).toBe(7);
|
||||
expect(component.trialLength).toBe(14);
|
||||
});
|
||||
|
||||
it("should read salesAssistedToken from query params", async () => {
|
||||
|
||||
@@ -5,11 +5,8 @@ import { FormBuilder, Validators } from "@angular/forms";
|
||||
import { ActivatedRoute, Router } from "@angular/router";
|
||||
import { firstValueFrom } from "rxjs";
|
||||
|
||||
import {
|
||||
InputPasswordFlow,
|
||||
PasswordInputResult,
|
||||
RegistrationFinishService,
|
||||
} from "@bitwarden/auth/angular";
|
||||
import { RegistrationFinishService } from "@bitwarden/angular/auth/registration";
|
||||
import { InputPasswordFlow, PasswordInputResult } from "@bitwarden/auth/angular";
|
||||
import { LoginStrategyServiceAbstraction, PasswordLoginCredentials } from "@bitwarden/auth/common";
|
||||
import { OrganizationResponse } from "@bitwarden/common/admin-console/models/response/organization.response";
|
||||
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
|
||||
|
||||
@@ -3,7 +3,7 @@ import { ActivatedRouteSnapshot, ResolveFn } from "@angular/router";
|
||||
import { ProductType } from "@bitwarden/common/billing/enums";
|
||||
import { Translation } from "@bitwarden/components";
|
||||
|
||||
import { DEFAULT_TRIAL_LENGTH_DAYS } from "../../../constants";
|
||||
import { MARKETING_SALES_TRIAL_LENGTH_DAYS } from "../../../constants";
|
||||
|
||||
export const freeTrialTextResolver: ResolveFn<Translation | null> = (
|
||||
route: ActivatedRouteSnapshot,
|
||||
@@ -13,7 +13,7 @@ export const freeTrialTextResolver: ResolveFn<Translation | null> = (
|
||||
|
||||
const trialLength = route.queryParams.trialLength
|
||||
? parseInt(route.queryParams.trialLength)
|
||||
: DEFAULT_TRIAL_LENGTH_DAYS;
|
||||
: MARKETING_SALES_TRIAL_LENGTH_DAYS;
|
||||
|
||||
const onlyPasswordManager = products.length === 1 && products[0] === ProductType.PasswordManager;
|
||||
const onlySecretsManager = products.length === 1 && products[0] === ProductType.SecretsManager;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ProductTierType, ProductType } from "@bitwarden/common/billing/enums";
|
||||
import { DEFAULT_TRIAL_LENGTH_DAYS } from "@bitwarden/web-vault/app/billing/constants";
|
||||
import { MARKETING_SALES_TRIAL_LENGTH_DAYS } from "@bitwarden/web-vault/app/billing/constants";
|
||||
|
||||
import { parseTrialInitiationParams } from "./trial-initiation-params";
|
||||
|
||||
@@ -80,7 +80,7 @@ describe("parseTrialInitiationParams", () => {
|
||||
});
|
||||
|
||||
it("defaults the trial length and preserves an explicit zero", () => {
|
||||
expect(parseTrialInitiationParams({}).trialLength).toBe(DEFAULT_TRIAL_LENGTH_DAYS);
|
||||
expect(parseTrialInitiationParams({}).trialLength).toBe(MARKETING_SALES_TRIAL_LENGTH_DAYS);
|
||||
expect(parseTrialInitiationParams({ trialLength: "0" }).trialLength).toBe(0);
|
||||
expect(parseTrialInitiationParams({ trialLength: "14" }).trialLength).toBe(14);
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Params } from "@angular/router";
|
||||
|
||||
import { ProductTierType, ProductType } from "@bitwarden/common/billing/enums";
|
||||
import { DEFAULT_TRIAL_LENGTH_DAYS } from "@bitwarden/web-vault/app/billing/constants";
|
||||
import { MARKETING_SALES_TRIAL_LENGTH_DAYS } from "@bitwarden/web-vault/app/billing/constants";
|
||||
|
||||
/** Products a trial link can request. */
|
||||
const trialProducts: ProductType[] = [
|
||||
@@ -59,7 +59,7 @@ export function parseTrialInitiationParams(queryParams: Params): TrialInitiation
|
||||
product: baseProduct(products),
|
||||
privilegedControlsRequested: products.includes(ProductType.PrivilegedControls),
|
||||
productTier: toOptionalInt(queryParams.productTier) as ProductTierType | undefined,
|
||||
trialLength: toOptionalInt(queryParams.trialLength) ?? DEFAULT_TRIAL_LENGTH_DAYS,
|
||||
trialLength: toOptionalInt(queryParams.trialLength) ?? MARKETING_SALES_TRIAL_LENGTH_DAYS,
|
||||
paymentOptional: queryParams.paymentOptional === "true",
|
||||
sponsorshipToken: queryParams.sponsorshipToken ?? undefined,
|
||||
};
|
||||
|
||||
@@ -16,6 +16,7 @@ import { DefaultLoginViaWebAuthnComponentService } from "@bitwarden/angular/auth
|
||||
import { LoginViaWebAuthnComponentService } from "@bitwarden/angular/auth/login-via-webauthn/login-via-webauthn-component.service";
|
||||
import { ChangePasswordService } from "@bitwarden/angular/auth/password-management/change-password";
|
||||
import { SetInitialPasswordService } from "@bitwarden/angular/auth/password-management/set-initial-password/set-initial-password.service.abstraction";
|
||||
import { RegistrationFinishService as RegistrationFinishServiceAbstraction } from "@bitwarden/angular/auth/registration";
|
||||
import { PremiumInterestStateService } from "@bitwarden/angular/billing/services/premium-interest/premium-interest-state.service.abstraction";
|
||||
import { SafeProvider, safeProvider } from "@bitwarden/angular/platform/utils/safe-provider";
|
||||
import {
|
||||
@@ -36,7 +37,6 @@ import { JslibServicesModule } from "@bitwarden/angular/services/jslib-services.
|
||||
import {
|
||||
LoginComponentService,
|
||||
LoginDecryptionOptionsService,
|
||||
RegistrationFinishService as RegistrationFinishServiceAbstraction,
|
||||
SsoComponentService,
|
||||
TwoFactorAuthDuoComponentService,
|
||||
} from "@bitwarden/auth/angular";
|
||||
|
||||
@@ -16,6 +16,13 @@ import {
|
||||
import { LoginViaWebAuthnComponent } from "@bitwarden/angular/auth/login-via-webauthn/login-via-webauthn.component";
|
||||
import { ChangePasswordComponent } from "@bitwarden/angular/auth/password-management/change-password";
|
||||
import { SetInitialPasswordComponent } from "@bitwarden/angular/auth/password-management/set-initial-password/set-initial-password.component";
|
||||
import {
|
||||
RegistrationFinishComponent,
|
||||
RegistrationStartComponent,
|
||||
RegistrationStartSecondaryComponent,
|
||||
RegistrationStartSecondaryComponentData,
|
||||
RegistrationLinkExpiredComponent,
|
||||
} from "@bitwarden/angular/auth/registration";
|
||||
import { canAccessFeature } from "@bitwarden/angular/platform/guard/feature-flag.guard";
|
||||
import {
|
||||
DevicesIcon,
|
||||
@@ -36,11 +43,6 @@ import {
|
||||
} from "@bitwarden/assets/svg";
|
||||
import {
|
||||
PasswordHintComponent,
|
||||
RegistrationFinishComponent,
|
||||
RegistrationStartComponent,
|
||||
RegistrationStartSecondaryComponent,
|
||||
RegistrationStartSecondaryComponentData,
|
||||
RegistrationLinkExpiredComponent,
|
||||
LoginComponent,
|
||||
LoginSecondaryContentComponent,
|
||||
LoginViaAuthRequestComponent,
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
@switch (viewState()) {
|
||||
@case ("auth") {
|
||||
<app-send-auth [id]="id" [key]="key" (accessGranted)="onAccessGranted($event)"></app-send-auth>
|
||||
<app-send-auth
|
||||
[id]="id()"
|
||||
[key]="key()"
|
||||
(accessGranted)="onAccessGranted($event)"
|
||||
></app-send-auth>
|
||||
}
|
||||
@case ("view") {
|
||||
<app-send-view
|
||||
[id]="id"
|
||||
[key]="key"
|
||||
[accessToken]="sendAccessToken"
|
||||
[id]="id()"
|
||||
[key]="key()"
|
||||
[accessToken]="sendAccessToken()"
|
||||
(authRequired)="onAuthRequired()"
|
||||
></app-send-view>
|
||||
}
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
// FIXME: Update this file to be type safe and remove this and next line
|
||||
// @ts-strict-ignore
|
||||
// FIXME(https://bitwarden.atlassian.net/browse/CL-1062): `OnPush` components should not use mutable properties
|
||||
/* eslint-disable @bitwarden/components/enforce-readonly-angular-properties */
|
||||
import { ChangeDetectionStrategy, Component, DestroyRef, OnInit, signal } from "@angular/core";
|
||||
import { takeUntilDestroyed } from "@angular/core/rxjs-interop";
|
||||
import { ActivatedRoute } from "@angular/router";
|
||||
@@ -27,25 +25,25 @@ type SendViewState = (typeof SendViewState)[keyof typeof SendViewState];
|
||||
})
|
||||
export class AccessComponent implements OnInit {
|
||||
readonly viewState = signal<SendViewState | null>(SendViewState.Auth);
|
||||
id: string;
|
||||
key: string;
|
||||
readonly id = signal<string>("");
|
||||
readonly key = signal<string>("");
|
||||
|
||||
sendAccessToken: SendAccessToken | null = null;
|
||||
readonly sendAccessToken = signal<SendAccessToken | null>(null);
|
||||
|
||||
constructor(
|
||||
private route: ActivatedRoute,
|
||||
private destroyRef: DestroyRef,
|
||||
private readonly route: ActivatedRoute,
|
||||
private readonly destroyRef: DestroyRef,
|
||||
) {}
|
||||
|
||||
ngOnInit() {
|
||||
this.route.params.pipe(takeUntilDestroyed(this.destroyRef)).subscribe((params) => {
|
||||
this.id = params.sendId;
|
||||
this.key = params.key;
|
||||
this.id.set(params.sendId);
|
||||
this.key.set(params.key);
|
||||
|
||||
// when pasting sequential Send URLs into the browser,
|
||||
// Angular reuses the SendAuthComponent instance
|
||||
// Reset state so child components are recreated with fresh data
|
||||
this.sendAccessToken = null;
|
||||
this.sendAccessToken.set(null);
|
||||
|
||||
// Temporarily set viewState to null to destroy the current child component,
|
||||
// then set it back to Auth on the next tick to recreate it with the new id/key.
|
||||
@@ -59,7 +57,7 @@ export class AccessComponent implements OnInit {
|
||||
}
|
||||
|
||||
onAccessGranted(event: { accessToken: SendAccessToken }) {
|
||||
this.sendAccessToken = event.accessToken;
|
||||
this.sendAccessToken.set(event.accessToken);
|
||||
this.viewState.set(SendViewState.View);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
// FIXME: Update this file to be type safe and remove this and next line
|
||||
// @ts-strict-ignore
|
||||
// FIXME(https://bitwarden.atlassian.net/browse/CL-1062): `OnPush` components should not use mutable properties
|
||||
/* eslint-disable @bitwarden/components/enforce-readonly-angular-properties */
|
||||
import { ChangeDetectionStrategy, Component, input } from "@angular/core";
|
||||
import { firstValueFrom } from "rxjs";
|
||||
|
||||
@@ -31,15 +29,15 @@ export class SendAccessFileComponent {
|
||||
readonly accessToken = input<SendAccessToken | null>(null);
|
||||
|
||||
constructor(
|
||||
private i18nService: I18nService,
|
||||
private toastService: ToastService,
|
||||
private encryptService: EncryptService,
|
||||
private fileDownloadService: FileDownloadService,
|
||||
private sendApiService: SendApiService,
|
||||
private environmentService: EnvironmentService,
|
||||
private readonly i18nService: I18nService,
|
||||
private readonly toastService: ToastService,
|
||||
private readonly encryptService: EncryptService,
|
||||
private readonly fileDownloadService: FileDownloadService,
|
||||
private readonly sendApiService: SendApiService,
|
||||
private readonly environmentService: EnvironmentService,
|
||||
) {}
|
||||
|
||||
protected download = async () => {
|
||||
protected readonly download = async () => {
|
||||
const accessToken = this.accessToken();
|
||||
if (this.send() == null || this.decKey() == null || !accessToken) {
|
||||
return;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user