1
0
mirror of https://github.com/bitwarden/browser synced 2025-12-06 00:13:28 +00:00

[PM-15200] add "generated credential" screen reader notification (#12877)

replaces website$ dependency with `GenerateRequest`
This commit is contained in:
✨ Audrey ✨
2025-01-24 14:44:42 -05:00
committed by GitHub
parent 9a5ebf94a0
commit 1fc20b55f2
21 changed files with 310 additions and 295 deletions

View File

@@ -56,7 +56,8 @@ const PASSPHRASE: CredentialGeneratorConfiguration<
category: "password",
nameKey: "passphrase",
generateKey: "generatePassphrase",
generatedValueKey: "passphrase",
onGeneratedMessageKey: "passphraseGenerated",
credentialTypeKey: "passphrase",
copyKey: "copyPassphrase",
useGeneratedValueKey: "useThisPassword",
onlyOnRequest: false,
@@ -118,7 +119,8 @@ const PASSWORD: CredentialGeneratorConfiguration<
category: "password",
nameKey: "password",
generateKey: "generatePassword",
generatedValueKey: "password",
onGeneratedMessageKey: "passwordGenerated",
credentialTypeKey: "password",
copyKey: "copyPassword",
useGeneratedValueKey: "useThisPassword",
onlyOnRequest: false,
@@ -195,7 +197,8 @@ const USERNAME: CredentialGeneratorConfiguration<EffUsernameGenerationOptions, N
category: "username",
nameKey: "randomWord",
generateKey: "generateUsername",
generatedValueKey: "username",
onGeneratedMessageKey: "usernameGenerated",
credentialTypeKey: "username",
copyKey: "copyUsername",
useGeneratedValueKey: "useThisUsername",
onlyOnRequest: false,
@@ -248,7 +251,8 @@ const CATCHALL: CredentialGeneratorConfiguration<CatchallGenerationOptions, NoPo
nameKey: "catchallEmail",
descriptionKey: "catchallEmailDesc",
generateKey: "generateEmail",
generatedValueKey: "email",
onGeneratedMessageKey: "emailGenerated",
credentialTypeKey: "email",
copyKey: "copyEmail",
useGeneratedValueKey: "useThisEmail",
onlyOnRequest: false,
@@ -304,7 +308,8 @@ const SUBADDRESS: CredentialGeneratorConfiguration<SubaddressGenerationOptions,
nameKey: "plusAddressedEmail",
descriptionKey: "plusAddressedEmailDesc",
generateKey: "generateEmail",
generatedValueKey: "email",
onGeneratedMessageKey: "emailGenerated",
credentialTypeKey: "email",
copyKey: "copyEmail",
useGeneratedValueKey: "useThisEmail",
onlyOnRequest: false,
@@ -362,7 +367,8 @@ export function toCredentialGeneratorConfiguration<Settings extends ApiSettings
nameKey: configuration.name,
descriptionKey: "forwardedEmailDesc",
generateKey: "generateEmail",
generatedValueKey: "email",
onGeneratedMessageKey: "emailGenerated",
credentialTypeKey: "email",
copyKey: "copyEmail",
useGeneratedValueKey: "useThisEmail",
onlyOnRequest: true,

View File

@@ -1,11 +1,11 @@
// FIXME: Update this file to be type safe and remove this and next line
// @ts-strict-ignore
import { EFFLongWordList } from "@bitwarden/common/platform/misc/wordlist";
import { GenerationRequest } from "@bitwarden/common/tools/types";
import {
CatchallGenerationOptions,
CredentialGenerator,
GenerateRequest,
GeneratedCredential,
SubaddressGenerationOptions,
} from "../types";
@@ -112,25 +112,37 @@ export class EmailRandomizer
}
generate(
request: GenerationRequest,
request: GenerateRequest,
settings: CatchallGenerationOptions,
): Promise<GeneratedCredential>;
generate(
request: GenerationRequest,
request: GenerateRequest,
settings: SubaddressGenerationOptions,
): Promise<GeneratedCredential>;
async generate(
_request: GenerationRequest,
request: GenerateRequest,
settings: CatchallGenerationOptions | SubaddressGenerationOptions,
) {
if (isCatchallGenerationOptions(settings)) {
const email = await this.randomAsciiCatchall(settings.catchallDomain);
return new GeneratedCredential(email, "catchall", Date.now());
return new GeneratedCredential(
email,
"catchall",
Date.now(),
request.source,
request.website,
);
} else if (isSubaddressGenerationOptions(settings)) {
const email = await this.randomAsciiSubaddress(settings.subaddressEmail);
return new GeneratedCredential(email, "subaddress", Date.now());
return new GeneratedCredential(
email,
"subaddress",
Date.now(),
request.source,
request.website,
);
}
throw new Error("Invalid settings received by generator.");

View File

@@ -1,10 +1,10 @@
// FIXME: Update this file to be type safe and remove this and next line
// @ts-strict-ignore
import { EFFLongWordList } from "@bitwarden/common/platform/misc/wordlist";
import { GenerationRequest } from "@bitwarden/common/tools/types";
import {
CredentialGenerator,
GenerateRequest,
GeneratedCredential,
PassphraseGenerationOptions,
PasswordGenerationOptions,
@@ -69,27 +69,39 @@ export class PasswordRandomizer
}
generate(
request: GenerationRequest,
request: GenerateRequest,
settings: PasswordGenerationOptions,
): Promise<GeneratedCredential>;
generate(
request: GenerationRequest,
request: GenerateRequest,
settings: PassphraseGenerationOptions,
): Promise<GeneratedCredential>;
async generate(
_request: GenerationRequest,
request: GenerateRequest,
settings: PasswordGenerationOptions | PassphraseGenerationOptions,
) {
if (isPasswordGenerationOptions(settings)) {
const request = optionsToRandomAsciiRequest(settings);
const password = await this.randomAscii(request);
const req = optionsToRandomAsciiRequest(settings);
const password = await this.randomAscii(req);
return new GeneratedCredential(password, "password", Date.now());
return new GeneratedCredential(
password,
"password",
Date.now(),
request.source,
request.website,
);
} else if (isPassphraseGenerationOptions(settings)) {
const request = optionsToEffWordListRequest(settings);
const passphrase = await this.randomEffLongWords(request);
const req = optionsToEffWordListRequest(settings);
const passphrase = await this.randomEffLongWords(req);
return new GeneratedCredential(passphrase, "passphrase", Date.now());
return new GeneratedCredential(
passphrase,
"passphrase",
Date.now(),
request.source,
request.website,
);
}
throw new Error("Invalid settings received by generator.");

View File

@@ -1,7 +1,11 @@
import { EFFLongWordList } from "@bitwarden/common/platform/misc/wordlist";
import { GenerationRequest } from "@bitwarden/common/tools/types";
import { CredentialGenerator, EffUsernameGenerationOptions, GeneratedCredential } from "../types";
import {
CredentialGenerator,
EffUsernameGenerationOptions,
GenerateRequest,
GeneratedCredential,
} from "../types";
import { Randomizer } from "./abstractions";
import { WordsRequest } from "./types";
@@ -51,14 +55,20 @@ export class UsernameRandomizer implements CredentialGenerator<EffUsernameGenera
return result;
}
async generate(_request: GenerationRequest, settings: EffUsernameGenerationOptions) {
async generate(request: GenerateRequest, settings: EffUsernameGenerationOptions) {
if (isEffUsernameGenerationOptions(settings)) {
const username = await this.randomWords({
digits: settings.wordIncludeNumber ? NUMBER_OF_DIGITS : 0,
casing: settings.wordCapitalize ? "TitleCase" : "lowercase",
});
return new GeneratedCredential(username, "username", Date.now());
return new GeneratedCredential(
username,
"username",
Date.now(),
request.source,
request.website,
);
}
throw new Error("Invalid settings received by generator.");

View File

@@ -1,5 +1,7 @@
// FIXME: remove ts-strict-ignore once `FakeAccountService` implements ts strict support
// @ts-strict-ignore
import { mock } from "jest-mock-extended";
import { BehaviorSubject, filter, firstValueFrom, Subject } from "rxjs";
import { BehaviorSubject, firstValueFrom, Subject } from "rxjs";
import { ApiService } from "@bitwarden/common/abstractions/api.service";
import { PolicyService } from "@bitwarden/common/admin-console/abstractions/policy/policy.service.abstraction";
@@ -23,6 +25,7 @@ import { Generators } from "../data";
import {
CredentialGeneratorConfiguration,
GeneratedCredential,
GenerateRequest,
GeneratorConstraints,
} from "../types";
@@ -72,7 +75,8 @@ const SomeAlgorithm = "passphrase";
const SomeCategory = "password";
const SomeNameKey = "passphraseKey";
const SomeGenerateKey = "generateKey";
const SomeGeneratedValueKey = "generatedValueKey";
const SomeCredentialTypeKey = "credentialTypeKey";
const SomeOnGeneratedMessageKey = "onGeneratedMessageKey";
const SomeCopyKey = "copyKey";
const SomeUseGeneratedValueKey = "useGeneratedValueKey";
@@ -82,7 +86,8 @@ const SomeConfiguration: CredentialGeneratorConfiguration<SomeSettings, SomePoli
category: SomeCategory,
nameKey: SomeNameKey,
generateKey: SomeGenerateKey,
generatedValueKey: SomeGeneratedValueKey,
onGeneratedMessageKey: SomeOnGeneratedMessageKey,
credentialTypeKey: SomeCredentialTypeKey,
copyKey: SomeCopyKey,
useGeneratedValueKey: SomeUseGeneratedValueKey,
onlyOnRequest: false,
@@ -91,8 +96,13 @@ const SomeConfiguration: CredentialGeneratorConfiguration<SomeSettings, SomePoli
create: (_randomizer) => {
return {
generate: (request, settings) => {
const credential = request.website ? `${request.website}|${settings.foo}` : settings.foo;
const result = new GeneratedCredential(credential, SomeAlgorithm, SomeTime);
const result = new GeneratedCredential(
settings.foo,
SomeAlgorithm,
SomeTime,
request.source,
request.website,
);
return Promise.resolve(result);
},
};
@@ -191,7 +201,33 @@ describe("CredentialGeneratorService", () => {
});
describe("generate$", () => {
it("emits a generation for the active user when subscribed", async () => {
it("completes when `on$` completes", async () => {
await stateProvider.setUserState(SettingsKey, { foo: "value" }, SomeUser);
const generator = new CredentialGeneratorService(
randomizer,
stateProvider,
policyService,
apiService,
i18nService,
encryptorProvider,
accountService,
);
const on$ = new Subject<GenerateRequest>();
let complete = false;
// confirm no emission during subscription
generator.generate$(SomeConfiguration, { on$ }).subscribe({
complete: () => {
complete = true;
},
});
on$.complete();
await awaitAsync();
expect(complete).toBeTruthy();
});
it("includes request.source in the generated credential", async () => {
const settings = { foo: "value" };
await stateProvider.setUserState(SettingsKey, settings, SomeUser);
const generator = new CredentialGeneratorService(
@@ -203,14 +239,35 @@ describe("CredentialGeneratorService", () => {
encryptorProvider,
accountService,
);
const generated = new ObservableTracker(generator.generate$(SomeConfiguration));
const on$ = new BehaviorSubject<GenerateRequest>({ source: "some source" });
const generated = new ObservableTracker(generator.generate$(SomeConfiguration, { on$ }));
const result = await generated.expectEmission();
expect(result).toEqual(new GeneratedCredential("value", SomeAlgorithm, SomeTime));
expect(result.source).toEqual("some source");
});
it("follows the active user", async () => {
it("includes request.website in the generated credential", async () => {
const settings = { foo: "value" };
await stateProvider.setUserState(SettingsKey, settings, SomeUser);
const generator = new CredentialGeneratorService(
randomizer,
stateProvider,
policyService,
apiService,
i18nService,
encryptorProvider,
accountService,
);
const on$ = new BehaviorSubject({ website: "some website" });
const generated = new ObservableTracker(generator.generate$(SomeConfiguration, { on$ }));
const result = await generated.expectEmission();
expect(result.website).toEqual("some website");
});
it("uses the active user's settings", async () => {
const someSettings = { foo: "some value" };
const anotherSettings = { foo: "another value" };
await stateProvider.setUserState(SettingsKey, someSettings, SomeUser);
@@ -224,34 +281,11 @@ describe("CredentialGeneratorService", () => {
encryptorProvider,
accountService,
);
const generated = new ObservableTracker(generator.generate$(SomeConfiguration));
const on$ = new BehaviorSubject({});
const generated = new ObservableTracker(generator.generate$(SomeConfiguration, { on$ }));
await accountService.switchAccount(AnotherUser);
await generated.pauseUntilReceived(2);
generated.unsubscribe();
expect(generated.emissions).toEqual([
new GeneratedCredential("some value", SomeAlgorithm, SomeTime),
new GeneratedCredential("another value", SomeAlgorithm, SomeTime),
]);
});
it("emits a generation when the settings change", async () => {
const someSettings = { foo: "some value" };
const anotherSettings = { foo: "another value" };
await stateProvider.setUserState(SettingsKey, someSettings, SomeUser);
const generator = new CredentialGeneratorService(
randomizer,
stateProvider,
policyService,
apiService,
i18nService,
encryptorProvider,
accountService,
);
const generated = new ObservableTracker(generator.generate$(SomeConfiguration));
await stateProvider.setUserState(SettingsKey, anotherSettings, SomeUser);
on$.next({});
await generated.pauseUntilReceived(2);
generated.unsubscribe();
@@ -265,78 +299,6 @@ describe("CredentialGeneratorService", () => {
it.todo("errors when the settings error");
it.todo("completes when the settings complete");
it("includes `website$`'s last emitted value", async () => {
const settings = { foo: "value" };
await stateProvider.setUserState(SettingsKey, settings, SomeUser);
const generator = new CredentialGeneratorService(
randomizer,
stateProvider,
policyService,
apiService,
i18nService,
encryptorProvider,
accountService,
);
const website$ = new BehaviorSubject("some website");
const generated = new ObservableTracker(generator.generate$(SomeConfiguration, { website$ }));
const result = await generated.expectEmission();
expect(result).toEqual(
new GeneratedCredential("some website|value", SomeAlgorithm, SomeTime),
);
});
it("errors when `website$` errors", async () => {
await stateProvider.setUserState(SettingsKey, null, SomeUser);
const generator = new CredentialGeneratorService(
randomizer,
stateProvider,
policyService,
apiService,
i18nService,
encryptorProvider,
accountService,
);
const website$ = new BehaviorSubject("some website");
let error = null;
generator.generate$(SomeConfiguration, { website$ }).subscribe({
error: (e: unknown) => {
error = e;
},
});
website$.error({ some: "error" });
await awaitAsync();
expect(error).toEqual({ some: "error" });
});
it("completes when `website$` completes", async () => {
await stateProvider.setUserState(SettingsKey, null, SomeUser);
const generator = new CredentialGeneratorService(
randomizer,
stateProvider,
policyService,
apiService,
i18nService,
encryptorProvider,
accountService,
);
const website$ = new BehaviorSubject("some website");
let completed = false;
generator.generate$(SomeConfiguration, { website$ }).subscribe({
complete: () => {
completed = true;
},
});
website$.complete();
await awaitAsync();
expect(completed).toBeTruthy();
});
it("emits a generation for a specific user when `user$` supplied", async () => {
await stateProvider.setUserState(SettingsKey, { foo: "value" }, SomeUser);
await stateProvider.setUserState(SettingsKey, { foo: "another" }, AnotherUser);
@@ -350,38 +312,17 @@ describe("CredentialGeneratorService", () => {
accountService,
);
const userId$ = new BehaviorSubject(AnotherUser).asObservable();
const generated = new ObservableTracker(generator.generate$(SomeConfiguration, { userId$ }));
const on$ = new Subject<GenerateRequest>();
const generated = new ObservableTracker(
generator.generate$(SomeConfiguration, { on$, userId$ }),
);
on$.next({});
const result = await generated.expectEmission();
expect(result).toEqual(new GeneratedCredential("another", SomeAlgorithm, SomeTime));
});
it("emits a generation for a specific user when `user$` emits", async () => {
await stateProvider.setUserState(SettingsKey, { foo: "value" }, SomeUser);
await stateProvider.setUserState(SettingsKey, { foo: "another" }, AnotherUser);
const generator = new CredentialGeneratorService(
randomizer,
stateProvider,
policyService,
apiService,
i18nService,
encryptorProvider,
accountService,
);
const userId = new BehaviorSubject(SomeUser);
const userId$ = userId.pipe(filter((u) => !!u));
const generated = new ObservableTracker(generator.generate$(SomeConfiguration, { userId$ }));
userId.next(AnotherUser);
const result = await generated.pauseUntilReceived(2);
expect(result).toEqual([
new GeneratedCredential("value", SomeAlgorithm, SomeTime),
new GeneratedCredential("another", SomeAlgorithm, SomeTime),
]);
});
it("errors when `user$` errors", async () => {
await stateProvider.setUserState(SettingsKey, null, SomeUser);
const generator = new CredentialGeneratorService(
@@ -393,10 +334,11 @@ describe("CredentialGeneratorService", () => {
encryptorProvider,
accountService,
);
const on$ = new Subject<GenerateRequest>();
const userId$ = new BehaviorSubject(SomeUser);
let error = null;
generator.generate$(SomeConfiguration, { userId$ }).subscribe({
generator.generate$(SomeConfiguration, { on$, userId$ }).subscribe({
error: (e: unknown) => {
error = e;
},
@@ -418,10 +360,11 @@ describe("CredentialGeneratorService", () => {
encryptorProvider,
accountService,
);
const on$ = new Subject<GenerateRequest>();
const userId$ = new BehaviorSubject(SomeUser);
let completed = false;
generator.generate$(SomeConfiguration, { userId$ }).subscribe({
generator.generate$(SomeConfiguration, { on$, userId$ }).subscribe({
complete: () => {
completed = true;
},
@@ -444,7 +387,7 @@ describe("CredentialGeneratorService", () => {
encryptorProvider,
accountService,
);
const on$ = new Subject<void>();
const on$ = new Subject<GenerateRequest>();
const results: any[] = [];
// confirm no emission during subscription
@@ -455,7 +398,7 @@ describe("CredentialGeneratorService", () => {
expect(results.length).toEqual(0);
// confirm forwarded emission
on$.next();
on$.next({});
await awaitAsync();
expect(results).toEqual([new GeneratedCredential("value", SomeAlgorithm, SomeTime)]);
@@ -465,7 +408,7 @@ describe("CredentialGeneratorService", () => {
expect(results.length).toBe(1);
// confirm forwarded emission takes latest value
on$.next();
on$.next({});
await awaitAsync();
sub.unsubscribe();
@@ -486,7 +429,7 @@ describe("CredentialGeneratorService", () => {
encryptorProvider,
accountService,
);
const on$ = new Subject<void>();
const on$ = new Subject<GenerateRequest>();
let error: any = null;
// confirm no emission during subscription
@@ -501,35 +444,8 @@ describe("CredentialGeneratorService", () => {
expect(error).toEqual({ some: "error" });
});
it("completes when `on$` completes", async () => {
await stateProvider.setUserState(SettingsKey, { foo: "value" }, SomeUser);
const generator = new CredentialGeneratorService(
randomizer,
stateProvider,
policyService,
apiService,
i18nService,
encryptorProvider,
accountService,
);
const on$ = new Subject<void>();
let complete = false;
// confirm no emission during subscription
generator.generate$(SomeConfiguration, { on$ }).subscribe({
complete: () => {
complete = true;
},
});
on$.complete();
await awaitAsync();
expect(complete).toBeTruthy();
});
// FIXME: test these when the fake state provider can delay its first emission
it.todo("emits when settings$ become available if on$ is called before they're ready.");
it.todo("emits when website$ become available if on$ is called before they're ready.");
});
describe("algorithms", () => {

View File

@@ -2,20 +2,15 @@
// @ts-strict-ignore
import {
BehaviorSubject,
combineLatest,
concat,
concatMap,
distinctUntilChanged,
endWith,
filter,
first,
firstValueFrom,
ignoreElements,
map,
Observable,
ReplaySubject,
share,
skipUntil,
switchMap,
takeUntil,
withLatestFrom,
@@ -34,9 +29,9 @@ import {
SingleUserDependency,
UserDependency,
} from "@bitwarden/common/tools/dependencies";
import { IntegrationId, IntegrationMetadata } from "@bitwarden/common/tools/integration";
import { IntegrationMetadata } from "@bitwarden/common/tools/integration";
import { RestClient } from "@bitwarden/common/tools/integration/rpc";
import { anyComplete } from "@bitwarden/common/tools/rx";
import { anyComplete, withLatestReady } from "@bitwarden/common/tools/rx";
import { UserStateSubject } from "@bitwarden/common/tools/state/user-state-subject";
import { UserId } from "@bitwarden/common/types/guid";
@@ -57,6 +52,7 @@ import {
CredentialPreference,
isForwarderIntegration,
ForwarderIntegration,
GenerateRequest,
} from "../types";
import {
CredentialGeneratorConfiguration as Configuration,
@@ -69,19 +65,7 @@ import { PREFERENCES } from "./credential-preferences";
type Policy$Dependencies = UserDependency;
type Settings$Dependencies = Partial<UserDependency>;
type Generate$Dependencies = Simplify<Partial<OnDependency> & Partial<UserDependency>> & {
/** Emits the active website when subscribed.
*
* The generator does not respond to emissions of this interface;
* If it is provided, the generator blocks until a value becomes available.
* When `website$` is omitted, the generator uses the empty string instead.
* When `website$` completes, the generator completes.
* When `website$` errors, the generator forwards the error.
*/
website$?: Observable<string>;
integration$?: Observable<IntegrationId>;
};
type Generate$Dependencies = Simplify<OnDependency<GenerateRequest> & Partial<UserDependency>>;
type Algorithms$Dependencies = Partial<UserDependency>;
@@ -111,43 +95,20 @@ export class CredentialGeneratorService {
/** Generates a stream of credentials
* @param configuration determines which generator's settings are loaded
* @param dependencies.on$ when specified, a new credential is emitted when
* this emits. Otherwise, a new credential is emitted when the settings
* update.
* @param dependencies.on$ Required. A new credential is emitted when this emits.
*/
generate$<Settings extends object, Policy>(
configuration: Readonly<Configuration<Settings, Policy>>,
dependencies?: Generate$Dependencies,
dependencies: Generate$Dependencies,
) {
// instantiate the engine
const engine = configuration.engine.create(this.getDependencyProvider());
// stream blocks until all of these values are received
const website$ = dependencies?.website$ ?? new BehaviorSubject<string>(null);
const request$ = website$.pipe(map((website) => ({ website })));
const settings$ = this.settings$(configuration, dependencies);
// if on$ triggers before settings are loaded, trigger as soon
// as they become available.
let readyOn$: Observable<any> = null;
if (dependencies?.on$) {
const NO_EMISSIONS = {};
const ready$ = combineLatest([settings$, request$]).pipe(
first(null, NO_EMISSIONS),
filter((value) => value !== NO_EMISSIONS),
share(),
);
readyOn$ = concat(
dependencies.on$?.pipe(switchMap(() => ready$)),
dependencies.on$.pipe(skipUntil(ready$)),
);
}
// generation proper
const generate$ = (readyOn$ ?? settings$).pipe(
withLatestFrom(request$, settings$),
concatMap(([, request, settings]) => engine.generate(request, settings)),
takeUntil(anyComplete([request$, settings$])),
const generate$ = dependencies.on$.pipe(
withLatestReady(settings$),
concatMap(([request, settings]) => engine.generate(request, settings)),
takeUntil(anyComplete([settings$])),
);
return generate$;
@@ -256,7 +217,8 @@ export class CredentialGeneratorService {
category: generator.category,
name: integration ? integration.name : this.i18nService.t(generator.nameKey),
generate: this.i18nService.t(generator.generateKey),
generatedValue: this.i18nService.t(generator.generatedValueKey),
onGeneratedMessage: this.i18nService.t(generator.onGeneratedMessageKey),
credentialType: this.i18nService.t(generator.credentialTypeKey),
copy: this.i18nService.t(generator.copyKey),
useGeneratedValue: this.i18nService.t(generator.useGeneratedValueKey),
onlyOnRequest: generator.onlyOnRequest,

View File

@@ -34,6 +34,9 @@ export type AlgorithmInfo = {
/* Localized generate button label */
generate: string;
/** Localized "credential generated" informational message */
onGeneratedMessage: string;
/* Localized copy button label */
copy: string;
@@ -41,7 +44,7 @@ export type AlgorithmInfo = {
useGeneratedValue: string;
/* Localized generated value label */
generatedValue: string;
credentialType: string;
/** Localized algorithm description */
description?: string;
@@ -79,17 +82,22 @@ export type CredentialGeneratorInfo = {
/** Localization key for the credential description*/
descriptionKey?: string;
/* Localization key for the generate command label */
/** Localization key for the generate command label */
generateKey: string;
/* Localization key for the copy button label */
/** Localization key for the copy button label */
copyKey: string;
/* Localized "use generated credential" button label */
/** Localization key for the "credential generated" informational message */
onGeneratedMessageKey: string;
/** Localized "use generated credential" button label */
useGeneratedValueKey: string;
/* Localization key for describing values generated by this generator */
generatedValueKey: string;
/** Localization key for describing the kind of credential generated
* by this generator.
*/
credentialTypeKey: string;
/** When true, credential generation must be explicitly requested.
* @remarks this property is useful when credential generation

View File

@@ -1,5 +1,4 @@
import { GenerationRequest } from "@bitwarden/common/tools/types";
import { GenerateRequest } from "./generate-request";
import { GeneratedCredential } from "./generated-credential";
/** An algorithm that generates credentials. */
@@ -8,5 +7,5 @@ export type CredentialGenerator<Settings> = {
* @param request runtime parameters
* @param settings stored parameters
*/
generate: (request: GenerationRequest, settings: Settings) => Promise<GeneratedCredential>;
generate: (request: GenerateRequest, settings: Settings) => Promise<GeneratedCredential>;
};

View File

@@ -0,0 +1,24 @@
/** Contextual information about the application state when a generator is invoked.
*/
export type GenerateRequest = {
/** Traces the origin of the generation request. This parameter is
* copied to the generated credential.
*
* @remarks This parameter it is provided solely so that generator
* consumers can differentiate request sources from one another.
* It never affects the random output of the generator algorithms,
* and it is never communicated to 3rd party systems. It MAY be
* tracked in the generator history.
*/
source?: string;
/** Traces the website associated with a generated credential.
*
* @remarks Random generators MUST NOT depend upon the website during credential
* generation. Non-random generators MAY include the website in the generated
* credential (e.g. a catchall email address). This parameter MAY be transmitted
* to 3rd party systems (e.g. as the description for a forwarding email).
* It MAY be tracked in the generator history.
*/
website?: string;
};

View File

@@ -11,11 +11,15 @@ export class GeneratedCredential {
* @param generationDate The date that the credential was generated.
* Numeric values should are interpreted using {@link Date.valueOf}
* semantics.
* @param source traces the origin of the request that generated this credential.
* @param website traces the website associated with the generated credential.
*/
constructor(
readonly credential: string,
readonly category: CredentialAlgorithm,
generationDate: Date | number,
readonly source?: string,
readonly website?: string,
) {
if (typeof generationDate === "number") {
this.generationDate = new Date(generationDate);
@@ -25,7 +29,7 @@ export class GeneratedCredential {
}
/** The date that the credential was generated */
generationDate: Date;
readonly generationDate: Date;
/** Constructs a credential from its `toJSON` representation */
static fromJSON(jsonValue: Jsonify<GeneratedCredential>) {
@@ -38,6 +42,9 @@ export class GeneratedCredential {
/** Serializes a credential to a JSON-compatible object */
toJSON() {
// omits the source and website because they were introduced to solve
// UI bugs and it's not yet known whether there's a desire to support
// them in the generator history view.
return {
credential: this.credential,
category: this.category,

View File

@@ -6,6 +6,7 @@ export * from "./credential-generator";
export * from "./credential-generator-configuration";
export * from "./eff-username-generator-options";
export * from "./forwarder-options";
export * from "./generate-request";
export * from "./generator-constraints";
export * from "./generated-credential";
export * from "./generator-options";