1
0
mirror of https://github.com/bitwarden/browser synced 2025-12-17 00:33:44 +00:00

[PM-16793] port credential generator service to providers (#14071)

* introduce extension service
* deprecate legacy forwarder types
* eliminate repeat algorithm emissions
* extend logging to preference management
* align forwarder ids with vendor ids
* fix duplicate policy emissions; debugging required logger enhancements

-----

Co-authored-by: Daniel James Smith <2670567+djsmith85@users.noreply.github.com>
This commit is contained in:
✨ Audrey ✨
2025-05-27 09:51:14 -04:00
committed by GitHub
parent f4f659c52a
commit 97a591e738
140 changed files with 3720 additions and 4085 deletions

View File

@@ -1,5 +1,3 @@
// FIXME: Update this file to be type safe and remove this and next line
// @ts-strict-ignore
import { LiveAnnouncer } from "@angular/cdk/a11y";
import { coerceBooleanProperty } from "@angular/cdk/coercion";
import {
@@ -22,12 +20,12 @@ import {
map,
ReplaySubject,
Subject,
switchMap,
takeUntil,
withLatestFrom,
} from "rxjs";
import { Account, AccountService } from "@bitwarden/common/auth/abstractions/account.service";
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
import {
SemanticLogger,
@@ -38,17 +36,22 @@ import { UserId } from "@bitwarden/common/types/guid";
import { ToastService, Option } from "@bitwarden/components";
import {
CredentialGeneratorService,
Generators,
GeneratedCredential,
AlgorithmInfo,
GenerateRequest,
isSameAlgorithm,
CredentialAlgorithm,
isPasswordAlgorithm,
AlgorithmInfo,
isSameAlgorithm,
GenerateRequest,
CredentialCategories,
Algorithm,
AlgorithmMetadata,
Type,
GeneratorProfile,
Profile,
} from "@bitwarden/generator-core";
import { GeneratorHistoryService } from "@bitwarden/generator-history";
import { toAlgorithmInfo, translate } from "./util";
/** Options group for passwords */
@Component({
selector: "tools-password-generator",
@@ -60,17 +63,21 @@ export class PasswordGeneratorComponent implements OnInit, OnChanges, OnDestroy
private generatorService: CredentialGeneratorService,
private generatorHistoryService: GeneratorHistoryService,
private toastService: ToastService,
private i18nService: I18nService,
private logService: LogService,
private accountService: AccountService,
private zone: NgZone,
private ariaLive: LiveAnnouncer,
) {}
/** exports algorithm symbols to the template */
protected readonly Algorithm = Algorithm;
/** Binds the component to a specific user's settings. When this input is not provided,
* the form binds to the active user
*/
@Input()
account: Account | null;
account: Account | null = null;
protected account$ = new ReplaySubject<Account>(1);
@@ -87,7 +94,11 @@ export class PasswordGeneratorComponent implements OnInit, OnChanges, OnDestroy
async ngOnChanges(changes: SimpleChanges) {
const account = changes?.account;
if (account?.previousValue?.id !== account?.currentValue?.id) {
if (
account &&
account.currentValue.id &&
account.previousValue.id !== account.currentValue.id
) {
this.log.debug(
{
previousUserId: account?.previousValue?.id as UserId,
@@ -95,15 +106,19 @@ export class PasswordGeneratorComponent implements OnInit, OnChanges, OnDestroy
},
"account input change detected",
);
this.account$.next(this.account);
this.account$.next(account.currentValue.id);
}
}
@Input()
profile: GeneratorProfile = Profile.account;
/** Removes bottom margin, passed to downstream components */
@Input({ transform: coerceBooleanProperty }) disableMargin = false;
@Input({ transform: coerceBooleanProperty })
disableMargin = false;
/** tracks the currently selected credential type */
protected credentialType$ = new BehaviorSubject<CredentialAlgorithm>(null);
protected credentialType$ = new BehaviorSubject<CredentialAlgorithm | null>(null);
/** Emits the last generated value. */
protected readonly value$ = new BehaviorSubject<string>("");
@@ -119,9 +134,11 @@ export class PasswordGeneratorComponent implements OnInit, OnChanges, OnDestroy
* origin in the debugger.
*/
protected async generate(source: string) {
this.log.debug({ source }, "generation requested");
const algorithm = await firstValueFrom(this.algorithm$);
const request: GenerateRequest = { source, algorithm: algorithm.id, profile: this.profile };
this.generate$.next({ source });
this.log.debug(request, "generation requested");
this.generate$.next(request);
}
/** Tracks changes to the selected credential type
@@ -146,16 +163,17 @@ export class PasswordGeneratorComponent implements OnInit, OnChanges, OnDestroy
async ngOnInit() {
this.log = ifEnabledSemanticLoggerProvider(this.debug, this.logService, {
type: "UsernameGeneratorComponent",
type: "PasswordGeneratorComponent",
});
if (!this.account) {
this.account = await firstValueFrom(this.accountService.activeAccount$);
this.log.info(
{ userId: this.account.id },
"account not specified; using active account settings",
);
this.account$.next(this.account);
const account = await firstValueFrom(this.accountService.activeAccount$);
if (!account) {
this.log.panic("active account cannot be `null`.");
}
this.log.info({ userId: account.id }, "account not specified; using active account settings");
this.account$.next(account);
}
this.generatorService
@@ -167,10 +185,9 @@ export class PasswordGeneratorComponent implements OnInit, OnChanges, OnDestroy
.subscribe(this.passwordOptions$);
// wire up the generator
this.algorithm$
this.generatorService
.generate$({ on$: this.generate$, account$: this.account$ })
.pipe(
filter((algorithm) => !!algorithm),
switchMap((algorithm) => this.typeToGenerator$(algorithm.id)),
catchError((error: unknown, generator) => {
if (typeof error === "string") {
this.toastService.showToast({
@@ -189,7 +206,7 @@ export class PasswordGeneratorComponent implements OnInit, OnChanges, OnDestroy
takeUntil(this.destroyed),
)
.subscribe(([generated, account, algorithm]) => {
this.log.debug({ source: generated.source }, "credential generated");
this.log.debug({ source: generated.source ?? null }, "credential generated");
this.generatorHistoryService
.track(account.id, generated.credential, generated.category, generated.generationDate)
@@ -201,7 +218,7 @@ export class PasswordGeneratorComponent implements OnInit, OnChanges, OnDestroy
// template bindings refresh immediately
this.zone.run(() => {
if (generated.source === this.USER_REQUEST) {
this.announce(algorithm.onGeneratedMessage);
this.announce(translate(algorithm.i18nKeys.credentialGenerated, this.i18nService));
}
this.onGenerated.next(generated);
@@ -219,10 +236,7 @@ export class PasswordGeneratorComponent implements OnInit, OnChanges, OnDestroy
)
.subscribe(([algorithm, preference]) => {
if (isPasswordAlgorithm(algorithm)) {
this.log.info(
{ algorithm, category: CredentialCategories.password },
"algorithm preferences updated",
);
this.log.info({ algorithm, type: Type.password }, "algorithm preferences updated");
preference.password.algorithm = algorithm;
preference.password.updated = new Date();
} else {
@@ -236,11 +250,17 @@ export class PasswordGeneratorComponent implements OnInit, OnChanges, OnDestroy
preferences
.pipe(
map(({ password }) => this.generatorService.algorithm(password.algorithm)),
distinctUntilChanged((prev, next) => isSameAlgorithm(prev?.id, next?.id)),
distinctUntilChanged((prev, next) => {
if (prev === null || next === null) {
return false;
} else {
return isSameAlgorithm(prev.id, next.id);
}
}),
takeUntil(this.destroyed),
)
.subscribe((algorithm) => {
this.log.debug(algorithm, "algorithm selected");
this.log.debug({ algorithm: algorithm.id }, "algorithm selected");
// update navigation
this.onCredentialTypeChanged(algorithm.id);
@@ -248,22 +268,22 @@ export class PasswordGeneratorComponent implements OnInit, OnChanges, OnDestroy
// update subjects within the angular zone so that the
// template bindings refresh immediately
this.zone.run(() => {
this.algorithm$.next(algorithm);
this.onAlgorithm.next(algorithm);
this.maybeAlgorithm$.next(algorithm);
this.onAlgorithm.next(toAlgorithmInfo(algorithm, this.i18nService));
});
});
// generate on load unless the generator prohibits it
this.algorithm$.pipe(takeUntil(this.destroyed)).subscribe((a) => {
this.maybeAlgorithm$.pipe(takeUntil(this.destroyed)).subscribe((a) => {
this.zone.run(() => {
if (!a || a.onlyOnRequest) {
this.log.debug("autogeneration disabled; clearing generated credential");
this.value$.next("-");
} else {
if (a?.capabilities?.autogenerate) {
this.log.debug("autogeneration enabled");
this.generate("autogenerate").catch((e: unknown) => {
this.log.error(e as object, "a failure occurred during autogeneration");
});
} else {
this.log.debug("autogeneration disabled; clearing generated credential");
this.value$.next("-");
}
});
});
@@ -275,59 +295,45 @@ export class PasswordGeneratorComponent implements OnInit, OnChanges, OnDestroy
this.ariaLive.announce(message).catch((e) => this.logService.error(e));
}
private typeToGenerator$(algorithm: CredentialAlgorithm) {
const dependencies = {
on$: this.generate$,
account$: this.account$,
};
this.log.debug({ algorithm }, "constructing generation stream");
switch (algorithm) {
case "password":
return this.generatorService.generate$(Generators.password, dependencies);
case "passphrase":
return this.generatorService.generate$(Generators.passphrase, dependencies);
default:
this.log.panic({ algorithm }, `Invalid generator type: "${algorithm}"`);
}
}
/** Lists the credential types supported by the component. */
protected passwordOptions$ = new BehaviorSubject<Option<CredentialAlgorithm>[]>([]);
/** Determines when the password/passphrase selector is visible. */
protected showCredentialTypes$ = this.passwordOptions$.pipe(map((options) => options.length > 1));
/** tracks the currently selected credential type */
protected algorithm$ = new ReplaySubject<AlgorithmInfo>(1);
protected maybeAlgorithm$ = new ReplaySubject<AlgorithmMetadata>(1);
/** tracks the last valid algorithm selection */
protected algorithm$ = this.maybeAlgorithm$.pipe(
filter((algorithm): algorithm is AlgorithmMetadata => !!algorithm),
);
/**
* Emits the copy button aria-label respective of the selected credential type
*/
protected credentialTypeCopyLabel$ = this.algorithm$.pipe(
filter((algorithm) => !!algorithm),
map(({ copy }) => copy),
map(({ i18nKeys: { copyCredential } }) => translate(copyCredential, this.i18nService)),
);
/**
* Emits the generate button aria-label respective of the selected credential type
*/
protected credentialTypeGenerateLabel$ = this.algorithm$.pipe(
filter((algorithm) => !!algorithm),
map(({ generate }) => generate),
map(({ i18nKeys: { generateCredential } }) => translate(generateCredential, this.i18nService)),
);
/**
* Emits the copy credential toast respective of the selected credential type
*/
protected credentialTypeLabel$ = this.algorithm$.pipe(
filter((algorithm) => !!algorithm),
map(({ credentialType }) => credentialType),
map(({ i18nKeys: { credentialType } }) => translate(credentialType, this.i18nService)),
);
private toOptions(algorithms: AlgorithmInfo[]) {
private toOptions(algorithms: AlgorithmMetadata[]) {
const options: Option<CredentialAlgorithm>[] = algorithms.map((algorithm) => ({
value: algorithm.id,
label: algorithm.name,
label: translate(algorithm.i18nKeys.name, this.i18nService),
}));
return options;