Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/servers/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export type Server = {
failed?: boolean;
webContentsId?: number;
userLoggedIn?: boolean;
userRoles?: string[];
gitCommitHash?: string;
allowedRedirects?: string[];
outlookCredentials?: OutlookCredentials;
Expand Down
3 changes: 3 additions & 0 deletions src/servers/preload/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import { setUserThemeAppearance } from './themeAppearance';
import { setTitle } from './title';
import { setUrlResolver } from './urls';
import { setUserLoggedIn } from './userLoggedIn';
import { setUserRoles } from './userRoles';

type ServerInfo = {
version: string;
Expand All @@ -59,6 +60,7 @@ type ExtendedIRocketChatDesktop = IRocketChatDesktop & {
callback: (payload: { phoneNumber: string; rawUri: string }) => void
) => void;
supportedDocumentViewerFormats: () => string[];
setUserRoles: (roles: string[]) => void;
};

declare global {
Expand Down Expand Up @@ -87,6 +89,7 @@ export const RocketChatDesktop: Window['RocketChatDesktop'] = {
setTitle,
setUserPresenceDetection,
setUserLoggedIn,
setUserRoles,
setUserThemeAppearance,
createNotification,
destroyNotification,
Expand Down
7 changes: 7 additions & 0 deletions src/servers/preload/userLoggedIn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { dispatch } from '../../store';
import { WEBVIEW_USER_LOGGED_IN } from '../../ui/actions';
import type { Server } from '../common';
import { getServerUrl } from './urls';
import { clearUserRoles, updateUserRoles } from './userRoles';

export const setUserLoggedIn = (userLoggedIn: Server['userLoggedIn']): void => {
dispatch({
Expand All @@ -11,4 +12,10 @@ export const setUserLoggedIn = (userLoggedIn: Server['userLoggedIn']): void => {
userLoggedIn,
},
});

if (userLoggedIn) {
void updateUserRoles();
} else {
clearUserRoles();
}
};
97 changes: 97 additions & 0 deletions src/servers/preload/userRoles.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import { dispatch } from '../../store';
import { WEBVIEW_USER_ROLES_CHANGED } from '../../ui/actions';
import { getServerUrl } from './urls';
import { clearUserRoles, setUserRoles, updateUserRoles } from './userRoles';

jest.mock('../../store', () => ({
dispatch: jest.fn(),
}));
jest.mock('./urls', () => ({
getServerUrl: jest.fn(() => 'https://rocket.chat'),
}));

const dispatchMock = dispatch as jest.MockedFunction<typeof dispatch>;
const getServerUrlMock = getServerUrl as jest.MockedFunction<
typeof getServerUrl
>;

describe('servers/preload/userRoles', () => {
const originalFetch = global.fetch;

const mockMeResponse = (roles: unknown): void => {
global.fetch = jest.fn().mockResolvedValue({
ok: true,
json: async () => ({ roles }),
}) as unknown as typeof global.fetch;
};

beforeEach(() => {
dispatchMock.mockClear();
getServerUrlMock.mockReturnValue('https://rocket.chat');
localStorage.setItem('Meteor.loginToken', 'token');
localStorage.setItem('Meteor.userId', 'user-id');
// Reset the module-level bridge flag between tests.
clearUserRoles();
dispatchMock.mockClear();
});

afterEach(() => {
global.fetch = originalFetch;
localStorage.clear();
});

it('dispatches roles pushed through the bridge', () => {
setUserRoles(['admin', 'user']);

expect(dispatchMock).toHaveBeenCalledWith({
type: WEBVIEW_USER_ROLES_CHANGED,
payload: { url: 'https://rocket.chat', userRoles: ['admin', 'user'] },
});
});

it('ignores non-string entries pushed through the bridge', () => {
setUserRoles(['admin', 42, null]);

expect(dispatchMock).toHaveBeenCalledWith({
type: WEBVIEW_USER_ROLES_CHANGED,
payload: { url: 'https://rocket.chat', userRoles: ['admin'] },
});
});

it('falls back to fetching /api/v1/me when the bridge has not provided roles', async () => {
mockMeResponse(['admin']);

await updateUserRoles();

expect(global.fetch).toHaveBeenCalledWith(
'https://rocket.chat/api/v1/me',
expect.objectContaining({
headers: { 'X-Auth-Token': 'token', 'X-User-Id': 'user-id' },
})
);
expect(dispatchMock).toHaveBeenCalledWith({
type: WEBVIEW_USER_ROLES_CHANGED,
payload: { url: 'https://rocket.chat', userRoles: ['admin'] },
});
});

it('skips the fetch fallback once the bridge has provided roles', async () => {
setUserRoles(['admin']);
dispatchMock.mockClear();
global.fetch = jest.fn() as unknown as typeof global.fetch;

await updateUserRoles();

expect(global.fetch).not.toHaveBeenCalled();
expect(dispatchMock).not.toHaveBeenCalled();
});

it('does not fetch when the session token is missing', async () => {
localStorage.removeItem('Meteor.loginToken');
global.fetch = jest.fn() as unknown as typeof global.fetch;

await updateUserRoles();

expect(global.fetch).not.toHaveBeenCalled();
});
});
86 changes: 86 additions & 0 deletions src/servers/preload/userRoles.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import { dispatch } from '../../store';
import { WEBVIEW_USER_ROLES_CHANGED } from '../../ui/actions';
import type { Server } from '../common';
import { getServerUrl } from './urls';

// When the web client pushes roles through the RocketChatDesktop.setUserRoles
// bridge, that source is authoritative and reactive, so the REST fallback must
// not override it. Older web clients never call the bridge, leaving this false
// and letting the fetch fallback run.
let rolesProvidedByBridge = false;

const dispatchUserRoles = (userRoles: Server['userRoles']): void => {
dispatch({
type: WEBVIEW_USER_ROLES_CHANGED,
payload: {
url: getServerUrl(),
userRoles,
},
});
};

const buildMeEndpoint = (serverUrl: string): string =>
`${serverUrl.replace(/\/$/, '')}/api/v1/me`;

/**
* Authoritative path: the web client observes its own reactive user and pushes
* roles. Reactive and free of token handling/REST. Takes precedence over the
* fetch fallback.
*/
export const setUserRoles = (roles: unknown): void => {
if (!Array.isArray(roles)) return;
const userRoles = roles.filter(
(role): role is string => typeof role === 'string'
);
rolesProvidedByBridge = true;
dispatchUserRoles(userRoles);
};

/**
* Fallback path for web clients that don't push roles through the bridge.
* Reads the logged-in user's roles from the workspace REST API. Skipped once
* the bridge has provided roles. Any failure leaves roles unset, which makes
* role-targeted messages fall back to being shown to everyone — the
* pre-existing behavior.
*/
export const updateUserRoles = async (): Promise<void> => {
if (rolesProvidedByBridge) return;

try {
const serverUrl = getServerUrl();
if (!serverUrl) return;

const authToken = localStorage.getItem('Meteor.loginToken');
const userId = localStorage.getItem('Meteor.userId');
if (!authToken || !userId) return;

const response = await fetch(buildMeEndpoint(serverUrl), {
headers: {
'X-Auth-Token': authToken,
'X-User-Id': userId,
},
});
if (!response.ok) return;

// The bridge may have resolved while the request was in flight; if so, keep
// the authoritative value.
if (rolesProvidedByBridge) return;

const data = await response.json();
const roles: unknown = data?.roles;
if (!Array.isArray(roles)) return;

const userRoles = roles.filter(
(role): role is string => typeof role === 'string'
);
dispatchUserRoles(userRoles);
Comment on lines +46 to +76

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Prevent stale roles from being persisted across failed or outdated fetches.

updateUserRoles can keep/apply stale role data: failed refresh paths never clear existing roles, and late async responses can overwrite state after auth context changes (logout/account switch). Guard the response against current auth context and clear stale roles before refresh.

💡 Suggested fix
 export const updateUserRoles = async (): Promise<void> => {
   try {
     const serverUrl = getServerUrl();
-    if (!serverUrl) return;
+    if (!serverUrl) {
+      dispatchUserRoles(undefined);
+      return;
+    }

     const authToken = localStorage.getItem('Meteor.loginToken');
     const userId = localStorage.getItem('Meteor.userId');
-    if (!authToken || !userId) return;
+    if (!authToken || !userId) {
+      dispatchUserRoles(undefined);
+      return;
+    }
+
+    // Avoid reusing stale roles while refresh is in flight.
+    dispatchUserRoles(undefined);

     const response = await fetch(buildMeEndpoint(serverUrl), {
       headers: {
         'X-Auth-Token': authToken,
         'X-User-Id': userId,
       },
     });
     if (!response.ok) return;

     const data = await response.json();
     const roles: unknown = data?.roles;
     if (!Array.isArray(roles)) return;

     const userRoles = roles.filter(
       (role): role is string => typeof role === 'string'
     );
+
+    // Drop stale responses if auth context changed while awaiting network/JSON.
+    if (
+      localStorage.getItem('Meteor.loginToken') !== authToken ||
+      localStorage.getItem('Meteor.userId') !== userId
+    ) {
+      return;
+    }
+
     dispatchUserRoles(userRoles);
   } catch {
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/servers/preload/userRoles.ts` around lines 26 - 50, The updateUserRoles
function can persist stale role data when async responses complete after the
authentication context changes (logout or account switch). After the fetch
completes in updateUserRoles, re-validate that the current authToken and userId
from localStorage still match the values used to initiate the fetch. If they do
not match, this indicates the user has logged out or switched accounts, and you
should call dispatchUserRoles with an empty array to clear stale roles instead
of persisting the fetched roles. Additionally, ensure that failed fetch
responses (when response.ok is false) also clear the existing roles by
dispatching an empty array rather than silently returning and leaving stale data
in place.

} catch {
// Network/parse errors are non-fatal: leave roles unset so role-targeted
// messages default to visible.
}
};

export const clearUserRoles = (): void => {
rolesProvidedByBridge = false;
dispatchUserRoles(undefined);
};
7 changes: 7 additions & 0 deletions src/servers/reducers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
WEBVIEW_TITLE_CHANGED,
WEBVIEW_UNREAD_CHANGED,
WEBVIEW_USER_LOGGED_IN,
WEBVIEW_USER_ROLES_CHANGED,
WEBVIEW_FAVICON_CHANGED,
WEBVIEW_DID_START_LOADING,
WEBVIEW_DID_FAIL_LOAD,
Expand Down Expand Up @@ -56,6 +57,7 @@ type ServersActionTypes =
| ActionOf<typeof WEBVIEW_TITLE_CHANGED>
| ActionOf<typeof WEBVIEW_UNREAD_CHANGED>
| ActionOf<typeof WEBVIEW_USER_LOGGED_IN>
| ActionOf<typeof WEBVIEW_USER_ROLES_CHANGED>
| ActionOf<typeof WEBVIEW_ALLOWED_REDIRECTS_CHANGED>
| ActionOf<typeof WEBVIEW_FAVICON_CHANGED>
| ActionOf<typeof APP_SETTINGS_LOADED>
Expand Down Expand Up @@ -195,6 +197,11 @@ export const servers: Reducer<Server[], ServersActionTypes> = (
return upsert(state, { url, userLoggedIn });
}

case WEBVIEW_USER_ROLES_CHANGED: {
const { url, userRoles } = action.payload;
return upsert(state, { url, userRoles });
}

case WEBVIEW_ALLOWED_REDIRECTS_CHANGED: {
const { url, allowedRedirects } = action.payload;
return upsert(state, { url, allowedRedirects });
Expand Down
66 changes: 66 additions & 0 deletions src/servers/supportedVersions/main.main.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -910,6 +910,72 @@ describe('supportedVersions/main.ts', () => {

expect(result.supported).toBe(false);
});

describe('message role targeting', () => {
const futureDate = new Date(Date.now() + 86400000);
const buildSupportedVersions = (roles?: string[]): SupportedVersions =>
({
enforcementStartDate: new Date(Date.now() + 172800000).toISOString(),
timestamp: new Date().toISOString(),
versions: [
{
version: '5.4.0',
expiration: futureDate,
},
],
messages: [
{
remainingDays: 30,
title: 'targeted',
subtitle: 'sub',
description: 'desc',
type: 'info',
...(roles ? { roles } : {}),
params: {},
link: '',
},
],
i18n: { en: {} },
}) as any;

it('shows a message with no roles to every user', async () => {
const result = await isServerVersionSupported(
{ ...mockServer, userRoles: ['user'] } as any,
buildSupportedVersions()
);

expect(result.message?.title).toBe('targeted');
});

it('shows a role-targeted message when the user has the role', async () => {
const result = await isServerVersionSupported(
{ ...mockServer, userRoles: ['admin', 'user'] } as any,
buildSupportedVersions(['admin'])
);

expect(result.message?.title).toBe('targeted');
});

it('hides a role-targeted message from users without the role', async () => {
const result = await isServerVersionSupported(
{ ...mockServer, userRoles: ['user'] } as any,
buildSupportedVersions(['admin'])
);

expect(result.supported).toBe(true);
expect(result.message).toBeUndefined();
});

it('hides a role-targeted message when user roles are unknown', async () => {
const result = await isServerVersionSupported(
mockServer as any,
buildSupportedVersions(['admin'])
);

expect(result.supported).toBe(true);
expect(result.message).toBeUndefined();
});
});
});

describe('Cache and Retry Integration', () => {
Expand Down
Loading
Loading