Compare commits

...

23 Commits

Author SHA1 Message Date
vinith-kovan c75aeefb6d
Merge 98cecb6de8 into 6ae086f89a 2024-04-27 20:10:11 +12:00
Jake Fink 6ae086f89a
pass userId when logging out and add error handling if one isn't found in background (#8946) 2024-04-26 18:02:45 -04:00
Cesar Gonzalez 5dc200577c
[PM-7663] Update Build Pipeline for Beta Labelling (#8903)
* [PM-7663] Update build pipeline for beta labeling

* [PM-7663] Update build pipeline for beta labelling

* [PM-7663] Update build pipeline for beta labelling

* [PM-7663] Update build pipeline for beta labelling

* [PM-7663] Update build pipeline for beta labelling

* [PM-7663] Incorporate build workflow for the Chrome manifest v3 beta

* [PM-7663] Update build pipeline for beta labeling

* [PM-7663] Update build pipeline for beta labeling

* [PM-7663] Update build pipeline for beta labeling

* [PM-7663] Ensure we can have a valid version number based on the github run id

* [PM-7663] Ensure we can have a valid version number based on the github run id

* [PM-7663] Reverting change made to the run id, as it will not function

* [PM-7663] Reverting change made to the run id, as it will not function

* [PM-7663] Reverting change made to the run id, as it will not function

* [PM-7663] Reverting change made to the run id, as it will not function

* [PM-7663] Reverting a typo

* Fix Duplicate `process.env

* Learn how to use

---------

Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com>
2024-04-26 15:15:36 -04:00
Justin Baur a8e4366ec0
Check that `self` is undefined instead of `window` (#8940) 2024-04-26 15:08:59 -04:00
Matt Gibson 089f251a0c
Remove memory storage cache from derived state. Use observable cache and port messaging (#8939) 2024-04-26 15:08:39 -04:00
renovate[bot] b3242145f9
[deps] Platform (CL): Update autoprefixer to v10.4.19 (#8735)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2024-04-26 14:59:15 -04:00
Justin Baur b482a15d34
Bandaid Folders Not Emitting (#8934)
* Bandaid Folders Not Emitting

* Remove VaultFilterComponent Change
2024-04-26 14:41:57 -04:00
Matt Gibson a4f1a3f13d
Use unique port names for derived states (#8938) 2024-04-26 16:17:34 +00:00
Matt Gibson 4c1c09f07f
Use unique port names for derived states (#8937) 2024-04-26 11:21:42 -04:00
Robyn MacCallum 67280f48dd
Make integrations links open in a new page (#8933)
* Make integrations links open in a new page

* Fix target warning
2024-04-26 10:53:11 -04:00
Justin Baur a7958c1a56
Display `version_name` in AboutComponent (#8931) 2024-04-26 10:23:11 -04:00
Jared Snider 7f5efcc18c
PM-7745 - SSO Login Strategy - trySetUserKeyWithDeviceKey should use the user id from the IdTokenResponse and not StateService as I suspect it's not working as expected. Thinking there might be a race condition where the user id is null or maybe incorrect. (#8927) 2024-04-26 10:18:05 -04:00
Justin Baur acea273f97
Fix ConfigService Merge Conflict (#8932) 2024-04-26 09:39:46 -04:00
Victoria League ec37e5e4d3
[CL-219][CL-218][CL-217] Add new extension layout components (#8728) 2024-04-26 09:35:32 -04:00
KiruthigaManivannan 2fa4c6e4f9
PM-4945 Update Two Factor verify dialog (#8580)
* PM-4945 Update Two Factor verify dialog

* PM-4945 Addressed review comments

* PM-4945 Removed legacy User verification component and used new one
2024-04-26 18:24:48 +05:30
github-actions[bot] 11ba8d188d
Autosync the updated translations (#8925)
Co-authored-by: bitwarden-devops-bot <106330231+bitwarden-devops-bot@users.noreply.github.com>
2024-04-26 11:06:19 +00:00
Oscar Hinton 14b2eb99a2
[PM-2282] Make feature flags type safe (#8612)
Refactors the feature flags in ConfigService to be type safe. It also moves the default value to a centralized location rather than the caller defining it. This ensures consistency across the various places they are used.
2024-04-26 12:57:26 +02:00
vinith-kovan 98cecb6de8
migrating activate autofill component 2024-04-24 10:28:29 +05:30
vinith-kovan ab73b7a354
Merge branch 'main' of https://github.com/bitwarden/clients into AC-2406-Migrate-activate-autofill-component 2024-04-24 10:20:10 +05:30
vinith-kovan ac4b6f614e
migrating activate autofill component 2024-04-23 23:33:32 +05:30
vinith-kovan 8158bc7607
Merge branch 'main' of https://github.com/bitwarden/clients into AC-2406-Migrate-activate-autofill-component 2024-04-23 23:11:53 +05:30
vinith-kovan 7628b7a782
Merge branch 'main' into AC-2406-Migrate-activate-autofill-component 2024-04-23 09:52:35 +05:30
vinith-kovan 9a711af951
migrating activate autofill component 2024-04-17 16:44:35 +05:30
95 changed files with 1112 additions and 495 deletions

View File

@ -164,6 +164,10 @@ jobs:
run: npm run dist:mv3
working-directory: browser-source/apps/browser
- name: Build Chrome Manifest v3 Beta
run: npm run dist:chrome:beta
working-directory: browser-source/apps/browser
- name: Gulp
run: gulp ci
working-directory: browser-source/apps/browser
@ -196,6 +200,13 @@ jobs:
path: browser-source/apps/browser/dist/dist-chrome-mv3.zip
if-no-files-found: error
- name: Upload Chrome MV3 Beta artifact (DO NOT USE FOR PROD)
uses: actions/upload-artifact@5d5d22a31266ced268874388b861e4b58bb5c2f3 # v4.3.1
with:
name: DO-NOT-USE-FOR-PROD-dist-chrome-MV3-beta-${{ env._BUILD_NUMBER }}.zip
path: browser-source/apps/browser/dist/dist-chrome-mv3-beta.zip
if-no-files-found: error
- name: Upload Firefox artifact
uses: actions/upload-artifact@5d5d22a31266ced268874388b861e4b58bb5c2f3 # v4.3.1
with:

View File

@ -9,6 +9,8 @@ const config: StorybookConfig = {
"../libs/components/src/**/*.stories.@(js|jsx|ts|tsx)",
"../apps/web/src/**/*.mdx",
"../apps/web/src/**/*.stories.@(js|jsx|ts|tsx)",
"../apps/browser/src/**/*.mdx",
"../apps/browser/src/**/*.stories.@(js|jsx|ts|tsx)",
"../bitwarden_license/bit-web/src/**/*.mdx",
"../bitwarden_license/bit-web/src/**/*.stories.@(js|jsx|ts|tsx)",
],

View File

@ -1,12 +1,10 @@
{
"extends": "../tsconfig",
"compilerOptions": {
"types": ["node", "jest", "chrome"],
"allowSyntheticDefaultImports": true
},
"exclude": ["../src/test.setup.ts", "../apps/src/**/*.spec.ts", "../libs/**/*.spec.ts"],
"exclude": ["../src/test.setup.ts", "../apps/**/*.spec.ts", "../libs/**/*.spec.ts"],
"files": [
"./typings.d.ts",
"./preview.tsx",
"../libs/components/src/main.ts",
"../libs/components/src/polyfills.ts"

View File

@ -1,4 +0,0 @@
declare module "*.md" {
const content: string;
export default content;
}

View File

@ -35,6 +35,9 @@ function buildString() {
if (process.env.MANIFEST_VERSION) {
build = `-mv${process.env.MANIFEST_VERSION}`;
}
if (process.env.BETA_BUILD === "1") {
build += "-beta";
}
if (process.env.BUILD_NUMBER && process.env.BUILD_NUMBER !== "") {
build = `-${process.env.BUILD_NUMBER}`;
}
@ -65,6 +68,9 @@ function distFirefox() {
manifest.optional_permissions = manifest.optional_permissions.filter(
(permission) => permission !== "privacy",
);
if (process.env.BETA_BUILD === "1") {
manifest = applyBetaLabels(manifest);
}
return manifest;
});
}
@ -72,6 +78,9 @@ function distFirefox() {
function distOpera() {
return dist("opera", (manifest) => {
delete manifest.applications;
if (process.env.BETA_BUILD === "1") {
manifest = applyBetaLabels(manifest);
}
return manifest;
});
}
@ -81,6 +90,9 @@ function distChrome() {
delete manifest.applications;
delete manifest.sidebar_action;
delete manifest.commands._execute_sidebar_action;
if (process.env.BETA_BUILD === "1") {
manifest = applyBetaLabels(manifest);
}
return manifest;
});
}
@ -90,6 +102,9 @@ function distEdge() {
delete manifest.applications;
delete manifest.sidebar_action;
delete manifest.commands._execute_sidebar_action;
if (process.env.BETA_BUILD === "1") {
manifest = applyBetaLabels(manifest);
}
return manifest;
});
}
@ -210,6 +225,9 @@ async function safariCopyBuild(source, dest) {
delete manifest.commands._execute_sidebar_action;
delete manifest.optional_permissions;
manifest.permissions.push("nativeMessaging");
if (process.env.BETA_BUILD === "1") {
manifest = applyBetaLabels(manifest);
}
return manifest;
}),
),
@ -235,6 +253,19 @@ async function ciCoverage(cb) {
.pipe(gulp.dest(paths.coverage));
}
function applyBetaLabels(manifest) {
manifest.name = "Bitwarden Password Manager BETA";
manifest.short_name = "Bitwarden BETA";
manifest.description = "THIS EXTENSION IS FOR BETA TESTING BITWARDEN.";
if (process.env.GITHUB_RUN_ID) {
manifest.version_name = `${manifest.version} beta - ${process.env.GITHUB_SHA.slice(0, 8)}`;
manifest.version = `${manifest.version}.${parseInt(process.env.GITHUB_RUN_ID.slice(-4))}`;
} else {
manifest.version = `${manifest.version}.0`;
}
return manifest;
}
exports["dist:firefox"] = distFirefox;
exports["dist:chrome"] = distChrome;
exports["dist:opera"] = distOpera;

View File

@ -7,10 +7,14 @@
"build:watch": "webpack --watch",
"build:watch:mv3": "cross-env MANIFEST_VERSION=3 webpack --watch",
"build:prod": "cross-env NODE_ENV=production webpack",
"build:prod:beta": "cross-env BETA_BUILD=1 NODE_ENV=production webpack",
"build:prod:watch": "cross-env NODE_ENV=production webpack --watch",
"dist": "npm run build:prod && gulp dist",
"dist:beta": "npm run build:prod:beta && cross-env BETA_BUILD=1 gulp dist",
"dist:mv3": "cross-env MANIFEST_VERSION=3 npm run build:prod && cross-env MANIFEST_VERSION=3 gulp dist",
"dist:mv3:beta": "cross-env MANIFEST_VERSION=3 npm run build:prod:beta && cross-env MANIFEST_VERSION=3 BETA_BUILD=1 gulp dist",
"dist:chrome": "npm run build:prod && gulp dist:chrome",
"dist:chrome:beta": "cross-env MANIFEST_VERSION=3 npm run build:prod:beta && cross-env MANIFEST_VERSION=3 BETA_BUILD=1 gulp dist:chrome",
"dist:firefox": "npm run build:prod && gulp dist:firefox",
"dist:opera": "npm run build:prod && gulp dist:opera",
"dist:safari": "npm run build:prod && gulp dist:safari",

View File

@ -7,7 +7,7 @@
"description": "Extension name, MUST be less than 40 characters (Safari restriction)"
},
"extDesc": {
"message": "At home, at work, or on the go, Bitwarden easily secures all your passwords, passkeys, and sensitive information",
"message": "W domu, w pracy, lub w ruchu, Bitwarden z łatwością zabezpiecza Twoje hasła, passkeys i poufne informacje",
"description": "Extension description, MUST be less than 112 characters (Safari restriction)"
},
"loginOrCreateNewAccount": {

View File

@ -7,7 +7,7 @@
"description": "Extension name, MUST be less than 40 characters (Safari restriction)"
},
"extDesc": {
"message": "At home, at work, or on the go, Bitwarden easily secures all your passwords, passkeys, and sensitive information",
"message": "Em qual lugar for, o Bitwarden protege suas senhas, chaves de acesso, e informações confidenciais",
"description": "Extension description, MUST be less than 112 characters (Safari restriction)"
},
"loginOrCreateNewAccount": {

View File

@ -3,11 +3,11 @@
"message": "Bitwarden"
},
"extName": {
"message": "Bitwarden Password Manager",
"message": "Bitwarden - Trình Quản lý Mật khẩu",
"description": "Extension name, MUST be less than 40 characters (Safari restriction)"
},
"extDesc": {
"message": "At home, at work, or on the go, Bitwarden easily secures all your passwords, passkeys, and sensitive information",
"message": "Ở nhà, ở cơ quan, hay trên đường đi, Bitwarden sẽ bảo mật tất cả mật khẩu, passkey, và thông tin cá nhân của bạn",
"description": "Extension description, MUST be less than 112 characters (Safari restriction)"
},
"loginOrCreateNewAccount": {
@ -650,7 +650,7 @@
"message": "'Thông báo Thêm đăng nhập' sẽ tự động nhắc bạn lưu các đăng nhập mới vào hầm an toàn của bạn bất cứ khi nào bạn đăng nhập trang web lần đầu tiên."
},
"addLoginNotificationDescAlt": {
"message": "Ask to add an item if one isn't found in your vault. Applies to all logged in accounts."
"message": "Đưa ra lựa chọn để thêm một mục nếu không tìm thấy mục đó trong hòm của bạn. Áp dụng với mọi tài khoản đăng nhập trên thiết bị."
},
"showCardsCurrentTab": {
"message": "Hiển thị thẻ trên trang Tab"
@ -685,13 +685,13 @@
"message": "Yêu cầu cập nhật mật khẩu đăng nhập khi phát hiện thay đổi trên trang web."
},
"changedPasswordNotificationDescAlt": {
"message": "Ask to update a login's password when a change is detected on a website. Applies to all logged in accounts."
"message": "Đưa ra lựa chọn để cập nhật mật khẩu khi phát hiện có sự thay đổi trên trang web. Áp dụng với mọi tài khoản đăng nhập trên thiết bị."
},
"enableUsePasskeys": {
"message": "Ask to save and use passkeys"
"message": "Đưa ra lựa chọn để lưu và sử dụng passkey"
},
"usePasskeysDesc": {
"message": "Ask to save new passkeys or log in with passkeys stored in your vault. Applies to all logged in accounts."
"message": "Đưa ra lựa chọn để lưu passkey mới hoặc đăng nhập bằng passkey đã lưu trong hòm. Áp dụng với mọi tài khoản đăng nhập trên thiết bị."
},
"notificationChangeDesc": {
"message": "Bạn có muốn cập nhật mật khẩu này trên Bitwarden không?"
@ -712,7 +712,7 @@
"message": "Sử dụng một đúp chuột để truy cập vào việc tạo mật khẩu và thông tin đăng nhập phù hợp cho trang web. "
},
"contextMenuItemDescAlt": {
"message": "Use a secondary click to access password generation and matching logins for the website. Applies to all logged in accounts."
"message": "Truy cập trình khởi tạo mật khẩu và các mục đăng nhập đã lưu của trang web bằng cách nhấn đúp chuột. Áp dụng với mọi tài khoản đăng nhập trên thiết bị."
},
"defaultUriMatchDetection": {
"message": "Phương thức kiểm tra URI mặc định",
@ -728,7 +728,7 @@
"message": "Thay đổi màu sắc ứng dụng."
},
"themeDescAlt": {
"message": "Change the application's color theme. Applies to all logged in accounts."
"message": "Thay đổi tông màu giao diện của ứng dụng. Áp dụng với mọi tài khoản đăng nhập trên thiết bị."
},
"dark": {
"message": "Tối",
@ -1061,10 +1061,10 @@
"message": "Tắt cài đặt trình quản lý mật khẩu tích hợp trong trình duyệt của bạn để tránh xung đột."
},
"turnOffBrowserBuiltInPasswordManagerSettingsLink": {
"message": "Edit browser settings."
"message": "Thay đổi cài đặt của trình duyệt."
},
"autofillOverlayVisibilityOff": {
"message": "Off",
"message": "Tắt",
"description": "Overlay setting select option for disabling autofill overlay"
},
"autofillOverlayVisibilityOnFieldFocus": {
@ -1168,7 +1168,7 @@
"message": "Hiển thị một ảnh nhận dạng bên cạnh mỗi lần đăng nhập."
},
"faviconDescAlt": {
"message": "Show a recognizable image next to each login. Applies to all logged in accounts."
"message": "Hiển thị một biểu tượng dễ nhận dạng bên cạnh mỗi mục đăng nhập. Áp dụng với mọi tài khoản đăng nhập trên thiết bị."
},
"enableBadgeCounter": {
"message": "Hiển thị biểu tượng bộ đếm"
@ -1500,7 +1500,7 @@
"message": "Mã PIN không hợp lệ."
},
"tooManyInvalidPinEntryAttemptsLoggingOut": {
"message": "Too many invalid PIN entry attempts. Logging out."
"message": "Mã PIN bị gõ sai quá nhiều lần. Đang đăng xuất."
},
"unlockWithBiometrics": {
"message": "Mở khóa bằng sinh trắc học"

View File

@ -1,4 +1,4 @@
import { Subject, firstValueFrom, merge } from "rxjs";
import { Subject, firstValueFrom, merge, timeout } from "rxjs";
import {
PinCryptoServiceAbstraction,
@ -490,7 +490,7 @@ export default class MainBackground {
this.accountService,
this.singleUserStateProvider,
);
this.derivedStateProvider = new BackgroundDerivedStateProvider(storageServiceProvider);
this.derivedStateProvider = new BackgroundDerivedStateProvider();
this.stateProvider = new DefaultStateProvider(
this.activeUserStateProvider,
this.singleUserStateProvider,
@ -1196,7 +1196,18 @@ export default class MainBackground {
}
async logout(expired: boolean, userId?: UserId) {
userId ??= (await firstValueFrom(this.accountService.activeAccount$))?.id;
userId ??= (
await firstValueFrom(
this.accountService.activeAccount$.pipe(
timeout({
first: 2000,
with: () => {
throw new Error("No active account found to logout");
},
}),
),
)
)?.id;
await this.eventUploadService.uploadEvents(userId as UserId);

View File

@ -3,15 +3,10 @@ import { DerivedStateProvider } from "@bitwarden/common/platform/state";
import { BackgroundDerivedStateProvider } from "../../state/background-derived-state.provider";
import { CachedServices, FactoryOptions, factory } from "./factory-options";
import {
StorageServiceProviderInitOptions,
storageServiceProviderFactory,
} from "./storage-service-provider.factory";
type DerivedStateProviderFactoryOptions = FactoryOptions;
export type DerivedStateProviderInitOptions = DerivedStateProviderFactoryOptions &
StorageServiceProviderInitOptions;
export type DerivedStateProviderInitOptions = DerivedStateProviderFactoryOptions;
export async function derivedStateProviderFactory(
cache: { derivedStateProvider?: DerivedStateProvider } & CachedServices,
@ -21,7 +16,6 @@ export async function derivedStateProviderFactory(
cache,
"derivedStateProvider",
opts,
async () =>
new BackgroundDerivedStateProvider(await storageServiceProviderFactory(cache, opts)),
async () => new BackgroundDerivedStateProvider(),
);
}

View File

@ -238,10 +238,6 @@ export class BrowserApi {
return typeof window !== "undefined" && window === BrowserApi.getBackgroundPage();
}
static getApplicationVersion(): string {
return chrome.runtime.getManifest().version;
}
/**
* Gets the extension views that match the given properties. This method is not
* available within background service worker. As a result, it will return an

View File

@ -0,0 +1,9 @@
<footer
class="tw-p-3 tw-border-0 tw-border-solid tw-border-t tw-border-secondary-300 tw-bg-background"
>
<div class="tw-max-w-screen-sm tw-mx-auto">
<div class="tw-flex tw-justify-start tw-gap-2">
<ng-content></ng-content>
</div>
</div>
</footer>

View File

@ -0,0 +1,9 @@
import { Component } from "@angular/core";
@Component({
selector: "popup-footer",
templateUrl: "popup-footer.component.html",
standalone: true,
imports: [],
})
export class PopupFooterComponent {}

View File

@ -0,0 +1,19 @@
<header
class="tw-p-4 tw-border-0 tw-border-solid tw-border-b tw-border-secondary-300 tw-bg-background"
>
<div class="tw-max-w-screen-sm tw-mx-auto tw-flex tw-justify-between tw-w-full">
<div class="tw-inline-flex tw-items-center tw-gap-2 tw-h-9">
<button
bitIconButton="bwi-back"
type="button"
*ngIf="showBackButton"
[title]="'back' | i18n"
[ariaLabel]="'back' | i18n"
></button>
<h1 bitTypography="h3" class="!tw-mb-0.5 tw-text-headers">{{ pageTitle }}</h1>
</div>
<div class="tw-inline-flex tw-items-center tw-gap-2 tw-h-9">
<ng-content select="[slot=end]"></ng-content>
</div>
</div>
</header>

View File

@ -0,0 +1,34 @@
import { BooleanInput, coerceBooleanProperty } from "@angular/cdk/coercion";
import { CommonModule, Location } from "@angular/common";
import { Component, Input } from "@angular/core";
import { JslibModule } from "@bitwarden/angular/jslib.module";
import { IconButtonModule, TypographyModule } from "@bitwarden/components";
@Component({
selector: "popup-header",
templateUrl: "popup-header.component.html",
standalone: true,
imports: [TypographyModule, CommonModule, IconButtonModule, JslibModule],
})
export class PopupHeaderComponent {
/** Display the back button, which uses Location.back() to go back one page in history */
@Input()
get showBackButton() {
return this._showBackButton;
}
set showBackButton(value: BooleanInput) {
this._showBackButton = coerceBooleanProperty(value);
}
private _showBackButton = false;
/** Title string that will be inserted as an h1 */
@Input({ required: true }) pageTitle: string;
constructor(private location: Location) {}
back() {
this.location.back();
}
}

View File

@ -0,0 +1,138 @@
import { Meta, Story, Canvas } from "@storybook/addon-docs";
import * as stories from "./popup-layout.stories";
<Meta of={stories} />
Please note that because these stories use `router-outlet`, there are issues with rendering content
when Light & Dark mode is selected. The stories are best viewed by selecting one color mode.
# Popup Tab Navigation
The popup tab navigation component composes together the popup page and the bottom tab navigation
footer. This component is intended to be used a level _above_ each extension tab's page code.
The navigation footer contains the 4 main page links for the browser extension. It uses the Angular
router to determine which page is currently active, and style the button appropriately. Clicking on
the buttons will navigate to the correct route. The navigation footer has a max-width built in so
that the page looks nice when the extension is popped out.
Long button names will be ellipsed.
Usage example:
```html
<popup-tab-navigation>
<popup-page></popup-page>
</popup-tab-navigation>
```
# Popup Page
The popup page handles positioning a page's `header` and `footer` elements, and inserting the rest
of the content into the `main` element with scroll. There is also a max-width built in so that the
page looks nice when the extension is popped out.
**Slots**
- `header`
- Use `popup-header` component.
- Every page should have a header.
- `footer`
- Use the `popup-footer` component.
- Not every page will have a footer.
- default
- Whatever content you want in `main`.
Basic usage example:
```html
<popup-page>
<popup-header slot="header"></popup-header>
<div>This is content</div>
<popup-footer slot="footer"></popup-footer>
</popup-page>
```
## Popup header
**Args**
- `pageTitle`: required
- Inserts title as an `h1`.
- `showBackButton`: optional, defaults to `false`
- Toggles the back button to appear. The back button uses `Location.back()` to navigate back one
page in history.
**Slots**
- `end`
- Use to insert one or more interactive elements.
- The header handles the spacing between elements passed to the `end` slot.
Usage example:
```html
<popup-header pageTitle="Test" showBackButton>
<ng-container slot="end">
<button></button>
<button></button>
</ng-container>
</popup-header>
```
Common interactive elements to insert into the `end` slot are:
- `app-current-account`: shows current account and switcher
- `app-pop-out`: shows popout button when the extension is not already popped out
- "Add" button: this can be accomplished with the Button component and any custom functionality for
that particular page
## Popup footer
Popup footer should be used when the page displays action buttons. It functions similarly to the
Dialog footer in that the calling code is responsible for passing in the different buttons that need
to be rendered.
Usage example:
```html
<popup-footer>
<button bitButton buttonType="primary">Save</button>
<button bitButton buttonType="secondary">Cancel</button>
</popup-footer>
```
# Page types
There are a few types of pages that are used in the browser extension.
View the story source code to see examples of how to construct these types of pages.
## Extension Tab
Example of wrapping an extension page in the `popup-tab-navigation` component.
<Canvas>
<Story of={stories.PopupTabNavigation} />
</Canvas>
## Extension Page
Examples of using just the `popup-page` component, without and with a footer.
<Canvas>
<Story of={stories.PopupPage} />
</Canvas>
<Canvas>
<Story of={stories.PopupPageWithFooter} />
</Canvas>
## Popped out
When the browser extension is popped out, the "popout" button should not be passed to the header.
<Canvas>
<Story of={stories.PoppedOut} />
</Canvas>

View File

@ -0,0 +1,367 @@
import { CommonModule } from "@angular/common";
import { Component, importProvidersFrom } from "@angular/core";
import { RouterModule } from "@angular/router";
import { Meta, StoryObj, applicationConfig, moduleMetadata } from "@storybook/angular";
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
import {
AvatarModule,
ButtonModule,
I18nMockService,
IconButtonModule,
} from "@bitwarden/components";
import { PopupFooterComponent } from "./popup-footer.component";
import { PopupHeaderComponent } from "./popup-header.component";
import { PopupPageComponent } from "./popup-page.component";
import { PopupTabNavigationComponent } from "./popup-tab-navigation.component";
@Component({
selector: "extension-container",
template: `
<div class="tw-h-[640px] tw-w-[380px] tw-border tw-border-solid tw-border-secondary-300">
<ng-content></ng-content>
</div>
`,
standalone: true,
})
class ExtensionContainerComponent {}
@Component({
selector: "vault-placeholder",
template: `
<div class="tw-mb-8 tw-text-main">vault item</div>
<div class="tw-my-8 tw-text-main">vault item</div>
<div class="tw-my-8 tw-text-main">vault item</div>
<div class="tw-my-8 tw-text-main">vault item</div>
<div class="tw-my-8 tw-text-main">vault item</div>
<div class="tw-my-8 tw-text-main">vault item</div>
<div class="tw-my-8 tw-text-main">vault item</div>
<div class="tw-my-8 tw-text-main">vault item</div>
<div class="tw-my-8 tw-text-main">vault item</div>
<div class="tw-my-8 tw-text-main">vault item</div>
<div class="tw-my-8 tw-text-main">vault item</div>
<div class="tw-my-8 tw-text-main">vault item</div>
<div class="tw-my-8 tw-text-main">vault item last item</div>
`,
standalone: true,
})
class VaultComponent {}
@Component({
selector: "generator-placeholder",
template: ` <div class="tw-text-main">generator stuff here</div> `,
standalone: true,
})
class GeneratorComponent {}
@Component({
selector: "send-placeholder",
template: ` <div class="tw-text-main">send some stuff</div> `,
standalone: true,
})
class SendComponent {}
@Component({
selector: "settings-placeholder",
template: ` <div class="tw-text-main">change your settings</div> `,
standalone: true,
})
class SettingsComponent {}
@Component({
selector: "mock-add-button",
template: `
<button bitButton buttonType="primary" type="button">
<i class="bwi bwi-plus-f" aria-hidden="true"></i>
Add
</button>
`,
standalone: true,
imports: [ButtonModule],
})
class MockAddButtonComponent {}
@Component({
selector: "mock-popout-button",
template: `
<button
bitIconButton="bwi-popout"
size="small"
type="button"
title="Pop out"
aria-label="Pop out"
></button>
`,
standalone: true,
imports: [IconButtonModule],
})
class MockPopoutButtonComponent {}
@Component({
selector: "mock-current-account",
template: `
<button class="tw-bg-transparent tw-border-none" type="button">
<bit-avatar text="Ash Ketchum" size="small"></bit-avatar>
</button>
`,
standalone: true,
imports: [AvatarModule],
})
class MockCurrentAccountComponent {}
@Component({
selector: "mock-vault-page",
template: `
<popup-page>
<popup-header slot="header" pageTitle="Test">
<ng-container slot="end">
<mock-add-button></mock-add-button>
<mock-popout-button></mock-popout-button>
<mock-current-account></mock-current-account>
</ng-container>
</popup-header>
<vault-placeholder></vault-placeholder>
</popup-page>
`,
standalone: true,
imports: [
PopupPageComponent,
PopupHeaderComponent,
MockAddButtonComponent,
MockPopoutButtonComponent,
MockCurrentAccountComponent,
VaultComponent,
],
})
class MockVaultPageComponent {}
@Component({
selector: "mock-vault-page-popped",
template: `
<popup-page>
<popup-header slot="header" pageTitle="Test">
<ng-container slot="end">
<mock-add-button></mock-add-button>
<mock-current-account></mock-current-account>
</ng-container>
</popup-header>
<vault-placeholder></vault-placeholder>
</popup-page>
`,
standalone: true,
imports: [
PopupPageComponent,
PopupHeaderComponent,
MockAddButtonComponent,
MockPopoutButtonComponent,
MockCurrentAccountComponent,
VaultComponent,
],
})
class MockVaultPagePoppedComponent {}
@Component({
selector: "mock-generator-page",
template: `
<popup-page>
<popup-header slot="header" pageTitle="Test">
<ng-container slot="end">
<mock-add-button></mock-add-button>
<mock-popout-button></mock-popout-button>
<mock-current-account></mock-current-account>
</ng-container>
</popup-header>
<generator-placeholder></generator-placeholder>
</popup-page>
`,
standalone: true,
imports: [
PopupPageComponent,
PopupHeaderComponent,
MockAddButtonComponent,
MockPopoutButtonComponent,
MockCurrentAccountComponent,
GeneratorComponent,
],
})
class MockGeneratorPageComponent {}
@Component({
selector: "mock-send-page",
template: `
<popup-page>
<popup-header slot="header" pageTitle="Test">
<ng-container slot="end">
<mock-add-button></mock-add-button>
<mock-popout-button></mock-popout-button>
<mock-current-account></mock-current-account>
</ng-container>
</popup-header>
<send-placeholder></send-placeholder>
</popup-page>
`,
standalone: true,
imports: [
PopupPageComponent,
PopupHeaderComponent,
MockAddButtonComponent,
MockPopoutButtonComponent,
MockCurrentAccountComponent,
SendComponent,
],
})
class MockSendPageComponent {}
@Component({
selector: "mock-settings-page",
template: `
<popup-page>
<popup-header slot="header" pageTitle="Test">
<ng-container slot="end">
<mock-add-button></mock-add-button>
<mock-popout-button></mock-popout-button>
<mock-current-account></mock-current-account>
</ng-container>
</popup-header>
<settings-placeholder></settings-placeholder>
</popup-page>
`,
standalone: true,
imports: [
PopupPageComponent,
PopupHeaderComponent,
MockAddButtonComponent,
MockPopoutButtonComponent,
MockCurrentAccountComponent,
SettingsComponent,
],
})
class MockSettingsPageComponent {}
@Component({
selector: "mock-vault-subpage",
template: `
<popup-page>
<popup-header slot="header" pageTitle="Test" showBackButton>
<ng-container slot="end">
<mock-popout-button></mock-popout-button>
</ng-container>
</popup-header>
<vault-placeholder></vault-placeholder>
<popup-footer slot="footer">
<button bitButton buttonType="primary">Save</button>
<button bitButton buttonType="secondary">Cancel</button>
</popup-footer>
</popup-page>
`,
standalone: true,
imports: [
PopupPageComponent,
PopupHeaderComponent,
PopupFooterComponent,
ButtonModule,
MockAddButtonComponent,
MockPopoutButtonComponent,
MockCurrentAccountComponent,
VaultComponent,
],
})
class MockVaultSubpageComponent {}
export default {
title: "Browser/Popup Layout",
component: PopupPageComponent,
decorators: [
moduleMetadata({
imports: [
PopupTabNavigationComponent,
CommonModule,
RouterModule,
ExtensionContainerComponent,
MockVaultSubpageComponent,
MockVaultPageComponent,
MockSendPageComponent,
MockGeneratorPageComponent,
MockSettingsPageComponent,
MockVaultPagePoppedComponent,
],
providers: [
{
provide: I18nService,
useFactory: () => {
return new I18nMockService({
back: "Back",
});
},
},
],
}),
applicationConfig({
providers: [
importProvidersFrom(
RouterModule.forRoot(
[
{ path: "", redirectTo: "vault", pathMatch: "full" },
{ path: "vault", component: MockVaultPageComponent },
{ path: "generator", component: MockGeneratorPageComponent },
{ path: "send", component: MockSendPageComponent },
{ path: "settings", component: MockSettingsPageComponent },
// in case you are coming from a story that also uses the router
{ path: "**", redirectTo: "vault" },
],
{ useHash: true },
),
),
],
}),
],
} as Meta;
type Story = StoryObj<PopupPageComponent>;
export const PopupTabNavigation: Story = {
render: (args) => ({
props: args,
template: /* HTML */ `
<extension-container>
<popup-tab-navigation>
<router-outlet></router-outlet>
</popup-tab-navigation>
</extension-container>
`,
}),
};
export const PopupPage: Story = {
render: (args) => ({
props: args,
template: /* HTML */ `
<extension-container>
<mock-vault-page></mock-vault-page>
</extension-container>
`,
}),
};
export const PopupPageWithFooter: Story = {
render: (args) => ({
props: args,
template: /* HTML */ `
<extension-container>
<mock-vault-subpage></mock-vault-subpage>
</extension-container>
`,
}),
};
export const PoppedOut: Story = {
render: (args) => ({
props: args,
template: /* HTML */ `
<div class="tw-h-[640px] tw-w-[900px] tw-border tw-border-solid tw-border-secondary-300">
<mock-vault-page-popped></mock-vault-page-popped>
</div>
`,
}),
};

View File

@ -0,0 +1,7 @@
<ng-content select="[slot=header]"></ng-content>
<main class="tw-bg-background-alt tw-p-3 tw-flex-1 tw-overflow-y-auto">
<div class="tw-max-w-screen-sm tw-mx-auto">
<ng-content></ng-content>
</div>
</main>
<ng-content select="[slot=footer]"></ng-content>

View File

@ -0,0 +1,11 @@
import { Component } from "@angular/core";
@Component({
selector: "popup-page",
templateUrl: "popup-page.component.html",
standalone: true,
host: {
class: "tw-h-full tw-flex tw-flex-col tw-flex-1 tw-overflow-y-auto",
},
})
export class PopupPageComponent {}

View File

@ -0,0 +1,32 @@
<div class="tw-h-full tw-overflow-y-auto [&>*]:tw-h-full [&>*]:tw-overflow-y-auto">
<ng-content></ng-content>
</div>
<footer class="tw-bg-background tw-border-0 tw-border-t tw-border-secondary-300 tw-border-solid">
<div class="tw-max-w-screen-sm tw-mx-auto">
<div class="tw-flex tw-flex-1">
<a
*ngFor="let button of navButtons"
class="tw-group tw-flex tw-flex-col tw-items-center tw-gap-1 tw-px-0.5 tw-pb-2 tw-pt-3 tw-w-1/4 tw-no-underline hover:tw-no-underline hover:tw-text-primary-600 hover:tw-bg-primary-100 tw-border-2 tw-border-solid tw-border-transparent focus-visible:tw-rounded-lg focus-visible:tw-border-primary-500"
[ngClass]="rla.isActive ? 'tw-font-bold tw-text-primary-600' : 'tw-text-muted'"
[title]="button.label"
[routerLink]="button.page"
routerLinkActive
#rla="routerLinkActive"
ariaCurrentWhenActive="page"
>
<i *ngIf="!rla.isActive" class="bwi bwi-lg bwi-{{ button.iconKey }}" aria-hidden="true"></i>
<i
*ngIf="rla.isActive"
class="bwi bwi-lg bwi-{{ button.iconKeyActive }}"
aria-hidden="true"
></i>
<span
class="tw-truncate tw-max-w-full"
[ngClass]="!rla.isActive && 'group-hover:tw-underline'"
>
{{ button.label }}
</span>
</a>
</div>
</div>
</footer>

View File

@ -0,0 +1,43 @@
import { CommonModule } from "@angular/common";
import { Component } from "@angular/core";
import { RouterModule } from "@angular/router";
import { LinkModule } from "@bitwarden/components";
@Component({
selector: "popup-tab-navigation",
templateUrl: "popup-tab-navigation.component.html",
standalone: true,
imports: [CommonModule, LinkModule, RouterModule],
host: {
class: "tw-block tw-h-full tw-w-full tw-flex tw-flex-col",
},
})
export class PopupTabNavigationComponent {
navButtons = [
{
label: "Vault",
page: "/vault",
iconKey: "lock",
iconKeyActive: "lock-f",
},
{
label: "Generator",
page: "/generator",
iconKey: "generate",
iconKeyActive: "generate-f",
},
{
label: "Send",
page: "/send",
iconKey: "send",
iconKeyActive: "send-f",
},
{
label: "Settings",
page: "/settings",
iconKey: "cog",
iconKeyActive: "cog-f",
},
];
}

View File

@ -175,11 +175,13 @@ export abstract class BrowserPlatformUtilsService implements PlatformUtilsServic
}
getApplicationVersion(): Promise<string> {
return Promise.resolve(BrowserApi.getApplicationVersion());
const manifest = chrome.runtime.getManifest();
return Promise.resolve(manifest.version_name ?? manifest.version);
}
async getApplicationVersionNumber(): Promise<string> {
return (await this.getApplicationVersion()).split(RegExp("[+|-]"))[0].trim();
getApplicationVersionNumber(): Promise<string> {
const manifest = chrome.runtime.getManifest();
return Promise.resolve(manifest.version.split(RegExp("[+|-]"))[0].trim());
}
supportsWebAuthn(win: Window): boolean {

View File

@ -1,9 +1,5 @@
import { Observable } from "rxjs";
import {
AbstractStorageService,
ObservableStorageService,
} from "@bitwarden/common/platform/abstractions/storage.service";
import { DeriveDefinition, DerivedState } from "@bitwarden/common/platform/state";
// eslint-disable-next-line import/no-restricted-paths -- extending this class for this client
import { DefaultDerivedStateProvider } from "@bitwarden/common/platform/state/implementations/default-derived-state.provider";
@ -16,14 +12,11 @@ export class BackgroundDerivedStateProvider extends DefaultDerivedStateProvider
parentState$: Observable<TFrom>,
deriveDefinition: DeriveDefinition<TFrom, TTo, TDeps>,
dependencies: TDeps,
storageLocation: [string, AbstractStorageService & ObservableStorageService],
): DerivedState<TTo> {
const [cacheKey, storageService] = storageLocation;
return new BackgroundDerivedState(
parentState$,
deriveDefinition,
storageService,
cacheKey,
deriveDefinition.buildCacheKey(),
dependencies,
);
}

View File

@ -1,10 +1,7 @@
import { Observable, Subscription } from "rxjs";
import { Observable, Subscription, concatMap } from "rxjs";
import { Jsonify } from "type-fest";
import {
AbstractStorageService,
ObservableStorageService,
} from "@bitwarden/common/platform/abstractions/storage.service";
import { Utils } from "@bitwarden/common/platform/misc/utils";
import { DeriveDefinition } from "@bitwarden/common/platform/state";
// eslint-disable-next-line import/no-restricted-paths -- extending this class for this client
import { DefaultDerivedState } from "@bitwarden/common/platform/state/implementations/default-derived-state";
@ -22,11 +19,10 @@ export class BackgroundDerivedState<
constructor(
parentState$: Observable<TFrom>,
deriveDefinition: DeriveDefinition<TFrom, TTo, TDeps>,
memoryStorage: AbstractStorageService & ObservableStorageService,
portName: string,
dependencies: TDeps,
) {
super(parentState$, deriveDefinition, memoryStorage, dependencies);
super(parentState$, deriveDefinition, dependencies);
// listen for foreground derived states to connect
BrowserApi.addListener(chrome.runtime.onConnect, (port) => {
@ -42,7 +38,20 @@ export class BackgroundDerivedState<
});
port.onMessage.addListener(listenerCallback);
const stateSubscription = this.state$.subscribe();
const stateSubscription = this.state$
.pipe(
concatMap(async (state) => {
await this.sendMessage(
{
action: "nextState",
data: JSON.stringify(state),
id: Utils.newGuid(),
},
port,
);
}),
)
.subscribe();
this.portSubscriptions.set(port, stateSubscription);
});

View File

@ -4,14 +4,13 @@
*/
import { NgZone } from "@angular/core";
import { FakeStorageService } from "@bitwarden/common/../spec/fake-storage.service";
import { awaitAsync, trackEmissions } from "@bitwarden/common/../spec/utils";
import { mock } from "jest-mock-extended";
import { Subject, firstValueFrom } from "rxjs";
import { DeriveDefinition } from "@bitwarden/common/platform/state";
// eslint-disable-next-line import/no-restricted-paths -- needed to define a derive definition
import { StateDefinition } from "@bitwarden/common/platform/state/state-definition";
import { awaitAsync, trackEmissions, ObservableTracker } from "@bitwarden/common/spec";
import { mockPorts } from "../../../spec/mock-port.spec-util";
@ -22,6 +21,7 @@ const stateDefinition = new StateDefinition("test", "memory");
const deriveDefinition = new DeriveDefinition(stateDefinition, "test", {
derive: (dateString: string) => (dateString == null ? null : new Date(dateString)),
deserializer: (dateString: string) => (dateString == null ? null : new Date(dateString)),
cleanupDelayMs: 1000,
});
// Mock out the runInsideAngular operator so we don't have to deal with zone.js
@ -35,7 +35,6 @@ describe("foreground background derived state interactions", () => {
let foreground: ForegroundDerivedState<Date>;
let background: BackgroundDerivedState<string, Date, Record<string, unknown>>;
let parentState$: Subject<string>;
let memoryStorage: FakeStorageService;
const initialParent = "2020-01-01";
const ngZone = mock<NgZone>();
const portName = "testPort";
@ -43,16 +42,9 @@ describe("foreground background derived state interactions", () => {
beforeEach(() => {
mockPorts();
parentState$ = new Subject<string>();
memoryStorage = new FakeStorageService();
background = new BackgroundDerivedState(
parentState$,
deriveDefinition,
memoryStorage,
portName,
{},
);
foreground = new ForegroundDerivedState(deriveDefinition, memoryStorage, portName, ngZone);
background = new BackgroundDerivedState(parentState$, deriveDefinition, portName, {});
foreground = new ForegroundDerivedState(deriveDefinition, portName, ngZone);
});
afterEach(() => {
@ -72,21 +64,13 @@ describe("foreground background derived state interactions", () => {
});
it("should initialize a late-connected foreground", async () => {
const newForeground = new ForegroundDerivedState(
deriveDefinition,
memoryStorage,
portName,
ngZone,
);
const backgroundEmissions = trackEmissions(background.state$);
const newForeground = new ForegroundDerivedState(deriveDefinition, portName, ngZone);
const backgroundTracker = new ObservableTracker(background.state$);
parentState$.next(initialParent);
await awaitAsync();
const foregroundTracker = new ObservableTracker(newForeground.state$);
const foregroundEmissions = trackEmissions(newForeground.state$);
await awaitAsync(10);
expect(backgroundEmissions).toEqual([new Date(initialParent)]);
expect(foregroundEmissions).toEqual([new Date(initialParent)]);
expect(await backgroundTracker.expectEmission()).toEqual(new Date(initialParent));
expect(await foregroundTracker.expectEmission()).toEqual(new Date(initialParent));
});
describe("forceValue", () => {

View File

@ -1,11 +1,6 @@
import { NgZone } from "@angular/core";
import { Observable } from "rxjs";
import {
AbstractStorageService,
ObservableStorageService,
} from "@bitwarden/common/platform/abstractions/storage.service";
import { StorageServiceProvider } from "@bitwarden/common/platform/services/storage-service.provider";
import { DeriveDefinition, DerivedState } from "@bitwarden/common/platform/state";
// eslint-disable-next-line import/no-restricted-paths -- extending this class for this client
import { DefaultDerivedStateProvider } from "@bitwarden/common/platform/state/implementations/default-derived-state.provider";
@ -14,19 +9,18 @@ import { DerivedStateDependencies } from "@bitwarden/common/src/types/state";
import { ForegroundDerivedState } from "./foreground-derived-state";
export class ForegroundDerivedStateProvider extends DefaultDerivedStateProvider {
constructor(
storageServiceProvider: StorageServiceProvider,
private ngZone: NgZone,
) {
super(storageServiceProvider);
constructor(private ngZone: NgZone) {
super();
}
override buildDerivedState<TFrom, TTo, TDeps extends DerivedStateDependencies>(
_parentState$: Observable<TFrom>,
deriveDefinition: DeriveDefinition<TFrom, TTo, TDeps>,
_dependencies: TDeps,
storageLocation: [string, AbstractStorageService & ObservableStorageService],
): DerivedState<TTo> {
const [cacheKey, storageService] = storageLocation;
return new ForegroundDerivedState(deriveDefinition, storageService, cacheKey, this.ngZone);
return new ForegroundDerivedState(
deriveDefinition,
deriveDefinition.buildCacheKey(),
this.ngZone,
);
}
}

View File

@ -1,11 +1,5 @@
/**
* need to update test environment so structuredClone works appropriately
* @jest-environment ../../libs/shared/test.environment.ts
*/
import { NgZone } from "@angular/core";
import { awaitAsync, trackEmissions } from "@bitwarden/common/../spec";
import { FakeStorageService } from "@bitwarden/common/../spec/fake-storage.service";
import { awaitAsync } from "@bitwarden/common/../spec";
import { mock } from "jest-mock-extended";
import { DeriveDefinition } from "@bitwarden/common/platform/state";
@ -32,15 +26,12 @@ jest.mock("../browser/run-inside-angular.operator", () => {
describe("ForegroundDerivedState", () => {
let sut: ForegroundDerivedState<Date>;
let memoryStorage: FakeStorageService;
const portName = "testPort";
const ngZone = mock<NgZone>();
beforeEach(() => {
memoryStorage = new FakeStorageService();
memoryStorage.internalUpdateValuesRequireDeserialization(true);
mockPorts();
sut = new ForegroundDerivedState(deriveDefinition, memoryStorage, portName, ngZone);
sut = new ForegroundDerivedState(deriveDefinition, portName, ngZone);
});
afterEach(() => {
@ -67,18 +58,4 @@ describe("ForegroundDerivedState", () => {
expect(disconnectSpy).toHaveBeenCalled();
expect(sut["port"]).toBeNull();
});
it("should emit when the memory storage updates", async () => {
const dateString = "2020-01-01";
const emissions = trackEmissions(sut.state$);
await memoryStorage.save(deriveDefinition.storageKey, {
derived: true,
value: new Date(dateString),
});
await awaitAsync();
expect(emissions).toEqual([new Date(dateString)]);
});
});

View File

@ -6,19 +6,14 @@ import {
filter,
firstValueFrom,
map,
merge,
of,
share,
switchMap,
tap,
timer,
} from "rxjs";
import { Jsonify, JsonObject } from "type-fest";
import { Jsonify } from "type-fest";
import {
AbstractStorageService,
ObservableStorageService,
} from "@bitwarden/common/platform/abstractions/storage.service";
import { Utils } from "@bitwarden/common/platform/misc/utils";
import { DeriveDefinition, DerivedState } from "@bitwarden/common/platform/state";
import { DerivedStateDependencies } from "@bitwarden/common/types/state";
@ -27,41 +22,28 @@ import { fromChromeEvent } from "../browser/from-chrome-event";
import { runInsideAngular } from "../browser/run-inside-angular.operator";
export class ForegroundDerivedState<TTo> implements DerivedState<TTo> {
private storageKey: string;
private port: chrome.runtime.Port;
private backgroundResponses$: Observable<DerivedStateMessage>;
state$: Observable<TTo>;
constructor(
private deriveDefinition: DeriveDefinition<unknown, TTo, DerivedStateDependencies>,
private memoryStorage: AbstractStorageService & ObservableStorageService,
private portName: string,
private ngZone: NgZone,
) {
this.storageKey = deriveDefinition.storageKey;
const initialStorageGet$ = defer(() => {
return this.getStoredValue();
}).pipe(
filter((s) => s.derived),
map((s) => s.value),
);
const latestStorage$ = this.memoryStorage.updates$.pipe(
filter((s) => s.key === this.storageKey),
switchMap(async (storageUpdate) => {
if (storageUpdate.updateType === "remove") {
return null;
}
return await this.getStoredValue();
}),
filter((s) => s.derived),
map((s) => s.value),
);
const latestValueFromPort$ = (port: chrome.runtime.Port) => {
return fromChromeEvent(port.onMessage).pipe(
map(([message]) => message as DerivedStateMessage),
filter((message) => message.originator === "background" && message.action === "nextState"),
map((message) => {
const json = JSON.parse(message.data) as Jsonify<TTo>;
return this.deriveDefinition.deserialize(json);
}),
);
};
this.state$ = defer(() => of(this.initializePort())).pipe(
switchMap(() => merge(initialStorageGet$, latestStorage$)),
switchMap(() => latestValueFromPort$(this.port)),
share({
connector: () => new ReplaySubject<TTo>(1),
resetOnRefCountZero: () =>
@ -130,28 +112,4 @@ export class ForegroundDerivedState<TTo> implements DerivedState<TTo> {
this.port = null;
this.backgroundResponses$ = null;
}
protected async getStoredValue(): Promise<{ derived: boolean; value: TTo | null }> {
if (this.memoryStorage.valuesRequireDeserialization) {
const storedJson = await this.memoryStorage.get<
Jsonify<{ derived: true; value: JsonObject }>
>(this.storageKey);
if (!storedJson?.derived) {
return { derived: false, value: null };
}
const value = this.deriveDefinition.deserialize(storedJson.value as any);
return { derived: true, value };
} else {
const stored = await this.memoryStorage.get<{ derived: true; value: TTo }>(this.storageKey);
if (!stored?.derived) {
return { derived: false, value: null };
}
return { derived: true, value: stored.value };
}
}
}

View File

@ -36,6 +36,10 @@ import { TwoFactorComponent } from "../auth/popup/two-factor.component";
import { UpdateTempPasswordComponent } from "../auth/popup/update-temp-password.component";
import { AutofillComponent } from "../autofill/popup/settings/autofill.component";
import { HeaderComponent } from "../platform/popup/header.component";
import { PopupFooterComponent } from "../platform/popup/layout/popup-footer.component";
import { PopupHeaderComponent } from "../platform/popup/layout/popup-header.component";
import { PopupPageComponent } from "../platform/popup/layout/popup-page.component";
import { PopupTabNavigationComponent } from "../platform/popup/layout/popup-tab-navigation.component";
import { FilePopoutCalloutComponent } from "../tools/popup/components/file-popout-callout.component";
import { GeneratorComponent } from "../tools/popup/generator/generator.component";
import { PasswordGeneratorHistoryComponent } from "../tools/popup/generator/password-generator-history.component";
@ -108,6 +112,10 @@ import "../platform/popup/locales";
AccountComponent,
ButtonModule,
ExportScopeCalloutComponent,
PopupPageComponent,
PopupTabNavigationComponent,
PopupFooterComponent,
PopupHeaderComponent,
],
declarations: [
ActionButtonsComponent,

View File

@ -68,7 +68,7 @@ img {
border: none;
}
a {
a:not(popup-page a, popup-tab-navigation a) {
text-decoration: none;
@include themify($themes) {
@ -171,7 +171,7 @@ cdk-virtual-scroll-viewport::-webkit-scrollbar-thumb,
}
}
header:not(bit-callout header, bit-dialog header) {
header:not(bit-callout header, bit-dialog header, popup-page header) {
height: 44px;
display: flex;
@ -448,7 +448,7 @@ app-root {
}
}
main {
main:not(popup-page main) {
position: absolute;
top: 44px;
bottom: 0;

View File

@ -473,7 +473,7 @@ const safeProviders: SafeProvider[] = [
safeProvider({
provide: DerivedStateProvider,
useClass: ForegroundDerivedStateProvider,
deps: [StorageServiceProvider, NgZone],
deps: [NgZone],
}),
safeProvider({
provide: AutofillSettingsServiceAbstraction,

View File

@ -5,7 +5,7 @@
<div bitDialogTitle>Bitwarden</div>
<div bitDialogContent>
<p>&copy; Bitwarden Inc. 2015-{{ year }}</p>
<p>{{ "version" | i18n }}: {{ version }}</p>
<p>{{ "version" | i18n }}: {{ version$ | async }}</p>
<ng-container *ngIf="data$ | async as data">
<p *ngIf="data.isCloud">
{{ "serverVersion" | i18n }}: {{ data.serverConfig?.version }}

View File

@ -1,14 +1,13 @@
import { CommonModule } from "@angular/common";
import { Component } from "@angular/core";
import { combineLatest, map } from "rxjs";
import { Observable, combineLatest, defer, map } from "rxjs";
import { JslibModule } from "@bitwarden/angular/jslib.module";
import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service";
import { EnvironmentService } from "@bitwarden/common/platform/abstractions/environment.service";
import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service";
import { ButtonModule, DialogModule } from "@bitwarden/components";
import { BrowserApi } from "../../platform/browser/browser-api";
@Component({
templateUrl: "about.component.html",
standalone: true,
@ -16,7 +15,7 @@ import { BrowserApi } from "../../platform/browser/browser-api";
})
export class AboutComponent {
protected year = new Date().getFullYear();
protected version = BrowserApi.getApplicationVersion();
protected version$: Observable<string>;
protected data$ = combineLatest([
this.configService.serverConfig$,
@ -26,5 +25,8 @@ export class AboutComponent {
constructor(
private configService: ConfigService,
private environmentService: EnvironmentService,
) {}
private platformUtilsService: PlatformUtilsService,
) {
this.version$ = defer(() => this.platformUtilsService.getApplicationVersion());
}
}

View File

@ -21,6 +21,7 @@ import { VaultTimeoutSettingsService } from "@bitwarden/common/abstractions/vaul
import { VaultTimeoutService } from "@bitwarden/common/abstractions/vault-timeout/vault-timeout.service";
import { PolicyService } from "@bitwarden/common/admin-console/abstractions/policy/policy.service.abstraction";
import { PolicyType } from "@bitwarden/common/admin-console/enums";
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
import { UserVerificationService } from "@bitwarden/common/auth/abstractions/user-verification/user-verification.service.abstraction";
import { DeviceType } from "@bitwarden/common/enums";
import { VaultTimeoutAction } from "@bitwarden/common/enums/vault-timeout-action.enum";
@ -86,6 +87,7 @@ export class SettingsComponent implements OnInit {
private destroy$ = new Subject<void>();
constructor(
private accountService: AccountService,
private policyService: PolicyService,
private formBuilder: FormBuilder,
private platformUtilsService: PlatformUtilsService,
@ -434,8 +436,9 @@ export class SettingsComponent implements OnInit {
type: "info",
});
const userId = (await firstValueFrom(this.accountService.activeAccount$))?.id;
if (confirmed) {
this.messagingService.send("logout");
this.messagingService.send("logout", { userId: userId });
}
}

View File

@ -183,7 +183,7 @@ class FilelessImporterBackground implements FilelessImporterBackgroundInterface
return;
}
const filelessImportFeatureFlagEnabled = await this.configService.getFeatureFlag<boolean>(
const filelessImportFeatureFlagEnabled = await this.configService.getFeatureFlag(
FeatureFlag.BrowserFilelessImport,
);
const userAuthStatus = await this.authService.getAuthStatus();

View File

@ -2,6 +2,7 @@
"compilerOptions": {
"moduleResolution": "node",
"noImplicitAny": true,
"allowSyntheticDefaultImports": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"module": "ES2020",

View File

@ -314,7 +314,7 @@ export class Main {
this.singleUserStateProvider,
);
this.derivedStateProvider = new DefaultDerivedStateProvider(storageServiceProvider);
this.derivedStateProvider = new DefaultDerivedStateProvider();
this.stateProvider = new DefaultStateProvider(
this.activeUserStateProvider,

View File

@ -157,7 +157,7 @@ export class Main {
activeUserStateProvider,
singleUserStateProvider,
globalStateProvider,
new DefaultDerivedStateProvider(storageServiceProvider),
new DefaultDerivedStateProvider(),
);
this.environmentService = new DefaultEnvironmentService(stateProvider, accountService);

View File

@ -58,7 +58,6 @@ export class OrganizationLayoutComponent implements OnInit, OnDestroy {
protected showPaymentMethodWarningBanners$ = this.configService.getFeatureFlag$(
FeatureFlag.ShowPaymentMethodWarningBanners,
false,
);
constructor(

View File

@ -218,7 +218,6 @@ export class MemberDialogComponent implements OnDestroy {
groups: groups$,
flexibleCollectionsV1Enabled: this.configService.getFeatureFlag$(
FeatureFlag.FlexibleCollectionsV1,
false,
),
})
.pipe(takeUntil(this.destroy$))

View File

@ -44,12 +44,10 @@ export class AccountComponent {
protected flexibleCollectionsMigrationEnabled$ = this.configService.getFeatureFlag$(
FeatureFlag.FlexibleCollectionsMigration,
false,
);
flexibleCollectionsV1Enabled$ = this.configService.getFeatureFlag$(
FeatureFlag.FlexibleCollectionsV1,
false,
);
// FormGroup validators taken from server Organization domain object

View File

@ -10,6 +10,7 @@ import { PolicyService } from "@bitwarden/common/admin-console/abstractions/poli
import { TwoFactorProviderType } from "@bitwarden/common/auth/enums/two-factor-provider-type";
import { BillingAccountProfileStateService } from "@bitwarden/common/billing/abstractions/account/billing-account-profile-state.service";
import { MessagingService } from "@bitwarden/common/platform/abstractions/messaging.service";
import { DialogService } from "@bitwarden/components";
import { TwoFactorDuoComponent } from "../../../auth/settings/two-factor-duo.component";
import { TwoFactorSetupComponent as BaseTwoFactorSetupComponent } from "../../../auth/settings/two-factor-setup.component";
@ -22,6 +23,7 @@ import { TwoFactorSetupComponent as BaseTwoFactorSetupComponent } from "../../..
export class TwoFactorSetupComponent extends BaseTwoFactorSetupComponent {
tabbedHeader = false;
constructor(
dialogService: DialogService,
apiService: ApiService,
modalService: ModalService,
messagingService: MessagingService,
@ -31,6 +33,7 @@ export class TwoFactorSetupComponent extends BaseTwoFactorSetupComponent {
billingAccountProfileStateService: BillingAccountProfileStateService,
) {
super(
dialogService,
apiService,
modalService,
messagingService,

View File

@ -90,7 +90,7 @@ export class UserKeyRotationService {
request.emergencyAccessKeys = await this.emergencyAccessService.getRotatedKeys(newUserKey);
request.resetPasswordKeys = await this.resetPasswordService.getRotatedKeys(newUserKey);
if (await this.configService.getFeatureFlag<boolean>(FeatureFlag.KeyRotationImprovements)) {
if (await this.configService.getFeatureFlag(FeatureFlag.KeyRotationImprovements)) {
await this.apiService.postUserKeyUpdate(request);
} else {
await this.rotateUserKeyAndEncryptedDataLegacy(request);

View File

@ -15,13 +15,6 @@
<span aria-hidden="true">&times;</span>
</button>
</div>
<app-two-factor-verify
[organizationId]="organizationId"
[type]="type"
(onAuthed)="auth($any($event))"
*ngIf="!authed"
>
</app-two-factor-verify>
<form
#form
(ngSubmit)="submit()"

View File

@ -15,13 +15,6 @@
<span aria-hidden="true">&times;</span>
</button>
</div>
<app-two-factor-verify
[organizationId]="organizationId"
[type]="type"
(onAuthed)="auth($any($event))"
*ngIf="!authed"
>
</app-two-factor-verify>
<form
#form
(ngSubmit)="submit()"

View File

@ -15,13 +15,6 @@
<span aria-hidden="true">&times;</span>
</button>
</div>
<app-two-factor-verify
[organizationId]="organizationId"
[type]="type"
(onAuthed)="auth($any($event))"
*ngIf="!authed"
>
</app-two-factor-verify>
<form
#form
(ngSubmit)="submit()"

View File

@ -15,8 +15,6 @@
<span aria-hidden="true">&times;</span>
</button>
</div>
<app-two-factor-verify [type]="type" (onAuthed)="auth($event)" *ngIf="!authed">
</app-two-factor-verify>
<ng-container *ngIf="authed">
<div class="modal-body text-center">
<ng-container *ngIf="code">

View File

@ -1,5 +1,5 @@
import { Component, OnDestroy, OnInit, Type, ViewChild, ViewContainerRef } from "@angular/core";
import { firstValueFrom, Observable, Subject, takeUntil } from "rxjs";
import { firstValueFrom, lastValueFrom, Observable, Subject, takeUntil } from "rxjs";
import { ModalRef } from "@bitwarden/angular/components/modal/modal.ref";
import { ModalService } from "@bitwarden/angular/services/modal.service";
@ -8,15 +8,23 @@ import { PolicyService } from "@bitwarden/common/admin-console/abstractions/poli
import { PolicyType } from "@bitwarden/common/admin-console/enums";
import { Organization } from "@bitwarden/common/admin-console/models/domain/organization";
import { TwoFactorProviderType } from "@bitwarden/common/auth/enums/two-factor-provider-type";
import { TwoFactorAuthenticatorResponse } from "@bitwarden/common/auth/models/response/two-factor-authenticator.response";
import { TwoFactorDuoResponse } from "@bitwarden/common/auth/models/response/two-factor-duo.response";
import { TwoFactorEmailResponse } from "@bitwarden/common/auth/models/response/two-factor-email.response";
import { TwoFactorWebAuthnResponse } from "@bitwarden/common/auth/models/response/two-factor-web-authn.response";
import { TwoFactorYubiKeyResponse } from "@bitwarden/common/auth/models/response/two-factor-yubi-key.response";
import { TwoFactorProviders } from "@bitwarden/common/auth/services/two-factor.service";
import { AuthResponse } from "@bitwarden/common/auth/types/auth-response";
import { BillingAccountProfileStateService } from "@bitwarden/common/billing/abstractions/account/billing-account-profile-state.service";
import { ProductType } from "@bitwarden/common/enums";
import { MessagingService } from "@bitwarden/common/platform/abstractions/messaging.service";
import { DialogService } from "@bitwarden/components";
import { TwoFactorAuthenticatorComponent } from "./two-factor-authenticator.component";
import { TwoFactorDuoComponent } from "./two-factor-duo.component";
import { TwoFactorEmailComponent } from "./two-factor-email.component";
import { TwoFactorRecoveryComponent } from "./two-factor-recovery.component";
import { TwoFactorVerifyComponent } from "./two-factor-verify.component";
import { TwoFactorWebAuthnComponent } from "./two-factor-webauthn.component";
import { TwoFactorYubiKeyComponent } from "./two-factor-yubikey.component";
@ -52,6 +60,7 @@ export class TwoFactorSetupComponent implements OnInit, OnDestroy {
private twoFactorAuthPolicyAppliesToActiveUser: boolean;
constructor(
protected dialogService: DialogService,
protected apiService: ApiService,
protected modalService: ModalService,
protected messagingService: MessagingService,
@ -114,50 +123,82 @@ export class TwoFactorSetupComponent implements OnInit, OnDestroy {
this.loading = false;
}
async callTwoFactorVerifyDialog(type?: TwoFactorProviderType) {
const twoFactorVerifyDialogRef = TwoFactorVerifyComponent.open(this.dialogService, {
data: { type: type, organizationId: this.organizationId },
});
return await lastValueFrom(twoFactorVerifyDialogRef.closed);
}
async manage(type: TwoFactorProviderType) {
switch (type) {
case TwoFactorProviderType.Authenticator: {
const result: AuthResponse<TwoFactorAuthenticatorResponse> =
await this.callTwoFactorVerifyDialog(type);
if (!result) {
return;
}
const authComp = await this.openModal(
this.authenticatorModalRef,
TwoFactorAuthenticatorComponent,
);
// eslint-disable-next-line rxjs-angular/prefer-takeuntil
authComp.onUpdated.subscribe((enabled: boolean) => {
await authComp.auth(result);
authComp.onUpdated.pipe(takeUntil(this.destroy$)).subscribe((enabled: boolean) => {
this.updateStatus(enabled, TwoFactorProviderType.Authenticator);
});
break;
}
case TwoFactorProviderType.Yubikey: {
const result: AuthResponse<TwoFactorYubiKeyResponse> =
await this.callTwoFactorVerifyDialog(type);
if (!result) {
return;
}
const yubiComp = await this.openModal(this.yubikeyModalRef, TwoFactorYubiKeyComponent);
// eslint-disable-next-line rxjs-angular/prefer-takeuntil
yubiComp.onUpdated.subscribe((enabled: boolean) => {
yubiComp.auth(result);
yubiComp.onUpdated.pipe(takeUntil(this.destroy$)).subscribe((enabled: boolean) => {
this.updateStatus(enabled, TwoFactorProviderType.Yubikey);
});
break;
}
case TwoFactorProviderType.Duo: {
const result: AuthResponse<TwoFactorDuoResponse> =
await this.callTwoFactorVerifyDialog(type);
if (!result) {
return;
}
const duoComp = await this.openModal(this.duoModalRef, TwoFactorDuoComponent);
// eslint-disable-next-line rxjs-angular/prefer-takeuntil
duoComp.onUpdated.subscribe((enabled: boolean) => {
duoComp.auth(result);
duoComp.onUpdated.pipe(takeUntil(this.destroy$)).subscribe((enabled: boolean) => {
this.updateStatus(enabled, TwoFactorProviderType.Duo);
});
break;
}
case TwoFactorProviderType.Email: {
const result: AuthResponse<TwoFactorEmailResponse> =
await this.callTwoFactorVerifyDialog(type);
if (!result) {
return;
}
const emailComp = await this.openModal(this.emailModalRef, TwoFactorEmailComponent);
// eslint-disable-next-line rxjs-angular/prefer-takeuntil
emailComp.onUpdated.subscribe((enabled: boolean) => {
await emailComp.auth(result);
emailComp.onUpdated.pipe(takeUntil(this.destroy$)).subscribe((enabled: boolean) => {
this.updateStatus(enabled, TwoFactorProviderType.Email);
});
break;
}
case TwoFactorProviderType.WebAuthn: {
const result: AuthResponse<TwoFactorWebAuthnResponse> =
await this.callTwoFactorVerifyDialog(type);
if (!result) {
return;
}
const webAuthnComp = await this.openModal(
this.webAuthnModalRef,
TwoFactorWebAuthnComponent,
);
// eslint-disable-next-line rxjs-angular/prefer-takeuntil
webAuthnComp.onUpdated.subscribe((enabled: boolean) => {
webAuthnComp.auth(result);
webAuthnComp.onUpdated.pipe(takeUntil(this.destroy$)).subscribe((enabled: boolean) => {
this.updateStatus(enabled, TwoFactorProviderType.WebAuthn);
});
break;
@ -167,10 +208,12 @@ export class TwoFactorSetupComponent implements OnInit, OnDestroy {
}
}
recoveryCode() {
// FIXME: Verify that this floating promise is intentional. If it is, add an explanatory comment and ensure there is proper error handling.
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.openModal(this.recoveryModalRef, TwoFactorRecoveryComponent);
async recoveryCode() {
const result = await this.callTwoFactorVerifyDialog(-1 as TwoFactorProviderType);
if (result) {
const recoverComp = await this.openModal(this.recoveryModalRef, TwoFactorRecoveryComponent);
recoverComp.auth(result);
}
}
async premiumRequired() {

View File

@ -1,15 +1,23 @@
<form #form (ngSubmit)="submit()" [appApiAction]="formPromise" ngNativeValidate>
<div class="modal-body">
<app-user-verification [(ngModel)]="secret" ngDefaultControl name="secret">
</app-user-verification>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary btn-submit" [disabled]="form.loading">
<i class="bwi bwi-spinner bwi-spin" title="{{ 'loading' | i18n }}" aria-hidden="true"></i>
<span>{{ "continue" | i18n }}</span>
</button>
<button type="button" class="btn btn-outline-secondary" data-dismiss="modal">
{{ "close" | i18n }}
</button>
</div>
<form [formGroup]="formGroup" [bitSubmit]="submit">
<bit-dialog dialogSize="default">
<span bitDialogTitle>
{{ "twoStepLogin" | i18n }}
<small class="tw-text-muted">{{ dialogTitle }}</small>
</span>
<ng-container bitDialogContent>
<app-user-verification-form-input
formControlName="secret"
ngDefaultControl
name="secret"
></app-user-verification-form-input>
</ng-container>
<ng-container bitDialogFooter>
<button bitButton bitFormButton type="submit" buttonType="primary">
{{ "continue" | i18n }}
</button>
<button bitButton type="button" buttonType="secondary" bitDialogClose>
{{ "close" | i18n }}
</button>
</ng-container>
</bit-dialog>
</form>

View File

@ -1,4 +1,6 @@
import { Component, EventEmitter, Input, Output } from "@angular/core";
import { DIALOG_DATA, DialogConfig, DialogRef } from "@angular/cdk/dialog";
import { Component, EventEmitter, Inject, Output } from "@angular/core";
import { FormControl, FormGroup } from "@angular/forms";
import { ApiService } from "@bitwarden/common/abstractions/api.service";
import { UserVerificationService } from "@bitwarden/common/auth/abstractions/user-verification/user-verification.service.abstraction";
@ -8,46 +10,74 @@ import { SecretVerificationRequest } from "@bitwarden/common/auth/models/request
import { AuthResponse } from "@bitwarden/common/auth/types/auth-response";
import { TwoFactorResponse } from "@bitwarden/common/auth/types/two-factor-response";
import { Verification } from "@bitwarden/common/auth/types/verification";
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
import { DialogService } from "@bitwarden/components";
type TwoFactorVerifyDialogData = {
type: TwoFactorProviderType;
organizationId: string;
};
@Component({
selector: "app-two-factor-verify",
templateUrl: "two-factor-verify.component.html",
})
export class TwoFactorVerifyComponent {
@Input() type: TwoFactorProviderType;
@Input() organizationId: string;
type: TwoFactorProviderType;
organizationId: string;
@Output() onAuthed = new EventEmitter<AuthResponse<TwoFactorResponse>>();
secret: Verification;
formPromise: Promise<TwoFactorResponse>;
protected formGroup = new FormGroup({
secret: new FormControl<Verification | null>(null),
});
constructor(
@Inject(DIALOG_DATA) protected data: TwoFactorVerifyDialogData,
private dialogRef: DialogRef,
private apiService: ApiService,
private logService: LogService,
private i18nService: I18nService,
private userVerificationService: UserVerificationService,
) {}
) {
this.type = data.type;
this.organizationId = data.organizationId;
}
async submit() {
submit = async () => {
let hashedSecret: string;
try {
this.formPromise = this.userVerificationService.buildRequest(this.secret).then((request) => {
this.formPromise = this.userVerificationService
.buildRequest(this.formGroup.value.secret)
.then((request) => {
hashedSecret =
this.secret.type === VerificationType.MasterPassword
this.formGroup.value.secret.type === VerificationType.MasterPassword
? request.masterPasswordHash
: request.otp;
return this.apiCall(request);
});
const response = await this.formPromise;
this.onAuthed.emit({
response: response,
secret: hashedSecret,
verificationType: this.secret.type,
});
} catch (e) {
this.logService.error(e);
const response = await this.formPromise;
this.dialogRef.close({
response: response,
secret: hashedSecret,
verificationType: this.formGroup.value.secret.type,
});
};
get dialogTitle(): string {
switch (this.type) {
case -1 as TwoFactorProviderType:
return this.i18nService.t("recoveryCodeTitle");
case TwoFactorProviderType.Duo:
return "Duo";
case TwoFactorProviderType.Email:
return this.i18nService.t("emailTitle");
case TwoFactorProviderType.WebAuthn:
return this.i18nService.t("webAuthnTitle");
case TwoFactorProviderType.Authenticator:
return this.i18nService.t("authenticatorAppTitle");
case TwoFactorProviderType.Yubikey:
return "Yubikey";
}
}
@ -72,4 +102,8 @@ export class TwoFactorVerifyComponent {
return this.apiService.getTwoFactorYubiKey(request);
}
}
static open(dialogService: DialogService, config: DialogConfig<TwoFactorVerifyDialogData>) {
return dialogService.open<AuthResponse<any>>(TwoFactorVerifyComponent, config);
}
}

View File

@ -15,13 +15,6 @@
<span aria-hidden="true">&times;</span>
</button>
</div>
<app-two-factor-verify
[organizationId]="organizationId"
[type]="type"
(onAuthed)="auth($any($event))"
*ngIf="!authed"
>
</app-two-factor-verify>
<form
#form
(ngSubmit)="submit()"

View File

@ -15,13 +15,6 @@
<span aria-hidden="true">&times;</span>
</button>
</div>
<app-two-factor-verify
[organizationId]="organizationId"
[type]="type"
(onAuthed)="auth($any($event))"
*ngIf="!authed"
>
</app-two-factor-verify>
<form
#form
(ngSubmit)="submit()"

View File

@ -84,7 +84,6 @@ export class OrganizationSubscriptionCloudComponent implements OnInit, OnDestroy
this.showUpdatedSubscriptionStatusSection$ = this.configService.getFeatureFlag$(
FeatureFlag.AC1795_UpdatedSubscriptionStatusSection,
false,
);
}

View File

@ -40,7 +40,6 @@ export class UserLayoutComponent implements OnInit {
protected showPaymentMethodWarningBanners$ = this.configService.getFeatureFlag$(
FeatureFlag.ShowPaymentMethodWarningBanners,
false,
);
constructor(

View File

@ -1,6 +1,9 @@
import { NgModule } from "@angular/core";
import { PasswordCalloutComponent } from "@bitwarden/auth/angular";
import {
PasswordCalloutComponent,
UserVerificationFormInputComponent,
} from "@bitwarden/auth/angular";
import { LayoutComponent, NavigationModule } from "@bitwarden/components";
import { OrganizationLayoutComponent } from "../admin-console/organizations/layouts/organization-layout.component";
@ -106,6 +109,7 @@ import { SharedModule } from "./shared.module";
OrganizationBadgeModule,
PipesModule,
PasswordCalloutComponent,
UserVerificationFormInputComponent,
DangerZoneComponent,
LayoutComponent,
NavigationModule,

View File

@ -76,7 +76,7 @@ export enum CollectionDialogAction {
})
export class CollectionDialogComponent implements OnInit, OnDestroy {
protected flexibleCollectionsV1Enabled$ = this.configService
.getFeatureFlag$(FeatureFlag.FlexibleCollectionsV1, false)
.getFeatureFlag$(FeatureFlag.FlexibleCollectionsV1)
.pipe(first());
private destroy$ = new Subject<void>();

View File

@ -54,7 +54,6 @@ export class BulkDeleteDialogComponent {
private flexibleCollectionsV1Enabled$ = this.configService.getFeatureFlag$(
FeatureFlag.FlexibleCollectionsV1,
false,
);
constructor(

View File

@ -60,9 +60,8 @@ export class VaultOnboardingComponent implements OnInit, OnChanges, OnDestroy {
) {}
async ngOnInit() {
this.showOnboardingAccess$ = await this.configService.getFeatureFlag$<boolean>(
this.showOnboardingAccess$ = await this.configService.getFeatureFlag$(
FeatureFlag.VaultOnboarding,
false,
);
this.onboardingTasks$ = this.vaultOnboardingService.vaultOnboardingState$;
await this.setOnboardingTasks();

View File

@ -148,7 +148,6 @@ export class VaultComponent implements OnInit, OnDestroy {
protected currentSearchText$: Observable<string>;
protected flexibleCollectionsV1Enabled$ = this.configService.getFeatureFlag$(
FeatureFlag.FlexibleCollectionsV1,
false,
);
private searchText$ = new Subject<string>();

View File

@ -60,7 +60,7 @@ export class AttachmentsComponent extends BaseAttachmentsComponent implements On
async ngOnInit() {
await super.ngOnInit();
this.flexibleCollectionsV1Enabled = await firstValueFrom(
this.configService.getFeatureFlag$(FeatureFlag.FlexibleCollectionsV1, false),
this.configService.getFeatureFlag$(FeatureFlag.FlexibleCollectionsV1),
);
}

View File

@ -70,10 +70,7 @@ export class BulkCollectionAssignmentDialogComponent implements OnDestroy, OnIni
) {}
async ngOnInit() {
const v1FCEnabled = await this.configService.getFeatureFlag(
FeatureFlag.FlexibleCollectionsV1,
false,
);
const v1FCEnabled = await this.configService.getFeatureFlag(FeatureFlag.FlexibleCollectionsV1);
const org = await this.organizationService.get(this.params.organizationId);
if (org.canEditAllCiphers(v1FCEnabled)) {

View File

@ -193,7 +193,6 @@ export class VaultComponent implements OnInit, OnDestroy {
this._flexibleCollectionsV1FlagEnabled = await this.configService.getFeatureFlag(
FeatureFlag.FlexibleCollectionsV1,
false,
);
const filter$ = this.routedVaultFilterService.filter$;

View File

@ -6,6 +6,6 @@
</app-callout>
<bit-form-control>
<input type="checkbox" bitCheckbox [formControl]="enabled" />
<input type="checkbox" id="enabled" bitCheckbox [formControl]="enabled" />
<bit-label>{{ "turnOn" | i18n }}</bit-label>
</bit-form-control>

View File

@ -42,7 +42,6 @@ export class ClientsComponent extends BaseClientsComponent {
protected consolidatedBillingEnabled$ = this.configService.getFeatureFlag$(
FeatureFlag.EnableConsolidatedBilling,
false,
);
constructor(

View File

@ -37,12 +37,10 @@ export class ProvidersLayoutComponent {
protected showPaymentMethodWarningBanners$ = this.configService.getFeatureFlag$(
FeatureFlag.ShowPaymentMethodWarningBanners,
false,
);
protected enableConsolidatedBilling$ = this.configService.getFeatureFlag$(
FeatureFlag.EnableConsolidatedBilling,
false,
);
constructor(

View File

@ -30,7 +30,6 @@ export class AccountComponent {
protected enableDeleteProvider$ = this.configService.getFeatureFlag$(
FeatureFlag.EnableDeleteProvider,
false,
);
constructor(

View File

@ -36,12 +36,10 @@ export class SetupComponent implements OnInit {
protected showPaymentMethodWarningBanners$ = this.configService.getFeatureFlag$(
FeatureFlag.ShowPaymentMethodWarningBanners,
false,
);
protected enableConsolidatedBilling$ = this.configService.getFeatureFlag$(
FeatureFlag.EnableConsolidatedBilling,
false,
);
constructor(

View File

@ -38,7 +38,6 @@ export class ManageClientOrganizationsComponent extends BaseClientsComponent {
private consolidatedBillingEnabled$ = this.configService.getFeatureFlag$(
FeatureFlag.EnableConsolidatedBilling,
false,
);
protected plans: PlanResponse[];

View File

@ -18,7 +18,8 @@
<a
class="tw-block tw-mb-0 tw-font-bold hover:tw-no-underline focus:tw-outline-none after:tw-content-[''] after:tw-block after:tw-absolute after:tw-w-full after:tw-h-full after:tw-left-0 after:tw-top-0"
[href]="linkURL"
[rel]="[externalURL ? 'noopener noreferrer' : null]"
rel="noopener noreferrer"
target="_blank"
>
{{ linkText }}
</a>

View File

@ -3,7 +3,7 @@ import { ComponentFixture, TestBed } from "@angular/core/testing";
import { By } from "@angular/platform-browser";
import { mock, MockProxy } from "jest-mock-extended";
import { FeatureFlag, FeatureFlagValue } from "@bitwarden/common/enums/feature-flag.enum";
import { AllowedFeatureFlagTypes, 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";
@ -41,10 +41,8 @@ describe("IfFeatureDirective", () => {
let content: HTMLElement;
let mockConfigService: MockProxy<ConfigService>;
const mockConfigFlagValue = (flag: FeatureFlag, flagValue: FeatureFlagValue) => {
mockConfigService.getFeatureFlag.mockImplementation((f, defaultValue) =>
flag == f ? Promise.resolve(flagValue) : Promise.resolve(defaultValue),
);
const mockConfigFlagValue = (flag: FeatureFlag, flagValue: AllowedFeatureFlagTypes) => {
mockConfigService.getFeatureFlag.mockImplementation((f) => Promise.resolve(flagValue as any));
};
const queryContent = (testId: string) =>

View File

@ -1,6 +1,6 @@
import { Directive, Input, OnInit, TemplateRef, ViewContainerRef } from "@angular/core";
import { FeatureFlag, FeatureFlagValue } from "@bitwarden/common/enums/feature-flag.enum";
import { AllowedFeatureFlagTypes, 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";
@ -23,7 +23,7 @@ export class IfFeatureDirective implements OnInit {
* Optional value to compare against the value of the feature flag in the config service.
* @default true
*/
@Input() appIfFeatureValue: FeatureFlagValue = true;
@Input() appIfFeatureValue: AllowedFeatureFlagTypes = true;
private hasView = false;

View File

@ -34,12 +34,12 @@ describe("canAccessFeature", () => {
flag == testFlag ? Promise.resolve(flagValue) : Promise.resolve(defaultValue),
);
} else if (typeof flagValue === "string") {
mockConfigService.getFeatureFlag.mockImplementation((flag, defaultValue = "") =>
flag == testFlag ? Promise.resolve(flagValue) : Promise.resolve(defaultValue),
mockConfigService.getFeatureFlag.mockImplementation((flag) =>
flag == testFlag ? Promise.resolve(flagValue as any) : Promise.resolve(""),
);
} else if (typeof flagValue === "number") {
mockConfigService.getFeatureFlag.mockImplementation((flag, defaultValue = 0) =>
flag == testFlag ? Promise.resolve(flagValue) : Promise.resolve(defaultValue),
mockConfigService.getFeatureFlag.mockImplementation((flag) =>
flag == testFlag ? Promise.resolve(flagValue as any) : Promise.resolve(0),
);
}

View File

@ -1047,7 +1047,7 @@ const safeProviders: SafeProvider[] = [
safeProvider({
provide: DerivedStateProvider,
useClass: DefaultDerivedStateProvider,
deps: [StorageServiceProvider],
deps: [],
}),
safeProvider({
provide: StateProvider,

View File

@ -182,7 +182,6 @@ export class AddEditComponent implements OnInit, OnDestroy {
async ngOnInit() {
this.flexibleCollectionsV1Enabled = await this.configService.getFeatureFlag(
FeatureFlag.FlexibleCollectionsV1,
false,
);
this.policyService

View File

@ -244,7 +244,7 @@ export class SsoLoginStrategy extends LoginStrategy {
// Only try to set user key with device key if admin approval request was not successful
if (!hasUserKey) {
await this.trySetUserKeyWithDeviceKey(tokenResponse);
await this.trySetUserKeyWithDeviceKey(tokenResponse, userId);
}
} else if (
masterKeyEncryptedUserKey != null &&
@ -312,11 +312,12 @@ export class SsoLoginStrategy extends LoginStrategy {
}
}
private async trySetUserKeyWithDeviceKey(tokenResponse: IdentityTokenResponse): Promise<void> {
private async trySetUserKeyWithDeviceKey(
tokenResponse: IdentityTokenResponse,
userId: UserId,
): Promise<void> {
const trustedDeviceOption = tokenResponse.userDecryptionOptions?.trustedDeviceOption;
const userId = (await this.stateService.getUserId()) as UserId;
const deviceKey = await this.deviceTrustService.getDeviceKey(userId);
const encDevicePrivateKey = trustedDeviceOption?.encryptedPrivateKey;
const encUserKey = trustedDeviceOption?.encryptedUserKey;

View File

@ -249,11 +249,11 @@ export class FakeDerivedStateProvider implements DerivedStateProvider {
deriveDefinition: DeriveDefinition<TFrom, TTo, TDeps>,
dependencies: TDeps,
): DerivedState<TTo> {
let result = this.states.get(deriveDefinition.buildCacheKey("memory")) as DerivedState<TTo>;
let result = this.states.get(deriveDefinition.buildCacheKey()) as DerivedState<TTo>;
if (result == null) {
result = new FakeDerivedState(parentState$, deriveDefinition, dependencies);
this.states.set(deriveDefinition.buildCacheKey("memory"), result);
this.states.set(deriveDefinition.buildCacheKey(), result);
}
return result;
}

View File

@ -5,3 +5,4 @@ export * from "./fake-state-provider";
export * from "./fake-state";
export * from "./fake-account-service";
export * from "./fake-storage.service";
export * from "./observable-tracker";

View File

@ -16,9 +16,11 @@ export class ObservableTracker<T> {
/**
* Awaits the next emission from the observable, or throws if the timeout is exceeded
* @param msTimeout The maximum time to wait for another emission before throwing
* @returns The next emission from the observable
* @throws If the timeout is exceeded
*/
async expectEmission(msTimeout = 50) {
await firstValueFrom(
async expectEmission(msTimeout = 50): Promise<T> {
return await firstValueFrom(
this.observable.pipe(
timeout({
first: msTimeout,

View File

@ -1,3 +1,8 @@
/**
* Feature flags.
*
* Flags MUST be short lived and SHALL be removed once enabled.
*/
export enum FeatureFlag {
BrowserFilelessImport = "browser-fileless-import",
ItemShare = "item-share",
@ -13,5 +18,32 @@ export enum FeatureFlag {
EnableDeleteProvider = "AC-1218-delete-provider",
}
// Replace this with a type safe lookup of the feature flag values in PM-2282
export type FeatureFlagValue = number | string | boolean;
export type AllowedFeatureFlagTypes = boolean | number | string;
// Helper to ensure the value is treated as a boolean.
const FALSE = false as boolean;
/**
* Default value for feature flags.
*
* DO NOT enable previously disabled flags, REMOVE them instead.
* We support true as a value as we prefer flags to "enable" not "disable".
*/
export const DefaultFeatureFlagValue = {
[FeatureFlag.BrowserFilelessImport]: FALSE,
[FeatureFlag.ItemShare]: FALSE,
[FeatureFlag.FlexibleCollectionsV1]: FALSE,
[FeatureFlag.VaultOnboarding]: FALSE,
[FeatureFlag.GeneratorToolsModernization]: FALSE,
[FeatureFlag.KeyRotationImprovements]: FALSE,
[FeatureFlag.FlexibleCollectionsMigration]: FALSE,
[FeatureFlag.ShowPaymentMethodWarningBanners]: FALSE,
[FeatureFlag.EnableConsolidatedBilling]: FALSE,
[FeatureFlag.AC1795_UpdatedSubscriptionStatusSection]: FALSE,
[FeatureFlag.UnassignedItemsBanner]: FALSE,
[FeatureFlag.EnableDeleteProvider]: FALSE,
} satisfies Record<FeatureFlag, AllowedFeatureFlagTypes>;
export type DefaultFeatureFlagValueType = typeof DefaultFeatureFlagValue;
export type FeatureFlagValueType<Flag extends FeatureFlag> = DefaultFeatureFlagValueType[Flag];

View File

@ -1,7 +1,7 @@
import { Observable } from "rxjs";
import { SemVer } from "semver";
import { FeatureFlag } from "../../../enums/feature-flag.enum";
import { FeatureFlag, FeatureFlagValueType } from "../../../enums/feature-flag.enum";
import { Region } from "../environment.service";
import { ServerConfig } from "./server-config";
@ -14,23 +14,15 @@ export abstract class ConfigService {
/**
* Retrieves the value of a feature flag for the currently active user
* @param key The feature flag to retrieve
* @param defaultValue The default value to return if the feature flag is not set or the server's config is irretrievable
* @returns An observable that emits the value of the feature flag, updates as the server config changes
*/
getFeatureFlag$: <T extends boolean | number | string>(
key: FeatureFlag,
defaultValue?: T,
) => Observable<T>;
getFeatureFlag$: <Flag extends FeatureFlag>(key: Flag) => Observable<FeatureFlagValueType<Flag>>;
/**
* Retrieves the value of a feature flag for the currently active user
* @param key The feature flag to retrieve
* @param defaultValue The default value to return if the feature flag is not set or the server's config is irretrievable
* @returns The value of the feature flag
*/
getFeatureFlag: <T extends boolean | number | string>(
key: FeatureFlag,
defaultValue?: T,
) => Promise<T>;
getFeatureFlag: <Flag extends FeatureFlag>(key: Flag) => Promise<FeatureFlagValueType<Flag>>;
/**
* Verifies whether the server version meets the minimum required version
* @param minimumRequiredServerVersion The minimum version required

View File

@ -1,5 +1,6 @@
import { Jsonify } from "type-fest";
import { AllowedFeatureFlagTypes } from "../../../enums/feature-flag.enum";
import {
ServerConfigData,
ThirdPartyServerConfigData,
@ -14,7 +15,7 @@ export class ServerConfig {
server?: ThirdPartyServerConfigData;
environment?: EnvironmentServerConfigData;
utcDate: Date;
featureStates: { [key: string]: string } = {};
featureStates: { [key: string]: AllowedFeatureFlagTypes } = {};
constructor(serverConfigData: ServerConfigData) {
this.version = serverConfigData.version;

View File

@ -10,7 +10,7 @@ import { CryptoService } from "../abstractions/crypto.service";
import { EncryptService } from "../abstractions/encrypt.service";
import { I18nService } from "../abstractions/i18n.service";
const nodeURL = typeof window === "undefined" ? require("url") : null;
const nodeURL = typeof self === "undefined" ? require("url") : null;
declare global {
/* eslint-disable-next-line no-var */

View File

@ -1,5 +1,6 @@
import { Jsonify } from "type-fest";
import { AllowedFeatureFlagTypes } from "../../../enums/feature-flag.enum";
import { Region } from "../../abstractions/environment.service";
import {
ServerConfigResponse,
@ -13,7 +14,7 @@ export class ServerConfigData {
server?: ThirdPartyServerConfigData;
environment?: EnvironmentServerConfigData;
utcDate: string;
featureStates: { [key: string]: string } = {};
featureStates: { [key: string]: AllowedFeatureFlagTypes } = {};
constructor(serverConfigResponse: Partial<ServerConfigResponse>) {
this.version = serverConfigResponse?.version;

View File

@ -13,7 +13,11 @@ import {
} from "rxjs";
import { SemVer } from "semver";
import { FeatureFlag, FeatureFlagValue } from "../../../enums/feature-flag.enum";
import {
DefaultFeatureFlagValue,
FeatureFlag,
FeatureFlagValueType,
} from "../../../enums/feature-flag.enum";
import { UserId } from "../../../types/guid";
import { ConfigApiServiceAbstraction } from "../../abstractions/config/config-api.service.abstraction";
import { ConfigService } from "../../abstractions/config/config.service";
@ -89,20 +93,21 @@ export class DefaultConfigService implements ConfigService {
map((config) => config?.environment?.cloudRegion ?? Region.US),
);
}
getFeatureFlag$<T extends FeatureFlagValue>(key: FeatureFlag, defaultValue?: T) {
getFeatureFlag$<Flag extends FeatureFlag>(key: Flag) {
return this.serverConfig$.pipe(
map((serverConfig) => {
if (serverConfig?.featureStates == null || serverConfig.featureStates[key] == null) {
return defaultValue;
return DefaultFeatureFlagValue[key];
}
return serverConfig.featureStates[key] as T;
return serverConfig.featureStates[key] as FeatureFlagValueType<Flag>;
}),
);
}
async getFeatureFlag<T extends FeatureFlagValue>(key: FeatureFlag, defaultValue?: T) {
return await firstValueFrom(this.getFeatureFlag$(key, defaultValue));
async getFeatureFlag<Flag extends FeatureFlag>(key: Flag) {
return await firstValueFrom(this.getFeatureFlag$(key));
}
checkServerMeetsVersionRequirement$(minimumRequiredServerVersion: SemVer) {

View File

@ -171,8 +171,8 @@ export class DeriveDefinition<TFrom, TTo, TDeps extends DerivedStateDependencies
return this.options.clearOnCleanup ?? true;
}
buildCacheKey(location: string): string {
return `derived_${location}_${this.stateDefinition.name}_${this.uniqueDerivationName}`;
buildCacheKey(): string {
return `derived_${this.stateDefinition.name}_${this.uniqueDerivationName}`;
}
/**

View File

@ -1,11 +1,6 @@
import { Observable } from "rxjs";
import { DerivedStateDependencies } from "../../../types/state";
import {
AbstractStorageService,
ObservableStorageService,
} from "../../abstractions/storage.service";
import { StorageServiceProvider } from "../../services/storage-service.provider";
import { DeriveDefinition } from "../derive-definition";
import { DerivedState } from "../derived-state";
import { DerivedStateProvider } from "../derived-state.provider";
@ -15,18 +10,14 @@ import { DefaultDerivedState } from "./default-derived-state";
export class DefaultDerivedStateProvider implements DerivedStateProvider {
private cache: Record<string, DerivedState<unknown>> = {};
constructor(protected storageServiceProvider: StorageServiceProvider) {}
constructor() {}
get<TFrom, TTo, TDeps extends DerivedStateDependencies>(
parentState$: Observable<TFrom>,
deriveDefinition: DeriveDefinition<TFrom, TTo, TDeps>,
dependencies: TDeps,
): DerivedState<TTo> {
// TODO: we probably want to support optional normal memory storage for browser
const [location, storageService] = this.storageServiceProvider.get("memory", {
browser: "memory-large-object",
});
const cacheKey = deriveDefinition.buildCacheKey(location);
const cacheKey = deriveDefinition.buildCacheKey();
const existingDerivedState = this.cache[cacheKey];
if (existingDerivedState != null) {
// I have to cast out of the unknown generic but this should be safe if rules
@ -34,10 +25,7 @@ export class DefaultDerivedStateProvider implements DerivedStateProvider {
return existingDerivedState as DefaultDerivedState<TFrom, TTo, TDeps>;
}
const newDerivedState = this.buildDerivedState(parentState$, deriveDefinition, dependencies, [
location,
storageService,
]);
const newDerivedState = this.buildDerivedState(parentState$, deriveDefinition, dependencies);
this.cache[cacheKey] = newDerivedState;
return newDerivedState;
}
@ -46,13 +34,7 @@ export class DefaultDerivedStateProvider implements DerivedStateProvider {
parentState$: Observable<TFrom>,
deriveDefinition: DeriveDefinition<TFrom, TTo, TDeps>,
dependencies: TDeps,
storageLocation: [string, AbstractStorageService & ObservableStorageService],
): DerivedState<TTo> {
return new DefaultDerivedState<TFrom, TTo, TDeps>(
parentState$,
deriveDefinition,
storageLocation[1],
dependencies,
);
return new DefaultDerivedState<TFrom, TTo, TDeps>(parentState$, deriveDefinition, dependencies);
}
}

View File

@ -5,7 +5,6 @@
import { Subject, firstValueFrom } from "rxjs";
import { awaitAsync, trackEmissions } from "../../../../spec";
import { FakeStorageService } from "../../../../spec/fake-storage.service";
import { DeriveDefinition } from "../derive-definition";
import { StateDefinition } from "../state-definition";
@ -29,7 +28,6 @@ const deriveDefinition = new DeriveDefinition<string, Date, { date: Date }>(
describe("DefaultDerivedState", () => {
let parentState$: Subject<string>;
let memoryStorage: FakeStorageService;
let sut: DefaultDerivedState<string, Date, { date: Date }>;
const deps = {
date: new Date(),
@ -38,8 +36,7 @@ describe("DefaultDerivedState", () => {
beforeEach(() => {
callCount = 0;
parentState$ = new Subject();
memoryStorage = new FakeStorageService();
sut = new DefaultDerivedState(parentState$, deriveDefinition, memoryStorage, deps);
sut = new DefaultDerivedState(parentState$, deriveDefinition, deps);
});
afterEach(() => {
@ -66,71 +63,33 @@ describe("DefaultDerivedState", () => {
expect(callCount).toBe(1);
});
it("should store the derived state in memory", async () => {
const dateString = "2020-01-01";
trackEmissions(sut.state$);
parentState$.next(dateString);
await awaitAsync();
expect(memoryStorage.internalStore[deriveDefinition.storageKey]).toEqual(
derivedValue(new Date(dateString)),
);
const calls = memoryStorage.mock.save.mock.calls;
expect(calls.length).toBe(1);
expect(calls[0][0]).toBe(deriveDefinition.storageKey);
expect(calls[0][1]).toEqual(derivedValue(new Date(dateString)));
});
describe("forceValue", () => {
const initialParentValue = "2020-01-01";
const forced = new Date("2020-02-02");
let emissions: Date[];
describe("without observers", () => {
beforeEach(async () => {
parentState$.next(initialParentValue);
await awaitAsync();
});
it("should store the forced value", async () => {
await sut.forceValue(forced);
expect(memoryStorage.internalStore[deriveDefinition.storageKey]).toEqual(
derivedValue(forced),
);
});
beforeEach(async () => {
emissions = trackEmissions(sut.state$);
parentState$.next(initialParentValue);
await awaitAsync();
});
describe("with observers", () => {
beforeEach(async () => {
emissions = trackEmissions(sut.state$);
parentState$.next(initialParentValue);
await awaitAsync();
});
it("should force the value", async () => {
await sut.forceValue(forced);
expect(emissions).toEqual([new Date(initialParentValue), forced]);
});
it("should store the forced value", async () => {
await sut.forceValue(forced);
expect(memoryStorage.internalStore[deriveDefinition.storageKey]).toEqual(
derivedValue(forced),
);
});
it("should only force the value once", async () => {
await sut.forceValue(forced);
it("should force the value", async () => {
await sut.forceValue(forced);
expect(emissions).toEqual([new Date(initialParentValue), forced]);
});
parentState$.next(initialParentValue);
await awaitAsync();
it("should only force the value once", async () => {
await sut.forceValue(forced);
parentState$.next(initialParentValue);
await awaitAsync();
expect(emissions).toEqual([
new Date(initialParentValue),
forced,
new Date(initialParentValue),
]);
});
expect(emissions).toEqual([
new Date(initialParentValue),
forced,
new Date(initialParentValue),
]);
});
});
@ -148,42 +107,6 @@ describe("DefaultDerivedState", () => {
expect(parentState$.observed).toBe(false);
});
it("should clear state after cleanup", async () => {
const subscription = sut.state$.subscribe();
parentState$.next(newDate);
await awaitAsync();
expect(memoryStorage.internalStore[deriveDefinition.storageKey]).toEqual(
derivedValue(new Date(newDate)),
);
subscription.unsubscribe();
// Wait for cleanup
await awaitAsync(cleanupDelayMs * 2);
expect(memoryStorage.internalStore[deriveDefinition.storageKey]).toBeUndefined();
});
it("should not clear state after cleanup if clearOnCleanup is false", async () => {
deriveDefinition.options.clearOnCleanup = false;
const subscription = sut.state$.subscribe();
parentState$.next(newDate);
await awaitAsync();
expect(memoryStorage.internalStore[deriveDefinition.storageKey]).toEqual(
derivedValue(new Date(newDate)),
);
subscription.unsubscribe();
// Wait for cleanup
await awaitAsync(cleanupDelayMs * 2);
expect(memoryStorage.internalStore[deriveDefinition.storageKey]).toEqual(
derivedValue(new Date(newDate)),
);
});
it("should not cleanup if there are still subscribers", async () => {
const subscription1 = sut.state$.subscribe();
const sub2Emissions: Date[] = [];
@ -260,7 +183,3 @@ describe("DefaultDerivedState", () => {
});
});
});
function derivedValue<T>(value: T) {
return { derived: true, value };
}

View File

@ -1,10 +1,6 @@
import { Observable, ReplaySubject, Subject, concatMap, merge, share, timer } from "rxjs";
import { DerivedStateDependencies } from "../../../types/state";
import {
AbstractStorageService,
ObservableStorageService,
} from "../../abstractions/storage.service";
import { DeriveDefinition } from "../derive-definition";
import { DerivedState } from "../derived-state";
@ -22,7 +18,6 @@ export class DefaultDerivedState<TFrom, TTo, TDeps extends DerivedStateDependenc
constructor(
private parentState$: Observable<TFrom>,
protected deriveDefinition: DeriveDefinition<TFrom, TTo, TDeps>,
private memoryStorage: AbstractStorageService & ObservableStorageService,
private dependencies: TDeps,
) {
this.storageKey = deriveDefinition.storageKey;
@ -34,7 +29,6 @@ export class DefaultDerivedState<TFrom, TTo, TDeps extends DerivedStateDependenc
derivedStateOrPromise = await derivedStateOrPromise;
}
const derivedState = derivedStateOrPromise;
await this.storeValue(derivedState);
return derivedState;
}),
);
@ -44,26 +38,13 @@ export class DefaultDerivedState<TFrom, TTo, TDeps extends DerivedStateDependenc
connector: () => {
return new ReplaySubject<TTo>(1);
},
resetOnRefCountZero: () =>
timer(this.deriveDefinition.cleanupDelayMs).pipe(
concatMap(async () => {
if (this.deriveDefinition.clearOnCleanup) {
await this.memoryStorage.remove(this.storageKey);
}
return true;
}),
),
resetOnRefCountZero: () => timer(this.deriveDefinition.cleanupDelayMs),
}),
);
}
async forceValue(value: TTo) {
await this.storeValue(value);
this.forcedValueSubject.next(value);
return value;
}
private storeValue(value: TTo) {
return this.memoryStorage.save(this.storageKey, { derived: true, value });
}
}

View File

@ -17,7 +17,11 @@
--color-background-alt3: 18 82 163;
--color-background-alt4: 13 60 119;
/* Can only be used behind the extension refresh flag */
--color-primary-100: 200 217 249;
--color-primary-300: 103 149 232;
/* Can only be used behind the extension refresh flag */
--color-primary-500: 23 93 220;
--color-primary-600: 23 93 220;
--color-primary-700: 18 82 163;
@ -43,6 +47,7 @@
--color-text-contrast: 255 255 255;
--color-text-alt2: 255 255 255;
--color-text-code: 192 17 118;
--color-text-headers: 2 15 102;
--tw-ring-offset-color: #ffffff;
}
@ -60,7 +65,9 @@
--color-background-alt3: 47 52 61;
--color-background-alt4: 16 18 21;
--color-primary-100: 8 31 73;
--color-primary-300: 23 93 220;
--color-primary-500: 54 117 232;
--color-primary-600: 106 153 240;
--color-primary-700: 180 204 249;
@ -86,6 +93,7 @@
--color-text-contrast: 25 30 38;
--color-text-alt2: 255 255 255;
--color-text-code: 240 141 199;
--color-text-headers: 226 227 228;
--tw-ring-offset-color: #1f242e;
}

View File

@ -24,7 +24,11 @@ module.exports = {
current: colors.current,
black: colors.black,
primary: {
// Can only be used behind the extension refresh flag
100: rgba("--color-primary-100"),
300: rgba("--color-primary-300"),
// Can only be used behind the extension refresh flag
500: rgba("--color-primary-500"),
600: rgba("--color-primary-600"),
700: rgba("--color-primary-700"),
},
@ -69,6 +73,7 @@ module.exports = {
main: rgba("--color-text-main"),
muted: rgba("--color-text-muted"),
contrast: rgba("--color-text-contrast"),
headers: rgba("--color-text-headers"),
alt2: rgba("--color-text-alt2"),
code: rgba("--color-text-code"),
success: rgba("--color-success-600"),

View File

@ -5,6 +5,7 @@ config.content = [
"libs/components/src/**/*.{html,ts,mdx}",
"libs/auth/src/**/*.{html,ts,mdx}",
"apps/web/src/**/*.{html,ts,mdx}",
"apps/browser/src/**/*.{html,ts,mdx}",
"bitwarden_license/bit-web/src/**/*.{html,ts,mdx}",
".storybook/preview.tsx",
];

10
package-lock.json generated
View File

@ -120,7 +120,7 @@
"@typescript-eslint/eslint-plugin": "7.4.0",
"@typescript-eslint/parser": "7.4.0",
"@webcomponents/custom-elements": "1.6.0",
"autoprefixer": "10.4.18",
"autoprefixer": "10.4.19",
"base64-loader": "1.0.0",
"chromatic": "10.9.6",
"concurrently": "8.2.2",
@ -12930,9 +12930,9 @@
}
},
"node_modules/autoprefixer": {
"version": "10.4.18",
"resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.4.18.tgz",
"integrity": "sha512-1DKbDfsr6KUElM6wg+0zRNkB/Q7WcKYAaK+pzXn+Xqmszm/5Xa9coeNdtP88Vi+dPzZnMjhge8GIV49ZQkDa+g==",
"version": "10.4.19",
"resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.4.19.tgz",
"integrity": "sha512-BaENR2+zBZ8xXhM4pUaKUxlVdxZ0EZhjvbopwnXmxRUfqDmwSpC2lAi/QXvx7NRdPCo1WKEcEF6mV64si1z4Ew==",
"dev": true,
"funding": [
{
@ -12950,7 +12950,7 @@
],
"dependencies": {
"browserslist": "^4.23.0",
"caniuse-lite": "^1.0.30001591",
"caniuse-lite": "^1.0.30001599",
"fraction.js": "^4.3.7",
"normalize-range": "^0.1.2",
"picocolors": "^1.0.0",

View File

@ -81,7 +81,7 @@
"@typescript-eslint/eslint-plugin": "7.4.0",
"@typescript-eslint/parser": "7.4.0",
"@webcomponents/custom-elements": "1.6.0",
"autoprefixer": "10.4.18",
"autoprefixer": "10.4.19",
"base64-loader": "1.0.0",
"chromatic": "10.9.6",
"concurrently": "8.2.2",

View File

@ -5,7 +5,7 @@
"noImplicitAny": true,
"target": "ES2016",
"module": "ES2020",
"lib": ["es5", "es6", "es7", "dom"],
"lib": ["es5", "es6", "es7", "dom", "ES2021"],
"sourceMap": true,
"allowSyntheticDefaultImports": true,
"experimentalDecorators": true,
@ -38,6 +38,16 @@
],
"useDefineForClassFields": false
},
"include": ["apps/web/src/**/*", "libs/*/src/**/*", "bitwarden_license/bit-web/src/**/*"],
"exclude": ["apps/web/src/**/*.spec.ts", "libs/*/src/**/*.spec.ts", "**/*.spec-util.ts"]
"include": [
"apps/web/src/**/*",
"apps/browser/src/**/*",
"libs/*/src/**/*",
"bitwarden_license/bit-web/src/**/*"
],
"exclude": [
"apps/web/src/**/*.spec.ts",
"apps/browser/src/**/*.spec.ts",
"libs/*/src/**/*.spec.ts",
"**/*.spec-util.ts"
]
}