1
0
mirror of https://github.com/bitwarden/browser.git synced 2024-12-18 15:47:57 +01:00

[PM-8282] credential generator (#11398)

* credential generator browser ui
* switch browser generate screen to extension refresh flag
* consolidate generator components into module
* add `@bitwarden/generator-components` readme
* normalize generator component rx subscriptions
This commit is contained in:
✨ Audrey ✨ 2024-10-08 14:08:34 -04:00 committed by GitHub
parent cfbe180352
commit dc1f014ad8
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
23 changed files with 592 additions and 100 deletions

View File

@ -381,7 +381,7 @@
},
"generator": {
"message": "Generator",
"description": "Short for 'Password Generator'."
"description": "Short for 'credential generator'."
},
"passGenInfo": {
"message": "Automatically generate strong, unique passwords for your logins."

View File

@ -11,7 +11,6 @@ import {
unauthGuardFn,
} from "@bitwarden/angular/auth/guards";
import { canAccessFeature } from "@bitwarden/angular/platform/guard/feature-flag.guard";
import { generatorSwap } from "@bitwarden/angular/tools/generator/generator-swap";
import { extensionRefreshRedirect } from "@bitwarden/angular/utils/extension-refresh-redirect";
import { extensionRefreshSwap } from "@bitwarden/angular/utils/extension-refresh-swap";
import {
@ -555,7 +554,7 @@ const routes: Routes = [
canDeactivate: [clearVaultStateGuard],
data: { state: "tabs_vault" } satisfies RouteDataProperties,
}),
...generatorSwap(GeneratorComponent, CredentialGeneratorComponent, {
...extensionRefreshSwap(GeneratorComponent, CredentialGeneratorComponent, {
path: "generator",
canActivate: [authGuard],
data: { state: "tabs_generator" } satisfies RouteDataProperties,

View File

@ -1,2 +1,15 @@
<!-- Note: this is all throwaway markup, so it won't follow best practices -->
<tools-username-generator />
<popup-page>
<popup-header slot="header" [pageTitle]="'generator' | i18n">
<ng-container slot="end">
<app-pop-out />
<app-current-account />
</ng-container>
</popup-header>
<tools-credential-generator />
<bit-item>
<a type="button" bit-item-content routerLink="/generator-history">
{{ "passwordHistory" | i18n }}
<i slot="end" class="bwi bwi-angle-right" aria-hidden="true"></i>
</a>
</bit-item>
</popup-page>

View File

@ -1,12 +1,28 @@
import { Component } from "@angular/core";
import { SectionComponent } from "@bitwarden/components";
import { UsernameGeneratorComponent } from "@bitwarden/generator-components";
import { JslibModule } from "@bitwarden/angular/jslib.module";
import { ItemModule } from "@bitwarden/components";
import { GeneratorModule } from "@bitwarden/generator-components";
import { CurrentAccountComponent } from "../../../auth/popup/account-switching/current-account.component";
import { PopOutComponent } from "../../../platform/popup/components/pop-out.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";
@Component({
standalone: true,
selector: "credential-generator",
templateUrl: "credential-generator.component.html",
imports: [UsernameGeneratorComponent, SectionComponent],
imports: [
GeneratorModule,
CurrentAccountComponent,
JslibModule,
PopOutComponent,
PopupHeaderComponent,
PopupPageComponent,
PopupFooterComponent,
ItemModule,
],
})
export class CredentialGeneratorComponent {}

View File

@ -2,12 +2,12 @@ import { Component } from "@angular/core";
import { JslibModule } from "@bitwarden/angular/jslib.module";
import { ButtonModule, DialogModule } from "@bitwarden/components";
import { PasswordGeneratorComponent } from "@bitwarden/generator-components";
import { GeneratorModule } from "@bitwarden/generator-components";
@Component({
standalone: true,
selector: "credential-generator",
templateUrl: "credential-generator.component.html",
imports: [DialogModule, ButtonModule, JslibModule, PasswordGeneratorComponent],
imports: [DialogModule, ButtonModule, JslibModule, GeneratorModule],
})
export class CredentialGeneratorComponent {}

View File

@ -2319,7 +2319,8 @@
"message": "Unlocked"
},
"generator": {
"message": "Generator"
"message": "Generator",
"description": "Short for 'credential generator'."
},
"whatWouldYouLikeToGenerate": {
"message": "What would you like to generate?"

View File

@ -6223,7 +6223,8 @@
"message": "Account settings"
},
"generator": {
"message": "Generator"
"message": "Generator",
"description": "Short for 'credential generator'."
},
"whatWouldYouLikeToGenerate": {
"message": "What would you like to generate?"

View File

@ -0,0 +1,40 @@
<!-- FIXME: make this one or more storybooks -->
## Using generator components
The components within this module require the following import.
```ts
import { GeneratorModule } from "@bitwarden/generator-components";
```
The credential generator provides access to all generator features.
```html
<!-- Bound to active user -->
<tools-credential-generator />
<!-- Bound to a specific user -->
<tools-credential-generator [user-id]="userId" />
<!-- receive updates when a credential is generated.
`$event` is a `GeneratedCredential`.
-->
<tools-credential-generator (onGenerated)="eventHandler($event)" />
```
Specialized components are provided for username and password generation. These
components support the same properties as the credential generator.
```html
<tools-password-generator [user-id]="userId" (onGenerated)="eventHandler($event)" />
<tools-username-generator [user-id]="userId" (onGenerated)="eventHandler($event)" />
```
The emission behavior of `onGenerated` varies according to credential type. When
a credential supports immediate execution, the component automatically generates
a value and emits from `onGenerated`. An additional emission occurs each time the
user changes a setting. Users may also request a regeneration.
When a credential does not support immediate execution, then `onGenerated` fires
only when the user clicks the "generate" button.

View File

@ -10,15 +10,12 @@ import {
Generators,
} from "@bitwarden/generator-core";
import { DependenciesModule } from "./dependencies";
import { completeOnAccountSwitch } from "./util";
/** Options group for catchall emails */
@Component({
standalone: true,
selector: "tools-catchall-settings",
templateUrl: "catchall-settings.component.html",
imports: [DependenciesModule],
})
export class CatchallSettingsComponent implements OnInit, OnDestroy {
/** Instantiates the component

View File

@ -0,0 +1,77 @@
<!-- FIXME: root$ should be powered using a reactive form -->
<bit-toggle-group
fullWidth
class="tw-mb-4"
[selected]="(root$ | async).nav"
(selectedChange)="onRootChanged($event)"
attr.aria-label="{{ 'type' | i18n }}"
>
<bit-toggle *ngFor="let option of rootOptions$ | async" [value]="option.value">
{{ option.label }}
</bit-toggle>
</bit-toggle-group>
<bit-card class="tw-flex tw-justify-between tw-mb-4">
<div class="tw-grow tw-flex tw-items-center">
<bit-color-password class="tw-font-mono" [password]="value$ | async"></bit-color-password>
</div>
<div class="tw-space-x-1">
<button type="button" bitIconButton="bwi-generate" buttonType="main" (click)="generate$.next()">
{{ "generatePassword" | i18n }}
</button>
<button
type="button"
bitIconButton="bwi-clone"
buttonType="main"
showToast
[appCopyClick]="value$ | async"
>
{{ "copyPassword" | i18n }}
</button>
</div>
</bit-card>
<tools-password-settings
class="tw-mt-6"
*ngIf="(algorithm$ | async)?.id === 'password'"
[userId]="userId$ | async"
(onUpdated)="generate$.next()"
/>
<tools-passphrase-settings
class="tw-mt-6"
*ngIf="(algorithm$ | async)?.id === 'passphrase'"
[userId]="userId$ | async"
(onUpdated)="generate$.next()"
/>
<bit-section *ngIf="(category$ | async) !== 'password'">
<bit-section-header>
<h6 bitTypography="h6">{{ "options" | i18n }}</h6>
</bit-section-header>
<div class="tw-mb-4">
<bit-card>
<form class="box" [formGroup]="username" class="tw-container">
<bit-form-field>
<bit-label>{{ "type" | i18n }}</bit-label>
<bit-select [items]="usernameOptions$ | async" formControlName="nav"> </bit-select>
<bit-hint *ngIf="!!(credentialTypeHint$ | async)">{{
credentialTypeHint$ | async
}}</bit-hint>
</bit-form-field>
</form>
<tools-catchall-settings
*ngIf="(algorithm$ | async)?.id === 'catchall'"
[userId]="userId$ | async"
(onUpdated)="generate$.next()"
/>
<tools-subaddress-settings
*ngIf="(algorithm$ | async)?.id === 'subaddress'"
[userId]="userId$ | async"
(onUpdated)="generate$.next()"
/>
<tools-username-settings
*ngIf="(algorithm$ | async)?.id === 'username'"
[userId]="userId$ | async"
(onUpdated)="generate$.next()"
/>
</bit-card>
</div>
</bit-section>

View File

@ -0,0 +1,293 @@
import { Component, EventEmitter, Input, NgZone, OnDestroy, OnInit, Output } from "@angular/core";
import { FormBuilder } from "@angular/forms";
import {
BehaviorSubject,
concat,
distinctUntilChanged,
filter,
map,
of,
ReplaySubject,
Subject,
switchMap,
takeUntil,
withLatestFrom,
} from "rxjs";
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
import { UserId } from "@bitwarden/common/types/guid";
import { Option } from "@bitwarden/components/src/select/option";
import {
CredentialAlgorithm,
CredentialCategory,
CredentialGeneratorInfo,
CredentialGeneratorService,
GeneratedCredential,
Generators,
isEmailAlgorithm,
isPasswordAlgorithm,
isUsernameAlgorithm,
PasswordAlgorithm,
} from "@bitwarden/generator-core";
/** root category that drills into username and email categories */
const IDENTIFIER = "identifier";
/** options available for the top-level navigation */
type RootNavValue = PasswordAlgorithm | typeof IDENTIFIER;
@Component({
selector: "tools-credential-generator",
templateUrl: "credential-generator.component.html",
})
export class CredentialGeneratorComponent implements OnInit, OnDestroy {
constructor(
private generatorService: CredentialGeneratorService,
private i18nService: I18nService,
private accountService: AccountService,
private zone: NgZone,
private formBuilder: FormBuilder,
) {}
/** Binds the component to a specific user's settings. When this input is not provided,
* the form binds to the active user
*/
@Input()
userId: UserId | null;
/** Emits credentials created from a generation request. */
@Output()
readonly onGenerated = new EventEmitter<GeneratedCredential>();
protected root$ = new BehaviorSubject<{ nav: RootNavValue }>({
nav: null,
});
protected onRootChanged(nav: RootNavValue) {
// prevent subscription cycle
if (this.root$.value.nav !== nav) {
this.zone.run(() => {
this.root$.next({ nav });
});
}
}
protected username = this.formBuilder.group({
nav: [null as CredentialAlgorithm],
});
async ngOnInit() {
if (this.userId) {
this.userId$.next(this.userId);
} else {
this.accountService.activeAccount$
.pipe(
map((acct) => acct.id),
distinctUntilChanged(),
takeUntil(this.destroyed),
)
.subscribe(this.userId$);
}
this.generatorService
.algorithms$(["email", "username"], { userId$: this.userId$ })
.pipe(
map((algorithms) => this.toOptions(algorithms)),
takeUntil(this.destroyed),
)
.subscribe(this.usernameOptions$);
this.generatorService
.algorithms$("password", { userId$: this.userId$ })
.pipe(
map((algorithms) => {
const options = this.toOptions(algorithms) as Option<RootNavValue>[];
options.push({ value: IDENTIFIER, label: this.i18nService.t("username") });
return options;
}),
takeUntil(this.destroyed),
)
.subscribe(this.rootOptions$);
this.algorithm$
.pipe(
map((a) => a?.descriptionKey && this.i18nService.t(a?.descriptionKey)),
takeUntil(this.destroyed),
)
.subscribe((hint) => {
// update subjects within the angular zone so that the
// template bindings refresh immediately
this.zone.run(() => {
this.credentialTypeHint$.next(hint);
});
});
this.algorithm$
.pipe(
map((a) => a.category),
distinctUntilChanged(),
takeUntil(this.destroyed),
)
.subscribe((category) => {
// update subjects within the angular zone so that the
// template bindings refresh immediately
this.zone.run(() => {
this.category$.next(category);
});
});
// wire up the generator
this.algorithm$
.pipe(
switchMap((algorithm) => this.typeToGenerator$(algorithm.id)),
takeUntil(this.destroyed),
)
.subscribe((generated) => {
// update subjects within the angular zone so that the
// template bindings refresh immediately
this.zone.run(() => {
this.onGenerated.next(generated);
this.value$.next(generated.credential);
});
});
// assume the last-visible generator algorithm is the user's preferred one
const preferences = await this.generatorService.preferences({ singleUserId$: this.userId$ });
this.root$
.pipe(
filter(({ nav }) => !!nav),
switchMap((root) => {
if (root.nav === IDENTIFIER) {
return concat(of(this.username.value), this.username.valueChanges);
} else {
return of(root as { nav: PasswordAlgorithm });
}
}),
filter(({ nav }) => !!nav),
withLatestFrom(preferences),
takeUntil(this.destroyed),
)
.subscribe(([{ nav: algorithm }, preference]) => {
function setPreference(category: CredentialCategory) {
const p = preference[category];
p.algorithm = algorithm;
p.updated = new Date();
}
// `is*Algorithm` decides `algorithm`'s type, which flows into `setPreference`
if (isEmailAlgorithm(algorithm)) {
setPreference("email");
} else if (isUsernameAlgorithm(algorithm)) {
setPreference("username");
} else if (isPasswordAlgorithm(algorithm)) {
setPreference("password");
} else {
return;
}
preferences.next(preference);
});
// populate the form with the user's preferences to kick off interactivity
preferences.pipe(takeUntil(this.destroyed)).subscribe(({ email, username, password }) => {
// the last preference set by the user "wins"
const userNav = email.updated > username.updated ? email : username;
const rootNav: any = userNav.updated > password.updated ? IDENTIFIER : password.algorithm;
const credentialType = rootNav === IDENTIFIER ? userNav.algorithm : password.algorithm;
// update navigation; break subscription loop
this.onRootChanged(rootNav);
this.username.setValue({ nav: userNav.algorithm }, { emitEvent: false });
// load algorithm metadata
const algorithm = this.generatorService.algorithm(credentialType);
// update subjects within the angular zone so that the
// template bindings refresh immediately
this.zone.run(() => {
this.algorithm$.next(algorithm);
});
});
// generate on load unless the generator prohibits it
this.algorithm$
.pipe(
distinctUntilChanged((prev, next) => prev.id === next.id),
filter((a) => !a.onlyOnRequest),
takeUntil(this.destroyed),
)
.subscribe(() => this.generate$.next());
}
private typeToGenerator$(type: CredentialAlgorithm) {
const dependencies = {
on$: this.generate$,
userId$: this.userId$,
};
switch (type) {
case "catchall":
return this.generatorService.generate$(Generators.catchall, dependencies);
case "subaddress":
return this.generatorService.generate$(Generators.subaddress, dependencies);
case "username":
return this.generatorService.generate$(Generators.username, dependencies);
case "password":
return this.generatorService.generate$(Generators.password, dependencies);
case "passphrase":
return this.generatorService.generate$(Generators.passphrase, dependencies);
default:
throw new Error(`Invalid generator type: "${type}"`);
}
}
/** Lists the credential types of the username algorithm box. */
protected usernameOptions$ = new BehaviorSubject<Option<CredentialAlgorithm>[]>([]);
/** Lists the top-level credential types supported by the component. */
protected rootOptions$ = new BehaviorSubject<Option<RootNavValue>[]>([]);
/** tracks the currently selected credential type */
protected algorithm$ = new ReplaySubject<CredentialGeneratorInfo>(1);
/** Emits hint key for the currently selected credential type */
protected credentialTypeHint$ = new ReplaySubject<string>(1);
/** tracks the currently selected credential category */
protected category$ = new ReplaySubject<string>(1);
/** Emits the last generated value. */
protected readonly value$ = new BehaviorSubject<string>("");
/** Emits when the userId changes */
protected readonly userId$ = new BehaviorSubject<UserId>(null);
/** Emits when a new credential is requested */
protected readonly generate$ = new Subject<void>();
private toOptions(algorithms: CredentialGeneratorInfo[]) {
const options: Option<CredentialAlgorithm>[] = algorithms.map((algorithm) => ({
value: algorithm.id,
label: this.i18nService.t(algorithm.nameKey),
}));
return options;
}
private readonly destroyed = new Subject<void>();
ngOnDestroy() {
this.destroyed.complete();
// finalize subjects
this.generate$.complete();
this.value$.complete();
// finalize component bindings
this.onGenerated.complete();
}
}

View File

@ -10,8 +10,8 @@ import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.se
import { StateProvider } from "@bitwarden/common/platform/state";
import {
CardComponent,
CheckboxModule,
ColorPasswordModule,
CheckboxModule,
FormFieldModule,
IconButtonModule,
InputModule,
@ -27,16 +27,24 @@ import {
Randomizer,
} from "@bitwarden/generator-core";
import { CatchallSettingsComponent } from "./catchall-settings.component";
import { CredentialGeneratorComponent } from "./credential-generator.component";
import { PassphraseSettingsComponent } from "./passphrase-settings.component";
import { PasswordGeneratorComponent } from "./password-generator.component";
import { PasswordSettingsComponent } from "./password-settings.component";
import { SubaddressSettingsComponent } from "./subaddress-settings.component";
import { UsernameGeneratorComponent } from "./username-generator.component";
import { UsernameSettingsComponent } from "./username-settings.component";
const RANDOMIZER = new SafeInjectionToken<Randomizer>("Randomizer");
/** Shared module containing generator component dependencies */
@NgModule({
imports: [CardComponent, SectionComponent, SectionHeaderComponent],
exports: [
imports: [
CardComponent,
ColorPasswordModule,
CheckboxModule,
CommonModule,
ColorPasswordModule,
FormFieldModule,
IconButtonModule,
InputModule,
@ -60,8 +68,18 @@ const RANDOMIZER = new SafeInjectionToken<Randomizer>("Randomizer");
deps: [RANDOMIZER, StateProvider, PolicyService],
}),
],
declarations: [],
declarations: [
CatchallSettingsComponent,
CredentialGeneratorComponent,
SubaddressSettingsComponent,
UsernameSettingsComponent,
PasswordGeneratorComponent,
PasswordSettingsComponent,
PassphraseSettingsComponent,
UsernameGeneratorComponent,
],
exports: [CredentialGeneratorComponent, PasswordGeneratorComponent, UsernameGeneratorComponent],
})
export class DependenciesModule {
export class GeneratorModule {
constructor() {}
}

View File

@ -1,9 +1,3 @@
export { CatchallSettingsComponent } from "./catchall-settings.component";
export { CredentialGeneratorHistoryComponent } from "./credential-generator-history.component";
export { EmptyCredentialHistoryComponent } from "./empty-credential-history.component";
export { PassphraseSettingsComponent } from "./passphrase-settings.component";
export { PasswordSettingsComponent } from "./password-settings.component";
export { PasswordGeneratorComponent } from "./password-generator.component";
export { SubaddressSettingsComponent } from "./subaddress-settings.component";
export { UsernameGeneratorComponent } from "./username-generator.component";
export { UsernameSettingsComponent } from "./username-settings.component";
export { GeneratorModule } from "./generator.module";

View File

@ -10,7 +10,6 @@ import {
PassphraseGenerationOptions,
} from "@bitwarden/generator-core";
import { DependenciesModule } from "./dependencies";
import { completeOnAccountSwitch, toValidators } from "./util";
const Controls = Object.freeze({
@ -22,10 +21,8 @@ const Controls = Object.freeze({
/** Options group for passphrases */
@Component({
standalone: true,
selector: "tools-passphrase-settings",
templateUrl: "passphrase-settings.component.html",
imports: [DependenciesModule],
})
export class PassphraseSettingsComponent implements OnInit, OnDestroy {
/** Instantiates the component

View File

@ -5,11 +5,8 @@
(selectedChange)="onCredentialTypeChanged($event)"
attr.aria-label="{{ 'type' | i18n }}"
>
<bit-toggle value="password">
{{ "password" | i18n }}
</bit-toggle>
<bit-toggle value="passphrase">
{{ "passphrase" | i18n }}
<bit-toggle *ngFor="let option of passwordOptions$ | async" [value]="option.value">
{{ option.label }}
</bit-toggle>
</bit-toggle-group>
<bit-card class="tw-flex tw-justify-between tw-mb-4">
@ -24,6 +21,7 @@
type="button"
bitIconButton="bwi-clone"
buttonType="main"
showToast
[appCopyClick]="value$ | async"
>
{{ "copyPassword" | i18n }}
@ -32,13 +30,13 @@
</bit-card>
<tools-password-settings
class="tw-mt-6"
*ngIf="(credentialType$ | async) === 'password'"
*ngIf="(algorithm$ | async)?.id === 'password'"
[userId]="this.userId$ | async"
(onUpdated)="generate$.next()"
/>
<tools-passphrase-settings
class="tw-mt-6"
*ngIf="(credentialType$ | async) === 'passphrase'"
*ngIf="(algorithm$ | async)?.id === 'passphrase'"
[userId]="this.userId$ | async"
(onUpdated)="generate$.next()"
/>

View File

@ -1,29 +1,39 @@
import { Component, EventEmitter, Input, NgZone, OnDestroy, OnInit, Output } from "@angular/core";
import { BehaviorSubject, distinctUntilChanged, map, Subject, switchMap, takeUntil } from "rxjs";
import {
BehaviorSubject,
distinctUntilChanged,
filter,
map,
ReplaySubject,
Subject,
switchMap,
takeUntil,
withLatestFrom,
} from "rxjs";
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
import { UserId } from "@bitwarden/common/types/guid";
import { Option } from "@bitwarden/components/src/select/option";
import {
CredentialGeneratorService,
Generators,
PasswordAlgorithm,
GeneratedCredential,
CredentialGeneratorInfo,
CredentialAlgorithm,
isPasswordAlgorithm,
} from "@bitwarden/generator-core";
import { DependenciesModule } from "./dependencies";
import { PassphraseSettingsComponent } from "./passphrase-settings.component";
import { PasswordSettingsComponent } from "./password-settings.component";
/** Options group for passwords */
@Component({
standalone: true,
selector: "tools-password-generator",
templateUrl: "password-generator.component.html",
imports: [DependenciesModule, PasswordSettingsComponent, PassphraseSettingsComponent],
})
export class PasswordGeneratorComponent implements OnInit, OnDestroy {
constructor(
private generatorService: CredentialGeneratorService,
private i18nService: I18nService,
private accountService: AccountService,
private zone: NgZone,
) {}
@ -36,7 +46,7 @@ export class PasswordGeneratorComponent implements OnInit, OnDestroy {
userId: UserId | null;
/** tracks the currently selected credential type */
protected credentialType$ = new BehaviorSubject<PasswordAlgorithm>("password");
protected credentialType$ = new BehaviorSubject<PasswordAlgorithm>(null);
/** Emits the last generated value. */
protected readonly value$ = new BehaviorSubject<string>("");
@ -51,9 +61,11 @@ export class PasswordGeneratorComponent implements OnInit, OnDestroy {
* @param type the new credential type
*/
protected onCredentialTypeChanged(type: PasswordAlgorithm) {
// break subscription cycle
if (this.credentialType$.value !== type) {
this.credentialType$.next(type);
this.generate$.next();
this.zone.run(() => {
this.credentialType$.next(type);
});
}
}
@ -74,9 +86,18 @@ export class PasswordGeneratorComponent implements OnInit, OnDestroy {
.subscribe(this.userId$);
}
this.credentialType$
this.generatorService
.algorithms$("password", { userId$: this.userId$ })
.pipe(
switchMap((type) => this.typeToGenerator$(type)),
map((algorithms) => this.toOptions(algorithms)),
takeUntil(this.destroyed),
)
.subscribe(this.passwordOptions$);
// wire up the generator
this.algorithm$
.pipe(
switchMap((algorithm) => this.typeToGenerator$(algorithm.id)),
takeUntil(this.destroyed),
)
.subscribe((generated) => {
@ -87,9 +108,52 @@ export class PasswordGeneratorComponent implements OnInit, OnDestroy {
this.value$.next(generated.credential);
});
});
// assume the last-visible generator algorithm is the user's preferred one
const preferences = await this.generatorService.preferences({ singleUserId$: this.userId$ });
this.credentialType$
.pipe(
filter((type) => !!type),
withLatestFrom(preferences),
takeUntil(this.destroyed),
)
.subscribe(([algorithm, preference]) => {
if (isPasswordAlgorithm(algorithm)) {
preference.password.algorithm = algorithm;
preference.password.updated = new Date();
} else {
return;
}
preferences.next(preference);
});
// populate the form with the user's preferences to kick off interactivity
preferences.pipe(takeUntil(this.destroyed)).subscribe(({ password }) => {
// update navigation
this.onCredentialTypeChanged(password.algorithm);
// load algorithm metadata
const algorithm = this.generatorService.algorithm(password.algorithm);
// update subjects within the angular zone so that the
// template bindings refresh immediately
this.zone.run(() => {
this.algorithm$.next(algorithm);
});
});
// generate on load unless the generator prohibits it
this.algorithm$
.pipe(
distinctUntilChanged((prev, next) => prev.id === next.id),
filter((a) => !a.onlyOnRequest),
takeUntil(this.destroyed),
)
.subscribe(() => this.generate$.next());
}
private typeToGenerator$(type: PasswordAlgorithm) {
private typeToGenerator$(type: CredentialAlgorithm) {
const dependencies = {
on$: this.generate$,
userId$: this.userId$,
@ -106,6 +170,21 @@ export class PasswordGeneratorComponent implements OnInit, OnDestroy {
}
}
/** Lists the credential types supported by the component. */
protected passwordOptions$ = new BehaviorSubject<Option<CredentialAlgorithm>[]>([]);
/** tracks the currently selected credential type */
protected algorithm$ = new ReplaySubject<CredentialGeneratorInfo>(1);
private toOptions(algorithms: CredentialGeneratorInfo[]) {
const options: Option<CredentialAlgorithm>[] = algorithms.map((algorithm) => ({
value: algorithm.id,
label: this.i18nService.t(algorithm.nameKey),
}));
return options;
}
private readonly destroyed = new Subject<void>();
ngOnDestroy(): void {
// tear down subscriptions

View File

@ -10,7 +10,6 @@ import {
PasswordGenerationOptions,
} from "@bitwarden/generator-core";
import { DependenciesModule } from "./dependencies";
import { completeOnAccountSwitch, toValidators } from "./util";
const Controls = Object.freeze({
@ -26,10 +25,8 @@ const Controls = Object.freeze({
/** Options group for passwords */
@Component({
standalone: true,
selector: "tools-password-settings",
templateUrl: "password-settings.component.html",
imports: [DependenciesModule],
})
export class PasswordSettingsComponent implements OnInit, OnDestroy {
/** Instantiates the component

View File

@ -10,15 +10,12 @@ import {
SubaddressGenerationOptions,
} from "@bitwarden/generator-core";
import { DependenciesModule } from "./dependencies";
import { completeOnAccountSwitch } from "./util";
/** Options group for plus-addressed emails */
@Component({
standalone: true,
selector: "tools-subaddress-settings",
templateUrl: "subaddress-settings.component.html",
imports: [DependenciesModule],
})
export class SubaddressSettingsComponent implements OnInit, OnDestroy {
/** Instantiates the component

View File

@ -10,6 +10,7 @@
type="button"
bitIconButton="bwi-clone"
buttonType="main"
showToast
[appCopyClick]="value$ | async"
>
{{ "copyPassword" | i18n }}

View File

@ -26,23 +26,10 @@ import {
isUsernameAlgorithm,
} from "@bitwarden/generator-core";
import { CatchallSettingsComponent } from "./catchall-settings.component";
import { DependenciesModule } from "./dependencies";
import { SubaddressSettingsComponent } from "./subaddress-settings.component";
import { UsernameSettingsComponent } from "./username-settings.component";
import { completeOnAccountSwitch } from "./util";
/** Component that generates usernames and emails */
@Component({
standalone: true,
selector: "tools-username-generator",
templateUrl: "username-generator.component.html",
imports: [
DependenciesModule,
CatchallSettingsComponent,
SubaddressSettingsComponent,
UsernameSettingsComponent,
],
})
export class UsernameGeneratorComponent implements OnInit, OnDestroy {
/** Instantiates the username generator
@ -72,14 +59,20 @@ export class UsernameGeneratorComponent implements OnInit, OnDestroy {
/** Tracks the selected generation algorithm */
protected credential = this.formBuilder.group({
type: ["username" as CredentialAlgorithm],
type: [null as CredentialAlgorithm],
});
async ngOnInit() {
if (this.userId) {
this.userId$.next(this.userId);
} else {
this.singleUserId$().pipe(takeUntil(this.destroyed)).subscribe(this.userId$);
this.accountService.activeAccount$
.pipe(
map((acct) => acct.id),
distinctUntilChanged(),
takeUntil(this.destroyed),
)
.subscribe(this.userId$);
}
this.generatorService
@ -121,7 +114,11 @@ export class UsernameGeneratorComponent implements OnInit, OnDestroy {
// assume the last-visible generator algorithm is the user's preferred one
const preferences = await this.generatorService.preferences({ singleUserId$: this.userId$ });
this.credential.valueChanges
.pipe(withLatestFrom(preferences), takeUntil(this.destroyed))
.pipe(
filter(({ type }) => !!type),
withLatestFrom(preferences),
takeUntil(this.destroyed),
)
.subscribe(([{ type }, preference]) => {
if (isEmailAlgorithm(type)) {
preference.email.algorithm = type;
@ -202,19 +199,6 @@ export class UsernameGeneratorComponent implements OnInit, OnDestroy {
/** Emits when a new credential is requested */
protected readonly generate$ = new Subject<void>();
private singleUserId$() {
// FIXME: this branch should probably scan for the user and make sure
// the account is unlocked
if (this.userId) {
return new BehaviorSubject(this.userId as UserId).asObservable();
}
return this.accountService.activeAccount$.pipe(
completeOnAccountSwitch(),
takeUntil(this.destroyed),
);
}
private toOptions(algorithms: CredentialGeneratorInfo[]) {
const options: Option<CredentialAlgorithm>[] = algorithms.map((algorithm) => ({
value: algorithm.id,

View File

@ -10,15 +10,12 @@ import {
Generators,
} from "@bitwarden/generator-core";
import { DependenciesModule } from "./dependencies";
import { completeOnAccountSwitch } from "./util";
/** Options group for usernames */
@Component({
standalone: true,
selector: "tools-username-settings",
templateUrl: "username-settings.component.html",
imports: [DependenciesModule],
})
export class UsernameSettingsComponent implements OnInit, OnDestroy {
/** Instantiates the component

View File

@ -3,10 +3,7 @@ import { ComponentFixture, TestBed } from "@angular/core/testing";
import { By } from "@angular/platform-browser";
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
import {
PasswordGeneratorComponent,
UsernameGeneratorComponent,
} from "@bitwarden/generator-components";
import { GeneratorModule } from "@bitwarden/generator-components";
import { CipherFormGeneratorComponent } from "@bitwarden/vault";
@Component({
@ -37,7 +34,7 @@ describe("CipherFormGeneratorComponent", () => {
providers: [{ provide: I18nService, useValue: { t: (key: string) => key } }],
})
.overrideComponent(CipherFormGeneratorComponent, {
remove: { imports: [PasswordGeneratorComponent, UsernameGeneratorComponent] },
remove: { imports: [GeneratorModule] },
add: { imports: [MockPasswordGeneratorComponent, MockUsernameGeneratorComponent] },
})
.compileComponents();

View File

@ -1,11 +1,7 @@
import { CommonModule } from "@angular/common";
import { Component, EventEmitter, Input, Output } from "@angular/core";
import { SectionComponent } from "@bitwarden/components";
import {
PasswordGeneratorComponent,
UsernameGeneratorComponent,
} from "@bitwarden/generator-components";
import { GeneratorModule } from "@bitwarden/generator-components";
import { GeneratedCredential } from "@bitwarden/generator-core";
/**
@ -16,7 +12,7 @@ import { GeneratedCredential } from "@bitwarden/generator-core";
selector: "vault-cipher-form-generator",
templateUrl: "./cipher-form-generator.component.html",
standalone: true,
imports: [CommonModule, SectionComponent, PasswordGeneratorComponent, UsernameGeneratorComponent],
imports: [CommonModule, GeneratorModule],
})
export class CipherFormGeneratorComponent {
/**