@kumori/aurora-backend-handler 1.0.130 → 1.0.132

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,11 @@
1
- import { Account, errors, Notification } from "@kumori/aurora-interfaces";
1
+ import {
2
+ Account,
3
+ errors,
4
+ Notification,
5
+ Tenant,
6
+ tenantRole,
7
+ } from "@kumori/aurora-interfaces";
8
+ import { AccountStatus } from "@kumori/aurora-interfaces/enums/accountStatusEnum";
2
9
  const CREDENTIAL_ERROR_CODES = new Set([
3
10
  "_error_retrieving_credentials_",
4
11
  "_invalid_account_credentials_",
@@ -184,6 +191,65 @@ export const syncAccountStatusFromNotifications = (
184
191
  }
185
192
  };
186
193
 
194
+ const invalidCredentialsNotifications = new Map<string, Notification>();
195
+ let lastInvalidCredentialsNotificationDate = 0;
196
+
197
+ const INVALID_CREDENTIALS_STATUSES = new Set<string>([
198
+ AccountStatus.INVALID_CREDENTIALS,
199
+ AccountStatus.INVALID_CREDENTIALS_SNAKE,
200
+ ]);
201
+
202
+ const CREDENTIALS_MANAGER_ROLES = new Set<string>([
203
+ tenantRole.OWNER,
204
+ tenantRole.ADMIN,
205
+ ]);
206
+
207
+ export const syncInvalidCredentialsNotifications = (
208
+ tenants: Iterable<Tenant>,
209
+ accounts: Iterable<Account>,
210
+ eventHelper: any,
211
+ ): void => {
212
+ const roleByTenant = new Map<string, string>();
213
+ for (const tenant of tenants) {
214
+ roleByTenant.set(tenant.id, tenant.role);
215
+ }
216
+
217
+ const pending = new Map<string, { tenant: string; account: string }>();
218
+ for (const account of accounts) {
219
+ if (!INVALID_CREDENTIALS_STATUSES.has(account.status)) continue;
220
+ if (!CREDENTIALS_MANAGER_ROLES.has(roleByTenant.get(account.tenant) ?? ""))
221
+ continue;
222
+ pending.set(`${account.tenant}/${account.name}`, {
223
+ tenant: account.tenant,
224
+ account: account.name,
225
+ });
226
+ }
227
+
228
+ invalidCredentialsNotifications.forEach((notification, key) => {
229
+ if (pending.has(key)) return;
230
+ invalidCredentialsNotifications.delete(key);
231
+ eventHelper.notification.publish.deletion(notification);
232
+ });
233
+
234
+ pending.forEach((data, key) => {
235
+ if (invalidCredentialsNotifications.has(key)) return;
236
+ lastInvalidCredentialsNotificationDate = Math.max(
237
+ Date.now(),
238
+ lastInvalidCredentialsNotificationDate + 1,
239
+ );
240
+ const notification: Notification = {
241
+ type: "error",
242
+ subtype: errors.account.invalidCredentials.subtype,
243
+ date: lastInvalidCredentialsNotificationDate.toString(),
244
+ status: "unread",
245
+ notificationType: "regular",
246
+ data,
247
+ };
248
+ invalidCredentialsNotifications.set(key, notification);
249
+ eventHelper.notification.publish.creation(notification);
250
+ });
251
+ };
252
+
187
253
  /**
188
254
  * Handles the "account" kind event from WebSocket messages.
189
255
  */
@@ -97,6 +97,21 @@ export const handleTokenEvent = ({
97
97
  };
98
98
  }
99
99
  };
