Skip to content

Commit

Permalink
Fix web_resources match patterns (#178)
Browse files Browse the repository at this point in the history
* Fix web_resources match patterns
  • Loading branch information
karaggeorge authored Sep 14, 2024
1 parent d829630 commit 85d2bc0
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@

import { cleanMatches } from "../clean-matches";

describe('cleanMatches', () => {
it('does not handle non-urls', () => {
expect(cleanMatches(['<all_urls>'])).toEqual(['<all_urls>']);
});

it('handles wildcards', () => {
expect(
cleanMatches([
'*://*/some/path',
'https://*.google.com/foo*bar',
])
).toEqual([
'*://*/*',
'https://*.google.com/*',
]);
});

it('cleans up all types of pathnames', () => {
expect(
cleanMatches([
'https://example.com',
'https://example.com/some/path/*',
'https://example.com/some/path',
])
).toEqual([
'https://example.com/*',
'https://example.com/*',
'https://example.com/*',
]);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@

/**
* From the docs at https://developer.chrome.com/docs/extensions/reference/manifest/web-accessible-resources#manifest_declaration
* > Google Chrome emits an "Invalid match pattern" error if the pattern has a path other than '/*'.
*
* We need to ensure that paths are cleaned up from the matches to avoid this error.
*/
export function cleanMatches(matches: string[]) {
return matches.map(match => {
try {
const url = new URL(
// Using a wildcard for the scheme (`*://`) is supported, but URL cannot parse it
match.replace(/^\*:\/\//, 'https://')
);

// URL.pathname will return `/` even if the URL is just `https://example.com`
if (match.endsWith(url.pathname)) {
return `${match.substring(0, match.length - url.pathname.length)}/*`;
} else if (url.pathname === '/') {
return `${match}/*`;
}

return match;
} catch {
// Special cases like <all_urls> will fail the URL parse, but we can ignore them
return match;
}
})
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
type Manifest
} from '../../webpack-types'
import * as utils from '../../lib/utils'
import { cleanMatches } from './clean-matches'

/**
* ResourcesPlugin is responsible for adding resources required
Expand Down Expand Up @@ -64,7 +65,9 @@ export class WebResourcesPlugin {
resources: resources.filter(
(resource) => !resource.endsWith('.map')
),
matches
// We pass `matches` from `content_scripts` to `web_accessible_resources`,
// but `web_accessible_resources` has stricter rules, so we need to sanitize them
matches: cleanMatches(matches),
})
}
} else {
Expand Down

0 comments on commit 85d2bc0

Please sign in to comment.