12 |
13 |
14 |
53 |
--------------------------------------------------------------------------------
/docs/contributing.md:
--------------------------------------------------------------------------------
1 | # How to Contribute
2 |
3 | We would love to accept your patches and contributions to this project.
4 |
5 | ## Before you begin
6 |
7 | ### Sign our Contributor License Agreement
8 |
9 | Contributions to this project must be accompanied by a
10 | [Contributor License Agreement](https://cla.developers.google.com/about) (CLA).
11 | You (or your employer) retain the copyright to your contribution; this simply
12 | gives us permission to use and redistribute your contributions as part of the
13 | project.
14 |
15 | If you or your current employer have already signed the Google CLA (even if it
16 | was for a different project), you probably don't need to do it again.
17 |
18 | Visit to see your current agreements or to
19 | sign a new one.
20 |
21 | ### Review our Community Guidelines
22 |
23 | This project follows [Google's Open Source Community
24 | Guidelines](https://opensource.google/conduct/).
25 |
26 | ## Contribution process
27 |
28 | ### Code Reviews
29 |
30 | All submissions, including submissions by project members, require review. We
31 | use [GitHub pull requests](https://docs.github.com/articles/about-pull-requests)
32 | for this purpose.
33 |
--------------------------------------------------------------------------------
/src/views/RulesEditorView.vue:
--------------------------------------------------------------------------------
1 |
23 |
24 |
25 |
26 |
17 |
18 | How to Use:
19 | 1. Upload Your Manifest File:
20 | Click on the "Upload Manifest" section or drag and drop your
21 | manifest.json file. Ensure that the file contains all
22 | necessary fields.
23 |
24 | 2. Upload Ruleset Files:
25 | After uploading the manifest, proceed to upload one or more ruleset
26 | files by clicking the "Upload Ruleset Files" section or by dragging
27 | and dropping them. Files should be in JSON format and follow the
28 | specified ruleset structure.
29 |
30 | 3. Create HTTP Requests to find the matching rule:
32 | Fill out the form and click submit to see the matching rule.
33 |
34 | 4. Review and Modify Rules:
35 | Once uploaded, your rules will be displayed in the rules editor. You
36 | can review, modify, or delete rules directly within this editor.
49 |
50 |
53 |
54 |
55 |
56 |
121 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | # Interactive DNR Tool
3 | ## About
4 | The goal of this project is to create a user-friendly web application that helps extension developers make extensions that use the [declarativeNetRequest API](https://developer.chrome.com/docs/extensions/reference/api/declarativeNetRequest). It aims to provide a visual representation of the flow of data and the execution of rules, helping developers monitor, preview and debug their extensions’ behaviour effectively.
5 |
6 | Complete project proposal: [GSoC '24 Proposal - DNR Interactive Tool for Chrome Extensions](https://docs.google.com/document/d/1u1KM-eUJV1uFelV0dwjk4DaX8g7enOsITz9cWW7NVq4/edit?usp=sharing)
7 |
8 | ## Installation
9 |
10 | To set up and run this project locally, follow these steps:
11 |
12 | 1. __Clone the Repository__: Clone the project repository to your local machine using the command `git clone https://github.com/GoogleChromeLabs/interactive-dnr-tool.git`.
13 | 2. __Navigate to the Project Directory__: Open your command line tool and navigate to the project directory using `cd interactive-dnr-tool`.
14 | 3. __Install Dependencies__: Run `npm install` to install all the necessary packages and dependencies.
15 | 4. __Run the Project__: Start the development server by running `npm run dev`. Open your web browser and go to the specified port to view the application.
16 |
17 | If you encounter any issues during installation, make sure all dependencies are correctly installed, review any error messages for clues, and check the project documentation or open an issue on GitHub for further assistance.
18 |
19 |
20 | ## How to Use
21 | To use this tool, you need to acquire the extension's source code and do the following:
22 |
23 | 1. __Upload Your Manifest File:__ Click on the "Upload Manifest" section or drag and drop your `manifest.json` file. Ensure that the file contains all necessary fields.
24 | 2. __Upload Ruleset files:__ After uploading the manifest, proceed to upload one or more ruleset files by clicking the "Upload Ruleset Files" section or by dragging and dropping them. Files should be in JSON format and follow the specified ruleset structure.
25 | 3. __Create HTTP Requests to find the matching rule:__ Fill out the form and click submit to see the matching rule.
26 | 4. __Review and Modify Rules:__ Once uploaded, your rules will be displayed in the rules editor. You can review, modify, or delete rules directly within this editor.
27 |
28 | ## TODO
29 | This project is still a long way from being complete, so contributions are welcome!
30 |
31 | 1. Animations to show events like when a rule matches a request, and improving user experience, flow of usage, and general look-and-feel (includes using properly licensed images)
32 | 2. Functionality to export modified rulesets
33 | 3. Embedding URL filter string parsing component as part of the [documentation](https://developer.chrome.com/docs/extensions/reference/api/declarativeNetRequest)
34 | 4. Including [response headers](https://github.com/w3c/webextensions/issues/460)
35 | 5. Writing tests, especially for key functions such as URL filter string parsing and matching
36 | 6. Enabling more requests types and with specific headers, the frame that made the request, etc.
37 |
--------------------------------------------------------------------------------
/src/utils.js:
--------------------------------------------------------------------------------
1 | // Checks validity of URLFilter string
2 | function isValidURLFilter(urlFilterString) {
3 | // Ensure only valid constructs are present
4 | const validConstructs = /^[*|^a-zA-Z0-9_\-.%?/;=@&:]+$/;
5 | if (!validConstructs.test(urlFilterString)) {
6 | return false; // Invalid constructs present
7 | }
8 | // Check for ASCII characters
9 | for (let i = 0; i < urlFilterString.length; i++) {
10 | if (urlFilterString.charCodeAt(i) > 127) {
11 | return false; // Non-ASCII character found
12 | }
13 | }
14 | if (urlFilterString.startsWith('||*')) {
15 | return false; // Cannot start with ||* - use only * at the beginning for the intended effect.
16 | }
17 | if (urlFilterString.includes('|') && !urlFilterString.includes('||')) {
18 | if (!urlFilterString.startsWith('|') && !urlFilterString.endsWith('|')) {
19 | return false; // Cannot start or end without |.
20 | }
21 | if (urlFilterString.length === 1) {
22 | return false; // Cannot have only |.
23 | }
24 | }
25 | if (urlFilterString.includes('||')) {
26 | if (!urlFilterString.startsWith('||')) {
27 | return false; // Cannot have || in the middle.
28 | }
29 | if (urlFilterString.length === 2) {
30 | return false; // Cannot have only ||.
31 | }
32 | if (
33 | urlFilterString.slice(2).includes('|') &&
34 | !urlFilterString.endsWith('|')
35 | ) {
36 | return false; // Cannot have | in the middle.
37 | }
38 | }
39 | if (
40 | urlFilterString.slice(1, -1).includes('|') &&
41 | urlFilterString.slice(0, 2) !== '||'
42 | ) {
43 | return false; // Cannot have | in the middle.
44 | }
45 | return true;
46 | }
47 | function sortRules(parsedRulesList) {
48 | parsedRulesList.sort((a, b) => {
49 | // Compare by developer-defined priority
50 | if (a.rule.priority !== b.rule.priority) {
51 | return b.rule.priority - a.rule.priority;
52 | }
53 |
54 | // If priorities are equal, compare by action field
55 | const actionOrder = [
56 | 'allow',
57 | 'allowAllRequests',
58 | 'block',
59 | 'upgradeScheme',
60 | 'redirect'
61 | ];
62 | const aActionIndex = actionOrder.indexOf(a.rule.action.type);
63 | const bActionIndex = actionOrder.indexOf(b.rule.action.type);
64 |
65 | if (aActionIndex !== bActionIndex) {
66 | return aActionIndex - bActionIndex;
67 | }
68 |
69 | // If both priority and action type are the same, compare modifyHeaders rules
70 | if (a.rule.action.type !== 'block' && a.rule.action.type !== 'redirect') {
71 | const aModifyHeaders = a.rule.action.modifyHeaders || [];
72 | const bModifyHeaders = b.rule.action.modifyHeaders || [];
73 |
74 | for (
75 | let i = 0;
76 | i < Math.min(aModifyHeaders.length, bModifyHeaders.length);
77 | i++
78 | ) {
79 | const aHeader = aModifyHeaders[i];
80 | const bHeader = bModifyHeaders[i];
81 |
82 | // Compare header modification operations
83 | if (aHeader.operation !== bHeader.operation) {
84 | const operationOrder = ['append', 'set', 'remove'];
85 | const aOperationIndex = operationOrder.indexOf(aHeader.operation);
86 | const bOperationIndex = operationOrder.indexOf(bHeader.operation);
87 | return aOperationIndex - bOperationIndex;
88 | }
89 | }
90 | }
91 |
92 | // If all criteria are the same, retain original order
93 | return 0;
94 | });
95 | }
96 |
97 | export { isValidURLFilter, sortRules };
98 |
--------------------------------------------------------------------------------
/docs/code-of-conduct.md:
--------------------------------------------------------------------------------
1 | # Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | In the interest of fostering an open and welcoming environment, we as
6 | contributors and maintainers pledge to making participation in our project and
7 | our community a harassment-free experience for everyone, regardless of age, body
8 | size, disability, ethnicity, gender identity and expression, level of
9 | experience, education, socio-economic status, nationality, personal appearance,
10 | race, religion, or sexual identity and orientation.
11 |
12 | ## Our Standards
13 |
14 | Examples of behavior that contributes to creating a positive environment
15 | include:
16 |
17 | * Using welcoming and inclusive language
18 | * Being respectful of differing viewpoints and experiences
19 | * Gracefully accepting constructive criticism
20 | * Focusing on what is best for the community
21 | * Showing empathy towards other community members
22 |
23 | Examples of unacceptable behavior by participants include:
24 |
25 | * The use of sexualized language or imagery and unwelcome sexual attention or
26 | advances
27 | * Trolling, insulting/derogatory comments, and personal or political attacks
28 | * Public or private harassment
29 | * Publishing others' private information, such as a physical or electronic
30 | address, without explicit permission
31 | * Other conduct which could reasonably be considered inappropriate in a
32 | professional setting
33 |
34 | ## Our Responsibilities
35 |
36 | Project maintainers are responsible for clarifying the standards of acceptable
37 | behavior and are expected to take appropriate and fair corrective action in
38 | response to any instances of unacceptable behavior.
39 |
40 | Project maintainers have the right and responsibility to remove, edit, or reject
41 | comments, commits, code, wiki edits, issues, and other contributions that are
42 | not aligned to this Code of Conduct, or to ban temporarily or permanently any
43 | contributor for other behaviors that they deem inappropriate, threatening,
44 | offensive, or harmful.
45 |
46 | ## Scope
47 |
48 | This Code of Conduct applies both within project spaces and in public spaces
49 | when an individual is representing the project or its community. Examples of
50 | representing a project or community include using an official project e-mail
51 | address, posting via an official social media account, or acting as an appointed
52 | representative at an online or offline event. Representation of a project may be
53 | further defined and clarified by project maintainers.
54 |
55 | This Code of Conduct also applies outside the project spaces when the Project
56 | Steward has a reasonable belief that an individual's behavior may have a
57 | negative impact on the project or its community.
58 |
59 | ## Conflict Resolution
60 |
61 | We do not believe that all conflict is bad; healthy debate and disagreement
62 | often yield positive results. However, it is never okay to be disrespectful or
63 | to engage in behavior that violates the project’s code of conduct.
64 |
65 | If you see someone violating the code of conduct, you are encouraged to address
66 | the behavior directly with those involved. Many issues can be resolved quickly
67 | and easily, and this gives people more control over the outcome of their
68 | dispute. If you are unable to resolve the matter for any reason, or if the
69 | behavior is threatening or harassing, report it. We are dedicated to providing
70 | an environment where participants feel welcome and safe.
71 |
72 | Reports should be directed to *[PROJECT STEWARD NAME(s) AND EMAIL(s)]*, the
73 | Project Steward(s) for *[PROJECT NAME]*. It is the Project Steward’s duty to
74 | receive and address reported violations of the code of conduct. They will then
75 | work with a committee consisting of representatives from the Open Source
76 | Programs Office and the Google Open Source Strategy team. If for any reason you
77 | are uncomfortable reaching out to the Project Steward, please email
78 | opensource@google.com.
79 |
80 | We will investigate every complaint, but you may not receive a direct response.
81 | We will use our discretion in determining when and how to follow up on reported
82 | incidents, which may range from not taking action to permanent expulsion from
83 | the project and project-sponsored spaces. We will notify the accused of the
84 | report and provide them an opportunity to discuss it before any action is taken.
85 | The identity of the reporter will be omitted from the details of the report
86 | supplied to the accused. In potentially harmful situations, such as ongoing
87 | harassment or threats to anyone's safety, we may take action without notice.
88 |
89 | ## Attribution
90 |
91 | This Code of Conduct is adapted from the Contributor Covenant, version 1.4,
92 | available at
93 | https://www.contributor-covenant.org/version/1/4/code-of-conduct/
94 |
--------------------------------------------------------------------------------
/src/stores/urlFilterStore.js:
--------------------------------------------------------------------------------
1 | import { defineStore } from 'pinia';
2 | import { isValidURLFilter } from '@/utils';
3 |
4 | //https://source.chromium.org/chromium/chromium/src/+/main:extensions/browser/api/declarative_net_request/indexed_rule.cc;l=47
5 | /* Returns an object 'indexedRule' with the following signature:-
6 | {
7 | anchorLeft: 'BOUNDARY' | 'SUBDOMAIN' | 'NONE',
8 | urlPatternType: 'SUBSTRING' | 'WILDCARDED',
9 | urlPattern: 'abc*def',
10 | anchorRight: 'BOUNDARY' | 'NONE'
11 | }
12 | */
13 | class URLFilterParser {
14 | constructor(urlFilter, indexedRule) {
15 | this.urlFilter = urlFilter || '';
16 | this.urlFilterLen = this.urlFilter.length;
17 | this.index = 0;
18 | this.indexedRule = indexedRule;
19 | }
20 |
21 | static parse(urlFilter, indexedRule) {
22 | if (!indexedRule) {
23 | throw new Error('IndexedRule is required');
24 | }
25 | if (!isValidURLFilter(urlFilter)) {
26 | throw new Error('Invalid URLFilter string');
27 | }
28 | new URLFilterParser(urlFilter, indexedRule).parseImpl();
29 | }
30 |
31 | parseImpl() {
32 | this.parseLeftAnchor();
33 | console.assert(this.index <= 2, 'Index should be less than or equal to 2');
34 | this.parseFilterString();
35 | console.assert(
36 | this.index === this.urlFilterLen || this.index + 1 === this.urlFilterLen,
37 | 'Index should be at the end or one before the end of urlFilter length'
38 | );
39 | this.parseRightAnchor();
40 | console.assert(
41 | this.index === this.urlFilterLen,
42 | 'Index should be equal to urlFilter length'
43 | );
44 | }
45 |
46 | parseLeftAnchor() {
47 | this.indexedRule.anchorLeft = 'NONE';
48 | if (this.isAtAnchor()) {
49 | ++this.index;
50 | this.indexedRule.anchorLeft = 'BOUNDARY';
51 | if (this.isAtAnchor()) {
52 | ++this.index;
53 | this.indexedRule.anchorLeft = 'SUBDOMAIN';
54 | }
55 | }
56 | }
57 |
58 | parseFilterString() {
59 | this.indexedRule.urlPatternType = 'SUBSTRING';
60 | let leftIndex = this.index;
61 | while (this.index < this.urlFilterLen && !this.isAtRightAnchor()) {
62 | if (this.isAtSeparatorOrWildcard()) {
63 | this.indexedRule.urlPatternType = 'WILDCARDED';
64 | }
65 | ++this.index;
66 | }
67 | this.indexedRule.urlPattern = this.urlFilter.substring(
68 | leftIndex,
69 | this.index
70 | );
71 | }
72 |
73 | parseRightAnchor() {
74 | this.indexedRule.anchorRight = 'NONE';
75 | if (this.isAtRightAnchor()) {
76 | ++this.index;
77 | this.indexedRule.anchorRight = 'BOUNDARY';
78 | }
79 | }
80 |
81 | isAtSeparatorOrWildcard() {
82 | return (
83 | this.isAtValidIndex() &&
84 | (this.urlFilter[this.index] === '^' || this.urlFilter[this.index] === '*')
85 | );
86 | }
87 |
88 | isAtRightAnchor() {
89 | return (
90 | this.isAtAnchor() &&
91 | this.index > 0 &&
92 | this.index + 1 === this.urlFilterLen
93 | );
94 | }
95 |
96 | isAtValidIndex() {
97 | return this.index < this.urlFilterLen;
98 | }
99 |
100 | isAtAnchor() {
101 | return this.isAtValidIndex() && this.urlFilter[this.index] === '|';
102 | }
103 | }
104 |
105 | export const useURLFilterStore = defineStore('urlFilter', {
106 | state: () => ({
107 | urlFilter: '',
108 | indexedRule: {},
109 | urlFilterParser: null
110 | }),
111 | actions: {
112 | initializeParser(urlFilter) {
113 | this.urlFilter = urlFilter;
114 | this.indexedRule = {};
115 | this.urlFilterParser = new URLFilterParser(urlFilter, this.indexedRule);
116 | },
117 | parseURLFilter(urlFilterString) {
118 | this.initializeParser(urlFilterString);
119 | if (this.urlFilterParser) {
120 | this.urlFilterParser.parseImpl();
121 | }
122 | if (this.indexedRule) {
123 | return this.indexedRule;
124 | }
125 | },
126 | // Test input url against the generated indexedRule object
127 | urlMatcher(url, indexedRule) {
128 | const urlPattern = indexedRule.urlPattern;
129 | let substrings = [];
130 | if (indexedRule.urlPatternType === 'SUBSTRING') {
131 | if (!url.includes(urlPattern)) {
132 | return false;
133 | }
134 | substrings.push(urlPattern);
135 | } else if (indexedRule.urlPatternType === 'WILDCARDED') {
136 | let string = '';
137 | for (let i = 0; i < urlPattern.length; i++) {
138 | if (
139 | urlPattern[i] === '*' ||
140 | urlPattern[i] === '^' ||
141 | urlPattern[i] === '|'
142 | ) {
143 | if (string) {
144 | substrings.push(string);
145 | string = '';
146 | }
147 | } else {
148 | string += urlPattern[i];
149 | }
150 | }
151 | if (string) {
152 | substrings.push(string);
153 | }
154 | }
155 | let x = 0; // index in urlPattern
156 | let index; // index in url where the checking starts
157 | if (indexedRule.anchorLeft === 'BOUNDARY') {
158 | index = 0;
159 | } else {
160 | index = url.indexOf(substrings[0]);
161 | if (index == -1) {
162 | return false;
163 | }
164 | }
165 | if (indexedRule.anchorRight === 'BOUNDARY') {
166 | if (
167 | urlPattern[urlPattern.length - 1] != '^' &&
168 | urlPattern[urlPattern.length - 1] != '*' &&
169 | url.endsWith(substrings[substrings.length - 1])
170 | ) {
171 | return true;
172 | }
173 | }
174 | if (indexedRule.anchorLeft === 'SUBDOMAIN') {
175 | index = url.indexOf(substrings[0]);
176 | if (index == -1 || url[index - 1] != '.') {
177 | return false;
178 | }
179 | }
180 | let unmatchables =
181 | 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-.%';
182 | // DOUBT: Can multiple wildcards be present in the urlPattern?
183 | while (urlPattern[x] == '*') {
184 | x++;
185 | }
186 | while (urlPattern[x] == '^') {
187 | if (unmatchables.includes(url[index])) {
188 | return false;
189 | }
190 | x++;
191 | index++;
192 | }
193 | let inOrder = url.indexOf(substrings[0], index) != -1;
194 | for (let i = 1; i < substrings.length; i++) {
195 | if (url.indexOf(substrings[i], url.indexOf(substrings[i - 1])) == -1) {
196 | inOrder = false;
197 | break;
198 | }
199 | }
200 | if (inOrder) {
201 | return true;
202 | } else {
203 | return false;
204 | }
205 | }
206 | }
207 | });
208 |
--------------------------------------------------------------------------------
/src/stores/manifestStore.js:
--------------------------------------------------------------------------------
1 | import { defineStore } from 'pinia';
2 |
3 | export const useManifestStore = defineStore('manifest', {
4 | state: () => ({
5 | /*
6 | Signature of each object in rulesetFilePaths
7 | {
8 | rulesetFileName: 'rules_1.json',
9 | rulesetFilePath: 'path/to/ruleset.json',
10 | rulesetId: 'rulesetId',
11 | isEnabled: true | false
12 | }
13 | */
14 | rulesetFilePaths: [],
15 | isFirstVisit: true
16 | }),
17 | getters: {
18 | getRulesetFilePaths(state) {
19 | return state.rulesetFilePaths;
20 | }
21 | },
22 | actions: {
23 | setIsFirstVisit(value) {
24 | this.isFirstVisit = value;
25 | },
26 | clearRulesetFilePaths() {
27 | this.rulesetFilePaths = [];
28 | },
29 | setRulesetFilePaths(manifest) {
30 | if (manifest.declarative_net_request.rule_resources) {
31 | manifest.declarative_net_request.rule_resources.forEach((ruleset) => {
32 | const rulesetFilePath = ruleset.path;
33 | const rulesetFileName = rulesetFilePath.split('/').pop();
34 |
35 | this.rulesetFilePaths.push({
36 | rulesetFileName: rulesetFileName,
37 | rulesetFilePath: rulesetFilePath,
38 | rulesetId: ruleset.id,
39 | isEnabled: ruleset.enabled
40 | });
41 | });
42 | }
43 | },
44 | toggleRulesetAvailability(rulesetFileName) {
45 | const rulesetFilePathObject = this.rulesetFilePaths.find(
46 | (ruleset) => ruleset.rulesetFileName === rulesetFileName
47 | );
48 | rulesetFilePathObject.isEnabled = !rulesetFilePathObject.isEnabled;
49 | },
50 | isValidManifest(manifest) {
51 | let syntaxError = {};
52 | syntaxError['type'] = [];
53 | syntaxError['missingFields'] = [];
54 | syntaxError['invalidValueTypes'] = [];
55 |
56 | // Check for required fields
57 | const requiredFieldsAndTypes = {
58 | // "description" and "icon" required for uploading to web store
59 | // permissions required for extensions such as those using DNR
60 | name: 'string',
61 | version: 'string',
62 | manifest_version: 'number',
63 | permissions: 'array'
64 | };
65 |
66 | for (let field of Object.keys(requiredFieldsAndTypes)) {
67 | if (!Object.prototype.hasOwnProperty.call(manifest, field)) {
68 | syntaxError.isError = true;
69 | if (!syntaxError['type'].includes('missingFields')) {
70 | syntaxError['type'].push('missingFields');
71 | syntaxError['missingFields'] = [];
72 | }
73 | syntaxError['missingFields'].push(field);
74 | } else {
75 | const expectedType = requiredFieldsAndTypes[field];
76 | const actualValue = manifest[field];
77 | if (expectedType === 'array') {
78 | if (!Array.isArray(actualValue)) {
79 | syntaxError.isError = true;
80 | if (!syntaxError['type'].includes('invalidValueTypes')) {
81 | syntaxError['type'].push('invalidValueTypes');
82 | syntaxError['invalidValueTypes'] = [];
83 | }
84 | syntaxError['invalidValueTypes'].push(field);
85 | }
86 | } else if (typeof actualValue !== expectedType) {
87 | syntaxError.isError = true;
88 | if (!syntaxError['type'].includes('invalidValueTypes')) {
89 | syntaxError['type'].push('invalidValueTypes');
90 | syntaxError['invalidValueTypes'] = [];
91 | }
92 | syntaxError['invalidValueTypes'].push(field);
93 | }
94 | }
95 | }
96 |
97 | const otherFieldsAndTypes = {
98 | action: 'object',
99 | author: 'string',
100 | background: 'object',
101 | browser_action: 'object',
102 | chrome_settings_overrides: 'object',
103 | chrome_ui_overrides: 'object',
104 | chrome_url_overrides: 'object',
105 | commands: 'object',
106 | content_security_policy: 'string',
107 | content_scripts: 'array',
108 | converted_from_user_script: 'boolean',
109 | current_locale: 'string',
110 | default_locale: 'string',
111 | description: 'string',
112 | devtools_page: 'string',
113 | event_rules: 'array',
114 | externally_connectable: 'object',
115 | file_browser_handlers: 'array',
116 | file_system_provider_capabilities: 'object',
117 | homepage_url: 'string',
118 | host_permissions: 'array',
119 | icons: 'object',
120 | import: 'array',
121 | incognito: 'object',
122 | input_components: 'object',
123 | key: 'string',
124 | minimum_chrome_version: 'string',
125 | nacl_modules: 'array',
126 | oauth2: 'object',
127 | offline_enabled: 'boolean',
128 | omnibox: 'object',
129 | optional_permissions: 'array',
130 | options_page: 'string',
131 | options_ui: 'object',
132 | page_action: 'object',
133 | platforms: 'object',
134 | replacement_web_app: 'object',
135 | requirements: 'object',
136 | sandbox: 'object',
137 | short_name: 'string',
138 | sidebar_action: 'object',
139 | storage: 'object',
140 | tts_engine: 'object',
141 | update_url: 'string',
142 | version_name: 'string',
143 | web_accessible_resources: 'array',
144 | webview: 'object'
145 | };
146 |
147 | for (let field of Object.keys(otherFieldsAndTypes)) {
148 | if (Object.prototype.hasOwnProperty.call(manifest, field)) {
149 | const expectedType = otherFieldsAndTypes[field];
150 | const actualValue = manifest[field];
151 | if (expectedType === 'array') {
152 | if (!Array.isArray(actualValue)) {
153 | syntaxError.isError = true;
154 | if (!syntaxError['type'].includes('invalidValueTypes')) {
155 | syntaxError['type'].push('invalidValueTypes');
156 | syntaxError['invalidValueTypes'] = [];
157 | }
158 | syntaxError['invalidValueTypes'].push(field);
159 | }
160 | } else if (typeof actualValue !== expectedType) {
161 | syntaxError.isError = true;
162 | if (!syntaxError['type'].includes('invalidValueTypes')) {
163 | syntaxError['type'].push('invalidValueTypes');
164 | syntaxError['invalidValueTypes'] = [];
165 | }
166 | syntaxError['invalidValueTypes'].push(field);
167 | }
168 | }
169 | }
170 |
171 | // Check for declarativeNetRequest and declarativeNetRequestWithHostAccess permissions
172 | if (
173 | Object.prototype.hasOwnProperty.call(manifest, 'permissions') &&
174 | !manifest.permissions.includes('declarativeNetRequest') &&
175 | !manifest.permissions.includes('declarativeNetRequestWithHostAccess')
176 | ) {
177 | syntaxError.isError = true;
178 | if (!syntaxError['type'].includes('missingPermissions')) {
179 | syntaxError['type'].push('missingPermissions');
180 | }
181 | }
182 |
183 | // Remove empty error types
184 | if (syntaxError['missingFields'].length === 0) {
185 | delete syntaxError['missingFields'];
186 | }
187 | if (syntaxError['invalidValueTypes'].length === 0) {
188 | delete syntaxError['invalidValueTypes'];
189 | }
190 |
191 | if (syntaxError.isError) {
192 | return syntaxError;
193 | } else {
194 | return true;
195 | }
196 | }
197 | },
198 | persist: {
199 | storage: sessionStorage,
200 | paths: ['rulesetFilePaths', 'isFirstVisit']
201 | }
202 | });
203 |
--------------------------------------------------------------------------------
/src/stores/rulesStore.js:
--------------------------------------------------------------------------------
1 | import { defineStore } from 'pinia';
2 | import { useURLFilterStore } from './urlFilterStore';
3 | import { useManifestStore } from './manifestStore';
4 | import { isValidURLFilter, sortRules } from '@/utils';
5 | import { parse } from 'vue/compiler-sfc';
6 |
7 | // const urlFilterStore = useURLFilterStore()
8 |
9 | export const useRulesStore = defineStore('rules', {
10 | state: () => ({
11 | /* Signature of each element of parsedRulesList:
12 | {
13 | rule: {
14 | id: 1,
15 | priority: 1,
16 | condition: {
17 | urlFilter: 'example.com'
18 | },
19 | action: {
20 | type: 'block'
21 | }
22 | },
23 | ruleId: 1,
24 | rulesetId: 1,
25 | urlParserIndexedRule: {},
26 | isEnabled: true | false,
27 | rulesetFileName: 'rules_1.json'
28 | }
29 | */
30 | parsedRulesList: [],
31 | requestMatched: false,
32 | matchedRuleString: '',
33 | urlFilterStore: useURLFilterStore(),
34 | manifestStore: useManifestStore()
35 | }),
36 | getters: {
37 | getParsedRulesList(state) {
38 | return state.parsedRulesList;
39 | },
40 | getRequestMatched(state) {
41 | return state.requestMatched;
42 | },
43 | getRulesetsList(state) {
44 | return state.rulesetsList;
45 | },
46 | getMatchedRuleString(state) {
47 | return state.matchedRuleString;
48 | },
49 | getParsedRulesListLength(state) {
50 | return state.parsedRulesList.length;
51 | }
52 | },
53 | actions: {
54 | clearParsedRulesList() {
55 | this.parsedRulesList = [];
56 | },
57 | setMatchedRuleString(value) {
58 | this.matchedRuleString = value;
59 | },
60 | setRequestMatched(value) {
61 | this.requestMatched = value;
62 | },
63 | // Return set of rules given the ruleset file name
64 | getRuleset(rulesetFileName) {
65 | if (!this.getParsedRulesList) {
66 | return [];
67 | }
68 | let ruleset = [];
69 | for (let index in this.parsedRulesList) {
70 | const ruleItem = this.parsedRulesList[index];
71 |
72 | if (ruleItem.rulesetFileName === rulesetFileName) {
73 | ruleset.push(ruleItem.rule);
74 | }
75 | }
76 | return ruleset;
77 | },
78 | // Update parsedRulesList with modified rule(s) of a given ruleset
79 | saveRuleset(rulesetFileName, ruleset) {
80 | let updatedRulesList = [];
81 | let processedRuleIds = new Set();
82 |
83 | let matchingParsedRules = this.parsedRulesList.filter(
84 | (parsedRule) => parsedRule.rulesetFileName === rulesetFileName
85 | );
86 | for (let parsedRule of matchingParsedRules) {
87 | let rule = ruleset.find((r) => r.id === parsedRule.ruleId);
88 |
89 | if (rule && this.isValidRule(rule)) {
90 | let indexedRule = this.urlFilterStore.parseURLFilter(
91 | rule.condition.urlFilter
92 | );
93 | parsedRule.rule = rule;
94 | parsedRule.urlParserIndexedRule = indexedRule;
95 | updatedRulesList.push(parsedRule);
96 | processedRuleIds.add(rule.id);
97 | } else {
98 | updatedRulesList.push(parsedRule);
99 | }
100 | }
101 | let nonMatchingParsedRules = this.parsedRulesList.filter(
102 | (parsedRule) => parsedRule.rulesetFileName !== rulesetFileName
103 | );
104 | updatedRulesList.push(...nonMatchingParsedRules);
105 |
106 | // Add new rules that are not present in parsedRulesList
107 | for (let rule of ruleset) {
108 | if (processedRuleIds.has(rule.id)) continue;
109 | if (this.isValidRule(rule)) {
110 | let indexedRule = this.urlFilterStore.parseURLFilter(
111 | rule.condition.urlFilter
112 | );
113 | updatedRulesList.push({
114 | rule: rule,
115 | urlParserIndexedRule: indexedRule,
116 | ruleId: rule.id,
117 | rulesetID: this.getRulesetIdForFileName(rulesetFileName), // Assuming a method to get rulesetID
118 | isEnabled: true,
119 | rulesetFileName: rulesetFileName
120 | });
121 | }
122 | }
123 |
124 | this.parsedRulesList = updatedRulesList;
125 | },
126 | // Checks validity of URLFilter string
127 | isValidURLFilter,
128 | // Checks validity of rule, including checking validity of its condition, i.e., the URLFilter string
129 | isValidRule(rule) {
130 | let isValid = true;
131 | if (!rule.id || (rule.id && !Number.isInteger(rule.id))) {
132 | isValid = false;
133 | console.log('id');
134 | }
135 | if (rule.priority && !Number.isInteger(rule.priority)) {
136 | isValid = false;
137 | console.log('priority');
138 | }
139 | if (!rule.condition || typeof rule.condition != 'object') {
140 | isValid = false;
141 | console.log('condition');
142 | }
143 | if (!this.isValidURLFilter(rule.condition.urlFilter)) {
144 | isValid = false;
145 | }
146 | return isValid;
147 | },
148 | // Checks syntax and validity of ruleset file
149 | isValidRuleset(ruleset) {
150 | // Check if the ruleset is an array and is non-empty
151 | if (!Array.isArray(ruleset) || ruleset.length === 0) {
152 | return false;
153 | }
154 | // Validate each rule in the ruleset
155 | for (let rule of ruleset) {
156 | if (!this.isValidRule(rule)) {
157 | return false;
158 | }
159 | }
160 | return true;
161 | },
162 | // Parse a given ruleset and set parsed rules list with each parsed rule
163 | setParsedRulesList(ruleset, fileName) {
164 | for (let rulesetFileInfoObjects of this.manifestStore.getRulesetFilePaths)
165 | if (rulesetFileInfoObjects.rulesetFilePath === fileName) {
166 | ruleset.forEach((rule) => {
167 | if (this.isValidRule(rule)) {
168 | let indexedRule = this.urlFilterStore.parseURLFilter(
169 | rule.condition.urlFilter
170 | );
171 | this.parsedRulesList.push({
172 | rule: rule,
173 | urlParserIndexedRule: indexedRule,
174 | ruleId: rule.id,
175 | rulesetID: rulesetFileInfoObjects.rulesetId,
176 | isEnabled: rulesetFileInfoObjects.isEnabled,
177 | rulesetFileName: fileName
178 | });
179 | }
180 | });
181 | }
182 | sortRules(this.parsedRulesList);
183 | },
184 | clearParsedRulesList() {
185 | this.parsedRulesList = [];
186 | },
187 | // Change the availability of a ruleset
188 | toggleRulesAvailability(rulesetFileName) {
189 | let updatedRulesList = [];
190 | for (let parsedRule of this.parsedRulesList) {
191 | if (parsedRule.rulesetFileName === rulesetFileName) {
192 | parsedRule.isEnabled = !parsedRule.isEnabled;
193 | }
194 | updatedRulesList.push(parsedRule);
195 | }
196 | this.parsedRulesList = updatedRulesList;
197 | },
198 | // Matches input HTTP request to parsed rule(s) and returns them
199 | requestMatcher(request) {
200 | let url = request.url;
201 | let matchedRules = [];
202 | for (let i = 0; i < this.parsedRulesList.length; i++) {
203 | let indexedRule = this.parsedRulesList[i].urlParserIndexedRule;
204 | if (
205 | this.urlFilterStore.urlMatcher(url, indexedRule) &&
206 | this.parsedRulesList[i].isEnabled
207 | ) {
208 | matchedRules.push(this.parsedRulesList[i]);
209 | }
210 | }
211 | return matchedRules;
212 | }
213 | },
214 | persist: {
215 | storage: sessionStorage,
216 | paths: ['parsedRulesList']
217 | }
218 | });
219 |
--------------------------------------------------------------------------------
/src/components/ExtensionUploadArea.vue:
--------------------------------------------------------------------------------
1 |
197 |
198 |
199 |
Upload Extension Files
200 |
201 |
202 |
203 |
204 | Upload Manifest
205 |
223 |
224 |
225 |
226 |
227 |
228 |
229 | Upload Ruleset Files
230 |
249 |
250 |
251 |
252 |
262 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright [yyyy] [name of copyright owner]
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
--------------------------------------------------------------------------------