Gerrit FE Dev Helper extension
v0.0.2

Change-Id: Ibf082ff6b12d23e2c3a5546bc3d09402dd0a09f9
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..5e942cc
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,4 @@
+dist
+node_modules
+package-lock.json
+gerrit_fe_dev_helper.zip
\ No newline at end of file
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..fc965b7
--- /dev/null
+++ b/README.md
@@ -0,0 +1,54 @@
+## Gerrit FE Dev Helper
+
+Gerrit FE Dev helper is a chrome extension that will focus on helping frontend developers on Gerrit development.
+
+As mentioned in [readme from polygerrit-ui](https://gerrit.googlesource.com/gerrit/+/refs/heads/master/polygerrit-ui/),
+we already support to start your local host for developing / debugging / testing, but it has quite a few restrictions:
+
+1. No auth support
+2. Restart needede to switch hosts
+3. Not easy to test plugins
+
+To solve these pain points, I created this chrome extension that basically just proxy all assets requests or any requests to local server, and you will have the ability to inject any plugins from local as well.
+
+### Features
+
+See in [release notes](./release-notes.md).
+
+### BUILD
+
+```
+npm run build
+```
+
+Then you should have `gerrit_fe_dev_helper.zip` that you can test with, or download from [chrome web store](https://chrome.google.com/webstore/category/extensions) here: https://chrome.google.com/webstore/detail/gerrit-fe-dev-helper/jimgomcnodkialnpmienbomamgomglkd.
+
+After you installed and enabled the extension, you should see something similar to [demo.png](./demo.png).
+
+### How to use
+
+1. Start the go server to host all assets locally
+```sh
+./polygerrit-ui/run-server.sh
+```
+2. Go to any gerrit sites, enable the extension by click the icon
+3. You should see this red notice show up in the bottom right of the page (`Gerrit dev helper is enabled`),
+and now your gerrit assets should be loaded from local server
+4. Change files locally and refresh the page, you should have the changes immediately
+
+The extension comes with a set of [default rules](./data/rules.json),
+but you can change the rules by just clicking the extension icon again.
+
+The extension supports six different type of rules:
+1. block: block a certain request
+2. redirect: redirect a url to another url
+3. injectHtmlCode: inject a piece of html code to the page
+4. injectJsCode: inject any js code to the page
+5. injectJsPlugin: inject a js plugin(url) to the site
+6. injectHtmlPlugin: inject a html plugin(url) to the site
+
+The two options of injecting any plugins meant to help you develop your plugins for your gerrit sites.
+
+### Contact
+
+Please don't hesitate to contact taoalpha@google.com for support on this extension.
\ No newline at end of file
diff --git a/data/rules.json b/data/rules.json
new file mode 100644
index 0000000..2386107
--- /dev/null
+++ b/data/rules.json
@@ -0,0 +1,44 @@
+[
+  {
+    "disabled": false,
+    "target": ".*play.google.com.*",
+    "operator": "block",
+    "destination": ""
+  },
+  {
+    "disabled": false,
+    "target": ".*csp.withgoogle.com.*",
+    "operator": "block",
+    "destination": ""
+  },
+  {
+    "disabled": false,
+    "target": ".*www.google-analytics.com.*",
+    "operator": "block",
+    "destination": ""
+  },
+  {
+    "disabled": false,
+    "target": "(.*)cdn.googlesource.com/polygerrit_ui/[0-9.]+/elements/.*",
+    "operator": "redirect",
+    "destination": "http://localhost:8081/elements/gr-app.html"
+  },
+  {
+    "disabled": false,
+    "target": "(.*)cdn.googlesource.com/polygerrit_ui/[0-9.]+/styles/",
+    "operator": "redirect",
+    "destination": "http://localhost:8081/styles/"
+  },
+  {
+    "disabled": false,
+    "target": "",
+    "operator": "injectJSCode",
+    "destination": "\n  const app = document.createElement(\"gr-app\");\n  app.id = \"app\";\n  document.querySelector(\"#app\").replaceWith(app);\n  "
+  },
+  {
+    "disabled": false,
+    "target": "",
+    "operator": "injectHtmlCode",
+    "destination": "<span style=\"color: white;font-weight:bold;padding:10px;z-index:10000;display:block;position:fixed;bottom:0;right:0;background-color:red;\">Gerrit dev helper is enabled</span>"
+  }
+]
\ No newline at end of file
diff --git a/demo.png b/demo.png
new file mode 100644
index 0000000..1b127b1
--- /dev/null
+++ b/demo.png
Binary files differ
diff --git a/package.json b/package.json
new file mode 100644
index 0000000..1c64761
--- /dev/null
+++ b/package.json
@@ -0,0 +1,30 @@
+{
+  "name": "gerrit-fe-dev-helper",
+  "license": "MIT",
+  "dependencies": {
+    "lit-element": "^2.2.1"
+  },
+  "devDependencies": {
+    "@bazel/bazel": "^1.1.0",
+    "@bazel/typescript": "0.39.1",
+    "@types/chrome": "0.0.91",
+    "ts-loader": "^6.2.1",
+    "typescript": "^3.7.2",
+    "webpack": "^4.41.2",
+    "webpack-cli": "^3.3.10"
+  },
+  "version": "0.0.1",
+  "description": "Dev helper for gerrit fe development",
+  "scripts": {
+    "assets:html": "cp src/*.html dist",
+    "assets:json": "cp src/*.json dist",
+    "assets:image": "cp src/*.png dist",
+    "assets": "npm run assets:html && npm run assets:json && npm run assets:image",
+    "zip": "cd dist && zip gerrit_fe_dev_helper.zip -r ./* && mv gerrit_fe_dev_helper.zip ../",
+    "webpack": "webpack --config webpack/webpack.config.js",
+    "build": "npm run clean && mkdir -p dist && npm run webpack && npm run assets && npm run zip",
+    "clean": "rm -rf dist",
+    "test": "echo \"Error: no test specified\" && exit 1"
+  },
+  "author": "taoalpha@google.com"
+}
diff --git a/release-notes.md b/release-notes.md
new file mode 100644
index 0000000..f9a9ed0
--- /dev/null
+++ b/release-notes.md
@@ -0,0 +1,18 @@
+#### v0.0.2
+
+- Remove restriction on gerrit sites (some features won't work if its not a valid gerrit site)
+- Update README
+
+#### v0.0.1
+
+- Enable the extension with a single click
+- Allow export / import rules
+- Show a error for 5s if rule destination is invalid (can not reach)
+- Show an announcement for the change for 3 seconds for first time users
+- Persist enable / disable state per tab
+- Support temporary disable rule without deleting it
+- Move injection to document_end
+- Support reset to reset rules to initial state
+- Support proxy live requests to local on googlesource sites
+- Support 6 types of rules: redirect, block, injectJS code/url, inject html code / url
+- Support add / remove / modify rules
\ No newline at end of file
diff --git a/src/LICENSE b/src/LICENSE
new file mode 100644
index 0000000..2909ff0
--- /dev/null
+++ b/src/LICENSE
@@ -0,0 +1,170 @@
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+   1. Definitions.
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+   END OF TERMS AND CONDITIONS
+   APPENDIX: How to apply the Apache License to your work.
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+   Copyright [yyyy] [name of copyright owner]
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+       http://www.apache.org/licenses/LICENSE-2.0
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
\ No newline at end of file
diff --git a/src/background.ts b/src/background.ts
new file mode 100644
index 0000000..f68db52
--- /dev/null
+++ b/src/background.ts
@@ -0,0 +1,236 @@
+import {DEFAULT_RULES, isInjectRule, isValidRule, Operator, Rule} from './utils';
+
+let rules: Rule[] = [...DEFAULT_RULES];
+
+interface TabState {
+  tab: chrome.tabs.Tab;
+}
+
+// Enable / disable with one click and persist states per tab
+const TabStates = new Map<number, TabState>();
+
+// Load default configs and states when install
+chrome.runtime.onInstalled.addListener(() => {
+  chrome.storage.sync.get(['rules'], (res) => {
+    const existingRules: Rule[] = res['rules'] || [];
+    const validRules = existingRules.filter(isValidRule);
+    if (!validRules.length) {
+      chrome.storage.sync.set({rules});
+    } else {
+      chrome.storage.sync.set({rules: validRules});
+    }
+  });
+});
+
+// Check if we should enable or disable the extension when activated tab changed
+chrome.tabs.onActivated.addListener(() => {
+  checkCurrentTab();
+});
+
+// keep a reference to lastFocusedWindow
+let lastFocusedWindow: chrome.tabs.Tab;
+
+// Communication channel between background and content_script / popup
+chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
+  if (request.type === 'updateRules') {
+    rules = request.rules;
+  } else if (request.type === 'disableHelper') {
+    const tab = request.tab || {id: undefined};
+    chrome.browserAction.disable(tab.id);
+    chrome.browserAction.setIcon({tabId: tab.id, path: 'gray-32.png'});
+    chrome.browserAction.setPopup({tabId: tab.id, popup: ''});
+    TabStates.delete(tab.id);
+  } else if (request.type === 'isEnabled') {
+    const tab = sender.tab || lastFocusedWindow || {id: undefined};
+    sendResponse(TabStates.has(tab.id));
+  }
+});
+
+function onHeadersReceived(resp: chrome.webRequest.WebResponseHeadersDetails) {
+  if (!resp || !resp.responseHeaders) return {};
+
+  if (!TabStates.has(resp.tabId)) {
+    return {responseHeaders: resp.responseHeaders};
+  }
+
+  let len = resp.responseHeaders.length;
+  if (len > 0) {
+    while (--len) {
+      const header = resp.responseHeaders[len];
+      if (header.name.toUpperCase() === 'X-WEBKIT-CSP') {
+        header.value = '*';
+        break;
+      } else if (header.name.toLowerCase() === 'access-control-allow-origin') {
+        resp.responseHeaders[len].value = '*';
+        break;
+      } else if (
+          header.name.toLowerCase() === 'cache-control' ||
+          header.name.toLowerCase() === 'x-google-cache-control') {
+        header.value = 'max-age=0, no-cache, no-store, must-revalidate';
+      }
+    }
+  }
+
+  // add cors and cache anyway
+  resp.responseHeaders.push(
+      {'name': 'Access-Control-Allow-Origin', 'value': '*'});
+  resp.responseHeaders.push({
+    'name': 'Cache-Control',
+    'value': 'max-age=0, no-cache, no-store, must-revalidate'
+  });
+  return {responseHeaders: resp.responseHeaders};
+}
+
+function onBeforeRequest(details: chrome.webRequest.WebRequestBodyDetails) {
+  if (!TabStates.has(details.tabId)) {
+    return {cancel: false};
+  }
+
+  const match = rules.filter(isValidRule)
+                    .find(
+                        rule => !isInjectRule(rule) && !rule.disabled &&
+                            new RegExp(rule.target).test(details.url));
+  if (match) {
+    if (match.operator === Operator.BLOCK) {
+      return {cancel: true};
+    }
+
+    if (match.operator === Operator.REDIRECT) {
+      return {
+        redirectUrl:
+            details.url.replace(new RegExp(match.target), match.destination),
+      };
+    }
+  }
+  return {cancel: false};
+}
+
+function onBeforeSendHeaders(
+    details: chrome.webRequest.WebRequestHeadersDetails) {
+  if (!details || !details.requestHeaders) return {};
+
+  if (!TabStates.has(details.tabId)) {
+    return {requestHeaders: details.requestHeaders};
+  }
+
+  let len = details.requestHeaders.length;
+  let added = false;
+  while (--len) {
+    const header = details.requestHeaders[len];
+    if (header.name.toLowerCase() === 'cache-control' ||
+        header.name.toLowerCase() === 'x-google-cache-control') {
+      header.value = 'max-age=0, no-cache, no-store, must-revalidate';
+      added = true;
+    }
+  }
+  if (!added) {
+    details.requestHeaders.push({
+      'name': 'Cache-Control',
+      'value': 'max-age=0, no-cache, no-store, must-revalidate'
+    });
+  }
+
+  return {requestHeaders: details.requestHeaders};
+}
+
+// remove csp
+// add cors header to all response
+function setUpListeners() {
+  // if already registered, return
+  if (chrome.webRequest.onHeadersReceived.hasListener(onHeadersReceived)) {
+    return;
+  }
+
+  // in case any listeners already set up, remove them first
+  removeListeners();
+  chrome.webRequest.onHeadersReceived.addListener(
+      onHeadersReceived, {urls: ['<all_urls>']},
+      ['blocking', 'responseHeaders']);
+
+  // blocking or redirecting
+  chrome.webRequest.onBeforeRequest.addListener(
+      onBeforeRequest, {urls: ['<all_urls>']}, ['blocking']);
+
+  // disabling cache
+  chrome.webRequest.onBeforeSendHeaders.addListener(
+      onBeforeSendHeaders, {urls: ['<all_urls>']},
+      ['blocking', 'requestHeaders']);
+}
+
+function removeListeners() {
+  if (chrome.webRequest.onHeadersReceived.hasListener(onHeadersReceived)) {
+    chrome.webRequest.onHeadersReceived.removeListener(onHeadersReceived);
+  }
+
+  if (chrome.webRequest.onBeforeRequest.hasListener(onBeforeRequest)) {
+    chrome.webRequest.onBeforeRequest.removeListener(onBeforeRequest);
+  }
+
+  if (chrome.webRequest.onBeforeSendHeaders.hasListener(onBeforeSendHeaders)) {
+    chrome.webRequest.onBeforeSendHeaders.removeListener(onBeforeSendHeaders);
+  }
+}
+
+function enableHelper(tab: chrome.tabs.Tab) {
+  // disable -> enable
+  chrome.browserAction.setIcon({tabId: tab.id, path: 'icon-32.png'});
+  chrome.browserAction.setPopup({tabId: tab.id, popup: 'popup.html'});
+  TabStates.set(tab.id, {tab});
+
+  // set up listeners
+  setUpListeners();
+}
+
+function disableHelper(tab: chrome.tabs.Tab) {
+  chrome.browserAction.setIcon({tabId: tab.id, path: 'gray-32.png'});
+  chrome.browserAction.setPopup({tabId: tab.id, popup: ''});
+  TabStates.delete(tab.id);
+
+  // Remove listeners if no tab enabled
+  if (TabStates.size === 0) {
+    removeListeners();
+  }
+}
+
+chrome.browserAction.onClicked.addListener((tab) => {
+    if (TabStates.has(tab.id)) {
+      // enable -> disable
+      disableHelper(tab);
+    } else {
+      // disable -> enable
+      enableHelper(tab);
+      if (lastFocusedWindow) {
+        chrome.tabs.update(lastFocusedWindow.id!, {url: lastFocusedWindow.url});
+      }
+    }
+});
+
+// Enable / disable the helper based on state of this tab
+// This will be called when tab was activated
+function checkCurrentTab() {
+  chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, ([tab]) => {
+    if (lastFocusedWindow === tab) return;
+    if (!tab || !tab.url) return;
+
+    if (TabStates.has(tab.id)) {
+      enableHelper(tab);
+    } else {
+      disableHelper(tab);
+    }
+
+    lastFocusedWindow = tab;
+
+    // read the latest states and rules
+    chrome.storage.sync.get(['rules'], (res) => {
+      rules = res['rules'] || [];
+    });
+  });
+}
+
+// when removed, clear
+chrome.tabs.onRemoved.addListener(tabId => {
+  TabStates.delete(tabId);
+  if (TabStates.size === 0) {
+    removeListeners();
+  }
+});
diff --git a/src/content_script.ts b/src/content_script.ts
new file mode 100644
index 0000000..1e3c978
--- /dev/null
+++ b/src/content_script.ts
@@ -0,0 +1,90 @@
+import { isInjectRule, Operator, Rule } from './utils';
+
+function nextTick(ts: number) {
+  return new Promise(resolve => {
+    setTimeout(resolve, ts);
+  });
+}
+
+// Since content-script can not access window.Gerrit,
+// here checks the readiness based on # of imports
+// (as plugin will inject more html imports once added)
+const onGerritReady = async () => {
+  let importLinks = document.querySelectorAll("link[rel=import]");
+  let gerritReady = importLinks && importLinks.length > 2;
+  while (!gerritReady) {
+    await nextTick(1000);
+    importLinks = document.querySelectorAll("link[rel=import]");
+    gerritReady = importLinks && importLinks.length > 2;
+  }
+  return true;
+}
+
+// Apply injection rules to Gerrit sites if enabled
+chrome.runtime.sendMessage({ type: 'isEnabled' }, (isEnabled) => {
+  if (!isEnabled) return;
+
+  chrome.storage.sync.get(['rules'], (result) => {
+    if (!result['rules']) return;
+    const rules = result['rules'] as Rule[];
+
+    // load
+    rules.filter(isInjectRule).forEach(rule => {
+      if (rule.disabled) return;
+      if (rule.operator === Operator.INJECT_HTML_PLUGIN) {
+        onGerritReady().then(() => {
+          const link = document.createElement('link');
+          link.href = rule.destination;
+          link.rel = 'import';
+          document.head.appendChild(link);
+        });
+      } else if (rule.operator === Operator.INJECT_HTML_CODE) {
+        const el = document.createElement('div');
+        el.innerHTML = rule.destination;
+        document.body.appendChild(el);
+      } else if (rule.operator === Operator.INJECT_JS_PLUGIN) {
+        onGerritReady().then(() => {
+          const link = document.createElement('script');
+          link.setAttribute('src', rule.destination);
+          document.head.appendChild(link);
+        });
+      } else if (rule.operator === Operator.INJECT_JS_CODE) {
+        const link = document.createElement('script');
+        link.innerHTML = rule.destination;
+        document.head.appendChild(link);
+      }
+    });
+
+    // test redirect rules
+    let idx = 0;
+    rules.filter(rule => !isInjectRule(rule)).forEach(rule => {
+      if (rule.operator === Operator.REDIRECT && !rule.disabled) {
+        fetch(rule.destination).then(res => {
+          if (res.status < 200 || res.status >= 300) throw new Error("Resource not found");
+        }).catch(e => {
+          const errorSnack = document.createElement('div');
+          errorSnack.style.position = 'absolute';
+          errorSnack.style.top = `${idx++ * 40}px`;
+          errorSnack.style.right = '10px';
+          errorSnack.style.backgroundColor = 'black';
+          errorSnack.style.color = 'white';
+          errorSnack.style.padding = '10px';
+          errorSnack.style.zIndex = '100';
+          errorSnack.innerHTML =
+            `You may have an invalid redirect rule from ${rule.target} to ${
+            rule.destination}`;
+          document.body.appendChild(errorSnack);
+
+          // in case body is unresolved
+          document.body.style.display = "block";
+          document.body.style.opacity = "1";
+
+          setTimeout(() => {
+            errorSnack.remove();
+            idx--;
+          }, 10 * 1000);
+        });
+      }
+    });
+  });
+});
\ No newline at end of file
diff --git a/src/gray-32.png b/src/gray-32.png
new file mode 100644
index 0000000..3c0bb30
--- /dev/null
+++ b/src/gray-32.png
Binary files differ
diff --git a/src/icon-32.png b/src/icon-32.png
new file mode 100644
index 0000000..4922242
--- /dev/null
+++ b/src/icon-32.png
Binary files differ
diff --git a/src/manifest.json b/src/manifest.json
new file mode 100644
index 0000000..d21cbd9
--- /dev/null
+++ b/src/manifest.json
@@ -0,0 +1,41 @@
+{
+    "manifest_version": 2,
+    "name": "Gerrit FE Dev Helper",
+    "description": "This extension can help you development on gerrit sites, frontend specifically",
+    "version": "0.0.2",
+    "browser_action": {
+      "default_icon": "gray-32.png",
+      "default_title": "Gerrit FE Dev Helper"
+    },
+    "background": {
+      "scripts": [
+        "background.js"
+      ],
+      "persistent": true
+    },
+
+    "content_scripts": [
+      {
+        "run_at": "document_end",
+        "matches": [
+          "<all_urls>"
+        ],
+        "js": [
+          "content_script.js"
+        ]
+      }
+    ],
+    "content_security_policy": "default-src 'none'; script-src 'self'; style-src 'unsafe-inline'; connect-src https://*",
+    "permissions": [
+      "debugger",
+      "activeTab",
+      "<all_urls>",
+      "notifications",
+      "storage",
+      "tabs",
+      "webRequest",
+      "webRequestBlocking",
+      "declarativeContent"
+    ]
+  }
+  
\ No newline at end of file
diff --git a/src/popup.html b/src/popup.html
new file mode 100644
index 0000000..4a29a29
--- /dev/null
+++ b/src/popup.html
@@ -0,0 +1,17 @@
+<!DOCTYPE html>
+<html>
+
+<head>
+  <style>
+    body {
+      min-width: 300px;
+    }
+  </style>
+</head>
+
+<body>
+    <gdh-app></gdh-app>
+    <script src="popup.js"></script>
+</body>
+
+</html>
diff --git a/src/popup.ts b/src/popup.ts
new file mode 100644
index 0000000..fa30ecd
--- /dev/null
+++ b/src/popup.ts
@@ -0,0 +1,465 @@
+import {css, customElement, html, LitElement, property } from 'lit-element';
+
+import {getDefaultRules, isInjectRule, Operator, Rule} from './utils';
+
+const EMPTY_RULE = {
+  disabled: false,
+  target: '',
+  operator: Operator.BLOCK,
+  destination: '',
+  isNew: true,
+};
+
+/**
+ * GdhApp component.
+ */
+@customElement('gdh-app')
+export class GdhApp extends LitElement {
+  @property({type: Array, attribute: false}) rules: Rule[] = [];
+  @property() changeId: string = '';
+  @property() announcementText = 'To get latest rules, click `reset`.';
+  @property({type: Boolean}) isImport = false;
+  @property() rulesStr = '';
+  @property() importError = '';
+
+  constructor() {
+    super();
+    this.loadRules();
+    const lastAnnouncement = window.localStorage.getItem('helper-announcement');
+    if (!lastAnnouncement || lastAnnouncement !== this.announcementText) {
+      window.localStorage.setItem('helper-announcement', this.announcementText);
+      setTimeout(() => {
+        this.announcementText = '';
+      }, 3 * 1000);
+    } else {
+      // only show it once, if showed, don't show them again
+      this.announcementText = '';
+    }
+  }
+
+  private loadRules() {
+    chrome.storage.sync.get(['rules', 'enabled'], (result) => {
+      if (!result['rules']) return;
+      this.rules =
+          (result['rules'] as Rule[]).map(rule => (rule.isNew = false, rule));
+      this.rulesStr = JSON.stringify(this.rules, null, 2);
+    });
+  }
+
+  saveRules() {
+    chrome.storage.sync.set({rules: this.rules.slice()});
+    chrome.runtime.sendMessage(
+        {type: 'updateRules', rules: this.rules.slice()});
+
+    this.refresh();
+  }
+
+  addNewRule() {
+    this.rules = [...this.rules, {...EMPTY_RULE}];
+  }
+
+  resetRules() {
+    getDefaultRules().then(rules => {
+      this.rules = [...rules];
+      this.rulesStr = JSON.stringify(this.rules, null, 2);
+      window.localStorage.removeItem('helper-announcement');
+      this.requestUpdate();
+    })
+  }
+
+  onRuleDeletion(event: CustomEvent<Rule>) {
+    this.rules = this.rules.filter(r => r !== event.detail);
+    this.rulesStr = JSON.stringify(this.rules, null, 2);
+  }
+
+  enableMeOnly(event: CustomEvent<Rule>) {
+    this.rules = this.rules.map(rule => {
+      const toggledRule = event.detail;
+      rule.disabled = rule !== toggledRule;
+      return {...rule};
+    });
+  }
+
+  onRuleChanged(event: CustomEvent<Rule>) {
+    this.rules = this.rules.map(rule => ({...rule}));
+  }
+
+  disableHelper() {
+    this.refresh(tab => {
+      chrome.runtime.sendMessage({type: 'disableHelper', tab});
+      return null;
+    });
+    window.close();
+  }
+
+  private refresh(runBefore?: (tab: chrome.tabs.Tab) => null) {
+    // refresh the tab now
+    chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
+      if (!tabs[0] || !tabs[0].id) return;
+      if (runBefore) runBefore(tabs[0]);
+      chrome.tabs.update(tabs[0].id, {url: tabs[0].url});
+    });
+  }
+
+  startImport() {
+    this.isImport = true;
+  }
+
+  confirmImport() {
+    try {
+      const rules = JSON.parse(this.rulesStr);
+      this.rules = rules;
+      this.saveRules();
+      this.isImport = false;
+    } catch (e) {
+      this.importError = e.message;
+    }
+  }
+
+  cancelImport() {
+    this.isImport = false;
+  }
+
+  handleRulesInputChange(e: Event) {
+    this.rulesStr = (e.target as HTMLInputElement).value;
+  }
+
+  exportRules() {
+    const dataStr = 'data:text/json;charset=utf-8,' +
+        encodeURIComponent(JSON.stringify(this.rules));
+    const downloadAnchorNode = document.createElement('a');
+    downloadAnchorNode.setAttribute('href', dataStr);
+    downloadAnchorNode.setAttribute('download', 'rules.json');
+    downloadAnchorNode.click();
+    downloadAnchorNode.remove();
+  }
+
+  render() {
+    return html`
+        <p ?hidden=${!this.announcementText}>${this.announcementText}</p>
+        <header>
+          <button @click=${this.disableHelper}>Disable</button>
+        </header>
+        <div ?hidden=${this.isImport}>
+          <gdh-rule-set
+            @enable-me-only=${this.enableMeOnly}
+            @rule-deleted=${this.onRuleDeletion}
+            @rule-changed=${this.onRuleChanged}
+            .rules=${this.rules}>
+          </gdh-rule-set>
+          <div class="buttons">
+            <button @click=${this.saveRules}>Save</button>
+            <button @click=${this.addNewRule}>Add</button>
+            <button @click=${this.resetRules}>Reset</button>
+            <button @click=${this.startImport}>Import</button>
+            <button @click=${this.exportRules}>Export</button>
+          </div>
+        </div>
+        <div ?hidden=${!this.isImport}>
+          <p ?hidden=${!this.importError}>${this.importError}</p>
+          <textarea
+            name="rules"
+            .value=${this.rulesStr}
+            @input=${this.handleRulesInputChange}>
+          </textarea>
+          <div class="buttons">
+            <button @click=${this.confirmImport}>Import</button>
+            <button @click=${this.cancelImport}>Cancel</button>
+            <button @click=${this.resetRules}>Reset</button>
+          </div>
+        </div>
+        `;
+  }
+
+  static get styles() {
+    return css`
+        p {
+          background: yellow;
+          padding: 10px;
+        }
+        button {
+          padding: 5px;
+        }
+
+        header {
+          display: flex;
+          flex-direction: row-reverse;
+        }
+
+        textarea {
+          min-width: 500px;
+          min-height: 500px;
+        }
+        `;
+  }
+}
+
+/**
+ * GdhRuleSet component.
+ */
+@customElement('gdh-rule-set')
+export class GdhRuleSet extends LitElement {
+  @property({type: Array, attribute: false}) rules: Rule[] = [];
+
+  render() {
+    return html`
+        <ul>
+          <li>
+            <span></span>
+            <span>Target</span>
+            <span>Operator</span>
+            <span>Destination</span>
+          </li>
+          ${
+        this.rules.map(
+            rule =>
+                html`<li><gdh-rule-item .rule=${rule}></gdh-rule-item></li>`)}
+        </ul>
+        `;
+  }
+
+  static get styles() {
+    return css`
+        :host {
+          position: relative;
+          display: flex;
+          flex-direction: row;
+        }
+        ul {
+          list-style: none;
+          margin: 0;
+          padding: 10px;
+          width: 100%;
+        }
+        ul li {
+          display: flex;
+          margin: 5px 0;
+          width: 100%;
+        }
+        li span {
+          text-align: center;
+        }
+        li span:nth-child(1) {
+          flex-basis: 30px;
+        }
+        li span:nth-child(2) {
+          flex-basis: 220px;
+        }
+        li span:nth-child(3) {
+          flex-basis: 130px;
+        }
+        li span:nth-child(4) {
+          flex: 1;
+        }
+        `;
+  }
+}
+
+/**
+ * GdhRuleItem component.
+ */
+@customElement('gdh-rule-item')
+export class GdhRuleItem extends LitElement {
+  @property({type: Object, attribute: false}) rule: Rule = {...EMPTY_RULE};
+
+  operators = [
+    Operator.BLOCK,
+    Operator.REDIRECT,
+    Operator.INJECT_HTML_PLUGIN,
+    Operator.INJECT_HTML_CODE,
+    Operator.INJECT_JS_PLUGIN,
+    Operator.INJECT_JS_CODE,
+  ];
+
+  handleInputOnTarget(e: Event) {
+    this.rule.target = (e.target as HTMLInputElement).value;
+    this.requestUpdate();
+  }
+
+  handleInputOnDestination(e: Event) {
+    this.rule.destination = (e.target as HTMLInputElement).value;
+    this.requestUpdate();
+  }
+
+  onSelectedChange(e: CustomEvent<number>) {
+    this.rule.operator = this.operators[e.detail];
+    this.requestUpdate();
+  }
+
+  onRuleDeletion(rule: Rule) {
+    this.dispatchEvent(new CustomEvent<Rule>('rule-deleted', {
+      detail: rule,
+      bubbles: true,
+      composed: true,
+    }));
+  }
+
+  toggleDisable(e: KeyboardEvent) {
+    this.rule.disabled = !this.rule.disabled;
+    // notify the change
+    this.dispatchEvent(new CustomEvent<Rule>('rule-changed', {
+      detail: this.rule,
+      bubbles: true,
+      composed: true,
+    }));
+  }
+
+  enableOnlyMe(e: KeyboardEvent) {
+    this.dispatchEvent(new CustomEvent<Rule>('enable-me-only', {
+      detail: this.rule,
+      bubbles: true,
+      composed: true,
+    }));
+  }
+
+  render() {
+    return html`
+        <input
+          type="checkbox"
+          .checked=${!this.rule.disabled}
+          @dblclick=${this.enableOnlyMe}
+          @click=${this.toggleDisable} />
+        <input
+          class="target"
+          .disabled=${isInjectRule(this.rule)}
+          type="text"
+          .value=${this.rule.target}
+          @input=${this.handleInputOnTarget} />
+        <gdh-dropdown
+          .selectedIndex=${this.operators.indexOf(this.rule.operator)}
+          @select-changed=${this.onSelectedChange}
+          .items=${this.operators}>
+        </gdh-dropdown>
+        <textarea
+          name="destination"
+          .value=${this.rule.destination}
+          @input=${this.handleInputOnDestination}
+          .disabled=${this.rule.operator === Operator.BLOCK}>
+        </textarea>
+        <span class="deleteBtn" @click=${
+        this.onRuleDeletion.bind(this, this.rule)}>x</span>
+        `;
+  }
+
+  static get styles() {
+    return css`
+        :host {
+          position: relative;
+          display: flex;
+          flex-direction: row;
+        }
+        .deleteBtn {
+          padding: 5px;
+          font-size: 18px;
+          cursor: pointer;
+          flex-basis: 20px;
+        }
+        input[type="checkbox"] {
+          margin: 10px;
+          flex-basis: 20px;
+        }
+        input[type="text"],
+        textarea {
+          flex: 1;
+          min-width: 220px;
+        }
+        input[disabled],
+        textarea[disabled] {
+          background: #ddd;
+        }
+        `;
+  }
+}
+
+/**
+ * GdhDropdown component.
+ */
+@customElement('gdh-dropdown')
+export class GdhDropdown extends LitElement {
+  @property({type: Array, attribute: false}) items: unknown[] = [];
+  @property({type: Number}) selectedIndex: number = 0;
+  @property({type: Boolean}) isVisible = false;
+
+  handleSelect(idx: number) {
+    this.selectedIndex = idx;
+    this.dispatchEvent(new CustomEvent<number>('select-changed', {
+      detail: idx,
+      bubbles: true,
+      composed: true,
+    }));
+    this.isVisible = false;
+  }
+
+  toggleVisible(e: Event) {
+    this.isVisible = (e.target as HTMLInputElement).checked;
+  }
+
+  render() {
+    return html`
+        <label for="trigger">
+          <div class="selected-value">${this.items[this.selectedIndex]}</div>
+          <input
+            .checked=${this.isVisible}
+            @input=${this.toggleVisible}
+            type="checkbox"
+            name="trigger" />
+          <ul class="options">
+          ${this.items.map((item, i) => html`
+            <li
+              @click=${this.handleSelect.bind(this, i)}
+              class="${i === this.selectedIndex ? 'active' : ''}">
+              ${item}
+            </li>
+            `)}
+          </ul>
+        </label>
+        `;
+  }
+
+  static get styles() {
+    return css`
+        :host {
+          position: relative;
+          display: flex;
+          flex-direction: column;
+        }
+        .selected-value {
+          padding: 8px 15px;
+          min-width: 100px;
+        }
+        ul {
+          display: none;
+          list-style: none;
+          margin: 0;
+          padding: 0;
+          width: 100%;
+          position: absolute;
+          top: 100%;
+          left: 0;
+          background: #eee;
+          z-index: 1;
+        }
+        input {
+          opacity: 0;
+          position: absolute;
+          top: 0;
+          width: 100%;
+          height: 100%;
+        }
+        input:checked + ul {
+          display: block;
+        }
+        input:checked + ul li:hover {
+          background: #ddd;
+        }
+        input:checked + ul li {
+          padding: 5px 10px;
+          cursor: pointer;
+        }
+        input:checked + ul li.active,
+        input:checked + ul li.active:hover {
+          background-color: #fff;
+        }
+        `;
+  }
+}
diff --git a/src/utils.ts b/src/utils.ts
new file mode 100644
index 0000000..20c5a45
--- /dev/null
+++ b/src/utils.ts
@@ -0,0 +1,68 @@
+import * as _DEFAULT_RULES from "../data/rules.json";
+
+/**
+ * Default rules.
+ */
+export const DEFAULT_RULES: Rule[] = _DEFAULT_RULES as Rule[];
+
+/**
+ * Retrieves default rules from remote rules file, fallback to existing DEFAULT_RULES
+ */
+export async function getDefaultRules() {
+    // try fetch from remote
+    const remoteRulesUrl = 'https://gerrit.googlesource.com/gerrit-fe-dev-helper/+/refs/heads/master/data/rules.json?format=TEXT';
+    try {
+        const response = await fetch(remoteRulesUrl)
+        const encodedText = await response.text();
+        return JSON.parse(atob(encodedText));
+    } catch(e) {
+        console.log(e);
+    }
+
+    // fallback to existing default rules
+    return DEFAULT_RULES;
+}
+
+/**
+ * Returns if it's a valid rule (syntax only).
+ */
+export function isValidRule(rule: Rule) {
+  return Object.values(Operator).includes(rule.operator) &&
+    ((rule.operator === Operator.BLOCK && rule.target) ||
+      (rule.operator === Operator.REDIRECT && rule.target &&
+        rule.destination) ||
+      !!rule.destination);
+}
+
+/**
+ * Returns if it's a inject rule.
+ */
+export function isInjectRule(rule: Rule) {
+  return [
+    Operator.INJECT_JS_PLUGIN, Operator.INJECT_HTML_CODE,
+    Operator.INJECT_HTML_PLUGIN, Operator.INJECT_JS_CODE
+  ].some(op => op === rule.operator);
+}
+
+/**
+ * Supported operators.
+ */
+export enum Operator {
+  BLOCK = 'block',
+  REDIRECT = 'redirect',
+  INJECT_HTML_PLUGIN = 'injectHtmlPlugin',
+  INJECT_HTML_CODE = 'injectHtmlCode',
+  INJECT_JS_PLUGIN = 'injectJSPlugin',
+  INJECT_JS_CODE = 'injectJSCode',
+}
+
+/**
+ * Rule type.
+ */
+export interface Rule {
+  disabled: boolean;
+  target: string;
+  operator: Operator;
+  destination: string;
+  isNew?: boolean;
+}
\ No newline at end of file
diff --git a/tsconfig.json b/tsconfig.json
new file mode 100644
index 0000000..83d3156
--- /dev/null
+++ b/tsconfig.json
@@ -0,0 +1,13 @@
+{
+    "compilerOptions": {
+        "module": "commonjs",
+        "target": "es6",
+        "resolveJsonModule": true,
+        "noImplicitAny": false,
+        "experimentalDecorators": true,
+        "sourceMap": true,
+        "outDir": "dist",
+        "noEmitOnError": true,
+        "typeRoots": [ "node_modules/@types" ]
+    },
+}
\ No newline at end of file
diff --git a/webpack/webpack.config.js b/webpack/webpack.config.js
new file mode 100644
index 0000000..e109fb4
--- /dev/null
+++ b/webpack/webpack.config.js
@@ -0,0 +1,32 @@
+const path = require('path');
+const srcDir = '../src/';
+
+const MODE = "production";
+
+module.exports = {
+    mode: MODE,
+    entry: {
+        popup: path.join(__dirname, srcDir + 'popup.ts'),
+        background: path.join(__dirname, srcDir + 'background.ts'),
+        content_script: path.join(__dirname, srcDir + 'content_script.ts')
+    },
+    optimization:{
+        minimize: MODE === "production",
+    },
+    output: {
+        path: path.join(__dirname, '../dist/'),
+        filename: '[name].js'
+    },
+    module: {
+        rules: [
+            {
+                test: /\.ts$/,
+                use: 'ts-loader',
+                exclude: /node_modules/
+            }
+        ]
+    },
+    resolve: {
+        extensions: ['.ts', '.js']
+    }
+};
\ No newline at end of file