1
0
mirror of https://github.com/bitwarden/browser synced 2025-12-10 21:33:27 +00:00

[PM-10611] End user notification sync (#14116)

* [PM-10611] Remove Angular dependencies from Notifications module

* [PM-10611] Move end user notification service to /libs/common/vault/notifications

* [PM-10611] Implement listenForEndUserNotifications() for EndUserNotificationService

* [PM-10611] Add missing taskId to notification models

* [PM-10611] Add switch cases for end user notification payloads

* [PM-10611] Mark task related notifications as read when visiting the at-risk password page

* [PM-10611] Revert change to default-notifications service

* [PM-10611] Fix test

* [PM-10611] Fix tests and log warning in case more notifications than the default page size are available

* [PM-10611] Use separate feature flag for end user notifications

* [PM-10611] Fix test
This commit is contained in:
Shane Melton
2025-04-21 08:57:57 -07:00
committed by GitHub
parent 43b1f55360
commit 143473927e
19 changed files with 557 additions and 344 deletions

View File

@@ -55,6 +55,7 @@ export enum FeatureFlag {
VaultBulkManagementAction = "vault-bulk-management-action",
SecurityTasks = "security-tasks",
CipherKeyEncryption = "cipher-key-encryption",
EndUserNotifications = "pm-10609-end-user-notifications",
/* Platform */
IpcChannelFramework = "ipc-channel-framework",
@@ -105,6 +106,7 @@ export const DefaultFeatureFlagValue = {
[FeatureFlag.VaultBulkManagementAction]: FALSE,
[FeatureFlag.SecurityTasks]: FALSE,
[FeatureFlag.CipherKeyEncryption]: FALSE,
[FeatureFlag.EndUserNotifications]: FALSE,
/* Auth */
[FeatureFlag.PM9112_DeviceApprovalPersistence]: FALSE,

View File

@@ -1,3 +1,5 @@
import { NotificationViewResponse as EndUserNotificationResponse } from "@bitwarden/common/vault/notifications/models";
import { NotificationType } from "../../enums";
import { BaseResponse } from "./base.response";
@@ -57,6 +59,10 @@ export class NotificationResponse extends BaseResponse {
case NotificationType.SyncOrganizationCollectionSettingChanged:
this.payload = new OrganizationCollectionSettingChangedPushNotification(payload);
break;
case NotificationType.Notification:
case NotificationType.NotificationStatus:
this.payload = new EndUserNotificationResponse(payload);
break;
default:
break;
}

View File

@@ -0,0 +1,47 @@
import { Observable, Subscription } from "rxjs";
import { NotificationId, UserId } from "@bitwarden/common/types/guid";
import { NotificationView } from "../models";
/**
* A service for retrieving and managing notifications for end users.
*/
export abstract class EndUserNotificationService {
/**
* Observable of all notifications for the given user.
* @param userId
*/
abstract notifications$(userId: UserId): Observable<NotificationView[]>;
/**
* Observable of all unread notifications for the given user.
* @param userId
*/
abstract unreadNotifications$(userId: UserId): Observable<NotificationView[]>;
/**
* Mark a notification as read.
* @param notificationId
* @param userId
*/
abstract markAsRead(notificationId: NotificationId, userId: UserId): Promise<void>;
/**
* Mark a notification as deleted.
* @param notificationId
* @param userId
*/
abstract markAsDeleted(notificationId: NotificationId, userId: UserId): Promise<void>;
/**
* Clear all notifications from state for the given user.
* @param userId
*/
abstract clearState(userId: UserId): Promise<void>;
/**
* Creates a subscription to listen for end user push notifications and notification status updates.
*/
abstract listenForEndUserNotifications(): Subscription;
}

View File

@@ -0,0 +1,2 @@
export { EndUserNotificationService } from "./abstractions/end-user-notification.service";
export { DefaultEndUserNotificationService } from "./services/default-end-user-notification.service";

View File

@@ -0,0 +1,3 @@
export * from "./notification-view";
export * from "./notification-view.data";
export * from "./notification-view.response";

View File

@@ -0,0 +1,40 @@
import { Jsonify } from "type-fest";
import { NotificationId, SecurityTaskId } from "@bitwarden/common/types/guid";
import { NotificationViewResponse } from "./notification-view.response";
export class NotificationViewData {
id: NotificationId;
priority: number;
title: string;
body: string;
date: Date;
taskId?: SecurityTaskId;
readDate: Date | null;
deletedDate: Date | null;
constructor(response: NotificationViewResponse) {
this.id = response.id;
this.priority = response.priority;
this.title = response.title;
this.body = response.body;
this.date = response.date;
this.taskId = response.taskId;
this.readDate = response.readDate;
this.deletedDate = response.deletedDate;
}
static fromJSON(obj: Jsonify<NotificationViewData>) {
return Object.assign(new NotificationViewData({} as NotificationViewResponse), obj, {
id: obj.id,
priority: obj.priority,
title: obj.title,
body: obj.body,
date: new Date(obj.date),
taskId: obj.taskId,
readDate: obj.readDate ? new Date(obj.readDate) : null,
deletedDate: obj.deletedDate ? new Date(obj.deletedDate) : null,
});
}
}

View File

@@ -0,0 +1,25 @@
import { BaseResponse } from "@bitwarden/common/models/response/base.response";
import { NotificationId, SecurityTaskId } from "@bitwarden/common/types/guid";
export class NotificationViewResponse extends BaseResponse {
id: NotificationId;
priority: number;
title: string;
body: string;
date: Date;
taskId?: SecurityTaskId;
readDate: Date;
deletedDate: Date;
constructor(response: any) {
super(response);
this.id = this.getResponseProperty("Id");
this.priority = this.getResponseProperty("Priority");
this.title = this.getResponseProperty("Title");
this.body = this.getResponseProperty("Body");
this.date = this.getResponseProperty("Date");
this.taskId = this.getResponseProperty("TaskId");
this.readDate = this.getResponseProperty("ReadDate");
this.deletedDate = this.getResponseProperty("DeletedDate");
}
}

View File

@@ -0,0 +1,23 @@
import { NotificationId, SecurityTaskId } from "@bitwarden/common/types/guid";
export class NotificationView {
id: NotificationId;
priority: number;
title: string;
body: string;
date: Date;
taskId?: SecurityTaskId;
readDate: Date | null;
deletedDate: Date | null;
constructor(obj: any) {
this.id = obj.id;
this.priority = obj.priority;
this.title = obj.title;
this.body = obj.body;
this.date = obj.date;
this.taskId = obj.taskId;
this.readDate = obj.readDate;
this.deletedDate = obj.deletedDate;
}
}

View File

@@ -0,0 +1,223 @@
import { mock } from "jest-mock-extended";
import { firstValueFrom, of } from "rxjs";
import { ApiService } from "@bitwarden/common/abstractions/api.service";
import { AuthService } from "@bitwarden/common/auth/abstractions/auth.service";
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
import { NotificationsService } from "@bitwarden/common/platform/notifications";
import { StateProvider } from "@bitwarden/common/platform/state";
import { NotificationId, UserId } from "@bitwarden/common/types/guid";
import { FakeStateProvider, mockAccountServiceWith } from "../../../../spec";
import { NotificationViewResponse } from "../models";
import { NOTIFICATIONS } from "../state/end-user-notification.state";
import {
DEFAULT_NOTIFICATION_PAGE_SIZE,
DefaultEndUserNotificationService,
} from "./default-end-user-notification.service";
describe("End User Notification Center Service", () => {
let fakeStateProvider: FakeStateProvider;
let mockApiService: jest.Mocked<ApiService>;
let mockNotificationsService: jest.Mocked<NotificationsService>;
let mockAuthService: jest.Mocked<AuthService>;
let mockLogService: jest.Mocked<LogService>;
let service: DefaultEndUserNotificationService;
beforeEach(() => {
fakeStateProvider = new FakeStateProvider(mockAccountServiceWith("user-id" as UserId));
mockApiService = {
send: jest.fn(),
} as any;
mockNotificationsService = {
notifications$: of(null),
} as any;
mockAuthService = {
authStatuses$: of({}),
} as any;
mockLogService = mock<LogService>();
service = new DefaultEndUserNotificationService(
fakeStateProvider as unknown as StateProvider,
mockApiService,
mockNotificationsService,
mockAuthService,
mockLogService,
);
});
describe("notifications$", () => {
it("should return notifications from state when not null", async () => {
fakeStateProvider.singleUser.mockFor("user-id" as UserId, NOTIFICATIONS, [
{
id: "notification-id" as NotificationId,
} as NotificationViewResponse,
]);
const result = await firstValueFrom(service.notifications$("user-id" as UserId));
expect(result.length).toBe(1);
expect(mockApiService.send).not.toHaveBeenCalled();
expect(mockLogService.warning).not.toHaveBeenCalled();
});
it("should return notifications API when state is null", async () => {
mockApiService.send.mockResolvedValue({
data: [
{
id: "notification-id",
},
] as NotificationViewResponse[],
});
fakeStateProvider.singleUser.mockFor("user-id" as UserId, NOTIFICATIONS, null as any);
const result = await firstValueFrom(service.notifications$("user-id" as UserId));
expect(result.length).toBe(1);
expect(mockApiService.send).toHaveBeenCalledWith(
"GET",
`/notifications?pageSize=${DEFAULT_NOTIFICATION_PAGE_SIZE}`,
null,
true,
true,
);
expect(mockLogService.warning).not.toHaveBeenCalled();
});
it("should log a warning if there are more notifications available", async () => {
mockApiService.send.mockResolvedValue({
data: [
...new Array(DEFAULT_NOTIFICATION_PAGE_SIZE + 1).fill({ id: "notification-id" }),
] as NotificationViewResponse[],
continuationToken: "next-token", // Presence of continuation token indicates more data
});
fakeStateProvider.singleUser.mockFor("user-id" as UserId, NOTIFICATIONS, null as any);
const result = await firstValueFrom(service.notifications$("user-id" as UserId));
expect(result.length).toBe(DEFAULT_NOTIFICATION_PAGE_SIZE + 1);
expect(mockApiService.send).toHaveBeenCalledWith(
"GET",
`/notifications?pageSize=${DEFAULT_NOTIFICATION_PAGE_SIZE}`,
null,
true,
true,
);
expect(mockLogService.warning).toHaveBeenCalledWith(
`More notifications available, but not fetched. Consider increasing the page size from ${DEFAULT_NOTIFICATION_PAGE_SIZE}`,
);
});
it("should share the same observable for the same user", async () => {
const first = service.notifications$("user-id" as UserId);
const second = service.notifications$("user-id" as UserId);
expect(first).toBe(second);
});
});
describe("unreadNotifications$", () => {
it("should return unread notifications from state when read value is null", async () => {
fakeStateProvider.singleUser.mockFor("user-id" as UserId, NOTIFICATIONS, [
{
id: "notification-id" as NotificationId,
readDate: null as any,
} as NotificationViewResponse,
]);
const result = await firstValueFrom(service.unreadNotifications$("user-id" as UserId));
expect(result.length).toBe(1);
expect(mockApiService.send).not.toHaveBeenCalled();
});
});
describe("getNotifications", () => {
it("should call getNotifications returning notifications from API", async () => {
mockApiService.send.mockResolvedValue({
data: [
{
id: "notification-id",
},
] as NotificationViewResponse[],
});
await service.refreshNotifications("user-id" as UserId);
expect(mockApiService.send).toHaveBeenCalledWith(
"GET",
`/notifications?pageSize=${DEFAULT_NOTIFICATION_PAGE_SIZE}`,
null,
true,
true,
);
});
it("should update local state when notifications are updated", async () => {
mockApiService.send.mockResolvedValue({
data: [
{
id: "notification-id",
},
] as NotificationViewResponse[],
});
const mock = fakeStateProvider.singleUser.mockFor(
"user-id" as UserId,
NOTIFICATIONS,
null as any,
);
await service.refreshNotifications("user-id" as UserId);
expect(mock.nextMock).toHaveBeenCalledWith([
expect.objectContaining({
id: "notification-id" as NotificationId,
} as NotificationViewResponse),
]);
});
});
describe("clear", () => {
it("should clear the local notification state for the user", async () => {
const mock = fakeStateProvider.singleUser.mockFor("user-id" as UserId, NOTIFICATIONS, [
{
id: "notification-id" as NotificationId,
} as NotificationViewResponse,
]);
await service.clearState("user-id" as UserId);
expect(mock.nextMock).toHaveBeenCalledWith([]);
});
});
describe("markAsDeleted", () => {
it("should send an API request to mark the notification as deleted", async () => {
await service.markAsDeleted("notification-id" as NotificationId, "user-id" as UserId);
expect(mockApiService.send).toHaveBeenCalledWith(
"DELETE",
"/notifications/notification-id/delete",
null,
true,
false,
);
});
});
describe("markAsRead", () => {
it("should send an API request to mark the notification as read", async () => {
await service.markAsRead("notification-id" as NotificationId, "user-id" as UserId);
expect(mockApiService.send).toHaveBeenCalledWith(
"PATCH",
"/notifications/notification-id/read",
null,
true,
false,
);
});
});
});

View File

@@ -0,0 +1,213 @@
import { concatMap, EMPTY, filter, map, Observable, Subscription, switchMap } from "rxjs";
import { ApiService } from "@bitwarden/common/abstractions/api.service";
import { AuthService } from "@bitwarden/common/auth/abstractions/auth.service";
import { AuthenticationStatus } from "@bitwarden/common/auth/enums/authentication-status";
import { NotificationType } from "@bitwarden/common/enums";
import { ListResponse } from "@bitwarden/common/models/response/list.response";
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
import { NotificationsService } from "@bitwarden/common/platform/notifications";
import { StateProvider } from "@bitwarden/common/platform/state";
import { NotificationId, UserId } from "@bitwarden/common/types/guid";
import {
filterOutNullish,
perUserCache$,
} from "@bitwarden/common/vault/utils/observable-utilities";
import { EndUserNotificationService } from "../abstractions/end-user-notification.service";
import { NotificationView, NotificationViewData, NotificationViewResponse } from "../models";
import { NOTIFICATIONS } from "../state/end-user-notification.state";
/**
* The default number of notifications to fetch from the API.
*/
export const DEFAULT_NOTIFICATION_PAGE_SIZE = 50;
const getLoggedInUserIds = map<Record<UserId, AuthenticationStatus>, UserId[]>((authStatuses) =>
Object.entries(authStatuses ?? {})
.filter(([, status]) => status >= AuthenticationStatus.Locked)
.map(([userId]) => userId as UserId),
);
/**
* A service for retrieving and managing notifications for end users.
*/
export class DefaultEndUserNotificationService implements EndUserNotificationService {
constructor(
private stateProvider: StateProvider,
private apiService: ApiService,
private notificationService: NotificationsService,
private authService: AuthService,
private logService: LogService,
) {}
notifications$ = perUserCache$((userId: UserId): Observable<NotificationView[]> => {
return this.notificationState(userId).state$.pipe(
switchMap(async (notifications) => {
if (notifications == null) {
await this.fetchNotificationsFromApi(userId);
return null;
}
return notifications;
}),
filterOutNullish(),
map((notifications) =>
notifications.map((notification) => new NotificationView(notification)),
),
);
});
unreadNotifications$ = perUserCache$((userId: UserId): Observable<NotificationView[]> => {
return this.notifications$(userId).pipe(
map((notifications) => notifications.filter((notification) => notification.readDate == null)),
);
});
async markAsRead(notificationId: NotificationId, userId: UserId): Promise<void> {
await this.apiService.send("PATCH", `/notifications/${notificationId}/read`, null, true, false);
await this.notificationState(userId).update((current) => {
const notification = current?.find((n) => n.id === notificationId);
if (notification) {
notification.readDate = new Date();
}
return current;
});
}
async markAsDeleted(notificationId: NotificationId, userId: UserId): Promise<void> {
await this.apiService.send(
"DELETE",
`/notifications/${notificationId}/delete`,
null,
true,
false,
);
await this.notificationState(userId).update((current) => {
const notification = current?.find((n) => n.id === notificationId);
if (notification) {
notification.deletedDate = new Date();
}
return current;
});
}
async clearState(userId: UserId): Promise<void> {
await this.replaceNotificationState(userId, []);
}
async refreshNotifications(userId: UserId) {
await this.fetchNotificationsFromApi(userId);
}
/**
* Helper observable to filter notifications by the notification type and user ids
* Returns EMPTY if no user ids are provided
* @param userIds
* @private
*/
private filteredEndUserNotifications$(userIds: UserId[]) {
if (userIds.length == 0) {
return EMPTY;
}
return this.notificationService.notifications$.pipe(
filter(
([{ type }, userId]) =>
(type === NotificationType.Notification ||
type === NotificationType.NotificationStatus) &&
userIds.includes(userId),
),
);
}
/**
* Creates a subscription to listen for end user push notifications and notification status updates.
*/
listenForEndUserNotifications(): Subscription {
return this.authService.authStatuses$
.pipe(
getLoggedInUserIds,
switchMap((userIds) => this.filteredEndUserNotifications$(userIds)),
concatMap(([notification, userId]) =>
this.upsertNotification(
userId,
new NotificationViewData(notification.payload as NotificationViewResponse),
),
),
)
.subscribe();
}
/**
* Fetches the notifications from the API and updates the local state
* @param userId
* @private
*/
private async fetchNotificationsFromApi(userId: UserId): Promise<void> {
const res = await this.apiService.send(
"GET",
`/notifications?pageSize=${DEFAULT_NOTIFICATION_PAGE_SIZE}`,
null,
true,
true,
);
const response = new ListResponse(res, NotificationViewResponse);
if (response.continuationToken != null) {
this.logService.warning(
`More notifications available, but not fetched. Consider increasing the page size from ${DEFAULT_NOTIFICATION_PAGE_SIZE}`,
);
}
const notificationData = response.data.map((n) => new NotificationViewData(n));
await this.replaceNotificationState(userId, notificationData);
}
/**
* Replaces the local state with notifications and returns the updated state
* @param userId
* @param notifications
* @private
*/
private replaceNotificationState(
userId: UserId,
notifications: NotificationViewData[],
): Promise<NotificationViewData[] | null> {
return this.notificationState(userId).update(() => notifications);
}
/**
* Updates the local state adding the new notification or updates an existing one with the same id
* Returns the entire updated notifications state
* @param userId
* @param notification
* @private
*/
private async upsertNotification(
userId: UserId,
notification: NotificationViewData,
): Promise<NotificationViewData[] | null> {
return this.notificationState(userId).update((current) => {
current ??= [];
const existingIndex = current.findIndex((n) => n.id === notification.id);
if (existingIndex === -1) {
current.push(notification);
} else {
current[existingIndex] = notification;
}
return current;
});
}
/**
* Returns the local state for notifications
* @param userId
* @private
*/
private notificationState(userId: UserId) {
return this.stateProvider.getUser(userId, NOTIFICATIONS);
}
}

View File

@@ -0,0 +1,15 @@
import { Jsonify } from "type-fest";
import { NOTIFICATION_DISK, UserKeyDefinition } from "@bitwarden/common/platform/state";
import { NotificationViewData } from "../models";
export const NOTIFICATIONS = UserKeyDefinition.array<NotificationViewData>(
NOTIFICATION_DISK,
"notifications",
{
deserializer: (notification: Jsonify<NotificationViewData>) =>
NotificationViewData.fromJSON(notification),
clearOn: ["logout", "lock"],
},
);