Skip to content
Merged
2 changes: 1 addition & 1 deletion src/libs/Navigation/helpers/getAdaptedStateFromPath.ts
Original file line number Diff line number Diff line change
Expand Up @@ -429,7 +429,7 @@ function getAdaptedState(state: PartialState<NavigationState<RootNavigatorParamL
*/
// We keep `options` in the signature for `linkingConfig` compatibility with react-navigation.
const getAdaptedStateFromPath: GetAdaptedStateFromPath = (path, options, shouldReplacePathInNestedState = true) => {
let normalizedPath = !path.startsWith('/') ? `/${path}` : path;
let normalizedPath = normalizePath(path);
normalizedPath = getMatchingNewRoute(normalizedPath) ?? normalizedPath;

const state = getStateFromPath(normalizedPath as RoutePath) as PartialState<NavigationState<RootNavigatorParamList>>;
Expand Down
7 changes: 2 additions & 5 deletions src/libs/Navigation/helpers/getPathFromState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import isDynamicRouteScreen from './dynamicRoutesUtils/isDynamicRouteScreen';
import joinPathSegments from './dynamicRoutesUtils/joinPathSegments';
import splitPathAndQuery from './dynamicRoutesUtils/splitPathAndQuery';
import findFocusedRouteWithOnyxTabGuard from './findFocusedRouteWithOnyxTabGuard';
import {collapseRepeatedSlashes} from './normalizePath';

function isScreen(name: string): name is Screen {
return name in normalizedConfigs;
Expand Down Expand Up @@ -167,11 +168,7 @@ function getPathFromStateWithDynamicRoute(state: State): string {

const combinedPath = joinPathSegments(`${basePathWithoutQuery}`, `${suffixPath}`);

// Safety net for this hand-built dynamic branch: guarantee exactly one leading slash and no internal `//`,
// so the browser never parses a segment as a host and `history.pushState` can't throw a SecurityError.
// React Navigation's own `getPathFromState` already normalizes slashes, so the standard-screen branch
// doesn't need this.
const normalizedPath = `/${combinedPath}`.replaceAll(/\/{2,}/g, '/');
const normalizedPath = collapseRepeatedSlashes(`/${combinedPath}`);
if (normalizedPath !== combinedPath) {
// Log `screenName` only - the path can carry sensitive query params that shouldn't be shared.
Log.alert('[Navigation] getPathFromStateWithDynamicRoute produced a malformed path', {screenName});
Expand Down
3 changes: 2 additions & 1 deletion src/libs/Navigation/helpers/getStateFromPath.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,14 @@ import getPathWithoutDynamicSuffix from './dynamicRoutesUtils/getPathWithoutDyna
import getStateForDynamicRoute from './dynamicRoutesUtils/getStateForDynamicRoute';
import findFocusedRouteWithOnyxTabGuard from './findFocusedRouteWithOnyxTabGuard';
import getMatchingNewRoute from './getMatchingNewRoute';
import normalizePath from './normalizePath';

/**
* @param path - The path to parse
* @returns - It's possible that there is no navigation action for the given path
*/
function getStateFromPath(path: Route): PartialState<NavigationState> {
const normalizedPath = !path.startsWith('/') ? `/${path}` : path;
const normalizedPath = normalizePath(path);
const normalizedPathAfterRedirection = getMatchingNewRoute(normalizedPath) ?? normalizedPath;

// Collect all syntactic matches and validate each one against entryScreens.
Expand Down
30 changes: 28 additions & 2 deletions src/libs/Navigation/helpers/normalizePath.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,32 @@
// Expensify uses path with leading '/' but react-navigation doesn't. This function normalizes the path to add the leading '/' for consistency.
import Log from '@libs/Log';
import {sanitizeUrlForLogging} from '@libs/sanitizeLogParams';

/**
* Collapses runs of two or more slashes into one. Pass the pathname only: a query or fragment can legitimately
* carry '//'. Three or more slashes resolve the same way as two, which is why this matches `{2,}`.
*/
function collapseRepeatedSlashes(path: string): string {
return path.replaceAll(/\/{2,}/g, '/');
}

/**
* Adds the leading '/' Expensify paths use but react-navigation doesn't, and collapses repeated slashes.
*/
function normalizePath(path: string) {
return !path.startsWith('/') ? `/${path}` : path;
const suffixIndex = path.search(/[?#]/);
const pathOnly = suffixIndex === -1 ? path : path.slice(0, suffixIndex);
const suffix = suffixIndex === -1 ? '' : path.slice(suffixIndex);

const collapsedPath = collapseRepeatedSlashes(pathOnly);

if (pathOnly.includes('//')) {
// The collapsed path is logged, not the raw one: repeated slashes break the `/v/:accountID/:validateCode`
// pattern `sanitizeUrlForLogging` matches on, so redaction only works once they're gone.
Log.alert('[Navigation] normalizePath received a malformed path', {path: sanitizeUrlForLogging(collapsedPath)});
}

return `${collapsedPath.startsWith('/') ? collapsedPath : `/${collapsedPath}`}${suffix}`;
}

export default normalizePath;
export {collapseRepeatedSlashes};
64 changes: 64 additions & 0 deletions tests/navigation/normalizePathTests.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import Log from '@libs/Log';
import normalizePath from '@libs/Navigation/helpers/normalizePath';

const mockLogAlert = jest.spyOn(Log, 'alert').mockImplementation(() => {});

describe('normalizePath', () => {
beforeEach(() => {
jest.clearAllMocks();
});

it('adds the leading slash', () => {
expect(normalizePath('settings/profile')).toBe('/settings/profile');
});

it('leaves a well-formed path untouched and does not alert', () => {
expect(normalizePath('/settings/profile')).toBe('/settings/profile');
expect(mockLogAlert).not.toHaveBeenCalled();
});

// A '//' path is protocol-relative to the browser, so pushState rejects it (#97470).
it.each([
['//settings/profile', '/settings/profile'],
['///settings/profile', '/settings/profile'],
['////workspaces/ABC123/accounting', '/workspaces/ABC123/accounting'],
['/workspaces//ABC123/accounting', '/workspaces/ABC123/accounting'],
])('collapses repeated slashes: %s', (input, expected) => {
expect(normalizePath(input)).toBe(expected);
});

it('alerts once for a malformed path, logging it without the query', () => {
normalizePath('//settings/profile?q=secret');

expect(mockLogAlert).toHaveBeenCalledTimes(1);
expect(mockLogAlert).toHaveBeenCalledWith(expect.stringContaining('malformed path'), {path: '/settings/profile'});
expect(JSON.stringify(mockLogAlert.mock.calls)).not.toContain('secret');
});

// Redaction relies on the `/v/:accountID/:validateCode` shape, which repeated slashes break, so the
// collapsed path is what gets logged.
it.each(['//v/123/CODE123', '/v//123/CODE123', '/v/123//CODE123', '//u/456/CODE123'])('redacts the validate code in %s', (input) => {
normalizePath(input);

expect(JSON.stringify(mockLogAlert.mock.calls)).not.toContain('CODE123');
expect(JSON.stringify(mockLogAlert.mock.calls)).toContain('redacted');
});

it('keeps a fragment intact, including a slash pair inside it', () => {
expect(normalizePath('//home#https://example.com')).toBe('/home#https://example.com');
});

it('does not alert for a fragment that contains a slash pair when the path is fine', () => {
expect(normalizePath('/home#https://example.com')).toBe('/home#https://example.com');
expect(mockLogAlert).not.toHaveBeenCalled();
});

it('keeps the query intact, including a slash pair inside a param', () => {
expect(normalizePath('//search?q=a&backTo=https://example.com')).toBe('/search?q=a&backTo=https://example.com');
});

it('does not alert for a query that contains a slash pair when the path is fine', () => {
expect(normalizePath('/search?backTo=https://example.com')).toBe('/search?backTo=https://example.com');
expect(mockLogAlert).not.toHaveBeenCalled();
});
});
Loading