Repository navigation
feat(supportedVersions): role-targeted expiration messages #3371
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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(); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| } 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); | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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.
updateUserRolescan 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