1
0
mirror of https://github.com/bitwarden/browser synced 2025-12-15 07:43:35 +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 {
Component,
EventEmitter,
@@ -17,7 +15,7 @@ import { Account } from "@bitwarden/common/auth/abstractions/account.service";
import {
CatchallGenerationOptions,
CredentialGeneratorService,
Generators,
BuiltIn,
} from "@bitwarden/generator-core";
/** Options group for catchall emails */
@@ -28,7 +26,6 @@ import {
})
export class CatchallSettingsComponent implements OnInit, OnDestroy, OnChanges {
/** Instantiates the component
* @param accountService queries user availability
* @param generatorService settings and policy logic
* @param formBuilder reactive form controls
*/
@@ -37,24 +34,26 @@ export class CatchallSettingsComponent implements OnInit, OnDestroy, OnChanges {
private generatorService: CredentialGeneratorService,
) {}
/** Binds the component to a specific user's settings.
/** Binds the component to a specific user's settings.\
* @remarks this is initialized to null but since it's a required input it'll
* never have that value in practice.
*/
@Input({ required: true })
account: Account;
account!: Account;
private account$ = new ReplaySubject<Account>(1);
/** Emits settings updates and completes if the settings become unavailable.
* @remarks this does not emit the initial settings. If you would like
* to receive live settings updates including the initial update,
* use `CredentialGeneratorService.settings$(...)` instead.
* use `CredentialGeneratorService.settings(...)` instead.
*/
@Output()
readonly onUpdated = new EventEmitter<CatchallGenerationOptions>();
/** The template's control bindings */
protected settings = this.formBuilder.group({
catchallDomain: [Generators.catchall.settings.initial.catchallDomain],
catchallDomain: [""],
});
async ngOnChanges(changes: SimpleChanges) {
@@ -64,7 +63,7 @@ export class CatchallSettingsComponent implements OnInit, OnDestroy, OnChanges {
}
async ngOnInit() {
const settings = await this.generatorService.settings(Generators.catchall, {
const settings = await this.generatorService.settings(BuiltIn.catchall, {
account$: this.account$,
});
@@ -79,7 +78,7 @@ export class CatchallSettingsComponent implements OnInit, OnDestroy, OnChanges {
this.saveSettings
.pipe(
withLatestFrom(this.settings.valueChanges),
map(([, settings]) => settings),
map(([, settings]) => settings as CatchallGenerationOptions),
takeUntil(this.destroyed$),
)
.subscribe(settings);

View File

@@ -6,6 +6,7 @@ import { BehaviorSubject, ReplaySubject, Subject, map, switchMap, takeUntil, tap
import { JslibModule } from "@bitwarden/angular/jslib.module";
import { Account } 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,
@@ -19,10 +20,11 @@ import {
ItemModule,
NoItemsModule,
} from "@bitwarden/components";
import { CredentialGeneratorService } from "@bitwarden/generator-core";
import { AlgorithmsByType, CredentialGeneratorService } from "@bitwarden/generator-core";
import { GeneratedCredential, GeneratorHistoryService } from "@bitwarden/generator-history";
import { GeneratorModule } from "./generator.module";
import { translate } from "./util";
@Component({
standalone: true,
@@ -45,6 +47,7 @@ export class CredentialGeneratorHistoryComponent implements OnChanges, OnInit, O
constructor(
private generatorService: CredentialGeneratorService,
private history: GeneratorHistoryService,
private i18nService: I18nService,
private logService: LogService,
) {}
@@ -94,13 +97,19 @@ export class CredentialGeneratorHistoryComponent implements OnChanges, OnInit, O
}
protected getCopyText(credential: GeneratedCredential) {
const info = this.generatorService.algorithm(credential.category);
return info.copy;
// there isn't a way way to look up category metadata so
// bodge it by looking up algorithm metadata
const [id] = AlgorithmsByType[credential.category];
const info = this.generatorService.algorithm(id);
return translate(info.i18nKeys.copyCredential, this.i18nService);
}
protected getGeneratedValueText(credential: GeneratedCredential) {
const info = this.generatorService.algorithm(credential.category);
return info.credentialType;
// there isn't a way way to look up category metadata so
// bodge it by looking up algorithm metadata
const [id] = AlgorithmsByType[credential.category];
const info = this.generatorService.algorithm(id);
return translate(info.i18nKeys.credentialType, this.i18nService);
}
ngOnDestroy() {

View File

@@ -42,13 +42,13 @@
</bit-card>
<tools-password-settings
class="tw-mt-6"
*ngIf="(showAlgorithm$ | async)?.id === 'password'"
*ngIf="(showAlgorithm$ | async)?.id === Algorithm.password"
[account]="account$ | async"
(onUpdated)="generate('password settings')"
/>
<tools-passphrase-settings
class="tw-mt-6"
*ngIf="(showAlgorithm$ | async)?.id === 'passphrase'"
*ngIf="(showAlgorithm$ | async)?.id === Algorithm.passphrase"
[account]="account$ | async"
(onUpdated)="generate('passphrase settings')"
/>
@@ -84,7 +84,7 @@
</bit-form-field>
</form>
<tools-catchall-settings
*ngIf="(showAlgorithm$ | async)?.id === 'catchall'"
*ngIf="(showAlgorithm$ | async)?.id === Algorithm.catchall"
[account]="account$ | async"
(onUpdated)="generate('catchall settings')"
/>
@@ -94,12 +94,12 @@
[forwarder]="forwarderId$ | async"
/>
<tools-subaddress-settings
*ngIf="(showAlgorithm$ | async)?.id === 'subaddress'"
*ngIf="(showAlgorithm$ | async)?.id === Algorithm.plusAddress"
[account]="account$ | async"
(onUpdated)="generate('subaddress settings')"
/>
<tools-username-settings
*ngIf="(showAlgorithm$ | async)?.id === 'username'"
*ngIf="(showAlgorithm$ | async)?.id === Algorithm.username"
[account]="account$ | async"
(onUpdated)="generate('username settings')"
/>

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 {
Component,
@@ -24,15 +22,15 @@ import {
map,
ReplaySubject,
Subject,
switchMap,
takeUntil,
tap,
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 { IntegrationId } from "@bitwarden/common/tools/integration";
import { VendorId } from "@bitwarden/common/tools/extension";
import {
SemanticLogger,
disabledSemanticLoggerProvider,
@@ -41,23 +39,25 @@ import {
import { UserId } from "@bitwarden/common/types/guid";
import { ToastService, Option } from "@bitwarden/components";
import {
AlgorithmInfo,
CredentialAlgorithm,
CredentialCategory,
CredentialType,
CredentialGeneratorService,
GenerateRequest,
GeneratedCredential,
Generators,
getForwarderConfiguration,
isEmailAlgorithm,
isForwarderIntegration,
isPasswordAlgorithm,
isForwarderExtensionId,
isSameAlgorithm,
isEmailAlgorithm,
isUsernameAlgorithm,
toCredentialGeneratorConfiguration,
isPasswordAlgorithm,
CredentialAlgorithm,
AlgorithmMetadata,
Algorithm,
AlgorithmsByType,
Type,
} from "@bitwarden/generator-core";
import { GeneratorHistoryService } from "@bitwarden/generator-history";
import { translate } from "./util";
// constants used to identify navigation selections that are not
// generator algorithms
const IDENTIFIER = "identifier";
@@ -84,11 +84,14 @@ export class CredentialGeneratorComponent implements OnInit, OnChanges, OnDestro
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;
/** Send structured debug logs from the credential generator component
* to the debugger console.
@@ -127,7 +130,7 @@ export class CredentialGeneratorComponent implements OnInit, OnChanges, OnDestro
@Output()
readonly onGenerated = new EventEmitter<GeneratedCredential>();
protected root$ = new BehaviorSubject<{ nav: string }>({
protected root$ = new BehaviorSubject<{ nav: string | null }>({
nav: null,
});
@@ -141,11 +144,11 @@ export class CredentialGeneratorComponent implements OnInit, OnChanges, OnDestro
}
protected username = this.formBuilder.group({
nav: [null as string],
nav: [null as string | null],
});
protected forwarder = this.formBuilder.group({
nav: [null as string],
nav: [null as string | null],
});
async ngOnInit() {
@@ -154,33 +157,52 @@ export class CredentialGeneratorComponent implements OnInit, OnChanges, OnDestro
});
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
.algorithms$(["email", "username"], { account$: this.account$ })
combineLatest([
this.generatorService.algorithms$("email", { account$: this.account$ }),
this.generatorService.algorithms$("username", { account$: this.account$ }),
])
.pipe(
map((algorithms) => algorithms.flat()),
map((algorithms) => {
const usernames = algorithms.filter((a) => !isForwarderIntegration(a.id));
// construct options for username and email algorithms; replace forwarder
// entry with a virtual entry for drill-down
const usernames = algorithms.filter((a) => !isForwarderExtensionId(a.id));
usernames.sort((a, b) => a.weight - b.weight);
const usernameOptions = this.toOptions(usernames);
usernameOptions.push({ value: FORWARDER, label: this.i18nService.t("forwardedEmail") });
usernameOptions.splice(-1, 0, {
value: FORWARDER,
label: this.i18nService.t("forwardedEmail"),
});
const forwarders = algorithms.filter((a) => isForwarderIntegration(a.id));
// construct options for forwarder algorithms; they get their own selection box
const forwarders = algorithms.filter((a) => isForwarderExtensionId(a.id));
forwarders.sort((a, b) => a.weight - b.weight);
const forwarderOptions = this.toOptions(forwarders);
forwarderOptions.unshift({ value: NONE_SELECTED, label: this.i18nService.t("select") });
return [usernameOptions, forwarderOptions] as const;
}),
tap((algorithms) =>
this.log.debug({ algorithms: algorithms as object }, "algorithms loaded"),
),
takeUntil(this.destroyed),
)
.subscribe(([usernames, forwarders]) => {
this.usernameOptions$.next(usernames);
this.forwarderOptions$.next(forwarders);
// update subjects within the angular zone so that the
// template bindings refresh immediately
this.zone.run(() => {
this.usernameOptions$.next(usernames);
this.forwarderOptions$.next(forwarders);
});
});
this.generatorService
@@ -195,9 +217,15 @@ export class CredentialGeneratorComponent implements OnInit, OnChanges, OnDestro
)
.subscribe(this.rootOptions$);
this.algorithm$
this.maybeAlgorithm$
.pipe(
map((a) => a?.description),
map((a) => {
if (a?.i18nKeys?.description) {
return translate(a.i18nKeys.description, this.i18nService);
} else {
return "";
}
}),
takeUntil(this.destroyed),
)
.subscribe((hint) => {
@@ -208,9 +236,9 @@ export class CredentialGeneratorComponent implements OnInit, OnChanges, OnDestro
});
});
this.algorithm$
this.maybeAlgorithm$
.pipe(
map((a) => a?.category),
map((a) => a?.type),
distinctUntilChanged(),
takeUntil(this.destroyed),
)
@@ -223,10 +251,12 @@ export class CredentialGeneratorComponent implements OnInit, OnChanges, OnDestro
});
// 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({
@@ -241,11 +271,14 @@ export class CredentialGeneratorComponent implements OnInit, OnChanges, OnDestro
// continue with origin stream
return generator;
}),
withLatestFrom(this.account$, this.algorithm$),
withLatestFrom(this.account$, this.maybeAlgorithm$),
takeUntil(this.destroyed),
)
.subscribe(([generated, account, algorithm]) => {
this.log.debug({ source: generated.source }, "credential generated");
this.log.debug(
{ source: generated.source ?? null, algorithm: algorithm?.id ?? null },
"credential generated",
);
this.generatorHistoryService
.track(account.id, generated.credential, generated.category, generated.generationDate)
@@ -256,8 +289,8 @@ export class CredentialGeneratorComponent implements OnInit, OnChanges, OnDestro
// update subjects within the angular zone so that the
// template bindings refresh immediately
this.zone.run(() => {
if (generated.source === this.USER_REQUEST) {
this.announce(algorithm.onGeneratedMessage);
if (algorithm && generated.source === this.USER_REQUEST) {
this.announce(translate(algorithm.i18nKeys.credentialGenerated, this.i18nService));
}
this.generatedCredential$.next(generated);
@@ -274,36 +307,46 @@ export class CredentialGeneratorComponent implements OnInit, OnChanges, OnDestro
this.root$
.pipe(
map(
(root): CascadeValue =>
root.nav === IDENTIFIER
? { nav: root.nav }
: { nav: root.nav, algorithm: JSON.parse(root.nav) },
),
map((root): CascadeValue => {
if (root.nav === IDENTIFIER) {
return { nav: root.nav };
} else if (root.nav) {
return { nav: root.nav, algorithm: JSON.parse(root.nav) };
} else {
return { nav: IDENTIFIER };
}
}),
takeUntil(this.destroyed),
)
.subscribe(activeRoot$);
this.username.valueChanges
.pipe(
map(
(username): CascadeValue =>
username.nav === FORWARDER
? { nav: username.nav }
: { nav: username.nav, algorithm: JSON.parse(username.nav) },
),
map((username): CascadeValue => {
if (username.nav === FORWARDER) {
return { nav: username.nav };
} else if (username.nav) {
return { nav: username.nav, algorithm: JSON.parse(username.nav) };
} else {
const [algorithm] = AlgorithmsByType[Type.username];
return { nav: JSON.stringify(algorithm), algorithm };
}
}),
takeUntil(this.destroyed),
)
.subscribe(activeIdentifier$);
this.forwarder.valueChanges
.pipe(
map(
(forwarder): CascadeValue =>
forwarder.nav === NONE_SELECTED
? { nav: forwarder.nav }
: { nav: forwarder.nav, algorithm: JSON.parse(forwarder.nav) },
),
map((forwarder): CascadeValue => {
if (forwarder.nav === NONE_SELECTED) {
return { nav: forwarder.nav };
} else if (forwarder.nav) {
return { nav: forwarder.nav, algorithm: JSON.parse(forwarder.nav) };
} else {
return { nav: NONE_SELECTED };
}
}),
takeUntil(this.destroyed),
)
.subscribe(activeForwarder$);
@@ -314,7 +357,7 @@ export class CredentialGeneratorComponent implements OnInit, OnChanges, OnDestro
map(([root, username, forwarder]) => {
const showForwarder = !root.algorithm && !username.algorithm;
const forwarderId =
showForwarder && isForwarderIntegration(forwarder.algorithm)
showForwarder && forwarder.algorithm && isForwarderExtensionId(forwarder.algorithm)
? forwarder.algorithm.forwarder
: null;
return [showForwarder, forwarderId] as const;
@@ -344,47 +387,51 @@ export class CredentialGeneratorComponent implements OnInit, OnChanges, OnDestro
return null;
}
}),
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 ?? null }, "algorithm selected");
// update subjects within the angular zone so that the
// template bindings refresh immediately
this.zone.run(() => {
this.algorithm$.next(algorithm);
this.maybeAlgorithm$.next(algorithm);
});
});
// assume the last-selected generator algorithm is the user's preferred one
const preferences = await this.generatorService.preferences({ account$: this.account$ });
this.algorithm$
.pipe(
filter((algorithm) => !!algorithm),
withLatestFrom(preferences),
takeUntil(this.destroyed),
)
.pipe(withLatestFrom(preferences), takeUntil(this.destroyed))
.subscribe(([algorithm, preference]) => {
function setPreference(category: CredentialCategory, log: SemanticLogger) {
const p = preference[category];
function setPreference(type: CredentialType) {
const p = preference[type];
p.algorithm = algorithm.id;
p.updated = new Date();
log.info({ algorithm, category }, "algorithm preferences updated");
}
// `is*Algorithm` decides `algorithm`'s type, which flows into `setPreference`
if (isEmailAlgorithm(algorithm.id)) {
setPreference("email", this.log);
setPreference("email");
} else if (isUsernameAlgorithm(algorithm.id)) {
setPreference("username", this.log);
setPreference("username");
} else if (isPasswordAlgorithm(algorithm.id)) {
setPreference("password", this.log);
setPreference("password");
} else {
return;
}
this.log.info(
{ algorithm: algorithm.id, type: algorithm.type },
"algorithm preferences updated",
);
preferences.next(preference);
});
@@ -392,10 +439,12 @@ export class CredentialGeneratorComponent implements OnInit, OnChanges, OnDestro
preferences
.pipe(
map(({ email, username, password }) => {
const forwarderPref = isForwarderIntegration(email.algorithm) ? email : null;
const usernamePref = email.updated > username.updated ? email : username;
const forwarderPref = isForwarderExtensionId(usernamePref.algorithm)
? usernamePref
: null;
// inject drilldown flags
// inject drill-down flags
const forwarderNav = !forwarderPref
? NONE_SELECTED
: JSON.stringify(forwarderPref.algorithm);
@@ -411,14 +460,14 @@ export class CredentialGeneratorComponent implements OnInit, OnChanges, OnDestro
selection: { nav: rootNav },
active: {
nav: rootNav,
algorithm: rootNav === IDENTIFIER ? null : password.algorithm,
algorithm: rootNav === IDENTIFIER ? undefined : password.algorithm,
} as CascadeValue,
},
username: {
selection: { nav: userNav },
active: {
nav: userNav,
algorithm: forwarderPref ? null : usernamePref.algorithm,
algorithm: forwarderPref ? undefined : usernamePref.algorithm,
},
},
forwarder: {
@@ -435,6 +484,15 @@ export class CredentialGeneratorComponent implements OnInit, OnChanges, OnDestro
takeUntil(this.destroyed),
)
.subscribe(({ root, username, forwarder }) => {
this.log.debug(
{
root: root.selection,
username: username.selection,
forwarder: forwarder.selection,
},
"navigation updated",
);
// update navigation; break subscription loop
this.onRootChanged(root.selection);
this.username.setValue(username.selection, { emitEvent: false });
@@ -448,16 +506,16 @@ export class CredentialGeneratorComponent implements OnInit, OnChanges, OnDestro
// automatically regenerate when the algorithm switches if the algorithm
// allows it; otherwise set a placeholder
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.generatedCredential$.next(null);
} 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.generatedCredential$.next(undefined);
}
});
});
@@ -469,41 +527,6 @@ export class CredentialGeneratorComponent implements OnInit, OnChanges, OnDestro
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 "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);
}
if (isForwarderIntegration(algorithm)) {
const forwarder = getForwarderConfiguration(algorithm.forwarder);
const configuration = toCredentialGeneratorConfiguration(forwarder);
const generator = this.generatorService.generate$(configuration, dependencies);
return generator;
}
this.log.panic({ algorithm }, `Invalid generator type: "${algorithm}"`);
}
/** Lists the top-level credential types supported by the component.
* @remarks This is string-typed because angular doesn't support
* structural equality for objects, which prevents `CredentialAlgorithm`
@@ -519,15 +542,20 @@ export class CredentialGeneratorComponent implements OnInit, OnChanges, OnDestro
protected forwarderOptions$ = new BehaviorSubject<Option<string>[]>([]);
/** Tracks the currently selected forwarder. */
protected forwarderId$ = new BehaviorSubject<IntegrationId>(null);
protected forwarderId$ = new BehaviorSubject<VendorId | null>(null);
/** Tracks forwarder control visibility */
protected showForwarder$ = new BehaviorSubject<boolean>(false);
/** tracks the currently selected credential type */
protected algorithm$ = new ReplaySubject<AlgorithmInfo>(1);
protected maybeAlgorithm$ = new ReplaySubject<AlgorithmMetadata | null>(1);
protected showAlgorithm$ = this.algorithm$.pipe(
/** tracks the last valid algorithm selection */
protected algorithm$ = this.maybeAlgorithm$.pipe(
filter((algorithm): algorithm is AlgorithmMetadata => !!algorithm),
);
protected showAlgorithm$ = this.maybeAlgorithm$.pipe(
combineLatestWith(this.showForwarder$),
map(([algorithm, showForwarder]) => (showForwarder ? null : algorithm)),
);
@@ -536,33 +564,32 @@ export class CredentialGeneratorComponent implements OnInit, OnChanges, OnDestro
* 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)),
);
/** Emits hint key for the currently selected credential type */
protected credentialTypeHint$ = new ReplaySubject<string>(1);
protected credentialTypeHint$ = new ReplaySubject<string | undefined>(1);
/** tracks the currently selected credential category */
protected category$ = new ReplaySubject<string>(1);
protected category$ = new ReplaySubject<string | undefined>(1);
private readonly generatedCredential$ = new BehaviorSubject<GeneratedCredential>(null);
private readonly generatedCredential$ = new BehaviorSubject<GeneratedCredential | undefined>(
undefined,
);
/** Emits the last generated value. */
protected readonly value$ = this.generatedCredential$.pipe(
@@ -580,15 +607,20 @@ export class CredentialGeneratorComponent implements OnInit, OnChanges, OnDestro
* origin in the debugger.
*/
protected async generate(source: string) {
const request = { source, website: this.website };
const algorithm = await firstValueFrom(this.algorithm$);
const request: GenerateRequest = { source, algorithm: algorithm.id };
if (this.website) {
request.website = this.website;
}
this.log.debug(request, "generation requested");
this.generate$.next(request);
}
private toOptions(algorithms: AlgorithmInfo[]) {
private toOptions(algorithms: AlgorithmMetadata[]) {
const options: Option<string>[] = algorithms.map((algorithm) => ({
value: JSON.stringify(algorithm.id),
label: algorithm.name,
label: translate(algorithm.i18nKeys.name, this.i18nService),
}));
return options;

View File

@@ -1,5 +1,3 @@
// FIXME: Update this file to be type safe and remove this and next line
// @ts-strict-ignore
import {
Component,
EventEmitter,
@@ -14,13 +12,11 @@ import { FormBuilder } from "@angular/forms";
import { map, ReplaySubject, skip, Subject, switchAll, takeUntil, withLatestFrom } from "rxjs";
import { Account } from "@bitwarden/common/auth/abstractions/account.service";
import { IntegrationId } from "@bitwarden/common/tools/integration";
import { VendorId } from "@bitwarden/common/tools/extension";
import {
CredentialGeneratorConfiguration,
CredentialGeneratorService,
getForwarderConfiguration,
NoPolicy,
toCredentialGeneratorConfiguration,
ForwarderOptions,
GeneratorMetadata,
} from "@bitwarden/generator-core";
const Controls = Object.freeze({
@@ -37,7 +33,6 @@ const Controls = Object.freeze({
})
export class ForwarderSettingsComponent implements OnInit, OnChanges, OnDestroy {
/** Instantiates the component
* @param accountService queries user availability
* @param generatorService settings and policy logic
* @param formBuilder reactive form controls
*/
@@ -47,14 +42,16 @@ export class ForwarderSettingsComponent implements OnInit, OnChanges, OnDestroy
) {}
/** Binds the component to a specific user's settings.
* @remarks this is initialized to null but since it's a required input it'll
* never have that value in practice.
*/
@Input({ required: true })
account: Account;
account: Account = null!;
protected account$ = new ReplaySubject<Account>(1);
@Input({ required: true })
forwarder: IntegrationId;
forwarder: VendorId = null!;
/** Emits settings updates and completes if the settings become unavailable.
* @remarks this does not emit the initial settings. If you would like
@@ -71,24 +68,19 @@ export class ForwarderSettingsComponent implements OnInit, OnChanges, OnDestroy
[Controls.baseUrl]: [""],
});
private forwarderId$ = new ReplaySubject<IntegrationId>(1);
private vendor = new ReplaySubject<VendorId>(1);
async ngOnInit() {
const forwarder$ = new ReplaySubject<CredentialGeneratorConfiguration<any, NoPolicy>>(1);
this.forwarderId$
const forwarder$ = new ReplaySubject<GeneratorMetadata<ForwarderOptions>>(1);
this.vendor
.pipe(
map((id) => getForwarderConfiguration(id)),
// type erasure necessary because the configuration properties are
// determined dynamically at runtime
// FIXME: this can be eliminated by unifying the forwarder settings types;
// see `ForwarderConfiguration<...>` for details.
map((forwarder) => toCredentialGeneratorConfiguration<any>(forwarder)),
map((vendor) => this.generatorService.forwarder(vendor)),
takeUntil(this.destroyed$),
)
.subscribe((forwarder) => {
this.displayDomain = forwarder.request.includes("domain");
this.displayToken = forwarder.request.includes("token");
this.displayBaseUrl = forwarder.request.includes("baseUrl");
this.displayDomain = forwarder.capabilities.fields.includes("domain");
this.displayToken = forwarder.capabilities.fields.includes("token");
this.displayBaseUrl = forwarder.capabilities.fields.includes("baseUrl");
forwarder$.next(forwarder);
});
@@ -107,10 +99,10 @@ export class ForwarderSettingsComponent implements OnInit, OnChanges, OnDestroy
forwarder$.pipe(takeUntil(this.destroyed$)).subscribe((forwarder) => {
for (const name in Controls) {
const control = this.settings.get(name);
if (forwarder.request.includes(name as any)) {
control.enable({ emitEvent: false });
if (forwarder.capabilities.fields.includes(name)) {
control?.enable({ emitEvent: false });
} else {
control.disable({ emitEvent: false });
control?.disable({ emitEvent: false });
}
}
});
@@ -128,7 +120,7 @@ export class ForwarderSettingsComponent implements OnInit, OnChanges, OnDestroy
this.saveSettings
.pipe(withLatestFrom(this.settings.valueChanges, settings$), takeUntil(this.destroyed$))
.subscribe(([, value, settings]) => {
settings.next(value);
settings.next(value as ForwarderOptions);
});
}
@@ -140,7 +132,7 @@ export class ForwarderSettingsComponent implements OnInit, OnChanges, OnDestroy
async ngOnChanges(changes: SimpleChanges) {
this.refresh$.complete();
if ("forwarder" in changes) {
this.forwarderId$.next(this.forwarder);
this.vendor.next(this.forwarder);
}
if ("account" in changes) {
@@ -148,9 +140,9 @@ export class ForwarderSettingsComponent implements OnInit, OnChanges, OnDestroy
}
}
protected displayDomain: boolean;
protected displayToken: boolean;
protected displayBaseUrl: boolean;
protected displayDomain: boolean = false;
protected displayToken: boolean = false;
protected displayBaseUrl: boolean = false;
private readonly refresh$ = new Subject<void>();

View File

@@ -7,19 +7,40 @@ import { ApiService } from "@bitwarden/common/abstractions/api.service";
import { PolicyService } from "@bitwarden/common/admin-console/abstractions/policy/policy.service.abstraction";
import { EncryptService } from "@bitwarden/common/key-management/crypto/abstractions/encrypt.service";
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service";
import { StateProvider } from "@bitwarden/common/platform/state";
import { KeyServiceLegacyEncryptorProvider } from "@bitwarden/common/tools/cryptography/key-service-legacy-encryptor-provider";
import { LegacyEncryptorProvider } from "@bitwarden/common/tools/cryptography/legacy-encryptor-provider";
import { disabledSemanticLoggerProvider } from "@bitwarden/common/tools/log";
import { Site } from "@bitwarden/common/tools/extension";
import { ExtensionRegistry } from "@bitwarden/common/tools/extension/extension-registry.abstraction";
import { ExtensionService } from "@bitwarden/common/tools/extension/extension.service";
import { DefaultFields, DefaultSites, Extension } from "@bitwarden/common/tools/extension/metadata";
import { RuntimeExtensionRegistry } from "@bitwarden/common/tools/extension/runtime-extension-registry";
import { VendorExtensions, Vendors } from "@bitwarden/common/tools/extension/vendor";
import { RestClient } from "@bitwarden/common/tools/integration/rpc";
import {
LogProvider,
disabledSemanticLoggerProvider,
enableLogForTypes,
} from "@bitwarden/common/tools/log";
import { SystemServiceProvider } from "@bitwarden/common/tools/providers";
import { UserStateSubjectDependencyProvider } from "@bitwarden/common/tools/state/user-state-subject-dependency-provider";
import {
BuiltIn,
createRandomizer,
CredentialGeneratorService,
Randomizer,
providers,
DefaultCredentialGeneratorService,
} from "@bitwarden/generator-core";
import { KeyService } from "@bitwarden/key-management";
export const RANDOMIZER = new SafeInjectionToken<Randomizer>("Randomizer");
const GENERATOR_SERVICE_PROVIDER = new SafeInjectionToken<providers.CredentialGeneratorProviders>(
"CredentialGeneratorProviders",
);
const SYSTEM_SERVICE_PROVIDER = new SafeInjectionToken<SystemServiceProvider>("SystemServices");
/** Shared module containing generator component dependencies */
@NgModule({
@@ -35,6 +56,116 @@ export const RANDOMIZER = new SafeInjectionToken<Randomizer>("Randomizer");
useClass: KeyServiceLegacyEncryptorProvider,
deps: [EncryptService, KeyService],
}),
safeProvider({
provide: ExtensionRegistry,
useFactory: () => {
const registry = new RuntimeExtensionRegistry(DefaultSites, DefaultFields);
registry.registerSite(Extension[Site.forwarder]);
for (const vendor of Vendors) {
registry.registerVendor(vendor);
}
for (const extension of VendorExtensions) {
registry.registerExtension(extension);
}
registry.setPermission({ all: true }, "default");
return registry;
},
deps: [],
}),
safeProvider({
provide: SYSTEM_SERVICE_PROVIDER,
useFactory: (
encryptor: LegacyEncryptorProvider,
state: StateProvider,
policy: PolicyService,
registry: ExtensionRegistry,
logger: LogService,
environment: PlatformUtilsService,
) => {
let log: LogProvider;
if (environment.isDev()) {
log = enableLogForTypes(logger, []);
} else {
log = disabledSemanticLoggerProvider;
}
const extension = new ExtensionService(registry, {
encryptor,
state,
log,
now: Date.now,
});
return {
policy,
extension,
log,
};
},
deps: [
LegacyEncryptorProvider,
StateProvider,
PolicyService,
ExtensionRegistry,
LogService,
PlatformUtilsService,
],
}),
safeProvider({
provide: GENERATOR_SERVICE_PROVIDER,
useFactory: (
system: SystemServiceProvider,
random: Randomizer,
encryptor: LegacyEncryptorProvider,
state: StateProvider,
i18n: I18nService,
api: ApiService,
) => {
const userStateDeps = {
encryptor,
state,
log: system.log,
now: Date.now,
} satisfies UserStateSubjectDependencyProvider;
const metadata = new providers.GeneratorMetadataProvider(
userStateDeps,
system,
Object.values(BuiltIn),
);
const profile = new providers.GeneratorProfileProvider(userStateDeps, system.policy);
const generator: providers.GeneratorDependencyProvider = {
randomizer: random,
client: new RestClient(api, i18n),
i18nService: i18n,
};
const userState: UserStateSubjectDependencyProvider = {
encryptor,
state,
log: system.log,
now: Date.now,
};
return {
userState,
generator,
profile,
metadata,
} satisfies providers.CredentialGeneratorProviders;
},
deps: [
SYSTEM_SERVICE_PROVIDER,
RANDOMIZER,
LegacyEncryptorProvider,
StateProvider,
I18nService,
ApiService,
],
}),
safeProvider({
provide: UserStateSubjectDependencyProvider,
useFactory: (encryptor: LegacyEncryptorProvider, state: StateProvider) =>
@@ -42,19 +173,14 @@ export const RANDOMIZER = new SafeInjectionToken<Randomizer>("Randomizer");
encryptor,
state,
log: disabledSemanticLoggerProvider,
now: Date.now,
}),
deps: [LegacyEncryptorProvider, StateProvider],
}),
safeProvider({
provide: CredentialGeneratorService,
useClass: CredentialGeneratorService,
deps: [
RANDOMIZER,
PolicyService,
ApiService,
I18nService,
UserStateSubjectDependencyProvider,
],
useClass: DefaultCredentialGeneratorService,
deps: [GENERATOR_SERVICE_PROVIDER, SYSTEM_SERVICE_PROVIDER],
}),
],
})

View File

@@ -1,5 +1,3 @@
// FIXME: Update this file to be type safe and remove this and next line
// @ts-strict-ignore
import { coerceBooleanProperty } from "@angular/cdk/coercion";
import {
OnInit,
@@ -12,14 +10,20 @@ import {
OnChanges,
} from "@angular/core";
import { FormBuilder } from "@angular/forms";
import { skip, takeUntil, Subject, map, withLatestFrom, ReplaySubject } from "rxjs";
import { skip, takeUntil, Subject, map, withLatestFrom, ReplaySubject, tap } from "rxjs";
import { Account } 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,
disabledSemanticLoggerProvider,
ifEnabledSemanticLoggerProvider,
} from "@bitwarden/common/tools/log";
import {
Generators,
CredentialGeneratorService,
PassphraseGenerationOptions,
BuiltIn,
} from "@bitwarden/generator-core";
const Controls = Object.freeze({
@@ -45,12 +49,26 @@ export class PassphraseSettingsComponent implements OnInit, OnChanges, OnDestroy
private formBuilder: FormBuilder,
private generatorService: CredentialGeneratorService,
private i18nService: I18nService,
private logService: LogService,
) {}
/** Send structured debug logs from the credential generator component
* to the debugger console.
*
* @warning this may reveal sensitive information in plaintext.
*/
@Input()
debug: boolean = false;
// this `log` initializer is overridden in `ngOnInit`
private log: SemanticLogger = disabledSemanticLoggerProvider({});
/** Binds the component to a specific user's settings.
* @remarks this is initialized to null but since it's a required input it'll
* never have that value in practice.
*/
@Input({ required: true })
account: Account;
account: Account = null!;
protected account$ = new ReplaySubject<Account>(1);
@@ -70,53 +88,66 @@ export class PassphraseSettingsComponent implements OnInit, OnChanges, OnDestroy
/** Emits settings updates and completes if the settings become unavailable.
* @remarks this does not emit the initial settings. If you would like
* to receive live settings updates including the initial update,
* use `CredentialGeneratorService.settings$(...)` instead.
* use {@link CredentialGeneratorService.settings} instead.
*/
@Output()
readonly onUpdated = new EventEmitter<PassphraseGenerationOptions>();
protected settings = this.formBuilder.group({
[Controls.numWords]: [Generators.passphrase.settings.initial.numWords],
[Controls.wordSeparator]: [Generators.passphrase.settings.initial.wordSeparator],
[Controls.capitalize]: [Generators.passphrase.settings.initial.capitalize],
[Controls.includeNumber]: [Generators.passphrase.settings.initial.includeNumber],
[Controls.numWords]: [0],
[Controls.wordSeparator]: [""],
[Controls.capitalize]: [false],
[Controls.includeNumber]: [false],
});
async ngOnInit() {
const settings = await this.generatorService.settings(Generators.passphrase, {
this.log = ifEnabledSemanticLoggerProvider(this.debug, this.logService, {
type: "PassphraseSettingsComponent",
});
const settings = await this.generatorService.settings(BuiltIn.passphrase, {
account$: this.account$,
});
// skips reactive event emissions to break a subscription cycle
settings.withConstraints$
.pipe(takeUntil(this.destroyed$))
.pipe(
tap((content) => this.log.debug(content, "passphrase settings loaded with constraints")),
takeUntil(this.destroyed$),
)
.subscribe(({ state, constraints }) => {
this.settings.patchValue(state, { emitEvent: false });
let boundariesHint = this.i18nService.t(
"spinboxBoundariesHint",
constraints.numWords.min?.toString(),
constraints.numWords.max?.toString(),
constraints.numWords?.min?.toString(),
constraints.numWords?.max?.toString(),
);
if (state.numWords <= (constraints.numWords.recommendation ?? 0)) {
if ((state.numWords ?? 0) <= (constraints.numWords?.recommendation ?? 0)) {
boundariesHint += this.i18nService.t(
"passphraseNumWordsRecommendationHint",
constraints.numWords.recommendation?.toString(),
constraints.numWords?.recommendation?.toString(),
);
}
this.numWordsBoundariesHint.next(boundariesHint);
});
// the first emission is the current value; subsequent emissions are updates
settings.pipe(skip(1), takeUntil(this.destroyed$)).subscribe(this.onUpdated);
settings
.pipe(
skip(1),
tap((settings) => this.log.debug(settings, "passphrase settings onUpdate event")),
takeUntil(this.destroyed$),
)
.subscribe(this.onUpdated);
// explain policy & disable policy-overridden fields
this.generatorService
.policy$(Generators.passphrase, { account$: this.account$ })
.policy$(BuiltIn.passphrase, { account$: this.account$ })
.pipe(takeUntil(this.destroyed$))
.subscribe(({ constraints }) => {
this.wordSeparatorMaxLength = constraints.wordSeparator.maxLength;
this.policyInEffect = constraints.policyInEffect;
this.wordSeparatorMaxLength = constraints.wordSeparator?.maxLength ?? 0;
this.policyInEffect = constraints.policyInEffect ?? false;
this.toggleEnabled(Controls.capitalize, !constraints.capitalize?.readonly);
this.toggleEnabled(Controls.includeNumber, !constraints.includeNumber?.readonly);
@@ -126,22 +157,25 @@ export class PassphraseSettingsComponent implements OnInit, OnChanges, OnDestroy
this.saveSettings
.pipe(
withLatestFrom(this.settings.valueChanges),
map(([, settings]) => settings),
tap(([source, form]) =>
this.log.debug({ source, form }, "save passphrase settings request"),
),
map(([, settings]) => settings as PassphraseGenerationOptions),
takeUntil(this.destroyed$),
)
.subscribe(settings);
}
/** attribute binding for wordSeparator[maxlength] */
protected wordSeparatorMaxLength: number;
protected wordSeparatorMaxLength: number = 0;
private saveSettings = new Subject<string>();
save(site: string = "component api call") {
this.saveSettings.next(site);
save(source: string = "component api call") {
this.saveSettings.next(source);
}
/** display binding for enterprise policy notice */
protected policyInEffect: boolean;
protected policyInEffect: boolean = false;
private numWordsBoundariesHint = new ReplaySubject<string>(1);
@@ -150,9 +184,9 @@ export class PassphraseSettingsComponent implements OnInit, OnChanges, OnDestroy
private toggleEnabled(setting: keyof typeof Controls, enabled: boolean) {
if (enabled) {
this.settings.get(setting).enable({ emitEvent: false });
this.settings.get(setting)?.enable({ emitEvent: false });
} else {
this.settings.get(setting).disable({ emitEvent: false });
this.settings.get(setting)?.disable({ emitEvent: false });
}
}

View File

@@ -3,6 +3,7 @@
class="tw-mb-4"
[selected]="credentialType$ | async"
(selectedChange)="onCredentialTypeChanged($event)"
*ngIf="showCredentialTypes$ | async"
attr.aria-label="{{ 'type' | i18n }}"
>
<bit-toggle *ngFor="let option of passwordOptions$ | async" [value]="option.value">
@@ -38,14 +39,14 @@
</bit-card>
<tools-password-settings
class="tw-mt-6"
*ngIf="(algorithm$ | async)?.id === 'password'"
*ngIf="(algorithm$ | async)?.id === Algorithm.password"
[account]="account$ | async"
[disableMargin]="disableMargin"
(onUpdated)="generate('password settings')"
/>
<tools-passphrase-settings
class="tw-mt-6"
*ngIf="(algorithm$ | async)?.id === 'passphrase'"
*ngIf="(algorithm$ | async)?.id === Algorithm.passphrase"
[account]="account$ | async"
(onUpdated)="generate('passphrase settings')"
[disableMargin]="disableMargin"

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;

View File

@@ -1,5 +1,3 @@
// FIXME: Update this file to be type safe and remove this and next line
// @ts-strict-ignore
import { coerceBooleanProperty } from "@angular/cdk/coercion";
import {
OnInit,
@@ -17,11 +15,13 @@ import { takeUntil, Subject, map, filter, tap, skip, ReplaySubject, withLatestFr
import { Account } from "@bitwarden/common/auth/abstractions/account.service";
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
import {
Generators,
CredentialGeneratorService,
PasswordGenerationOptions,
BuiltIn,
} from "@bitwarden/generator-core";
import { hasRangeOfValues } from "./util";
const Controls = Object.freeze({
length: "length",
uppercase: "uppercase",
@@ -52,9 +52,11 @@ export class PasswordSettingsComponent implements OnInit, OnChanges, OnDestroy {
) {}
/** Binds the component to a specific user's settings.
* @remarks this is initialized to null but since it's a required input it'll
* never have that value in practice.
*/
@Input({ required: true })
account: Account;
account: Account = null!;
protected account$ = new ReplaySubject<Account>(1);
@@ -78,40 +80,40 @@ export class PasswordSettingsComponent implements OnInit, OnChanges, OnDestroy {
/** Emits settings updates and completes if the settings become unavailable.
* @remarks this does not emit the initial settings. If you would like
* to receive live settings updates including the initial update,
* use `CredentialGeneratorService.settings$(...)` instead.
* use `CredentialGeneratorService.settings(...)` instead.
*/
@Output()
readonly onUpdated = new EventEmitter<PasswordGenerationOptions>();
protected settings = this.formBuilder.group({
[Controls.length]: [Generators.password.settings.initial.length],
[Controls.uppercase]: [Generators.password.settings.initial.uppercase],
[Controls.lowercase]: [Generators.password.settings.initial.lowercase],
[Controls.number]: [Generators.password.settings.initial.number],
[Controls.special]: [Generators.password.settings.initial.special],
[Controls.minNumber]: [Generators.password.settings.initial.minNumber],
[Controls.minSpecial]: [Generators.password.settings.initial.minSpecial],
[Controls.avoidAmbiguous]: [!Generators.password.settings.initial.ambiguous],
[Controls.length]: [0],
[Controls.uppercase]: [false],
[Controls.lowercase]: [false],
[Controls.number]: [false],
[Controls.special]: [false],
[Controls.minNumber]: [0],
[Controls.minSpecial]: [0],
[Controls.avoidAmbiguous]: [false],
});
private get numbers() {
return this.settings.get(Controls.number);
return this.settings.get(Controls.number)!;
}
private get special() {
return this.settings.get(Controls.special);
return this.settings.get(Controls.special)!;
}
private get minNumber() {
return this.settings.get(Controls.minNumber);
return this.settings.get(Controls.minNumber)!;
}
private get minSpecial() {
return this.settings.get(Controls.minSpecial);
return this.settings.get(Controls.minSpecial)!;
}
async ngOnInit() {
const settings = await this.generatorService.settings(Generators.password, {
const settings = await this.generatorService.settings(BuiltIn.password, {
account$: this.account$,
});
@@ -130,13 +132,13 @@ export class PasswordSettingsComponent implements OnInit, OnChanges, OnDestroy {
.subscribe(([state, constraints]) => {
let boundariesHint = this.i18nService.t(
"spinboxBoundariesHint",
constraints.length.min?.toString(),
constraints.length.max?.toString(),
constraints.length?.min?.toString(),
constraints.length?.max?.toString(),
);
if (state.length <= (constraints.length.recommendation ?? 0)) {
if (state.length <= (constraints.length?.recommendation ?? 0)) {
boundariesHint += this.i18nService.t(
"passwordLengthRecommendationHint",
constraints.length.recommendation?.toString(),
constraints.length?.recommendation?.toString(),
);
}
this.lengthBoundariesHint.next(boundariesHint);
@@ -147,19 +149,25 @@ export class PasswordSettingsComponent implements OnInit, OnChanges, OnDestroy {
// explain policy & disable policy-overridden fields
this.generatorService
.policy$(Generators.password, { account$: this.account$ })
.policy$(BuiltIn.password, { account$: this.account$ })
.pipe(takeUntil(this.destroyed$))
.subscribe(({ constraints }) => {
this.policyInEffect = constraints.policyInEffect;
this.policyInEffect = constraints.policyInEffect ?? false;
const toggles = [
[Controls.length, constraints.length.min < constraints.length.max],
[Controls.length, hasRangeOfValues(constraints.length?.min, constraints.length?.max)],
[Controls.uppercase, !constraints.uppercase?.readonly],
[Controls.lowercase, !constraints.lowercase?.readonly],
[Controls.number, !constraints.number?.readonly],
[Controls.special, !constraints.special?.readonly],
[Controls.minNumber, constraints.minNumber.min < constraints.minNumber.max],
[Controls.minSpecial, constraints.minSpecial.min < constraints.minSpecial.max],
[
Controls.minNumber,
hasRangeOfValues(constraints.minNumber?.min, constraints.minNumber?.max),
],
[
Controls.minSpecial,
hasRangeOfValues(constraints.minSpecial?.min, constraints.minSpecial?.max),
],
] as [keyof typeof Controls, boolean][];
for (const [control, enabled] of toggles) {
@@ -172,7 +180,7 @@ export class PasswordSettingsComponent implements OnInit, OnChanges, OnDestroy {
let lastMinNumber = 1;
this.numbers.valueChanges
.pipe(
filter((checked) => !(checked && this.minNumber.value > 0)),
filter((checked) => !(checked && (this.minNumber.value ?? 0) > 0)),
map((checked) => (checked ? lastMinNumber : 0)),
takeUntil(this.destroyed$),
)
@@ -180,8 +188,11 @@ export class PasswordSettingsComponent implements OnInit, OnChanges, OnDestroy {
this.minNumber.valueChanges
.pipe(
map((value) => [value, value > 0] as const),
tap(([value, checkNumbers]) => (lastMinNumber = checkNumbers ? value : lastMinNumber)),
map((value) => [value, (value ?? 0) > 0] as const),
tap(
([value, checkNumbers]) =>
(lastMinNumber = checkNumbers && value ? value : lastMinNumber),
),
takeUntil(this.destroyed$),
)
.subscribe(([, checkNumbers]) => this.numbers.setValue(checkNumbers, { emitEvent: false }));
@@ -189,7 +200,7 @@ export class PasswordSettingsComponent implements OnInit, OnChanges, OnDestroy {
let lastMinSpecial = 1;
this.special.valueChanges
.pipe(
filter((checked) => !(checked && this.minSpecial.value > 0)),
filter((checked) => !(checked && (this.minSpecial.value ?? 0) > 0)),
map((checked) => (checked ? lastMinSpecial : 0)),
takeUntil(this.destroyed$),
)
@@ -197,8 +208,11 @@ export class PasswordSettingsComponent implements OnInit, OnChanges, OnDestroy {
this.minSpecial.valueChanges
.pipe(
map((value) => [value, value > 0] as const),
tap(([value, checkSpecial]) => (lastMinSpecial = checkSpecial ? value : lastMinSpecial)),
map((value) => [value, (value ?? 0) > 0] as const),
tap(
([value, checkSpecial]) =>
(lastMinSpecial = checkSpecial && value ? value : lastMinSpecial),
),
takeUntil(this.destroyed$),
)
.subscribe(([, checkSpecial]) => this.special.setValue(checkSpecial, { emitEvent: false }));
@@ -230,7 +244,7 @@ export class PasswordSettingsComponent implements OnInit, OnChanges, OnDestroy {
}
/** display binding for enterprise policy notice */
protected policyInEffect: boolean;
protected policyInEffect: boolean = false;
private lengthBoundariesHint = new ReplaySubject<string>(1);
@@ -239,9 +253,9 @@ export class PasswordSettingsComponent implements OnInit, OnChanges, OnDestroy {
private toggleEnabled(setting: keyof typeof Controls, enabled: boolean) {
if (enabled) {
this.settings.get(setting).enable({ emitEvent: false });
this.settings.get(setting)?.enable({ emitEvent: false });
} else {
this.settings.get(setting).disable({ emitEvent: false });
this.settings.get(setting)?.disable({ emitEvent: false });
}
}

View File

@@ -1,5 +1,3 @@
// FIXME: Update this file to be type safe and remove this and next line
// @ts-strict-ignore
import {
Component,
EventEmitter,
@@ -13,10 +11,10 @@ import {
import { FormBuilder } from "@angular/forms";
import { map, ReplaySubject, skip, Subject, takeUntil, withLatestFrom } from "rxjs";
import { Account, AccountService } from "@bitwarden/common/auth/abstractions/account.service";
import { Account } from "@bitwarden/common/auth/abstractions/account.service";
import {
CredentialGeneratorService,
Generators,
BuiltIn,
SubaddressGenerationOptions,
} from "@bitwarden/generator-core";
@@ -28,20 +26,20 @@ import {
})
export class SubaddressSettingsComponent implements OnInit, OnChanges, OnDestroy {
/** Instantiates the component
* @param accountService queries user availability
* @param generatorService settings and policy logic
* @param formBuilder reactive form controls
*/
constructor(
private formBuilder: FormBuilder,
private generatorService: CredentialGeneratorService,
private accountService: AccountService,
) {}
/** Binds the component to a specific user's settings.
* @remarks this is initialized to null but since it's a required input it'll
* never have that value in practice.
*/
@Input({ required: true })
account: Account;
account: Account = null!;
protected account$ = new ReplaySubject<Account>(1);
@@ -54,18 +52,18 @@ export class SubaddressSettingsComponent implements OnInit, OnChanges, OnDestroy
/** Emits settings updates and completes if the settings become unavailable.
* @remarks this does not emit the initial settings. If you would like
* to receive live settings updates including the initial update,
* use `CredentialGeneratorService.settings$(...)` instead.
* use `CredentialGeneratorService.settings(...)` instead.
*/
@Output()
readonly onUpdated = new EventEmitter<SubaddressGenerationOptions>();
/** The template's control bindings */
protected settings = this.formBuilder.group({
subaddressEmail: [Generators.subaddress.settings.initial.subaddressEmail],
subaddressEmail: [""],
});
async ngOnInit() {
const settings = await this.generatorService.settings(Generators.subaddress, {
const settings = await this.generatorService.settings(BuiltIn.plusAddress, {
account$: this.account$,
});
@@ -79,7 +77,7 @@ export class SubaddressSettingsComponent implements OnInit, OnChanges, OnDestroy
this.saveSettings
.pipe(
withLatestFrom(this.settings.valueChanges),
map(([, settings]) => settings),
map(([, settings]) => settings as SubaddressGenerationOptions),
takeUntil(this.destroyed$),
)
.subscribe(settings);

View File

@@ -59,7 +59,7 @@
</bit-form-field>
</form>
<tools-catchall-settings
*ngIf="(algorithm$ | async)?.id === 'catchall'"
*ngIf="(showAlgorithm$ | async)?.id === Algorithm.catchall"
[account]="account$ | async"
(onUpdated)="generate('catchall settings')"
/>
@@ -69,12 +69,12 @@
[account]="account$ | async"
/>
<tools-subaddress-settings
*ngIf="(algorithm$ | async)?.id === 'subaddress'"
*ngIf="(showAlgorithm$ | async)?.id === Algorithm.plusAddress"
[account]="account$ | async"
(onUpdated)="generate('subaddress settings')"
/>
<tools-username-settings
*ngIf="(algorithm$ | async)?.id === 'username'"
*ngIf="(showAlgorithm$ | async)?.id === Algorithm.username"
[account]="account$ | async"
(onUpdated)="generate('username settings')"
/>

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 {
@@ -25,15 +23,15 @@ import {
map,
ReplaySubject,
Subject,
switchMap,
takeUntil,
tap,
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 { IntegrationId } from "@bitwarden/common/tools/integration";
import { VendorId } from "@bitwarden/common/tools/extension";
import {
SemanticLogger,
disabledSemanticLoggerProvider,
@@ -43,21 +41,23 @@ import { UserId } from "@bitwarden/common/types/guid";
import { ToastService, Option } from "@bitwarden/components";
import {
AlgorithmInfo,
CredentialAlgorithm,
CredentialCategories,
CredentialGeneratorService,
GenerateRequest,
GeneratedCredential,
Generators,
getForwarderConfiguration,
isForwarderExtensionId,
isEmailAlgorithm,
isForwarderIntegration,
isSameAlgorithm,
isUsernameAlgorithm,
toCredentialGeneratorConfiguration,
isSameAlgorithm,
CredentialAlgorithm,
AlgorithmMetadata,
AlgorithmsByType,
Type,
Algorithm,
} from "@bitwarden/generator-core";
import { GeneratorHistoryService } from "@bitwarden/generator-history";
import { toAlgorithmInfo, translate } from "./util";
// constants used to identify navigation selections that are not
// generator algorithms
const FORWARDER = "forwarder";
@@ -89,11 +89,14 @@ export class UsernameGeneratorComponent implements OnInit, OnChanges, OnDestroy
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);
@@ -110,7 +113,11 @@ export class UsernameGeneratorComponent 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,
@@ -118,7 +125,7 @@ export class UsernameGeneratorComponent implements OnInit, OnChanges, OnDestroy
},
"account input change detected",
);
this.account$.next(this.account);
this.account$.next(account.currentValue.id);
}
}
@@ -134,18 +141,18 @@ export class UsernameGeneratorComponent implements OnInit, OnChanges, OnDestroy
/** emits algorithm info when the selected algorithm changes */
@Output()
readonly onAlgorithm = new EventEmitter<AlgorithmInfo>();
readonly onAlgorithm = new EventEmitter<AlgorithmInfo | null>();
/** Removes bottom margin from internal elements */
@Input({ transform: coerceBooleanProperty }) disableMargin = false;
/** Tracks the selected generation algorithm */
protected username = this.formBuilder.group({
nav: [null as string],
nav: [null as string | null],
});
protected forwarder = this.formBuilder.group({
nav: [null as string],
nav: [null as string | null],
});
async ngOnInit() {
@@ -154,38 +161,63 @@ export class UsernameGeneratorComponent implements OnInit, OnChanges, OnDestroy
});
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
.algorithms$(["email", "username"], { account$: this.account$ })
combineLatest([
this.generatorService.algorithms$("email", { account$: this.account$ }),
this.generatorService.algorithms$("username", { account$: this.account$ }),
])
.pipe(
map((algorithms) => algorithms.flat()),
map((algorithms) => {
const usernames = algorithms.filter((a) => !isForwarderIntegration(a.id));
// construct options for username and email algorithms; replace forwarder
// entry with a virtual entry for drill-down
const usernames = algorithms.filter((a) => !isForwarderExtensionId(a.id));
usernames.sort((a, b) => a.weight - b.weight);
const usernameOptions = this.toOptions(usernames);
usernameOptions.push({ value: FORWARDER, label: this.i18nService.t("forwardedEmail") });
usernameOptions.splice(-1, 0, {
value: FORWARDER,
label: this.i18nService.t("forwardedEmail"),
});
const forwarders = algorithms.filter((a) => isForwarderIntegration(a.id));
// construct options for forwarder algorithms; they get their own selection box
const forwarders = algorithms.filter((a) => isForwarderExtensionId(a.id));
forwarders.sort((a, b) => a.weight - b.weight);
const forwarderOptions = this.toOptions(forwarders);
forwarderOptions.unshift({ value: NONE_SELECTED, label: this.i18nService.t("select") });
return [usernameOptions, forwarderOptions] as const;
}),
tap((algorithms) =>
this.log.debug({ algorithms: algorithms as object }, "algorithms loaded"),
),
takeUntil(this.destroyed),
)
.subscribe(([usernames, forwarders]) => {
this.typeOptions$.next(usernames);
this.forwarderOptions$.next(forwarders);
// update subjects within the angular zone so that the
// template bindings refresh immediately
this.zone.run(() => {
this.typeOptions$.next(usernames);
this.forwarderOptions$.next(forwarders);
});
});
this.algorithm$
this.maybeAlgorithm$
.pipe(
map((a) => a?.description),
map((a) => {
if (a?.i18nKeys?.description) {
return translate(a.i18nKeys.description, this.i18nService);
} else {
return "";
}
}),
takeUntil(this.destroyed),
)
.subscribe((hint) => {
@@ -197,10 +229,12 @@ export class UsernameGeneratorComponent implements OnInit, OnChanges, OnDestroy
});
// 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({
@@ -215,11 +249,14 @@ export class UsernameGeneratorComponent implements OnInit, OnChanges, OnDestroy
// continue with origin stream
return generator;
}),
withLatestFrom(this.account$, this.algorithm$),
withLatestFrom(this.account$, this.maybeAlgorithm$),
takeUntil(this.destroyed),
)
.subscribe(([generated, account, algorithm]) => {
this.log.debug({ source: generated.source }, "credential generated");
this.log.debug(
{ source: generated.source ?? null, algorithm: algorithm?.id ?? null },
"credential generated",
);
this.generatorHistoryService
.track(account.id, generated.credential, generated.category, generated.generationDate)
@@ -230,12 +267,12 @@ export class UsernameGeneratorComponent implements OnInit, OnChanges, OnDestroy
// update subjects within the angular zone so that the
// template bindings refresh immediately
this.zone.run(() => {
if (generated.source === this.USER_REQUEST) {
this.announce(algorithm.onGeneratedMessage);
if (algorithm && generated.source === this.USER_REQUEST) {
this.announce(translate(algorithm.i18nKeys.credentialGenerated, this.i18nService));
}
this.generatedCredential$.next(generated);
this.onGenerated.next(generated);
this.value$.next(generated.credential);
});
});
@@ -248,24 +285,31 @@ export class UsernameGeneratorComponent implements OnInit, OnChanges, OnDestroy
this.username.valueChanges
.pipe(
map(
(username): CascadeValue =>
username.nav === FORWARDER
? { nav: username.nav }
: { nav: username.nav, algorithm: JSON.parse(username.nav) },
),
map((username): CascadeValue => {
if (username.nav === FORWARDER) {
return { nav: username.nav };
} else if (username.nav) {
return { nav: username.nav, algorithm: JSON.parse(username.nav) };
} else {
const [algorithm] = AlgorithmsByType[Type.username];
return { nav: JSON.stringify(algorithm), algorithm };
}
}),
takeUntil(this.destroyed),
)
.subscribe(activeIdentifier$);
this.forwarder.valueChanges
.pipe(
map(
(forwarder): CascadeValue =>
forwarder.nav === NONE_SELECTED
? { nav: forwarder.nav }
: { nav: forwarder.nav, algorithm: JSON.parse(forwarder.nav) },
),
map((forwarder): CascadeValue => {
if (forwarder.nav === NONE_SELECTED) {
return { nav: forwarder.nav };
} else if (forwarder.nav) {
return { nav: forwarder.nav, algorithm: JSON.parse(forwarder.nav) };
} else {
return { nav: NONE_SELECTED };
}
}),
takeUntil(this.destroyed),
)
.subscribe(activeForwarder$);
@@ -276,7 +320,7 @@ export class UsernameGeneratorComponent implements OnInit, OnChanges, OnDestroy
map(([username, forwarder]) => {
const showForwarder = !username.algorithm;
const forwarderId =
showForwarder && isForwarderIntegration(forwarder.algorithm)
showForwarder && forwarder.algorithm && isForwarderExtensionId(forwarder.algorithm)
? forwarder.algorithm.forwarder
: null;
return [showForwarder, forwarderId] as const;
@@ -306,57 +350,61 @@ export class UsernameGeneratorComponent implements OnInit, OnChanges, OnDestroy
return null;
}
}),
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 ?? null }, "algorithm selected");
// 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);
if (algorithm) {
this.onAlgorithm.next(toAlgorithmInfo(algorithm, this.i18nService));
} else {
this.onAlgorithm.next(null);
}
});
});
// assume the last-visible generator algorithm is the user's preferred one
const preferences = await this.generatorService.preferences({ account$: this.account$ });
this.algorithm$
.pipe(
filter((algorithm) => !!algorithm),
withLatestFrom(preferences),
takeUntil(this.destroyed),
)
.pipe(withLatestFrom(preferences), takeUntil(this.destroyed))
.subscribe(([algorithm, preference]) => {
if (isEmailAlgorithm(algorithm.id)) {
this.log.info(
{ algorithm, category: CredentialCategories.email },
"algorithm preferences updated",
);
preference.email.algorithm = algorithm.id;
preference.email.updated = new Date();
} else if (isUsernameAlgorithm(algorithm.id)) {
this.log.info(
{ algorithm, category: CredentialCategories.username },
"algorithm preferences updated",
);
preference.username.algorithm = algorithm.id;
preference.username.updated = new Date();
} else {
return;
}
this.log.info(
{ algorithm: algorithm.id, type: algorithm.type },
"algorithm preferences updated",
);
preferences.next(preference);
});
preferences
.pipe(
map(({ email, username }) => {
const forwarderPref = isForwarderIntegration(email.algorithm) ? email : null;
const usernamePref = email.updated > username.updated ? email : username;
const forwarderPref = isForwarderExtensionId(usernamePref.algorithm)
? usernamePref
: null;
// inject drilldown flags
// inject drill-down flags
const forwarderNav = !forwarderPref
? NONE_SELECTED
: JSON.stringify(forwarderPref.algorithm);
@@ -368,7 +416,7 @@ export class UsernameGeneratorComponent implements OnInit, OnChanges, OnDestroy
selection: { nav: userNav },
active: {
nav: userNav,
algorithm: forwarderPref ? null : usernamePref.algorithm,
algorithm: forwarderPref ? undefined : usernamePref.algorithm,
},
},
forwarder: {
@@ -385,6 +433,14 @@ export class UsernameGeneratorComponent implements OnInit, OnChanges, OnDestroy
takeUntil(this.destroyed),
)
.subscribe(({ username, forwarder }) => {
this.log.debug(
{
username: username.selection,
forwarder: forwarder.selection,
},
"navigation updated",
);
// update navigation; break subscription loop
this.username.setValue(username.selection, { emitEvent: false });
this.forwarder.setValue(forwarder.selection, { emitEvent: false });
@@ -396,17 +452,16 @@ export class UsernameGeneratorComponent implements OnInit, OnChanges, OnDestroy
// automatically regenerate when the algorithm switches if the algorithm
// allows it; otherwise set a placeholder
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.generatedCredential$.next(undefined);
}
});
});
@@ -414,34 +469,6 @@ export class UsernameGeneratorComponent implements OnInit, OnChanges, OnDestroy
this.log.debug("component initialized");
}
private typeToGenerator$(algorithm: CredentialAlgorithm) {
const dependencies = {
on$: this.generate$,
account$: this.account$,
};
this.log.debug({ algorithm }, "constructing generation stream");
switch (algorithm) {
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);
}
if (isForwarderIntegration(algorithm)) {
const forwarder = getForwarderConfiguration(algorithm.forwarder);
const configuration = toCredentialGeneratorConfiguration(forwarder);
return this.generatorService.generate$(configuration, dependencies);
}
this.log.panic({ algorithm }, `Invalid generator type: "${algorithm}"`);
}
private announce(message: string) {
this.ariaLive.announce(message).catch((e) => this.logService.error(e));
}
@@ -450,7 +477,7 @@ export class UsernameGeneratorComponent implements OnInit, OnChanges, OnDestroy
protected typeOptions$ = new BehaviorSubject<Option<string>[]>([]);
/** Tracks the currently selected forwarder. */
protected forwarderId$ = new BehaviorSubject<IntegrationId>(null);
protected forwarderId$ = new BehaviorSubject<VendorId | null>(null);
/** Lists the credential types supported by the component. */
protected forwarderOptions$ = new BehaviorSubject<Option<string>[]>([]);
@@ -458,19 +485,30 @@ export class UsernameGeneratorComponent implements OnInit, OnChanges, OnDestroy
/** Tracks forwarder control visibility */
protected showForwarder$ = new BehaviorSubject<boolean>(false);
/** tracks the currently selected credential type */
protected algorithm$ = new ReplaySubject<AlgorithmInfo>(1);
/** tracks the currently selected algorithm; emits `null` when no algorithm selected */
protected maybeAlgorithm$ = new ReplaySubject<AlgorithmMetadata | null>(1);
/** tracks the last valid algorithm selection */
protected algorithm$ = this.maybeAlgorithm$.pipe(
filter((algorithm): algorithm is AlgorithmMetadata => !!algorithm),
);
/** Emits hint key for the currently selected credential type */
protected credentialTypeHint$ = new ReplaySubject<string>(1);
private readonly generatedCredential$ = new BehaviorSubject<GeneratedCredential | undefined>(
undefined,
);
/** Emits the last generated value. */
protected readonly value$ = new BehaviorSubject<string>("");
protected readonly value$ = this.generatedCredential$.pipe(
map((generated) => generated?.credential ?? "-"),
);
/** Emits when a new credential is requested */
private readonly generate$ = new Subject<GenerateRequest>();
protected showAlgorithm$ = this.algorithm$.pipe(
protected showAlgorithm$ = this.maybeAlgorithm$.pipe(
combineLatestWith(this.showForwarder$),
map(([algorithm, showForwarder]) => (showForwarder ? null : algorithm)),
);
@@ -479,24 +517,21 @@ export class UsernameGeneratorComponent implements OnInit, OnChanges, OnDestroy
* 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)),
);
/** Identifies generator requests that were requested by the user */
@@ -507,15 +542,20 @@ export class UsernameGeneratorComponent implements OnInit, OnChanges, OnDestroy
* origin in the debugger.
*/
protected async generate(source: string) {
const request = { source, website: this.website };
const algorithm = await firstValueFrom(this.algorithm$);
const request: GenerateRequest = { source, algorithm: algorithm.id };
if (this.website) {
request.website = this.website;
}
this.log.debug(request, "generation requested");
this.generate$.next(request);
}
private toOptions(algorithms: AlgorithmInfo[]) {
private toOptions(algorithms: AlgorithmMetadata[]) {
const options: Option<string>[] = algorithms.map((algorithm) => ({
value: JSON.stringify(algorithm.id),
label: algorithm.name,
label: translate(algorithm.i18nKeys.name, this.i18nService),
}));
return options;
@@ -528,9 +568,11 @@ export class UsernameGeneratorComponent implements OnInit, OnChanges, OnDestroy
// finalize subjects
this.generate$.complete();
this.value$.complete();
this.generatedCredential$.complete();
// finalize component bindings
this.onGenerated.complete();
this.log.debug("component destroyed");
}
}

View File

@@ -1,5 +1,3 @@
// FIXME: Update this file to be type safe and remove this and next line
// @ts-strict-ignore
import {
Component,
EventEmitter,
@@ -17,7 +15,7 @@ import { Account } from "@bitwarden/common/auth/abstractions/account.service";
import {
CredentialGeneratorService,
EffUsernameGenerationOptions,
Generators,
BuiltIn,
} from "@bitwarden/generator-core";
/** Options group for usernames */
@@ -28,7 +26,6 @@ import {
})
export class UsernameSettingsComponent implements OnInit, OnChanges, OnDestroy {
/** Instantiates the component
* @param accountService queries user availability
* @param generatorService settings and policy logic
* @param formBuilder reactive form controls
*/
@@ -38,9 +35,11 @@ export class UsernameSettingsComponent implements OnInit, OnChanges, OnDestroy {
) {}
/** Binds the component to a specific user's settings.
* @remarks this is initialized to null but since it's a required input it'll
* never have that value in practice.
*/
@Input({ required: true })
account: Account;
account: Account = null!;
protected account$ = new ReplaySubject<Account>(1);
@@ -53,19 +52,19 @@ export class UsernameSettingsComponent implements OnInit, OnChanges, OnDestroy {
/** Emits settings updates and completes if the settings become unavailable.
* @remarks this does not emit the initial settings. If you would like
* to receive live settings updates including the initial update,
* use `CredentialGeneratorService.settings$(...)` instead.
* use `CredentialGeneratorService.settings(...)` instead.
*/
@Output()
readonly onUpdated = new EventEmitter<EffUsernameGenerationOptions>();
/** The template's control bindings */
protected settings = this.formBuilder.group({
wordCapitalize: [Generators.username.settings.initial.wordCapitalize],
wordIncludeNumber: [Generators.username.settings.initial.wordIncludeNumber],
wordCapitalize: [false],
wordIncludeNumber: [false],
});
async ngOnInit() {
const settings = await this.generatorService.settings(Generators.username, {
const settings = await this.generatorService.settings(BuiltIn.effWordList, {
account$: this.account$,
});
@@ -79,7 +78,7 @@ export class UsernameSettingsComponent implements OnInit, OnChanges, OnDestroy {
this.saveSettings
.pipe(
withLatestFrom(this.settings.valueChanges),
map(([, settings]) => settings),
map(([, settings]) => settings as EffUsernameGenerationOptions),
takeUntil(this.destroyed$),
)
.subscribe(settings);

View File

@@ -1,71 +1,46 @@
// FIXME: Update this file to be type safe and remove this and next line
// @ts-strict-ignore
import { ValidatorFn, Validators } from "@angular/forms";
import { distinctUntilChanged, map, pairwise, pipe, skipWhile, startWith, takeWhile } from "rxjs";
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
import { I18nKeyOrLiteral } from "@bitwarden/common/tools/types";
import { isI18nKey } from "@bitwarden/common/tools/util";
import { AlgorithmInfo, AlgorithmMetadata } from "@bitwarden/generator-core";
import { AnyConstraint, Constraints } from "@bitwarden/common/tools/types";
import { UserId } from "@bitwarden/common/types/guid";
import { CredentialGeneratorConfiguration } from "@bitwarden/generator-core";
/** Adapts {@link AlgorithmMetadata} to legacy {@link AlgorithmInfo} structure. */
export function toAlgorithmInfo(metadata: AlgorithmMetadata, i18n: I18nService) {
const info: AlgorithmInfo = {
id: metadata.id,
type: metadata.type,
name: translate(metadata.i18nKeys.name, i18n),
generate: translate(metadata.i18nKeys.generateCredential, i18n),
onGeneratedMessage: translate(metadata.i18nKeys.credentialGenerated, i18n),
credentialType: translate(metadata.i18nKeys.credentialType, i18n),
copy: translate(metadata.i18nKeys.copyCredential, i18n),
useGeneratedValue: translate(metadata.i18nKeys.useCredential, i18n),
onlyOnRequest: !metadata.capabilities.autogenerate,
request: metadata.capabilities.fields,
};
export function completeOnAccountSwitch() {
return pipe(
map(({ id }: { id: UserId | null }) => id),
skipWhile((id) => !id),
startWith(null as UserId),
pairwise(),
takeWhile(([prev, next]) => (prev ?? next) === next),
map(([_, id]) => id),
distinctUntilChanged(),
);
if (metadata.i18nKeys.description) {
info.description = translate(metadata.i18nKeys.description, i18n);
}
return info;
}
export function toValidators<Policy, Settings>(
target: keyof Settings,
configuration: CredentialGeneratorConfiguration<Settings, Policy>,
policy?: Constraints<Settings>,
) {
const validators: Array<ValidatorFn> = [];
// widen the types to avoid typecheck issues
const config: AnyConstraint = configuration.settings.constraints[target];
const runtime: AnyConstraint = policy[target];
const required = getConstraint("required", config, runtime) ?? false;
if (required) {
validators.push(Validators.required);
}
const maxLength = getConstraint("maxLength", config, runtime);
if (maxLength !== undefined) {
validators.push(Validators.maxLength(maxLength));
}
const minLength = getConstraint("minLength", config, runtime);
if (minLength !== undefined) {
validators.push(Validators.minLength(config.minLength));
}
const min = getConstraint("min", config, runtime);
if (min !== undefined) {
validators.push(Validators.min(min));
}
const max = getConstraint("max", config, runtime);
if (max !== undefined) {
validators.push(Validators.max(max));
}
return validators;
/** Translates an internationalization key
* @param key the key to translate
* @param i18n the service providing translations
* @returns the translated key; if the key is a literal the literal
* is returned instead.
*/
export function translate(key: I18nKeyOrLiteral, i18n: I18nService) {
return isI18nKey(key) ? i18n.t(key) : key.literal;
}
function getConstraint<Key extends keyof AnyConstraint>(
key: Key,
config: AnyConstraint,
policy?: AnyConstraint,
) {
if (policy && key in policy) {
return policy[key] ?? config[key];
} else if (config && key in config) {
return config[key];
}
/** Returns true when min < max
* @param min the minimum value to check; when this is nullish it becomes 0.
* @param max the maximum value to check; when this is nullish it becomes +Infinity.
*/
export function hasRangeOfValues(min?: number, max?: number) {
const minimum = min ?? 0;
const maximum = max ?? Number.POSITIVE_INFINITY;
return minimum < maximum;
}