100
+ export const applyKnownTokenData = (
101
+ tokens: Token[],
102
+ tokenMap: Map<string, Token>
103
+ ): Token[] =>
104
+ tokens.map((userToken) => {
105
+ const known = tokenMap.get(userToken.name);
106
+ if (!known) return userToken;
107
+ const token = known.token || userToken.token;
108
+ const lastUsed = known.lastUsed || userToken.lastUsed;
109
+ if (token === userToken.token && lastUsed === userToken.lastUsed) {
110
+ return userToken;
111
+ }
112
+ return { ...userToken, token, lastUsed };
113
+ });
114
+
100
115
  interface HandleTokenOperationSuccessParams {
101
116
  responsePayload: any;
102
117
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kumori/aurora-backend-handler",
3
- "version": "1.0.130",
3
+ "version": "1.0.132",
4
4
  "description": "backend handler",
5
5
  "main": "backend-handler.ts",
6
6
  "scripts": {
@@ -11,7 +11,7 @@
11
11
  "glob": "^11.0.0"
12
12
  },
13
13
  "dependencies": {
14
- "@kumori/aurora-interfaces": "1.0.39",
14
+ "@kumori/aurora-interfaces": "^1.0.40",
15
15
  "@kumori/kumori-dsl-generator": "1.0.11",
16
16
  "@kumori/kumori-module-generator": "^1.1.6",
17
17
  "ts-node": "^10.9.2",
@@ -0,0 +1,144 @@
1
+ import { Account, Tenant } from '@kumori/aurora-interfaces';
2
+ import { syncInvalidCredentialsNotifications } from '../helpers/account-helper';
3
+
4
+ const buildTenant = (id: string, role: string) =>
5
+ ({ id, name: id, role }) as unknown as Tenant;
6
+
7
+ const buildAccount = (tenant: string, name: string, status: string) =>
8
+ ({ id: name, name, tenant, status }) as unknown as Account;
9
+
10
+ const buildEventHelper = () => ({
11
+ notification: { publish: { creation: jest.fn(), deletion: jest.fn() } },
12
+ });
13
+
14
+ describe('syncInvalidCredentialsNotifications', () => {
15
+ afterEach(() => {
16
+ syncInvalidCredentialsNotifications([], [], buildEventHelper());
17
+ });
18
+
19
+ it.each(['owner', 'admin'])(
20
+ 'crea la notificacion ACC-01 para una cuenta con credenciales invalidas cuando el rol es %s',
21
+ (role) => {
22
+ const eventHelper = buildEventHelper();
23
+
24
+ syncInvalidCredentialsNotifications(
25
+ [buildTenant('tenant-a', role)],
26
+ [buildAccount('tenant-a', 'account-a', 'invalid_credentials')],
27
+ eventHelper,
28
+ );
29
+
30
+ expect(eventHelper.notification.publish.creation).toHaveBeenCalledTimes(1);
31
+ expect(eventHelper.notification.publish.creation).toHaveBeenCalledWith(
32
+ expect.objectContaining({
33
+ type: 'error',
34
+ subtype: 'account-invalid-credentials',
35
+ status: 'unread',
36
+ notificationType: 'regular',
37
+ data: { tenant: 'tenant-a', account: 'account-a' },
38
+ }),
39
+ );
40
+ },
41
+ );
42
+
43
+ it('reconoce tambien el estado InvalidCredentials del evento del backend', () => {
44
+ const eventHelper = buildEventHelper();
45
+
46
+ syncInvalidCredentialsNotifications(
47
+ [buildTenant('tenant-b', 'owner')],
48
+ [buildAccount('tenant-b', 'account-b', 'InvalidCredentials')],
49
+ eventHelper,
50
+ );
51
+
52
+ expect(eventHelper.notification.publish.creation).toHaveBeenCalledTimes(1);
53
+ });
54
+
55
+ it('no crea nada para un rol plain, un tenant desconocido o una cuenta con otro estado', () => {
56
+ const eventHelper = buildEventHelper();
57
+
58
+ syncInvalidCredentialsNotifications(
59
+ [buildTenant('tenant-c', 'plain'), buildTenant('tenant-d', 'owner')],
60
+ [
61
+ buildAccount('tenant-c', 'account-c', 'invalid_credentials'),
62
+ buildAccount('tenant-unknown', 'account-x', 'invalid_credentials'),
63
+ buildAccount('tenant-d', 'account-d', 'active'),
64
+ buildAccount('tenant-d', 'account-e', 'pending'),
65
+ ],
66
+ eventHelper,
67
+ );
68
+
69
+ expect(eventHelper.notification.publish.creation).not.toHaveBeenCalled();
70
+ expect(eventHelper.notification.publish.deletion).not.toHaveBeenCalled();
71
+ });
72
+
73
+ it('no duplica la notificacion mientras la cuenta sigue con credenciales invalidas', () => {
74
+ const eventHelper = buildEventHelper();
75
+ const tenants = [buildTenant('tenant-e', 'admin')];
76
+ const accounts = [buildAccount('tenant-e', 'account-f', 'invalid_credentials')];
77
+
78
+ syncInvalidCredentialsNotifications(tenants, accounts, eventHelper);
79
+ syncInvalidCredentialsNotifications(tenants, accounts, eventHelper);
80
+
81
+ expect(eventHelper.notification.publish.creation).toHaveBeenCalledTimes(1);
82
+ });
83
+
84
+ it('descarta la notificacion cuando la cuenta vuelve a un estado valido', () => {
85
+ const eventHelper = buildEventHelper();
86
+ const tenants = [buildTenant('tenant-f', 'owner')];
87
+
88
+ syncInvalidCredentialsNotifications(
89
+ tenants,
90
+ [buildAccount('tenant-f', 'account-g', 'invalid_credentials')],
91
+ eventHelper,
92
+ );
93
+ const created = eventHelper.notification.publish.creation.mock.calls[0][0];
94
+
95
+ syncInvalidCredentialsNotifications(
96
+ tenants,
97
+ [buildAccount('tenant-f', 'account-g', 'active')],
98
+ eventHelper,
99
+ );
100
+
101
+ expect(eventHelper.notification.publish.deletion).toHaveBeenCalledTimes(1);
102
+ expect(eventHelper.notification.publish.deletion).toHaveBeenCalledWith(created);
103
+ });
104
+
105
+ it('descarta la notificacion cuando la cuenta se elimina o el usuario deja de gestionar el tenant', () => {
106
+ const eventHelper = buildEventHelper();
107
+
108
+ syncInvalidCredentialsNotifications(
109
+ [buildTenant('tenant-g', 'owner'), buildTenant('tenant-h', 'admin')],
110
+ [
111
+ buildAccount('tenant-g', 'account-h', 'invalid_credentials'),
112
+ buildAccount('tenant-h', 'account-i', 'invalid_credentials'),
113
+ ],
114
+ eventHelper,
115
+ );
116
+
117
+ syncInvalidCredentialsNotifications(
118
+ [buildTenant('tenant-g', 'owner'), buildTenant('tenant-h', 'plain')],
119
+ [buildAccount('tenant-h', 'account-i', 'invalid_credentials')],
120
+ eventHelper,
121
+ );
122
+
123
+ expect(eventHelper.notification.publish.creation).toHaveBeenCalledTimes(2);
124
+ expect(eventHelper.notification.publish.deletion).toHaveBeenCalledTimes(2);
125
+ });
126
+
127
+ it('asigna fechas estrictamente crecientes a notificaciones creadas a la vez', () => {
128
+ const eventHelper = buildEventHelper();
129
+
130
+ syncInvalidCredentialsNotifications(
131
+ [buildTenant('tenant-i', 'owner')],
132
+ [
133
+ buildAccount('tenant-i', 'account-j', 'invalid_credentials'),
134
+ buildAccount('tenant-i', 'account-k', 'invalid_credentials'),
135
+ ],
136
+ eventHelper,
137
+ );
138
+
139
+ const [first, second] = eventHelper.notification.publish.creation.mock.calls.map(
140
+ ([notification]: [{ date: string }]) => Number(notification.date),
141
+ );
142
+ expect(second).toBeGreaterThan(first);
143
+ });
144
+ });
@@ -55,6 +55,7 @@ import {
55
55
  handleAccountOperationError,
56
56
  handleAccountOperationSuccess,
57
57
  syncAccountStatusFromNotifications,
58
+ syncInvalidCredentialsNotifications,
58
59
  } from "./helpers/account-helper";
59
60
  import {
60
61
  handleCAEvent,
@@ -72,6 +73,7 @@ import {
72
73
  } from "./helpers/plan-helper";
73
74
  import { handleRegistryEvent } from "./helpers/registry-helper";
74
75
  import {
76
+ applyKnownTokenData,
75
77
  handleTokenDeletion,
76
78
  handleTokenEvent,
77
79
  handleTokenOperationSuccess,
@@ -678,6 +680,11 @@ const computePromotionInfo = (
678
680
 
679
681
  const rebuildHierarchy = () => {
680
682
  const preservedUserData = { ...userData };
683
+ syncInvalidCredentialsNotifications(
684
+ tenantsMap.values(),
685
+ accountsMap.values(),
686
+ eventHelper,
687
+ );
681
688
 
682
689
  tenantsMap.forEach((tenant) => {
683
690
  tenant.accounts = Array.from(accountsMap.values()).filter((account) => {
@@ -717,11 +724,13 @@ const rebuildHierarchy = () => {
717
724
  notificationsEnabled: preservedUserData.notificationsEnabled,
718
725
  organizations: Array.from(organizationsMap.values()),
719
726
  clusterTokens: Array.from(clusterTokensMap.values()),
720
- tokens: (
721
- tokenMap.size > 0
727
+ tokens: applyKnownTokenData(
728
+ (tokenMap.size > 0
722
729
  ? (preservedUserData.tokens || []).filter(t => tokenMap.has(t.name))
723
730
  : (preservedUserData.tokens || [])
724
- ).filter(t => !deletedTokenIds.has(t.name)),
731
+ ).filter(t => !deletedTokenIds.has(t.name)),
732
+ tokenMap,
733
+ ),
725
734
  tenants: Array.from(tenantsMap.values()),
726
735
  axebowPlan: preservedUserData.axebowPlan,
727
736
  companyName: preservedUserData.companyName,
@@ -900,6 +909,7 @@ const handleEvent = async (message: WSMessage) => {
900
909
  ...serviceResult.updatedPendingRevisionErrors,
901
910
  );
902
911
 
912
+ const isFirstSightingOfService = !servicesMap.has(serviceResult.serviceFullKey);
903
913
  const resolvedService = resolveServiceStatus(serviceResult.service);
904
914
  servicesMap.set(serviceResult.serviceFullKey, resolvedService);
905
915
 
@@ -922,6 +932,14 @@ const handleEvent = async (message: WSMessage) => {
922
932
  eventHelper.service.publish.deployed(resolvedService);
923
933
  }
924
934
  }
935
+ if (
936
+ isFirstSightingOfService &&
937
+ resolvedService.error &&
938
+ resolvedService.status?.code !== "REMOVING_SERVICE" &&
939
+ !eventData.meta?.deleted
940
+ ) {
941
+ eventHelper.service.publish.deploymentError(resolvedService);
942
+ }
925
943
  const serviceState = eventData.status?.state?.code;
926
944
  if (serviceState === "SERVICE_READY") {
927
945
  const serviceKey = `${parentParts.tenant}/${entityId}`;
@@ -2164,10 +2182,13 @@ export const updateUserComplete = (updatedUserData: UserData): User => {
2164
2182
  const localOnlyTokens = (userData.tokens || []).filter(
2165
2183
  (t) => !incomingTokenNames.has(t.name)
2166
2184
  );
2167
- const mergedTokens = [...(updatedUserData.tokens || []), ...localOnlyTokens]
2168
- .filter((t, index, arr) => arr.findIndex(x => x.name === t.name) === index)
2169
- .filter(t => tokenMap.size === 0 || tokenMap.has(t.name))
2170
- .filter(t => !deletedTokenIds.has(t.name));
2185
+ const mergedTokens = applyKnownTokenData(
2186
+ [...(updatedUserData.tokens || []), ...localOnlyTokens]
2187
+ .filter((t, index, arr) => arr.findIndex(x => x.name === t.name) === index)
2188
+ .filter(t => tokenMap.size === 0 || tokenMap.has(t.name))
2189
+ .filter(t => !deletedTokenIds.has(t.name)),
2190
+ tokenMap,
2191
+ );
2171
2192
 
2172
2193
  userData = {
2173
2194
  id: updatedUserData.id || userData.id,