├── .babelrc ├── .editorconfig ├── .eslintignore ├── .eslintrc ├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── docs ├── README.md ├── add-zipkin-endpoint.png ├── opening-1.png ├── opening-2.png └── show-traces.png ├── manifest.json ├── package-lock.json ├── package.json ├── src ├── background.js ├── devtools.js ├── html │ ├── devtools.html │ └── panel.html ├── img │ └── icon64.png ├── lib │ ├── ExtensionToPanelPubsub.js │ ├── PanelToExtensionPubsub.js │ ├── PluginStorage.js │ ├── Pubsub.js │ ├── RemoteSetInterval.js │ ├── RemoteStorage.js │ ├── ZipkinPanel.js │ ├── ZipkinPlugin.js │ ├── addNetworkEvents.js │ ├── attachBeforeSendHeadersListener.js │ ├── checkZipkinUI.js │ ├── matchUrl.js │ └── zipkinUI.js └── panel.js ├── test-server.js ├── test └── matchUrl.test.js ├── upload.js ├── webpack.config.js └── zipkin.png /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | ["env", { 4 | "modules": false, 5 | "targets": { 6 | "browsers": ["last 2 Chrome versions", "last 2 Firefox versions"] 7 | } 8 | }], 9 | "react" 10 | ], 11 | "plugins": [ 12 | "transform-object-rest-spread", 13 | "transform-class-properties" 14 | ], 15 | "env": { 16 | "test": { 17 | "plugins": ["transform-es2015-modules-commonjs"] 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | [*.js] 2 | end_of_line = lf 3 | insert_final_newline = true 4 | indent_style = space 5 | indent_size = 2 6 | trim_trailing_whitespace = true 7 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | build/ 2 | dist/ 3 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "root": true, 3 | "parser": "babel-eslint", 4 | "extends": ["airbnb", "prettier"], 5 | "plugins": ["prettier"], 6 | "env": { 7 | "browser": true, 8 | "shared-node-browser": true 9 | }, 10 | "globals": { 11 | "browser": false 12 | }, 13 | "rules": { 14 | "react/jsx-filename-extension": "off", 15 | "class-methods-use-this": "off", 16 | "no-plusplus": "off", 17 | "no-alert": "off", 18 | "no-console": "off", 19 | "prettier/prettier": ["error", { "singleQuote": true, "trailingComma": "all" }] 20 | }, 21 | "overrides": [ 22 | { 23 | "files": "test/**/*", 24 | "env": { 25 | "jest": true 26 | } 27 | } 28 | ] 29 | } 30 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | client-secret.txt 3 | refresh-token.txt 4 | build/ 5 | dist/ 6 | coverage/ 7 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 8 3 | 4 | script: 5 | - npm run build 6 | - npm run lint 7 | 8 | notifications: 9 | webhooks: 10 | urls: 11 | - https://webhooks.gitter.im/e/ead3c37d57527214e9f2 12 | - https://webhooks.gitter.im/e/e57478303f87ecd7bffc 13 | on_success: change 14 | on_failure: always 15 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | 3 | Version 2.0, January 2004 4 | 5 | http://www.apache.org/licenses/ 6 | 7 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 8 | 9 | 1. Definitions. 10 | 11 | "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. 14 | 15 | "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. 16 | 17 | "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. 18 | 19 | "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. 20 | 21 | "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. 22 | 23 | "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). 24 | 25 | "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. 26 | 27 | "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." 28 | 29 | "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. 30 | 31 | 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. 32 | 33 | 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. 34 | 35 | 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: 36 | 37 | You must give any other recipients of the Work or Derivative Works a copy of this License; and 38 | You must cause any modified files to carry prominent notices stating that You changed the files; and 39 | 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 40 | 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. 41 | 42 | 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. 43 | 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. 44 | 45 | 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. 46 | 47 | 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. 48 | 49 | 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. 50 | 51 | 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. 52 | 53 | END OF TERMS AND CONDITIONS -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://travis-ci.org/openzipkin/zipkin-browser-extension.svg?branch=master)](https://travis-ci.org/openzipkin/zipkin-browser-extension) 2 | 3 | # Zipkin Chrome Extension 4 | 5 | This is an extension to the Chrome browser that lets you trigger trace generation when using your application. 6 | 7 | ## Installing 8 | 9 | The Chrome extension can be [installed directly from Chrome Web Store](https://chrome.google.com/webstore/detail/zipkin-chrome-extension/jdpmaacocdhbmkppghmgnjmfikeeldfe). 10 | 11 | The Firefox plugin is not production-ready yet, but can be installed manuelly by building the project from source. 12 | 13 | ## Usage 14 | 15 | Check out the [Usage documentation](https://github.com/openzipkin/zipkin-chrome-extension/blob/master/docs/README.md). 16 | 17 | ## Developing on Chrome 18 | 19 | - git clone [repo url] into [working directory] 20 | - npm install 21 | - npm run dev-chrome 22 | - Follow [Google's guide](https://developer.chrome.com/extensions/getstarted#unpacked) on how to set up 23 | a local development environment for the extension. 24 | 25 | ## Developing on Firefox 26 | 27 | - git clone [repo url] into [working directory] 28 | - npm install 29 | - npm install -g jpm 30 | - npm run dev-firefox 31 | - cd build/firefox 32 | - jpm run 33 | 34 | ## Building 35 | 36 | - npm install 37 | - npm run build 38 | 39 | This will build a .zip file that should be uploaded to Chrome Web Store. 40 | 41 | ## Publishing to Chrome Web Store 42 | 43 | First, you need two API secrets; 44 | 1) create the file `client-secret.txt` in the root directory of this repository, with our client secret. 45 | 2) create the file `refresh-token.txt` in the root directory of this repository, with our refresh token. 46 | 47 | - Upload the artifact to Chrome Web Store: `node upload.js upload` 48 | 49 | - Publish the latest uploaded artifact: `node upload.js publish` 50 | 51 | - Increment the version in the `VERSION` file 52 | 53 | ## Directory structure 54 | 55 | This is the blog post the directory structure of this project is inspired from: 56 | 57 | http://frontendbabel.info/articles/developing-cross-browser-extensions/ 58 | -------------------------------------------------------------------------------- /docs/README.md: -------------------------------------------------------------------------------- 1 | Usage 2 | ===== 3 | 4 | 1) Install the extension, either via Chrome Web Store, or build it manually from source. 5 | 6 | ![Opening 1](https://raw.githubusercontent.com/openzipkin/zipkin-chrome-extension/master/docs/opening-1.png) 7 | 8 | 2) Open Chrome and go to a web site, right-click -> Inspect. This will open Chrome developer tools. 9 | 10 | ![Opening 2](https://raw.githubusercontent.com/openzipkin/zipkin-chrome-extension/master/docs/opening-2.png) 11 | 12 | 3) A panel appears, called Zipkin. Choose it. 13 | 14 | ![Add Zipkin endpoint](https://raw.githubusercontent.com/openzipkin/zipkin-chrome-extension/master/docs/add-zipkin-endpoint.png) 15 | 16 | 4) Here, you'll need to configure the URL to your Zipkin UI/query server. 17 | 18 | Once you've provided a URL, Chrome will attempt to contact that server, and "auto-discover" its configuration. 19 | You can configure multiple Zipkin endpoints if you want to; e.g. one for your development environment, and one for production. 20 | In this example case, we specified there's a Zipkin UI running on http://localhost:9411, which probably isn't what you will have in an actual environment; only if you're running the Zipkin server locally. Usually, it would be set to something like http://zipkin.mysite.com/. 21 | 22 | ![Show traces](https://raw.githubusercontent.com/openzipkin/zipkin-chrome-extension/master/docs/show-traces.png) 23 | 24 | 5) Use your application and generate traces 25 | While you navigate around, Chrome will add Zipkin trace headers to all HTTP requests. In the Zipkin extension, you can 26 | click on a generated trace ID to take you directly to the Zipkin UI, displaying that trace. 27 | -------------------------------------------------------------------------------- /docs/add-zipkin-endpoint.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/openzipkin/zipkin-browser-extension/f02c385e1d239026d435ea18056ceba3c5e7e265/docs/add-zipkin-endpoint.png -------------------------------------------------------------------------------- /docs/opening-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/openzipkin/zipkin-browser-extension/f02c385e1d239026d435ea18056ceba3c5e7e265/docs/opening-1.png -------------------------------------------------------------------------------- /docs/opening-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/openzipkin/zipkin-browser-extension/f02c385e1d239026d435ea18056ceba3c5e7e265/docs/opening-2.png -------------------------------------------------------------------------------- /docs/show-traces.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/openzipkin/zipkin-browser-extension/f02c385e1d239026d435ea18056ceba3c5e7e265/docs/show-traces.png -------------------------------------------------------------------------------- /manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "manifest_version": 2, 3 | "name": "Zipkin Browser Extension", 4 | "devtools_page": "devtools.html", 5 | "background": { 6 | "scripts": [ 7 | "browser-polyfill.js", 8 | "background.bundle.js" 9 | ], 10 | "persistent": true 11 | }, 12 | "icons": { 13 | "48": "icon64.png" 14 | }, 15 | "permissions": [ 16 | "activeTab", 17 | "webRequest", 18 | "webRequestBlocking", 19 | "storage", 20 | "http://*/", 21 | "https://*/" 22 | ] 23 | } 24 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "zipkin-browser-extension", 3 | "version": "0.0.4", 4 | "description": "Lets you trigger Zipkin traces from the browser, while using your application", 5 | "scripts": { 6 | "lint": "eslint .", 7 | "clean": "rimraf build/ dist/", 8 | "dev": "npm run clean && webpack", 9 | "dev:firefox": "npm run dev && web-ext run --source-dir ./build", 10 | "test": "jest", 11 | "build": "npm test && npm run dev" 12 | }, 13 | "author": "OpenZipkin", 14 | "license": "Apache-2.0", 15 | "repository": "openzipkin/zipkin-browser-extension", 16 | "devDependencies": { 17 | "babel-core": "^6.7.4", 18 | "babel-eslint": "^7.2.3", 19 | "babel-loader": "^7.1.2", 20 | "babel-plugin-transform-class-properties": "^6.24.1", 21 | "babel-plugin-transform-es2015-modules-commonjs": "^6.26.0", 22 | "babel-plugin-transform-object-rest-spread": "^6.26.0", 23 | "babel-preset-env": "^1.6.0", 24 | "babel-preset-react": "^6.24.1", 25 | "chrome-dev-webpack-plugin": "^0.3.3", 26 | "copy-webpack-plugin": "^4.0.1", 27 | "eslint": "^4.6.1", 28 | "eslint-config-airbnb": "^15.1.0", 29 | "eslint-config-prettier": "^2.3.0", 30 | "eslint-plugin-import": "^2.7.0", 31 | "eslint-plugin-jsx-a11y": "^5.1.1", 32 | "eslint-plugin-prettier": "^2.2.0", 33 | "eslint-plugin-react": "^7.3.0", 34 | "express": "^4.13.4", 35 | "extract-text-webpack-plugin": "^3.0.0", 36 | "file-loader": "^0.11.2", 37 | "google-auth-library": "^0.9.7", 38 | "jest": "^21.0.1", 39 | "node-fetch": "^1.5.1", 40 | "prettier": "^1.6.1", 41 | "rimraf": "^2.6.1", 42 | "web-ext": "^2.0.0", 43 | "webextension-polyfill": "^0.1.1", 44 | "webpack": "^3.5.5", 45 | "zip-webpack-plugin": "^2.0.0" 46 | }, 47 | "dependencies": { 48 | "prop-types": "^15.5.10", 49 | "random-js": "^1.0.8", 50 | "react": "^15.6.1", 51 | "react-dom": "^15.6.1" 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/background.js: -------------------------------------------------------------------------------- 1 | import ExtensionToPanelPubsub from './lib/ExtensionToPanelPubsub'; 2 | import { RemoteStorageClient } from './lib/RemoteStorage'; 3 | import { RemoteSetIntervalClient } from './lib/RemoteSetInterval'; 4 | import ZipkinPlugin from './lib/ZipkinPlugin'; 5 | 6 | import attachBeforeSendHeadersListener from './lib/attachBeforeSendHeadersListener'; 7 | 8 | attachBeforeSendHeadersListener(browser.webRequest); 9 | 10 | const pubsub = new ExtensionToPanelPubsub(browser.runtime); 11 | const storage = new RemoteStorageClient(pubsub); 12 | const remoteSetInterval = new RemoteSetIntervalClient(pubsub); 13 | // eslint-disable-next-line no-new 14 | new ZipkinPlugin({ 15 | pubsub, 16 | storage, 17 | setInterval: remoteSetInterval.setInterval, 18 | clearInterval: remoteSetInterval.clearInterval, 19 | // network: browser.devtools.network 20 | }); 21 | -------------------------------------------------------------------------------- /src/devtools.js: -------------------------------------------------------------------------------- 1 | browser.devtools.panels.create('Zipkin', 'icon64.png', 'panel.html'); 2 | -------------------------------------------------------------------------------- /src/html/devtools.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Zipkin Chrome Extension 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /src/html/panel.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /src/img/icon64.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/openzipkin/zipkin-browser-extension/f02c385e1d239026d435ea18056ceba3c5e7e265/src/img/icon64.png -------------------------------------------------------------------------------- /src/lib/ExtensionToPanelPubsub.js: -------------------------------------------------------------------------------- 1 | import Pubsub from './Pubsub'; 2 | 3 | export default class ExtensionToPanelPubsub extends Pubsub { 4 | constructor(browserRuntime) { 5 | super(); 6 | const setupConnection = () => { 7 | this.connectionPromise = new Promise(resolve => { 8 | console.log('setting up connection to panel'); 9 | browserRuntime.onConnect.addListener(devToolsConnection => { 10 | console.log('connection to panel established!'); 11 | const devToolsListener = request => { 12 | console.log( 13 | `extension received message ${request.type}`, 14 | request.message, 15 | ); 16 | this.notifySubscribers(request.type, request.message); 17 | }; 18 | devToolsConnection.onMessage.addListener(devToolsListener); 19 | devToolsConnection.onDisconnect.addListener(() => { 20 | console.log('WE DISCONNECTED!'); 21 | devToolsConnection.onMessage.removeListener(devToolsListener); 22 | setupConnection(); 23 | }); 24 | resolve(devToolsConnection); 25 | }); 26 | }); 27 | }; 28 | setupConnection(); 29 | } 30 | 31 | async pub(topic, message = {}) { 32 | this.notifySubscribers(topic, message); 33 | console.log('publishing from extension to panel we need connection first'); 34 | const conn = await this.connectionPromise; 35 | console.log('we now have connection to the panel, we can publish', { 36 | topic, 37 | message, 38 | }); 39 | return conn.postMessage({ type: topic, message }); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/lib/PanelToExtensionPubsub.js: -------------------------------------------------------------------------------- 1 | import Pubsub from './Pubsub'; 2 | 3 | export default class PanelToExtensionPubsub extends Pubsub { 4 | constructor() { 5 | super(); 6 | const connectToBackgroundPage = () => { 7 | console.log('Connecting to extension'); 8 | this.backgroundPageConnection = browser.runtime.connect({ 9 | name: 'devtools-page', 10 | }); 11 | console.log('connected to extension'); 12 | 13 | const messageListener = request => { 14 | console.log(`panel received message ${request.type}`, request.message); 15 | console.log('substribers are', this.handlers); 16 | this.notifySubscribers(request.type, request.message); 17 | }; 18 | 19 | this.backgroundPageConnection.onMessage.addListener(messageListener); 20 | this.backgroundPageConnection.onDisconnect.addListener(() => { 21 | this.backgroundPageConnection.onMessage.removeListener(messageListener); 22 | connectToBackgroundPage(); 23 | }); 24 | }; 25 | connectToBackgroundPage(); 26 | } 27 | pub(topic, message = {}) { 28 | console.log(`publishing from panel to extension ${topic}`, message); 29 | this.notifySubscribers(topic, message); 30 | console.log( 31 | 'all local subscribers were notified, now posting to background page connection', 32 | ); 33 | this.backgroundPageConnection.postMessage({ 34 | type: topic, 35 | message, 36 | }); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/lib/PluginStorage.js: -------------------------------------------------------------------------------- 1 | export default class PluginStorage { 2 | constructor(browserStorage) { 3 | this.browserStorage = browserStorage; 4 | this.listeners = {}; 5 | this.browserStorage.onChanged.addListener(changes => { 6 | Object.entries(changes) 7 | .filter(([key]) => this.listeners[key]) 8 | .forEach(([key, value]) => { 9 | this.listeners[key].forEach(listener => listener(value.newValue)); 10 | }); 11 | }); 12 | } 13 | 14 | async get(key, defaultValue = undefined) { 15 | console.log('sync getting', key); 16 | 17 | const data = await this.browserStorage.sync.get(key); 18 | console.log('sync got', data); 19 | 20 | return data[key] !== undefined ? data[key] : defaultValue; 21 | } 22 | 23 | set(key, value) { 24 | console.log('sync ZETting', value); 25 | const data = {}; 26 | data[key] = value; 27 | 28 | return this.browserStorage.sync.set(data); 29 | } 30 | 31 | onChange(key, listener) { 32 | this.listeners[key] = this.listeners[key] || {}; 33 | this.listeners[key].push(listener); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/lib/Pubsub.js: -------------------------------------------------------------------------------- 1 | // eslint-disable-next-line no-unused-vars 2 | function consoleDebug(msg) { 3 | // This can be uncommented for more debugging 4 | // console.log(msg); 5 | } 6 | 7 | export default class Pubsub { 8 | constructor() { 9 | this.handlers = {}; 10 | this.queryId = 0; 11 | } 12 | 13 | query(topic, message, callback) { 14 | consoleDebug(`query for ${topic}`, message); 15 | const currentQueryId = this.queryId; 16 | const cb = reply => { 17 | if (reply.queryId === currentQueryId) { 18 | consoleDebug(`got reply for ${topic}`, reply); 19 | this.unsub(cb); 20 | callback(reply.response); 21 | } 22 | }; 23 | this.sub(`${topic}.response`, cb); 24 | this.pub(`${topic}.request`, { 25 | queryId: currentQueryId, 26 | query: message, 27 | }); 28 | this.queryId++; 29 | } 30 | 31 | serve(topic, handler) { 32 | consoleDebug(`set up server for ${topic}`); 33 | this.sub(`${topic}.request`, ({ queryId, query }) => { 34 | consoleDebug(`received request for ${topic}(id=${queryId})`, query); 35 | handler(query, response => { 36 | consoleDebug( 37 | `the handler for ${topic} was finished, responding with`, 38 | response, 39 | ); 40 | this.pub(`${topic}.response`, { queryId, response }); 41 | }); 42 | }); 43 | } 44 | 45 | // pub(topic, message) {} is abstract and 46 | // should be implemented by pubsub implementations. 47 | 48 | notifySubscribers(topic, message) { 49 | if (this.handlers[topic]) { 50 | consoleDebug(`notifying subscriber for ${topic}`, message); 51 | this.handlers[topic].forEach(listener => listener(message)); 52 | } 53 | } 54 | 55 | sub(topic, listener) { 56 | consoleDebug('before sub, listeners are', this.handlers[topic]); 57 | this.handlers[topic] = this.handlers[topic] || []; 58 | consoleDebug('attaching listener', listener); 59 | this.handlers[topic].push(listener); 60 | consoleDebug('all handlers are now', this.handlers); 61 | this.handlers[topic].forEach(handler => { 62 | consoleDebug('the type of handler is', handler); 63 | }); 64 | } 65 | 66 | unsub(topic, listener) { 67 | consoleDebug('before unsub, listeners are', this.handlers[topic]); 68 | if (this.handlers[topic]) { 69 | this.handlers[topic].splice(this.handlers[topic].indexOf(listener), 1); 70 | } 71 | consoleDebug('after unsub, listeners are', this.handlers[topic]); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/lib/RemoteSetInterval.js: -------------------------------------------------------------------------------- 1 | export function RemoteSetIntervalClient(pubsub) { 2 | let internalIntervalId = 0; 3 | const callbacks = []; 4 | pubsub.sub('setInterval.response', ({ intervalId }) => { 5 | console.log('Client: received setInterval poll', intervalId); 6 | if (callbacks[intervalId]) { 7 | callbacks[intervalId].call(); 8 | } 9 | }); 10 | 11 | function setInterval(callback, interval) { 12 | console.log( 13 | 'Client: Now setting up remote setInterval', 14 | internalIntervalId, 15 | ); 16 | pubsub.pub('setInterval.request', { 17 | intervalId: internalIntervalId, 18 | interval, 19 | }); 20 | callbacks[internalIntervalId] = callback; 21 | internalIntervalId++; 22 | } 23 | function clearInterval(callback) { 24 | const intervalId = callbacks.indexOf(callback); 25 | if (intervalId !== -1) { 26 | pubsub.pub('setInterval.clear', { intervalId }); 27 | delete callbacks[intervalId]; 28 | } 29 | } 30 | 31 | return { 32 | setInterval, 33 | clearInterval, 34 | }; 35 | } 36 | 37 | export function RemoteSetIntervalServer(pubsub, setInterval, clearInterval) { 38 | const responders = []; 39 | 40 | function makeResponder(intervalId) { 41 | console.log('Server: sending setInterval poll', intervalId); 42 | return () => pubsub.pub('setInterval.response', { intervalId }); 43 | } 44 | 45 | pubsub.sub('setInterval.request', ({ intervalId, interval }) => { 46 | console.log('Server: Received request for setInterval', intervalId); 47 | responders[intervalId] = makeResponder(intervalId); 48 | setInterval(responders[intervalId], interval); 49 | }); 50 | 51 | pubsub.sub('setInterval.clear', ({ intervalId }) => { 52 | clearInterval(responders[intervalId]); 53 | delete responders[intervalId]; 54 | }); 55 | } 56 | -------------------------------------------------------------------------------- /src/lib/RemoteStorage.js: -------------------------------------------------------------------------------- 1 | export class RemoteStorageClient { 2 | constructor(pubsub) { 3 | this.pubsub = pubsub; 4 | } 5 | 6 | get(key, defaultValue = undefined) { 7 | return new Promise(resolve => 8 | this.pubsub.query('remoteStorage.get', { key, defaultValue }, resolve), 9 | ); 10 | } 11 | 12 | set(key, value) { 13 | return new Promise(resolve => 14 | this.pubsub.query('remoteStorage.set', { key, value }, resolve), 15 | ); 16 | } 17 | 18 | onChange(key, listener) { 19 | this.pubsub.sub('remoteStorage.onchange', key, listener); 20 | } 21 | } 22 | 23 | export class RemoteStorageServer { 24 | constructor(pubsub, storage) { 25 | pubsub.serve('remoteStorage.get', ({ key, defaultValue }, callback) => 26 | storage.get(key, defaultValue).then(callback), 27 | ); 28 | pubsub.serve('remoteStorage.set', ({ key, value }, callback) => 29 | storage.set(key, value).then(callback), 30 | ); 31 | pubsub.serve('remoteStorage.onchange', (key, resolve) => 32 | storage.onChange(key, resolve), 33 | ); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/lib/ZipkinPanel.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import PropTypes from 'prop-types'; 3 | import ZipkinUI from './zipkinUI'; 4 | import matchUrl from './matchUrl'; 5 | 6 | export default class ZipkinPanel extends Component { 7 | static propTypes = { 8 | pubsub: PropTypes.shape({ 9 | sub: PropTypes.func().isRequired, 10 | }).isRequired, 11 | themeName: PropTypes.string(), 12 | }; 13 | 14 | static defaultProps = { 15 | themeName: 'default', 16 | }; 17 | 18 | constructor(props) { 19 | super(props); 20 | this.state = { 21 | requests: [], 22 | zipkinUrls: [], 23 | }; 24 | } 25 | 26 | componentDidMount() { 27 | this.props.pubsub.sub( 28 | 'zipkinUrls.status', 29 | this.handleZipkinUrlsChange.bind(this), 30 | ); 31 | this.props.pubsub.sub('navigated', () => this.setState({ requests: [] })); 32 | this.props.pubsub.sub( 33 | 'requestFinished', 34 | this.handleRequestFinished.bind(this), 35 | ); 36 | } 37 | 38 | handleRequestFinished(request) { 39 | const [traceId] = request.headers.filter( 40 | h => h.name.toLowerCase() === 'x-b3-traceid', 41 | ); 42 | if (traceId) { 43 | this.setState({ 44 | requests: [ 45 | ...this.state.requests, 46 | { 47 | traceId: traceId.value, 48 | url: request.url, 49 | }, 50 | ], 51 | }); 52 | } 53 | } 54 | 55 | traceLink(traceId, requestUrl) { 56 | const url = matchUrl(requestUrl, this.state.zipkinUrls); 57 | if (url == null) { 58 | return null; 59 | } 60 | return `${url.url}/traces/${encodeURIComponent(traceId)}`; 61 | } 62 | 63 | handleZipkinUrlsChange(value) { 64 | this.setState({ 65 | zipkinUrls: value, 66 | }); 67 | } 68 | 69 | render() { 70 | const darkTheme = this.props.themeName === 'dark'; 71 | const textColor = darkTheme ? '#a5a5a5' : '#000'; 72 | const linkColor = darkTheme ? '#66ccff' : undefined; 73 | 74 | const alignLeft = { textAlign: 'left', verticalAlign: 'top' }; 75 | return ( 76 |
77 |
78 |
79 |

Zipkin traces

80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | {this.state.requests.length > 0 ? ( 90 | this.state.requests.map(request => ( 91 | 92 | 101 | 102 | 103 | )) 104 | ) : ( 105 | 106 | 110 | 111 | )} 112 | 113 |
TraceRequest
93 | 98 | {request.traceId} 99 | 100 | {request.url}
107 | Recording network activity... Perform a request or hit F5 108 | to record the reload. 109 |
114 |
115 |
116 |
117 | ); 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /src/lib/ZipkinPlugin.js: -------------------------------------------------------------------------------- 1 | import checkZipkinUI from './checkZipkinUI'; 2 | 3 | export default class ZipkinPlugin { 4 | constructor({ pubsub, storage, setInterval, clearInterval /* network */ }) { 5 | this.pubsub = pubsub; 6 | this.storage = storage; 7 | this.setInterval = setInterval; 8 | this.clearInterval = clearInterval; 9 | this.zipkinUrls = []; 10 | 11 | this.pubsub.sub('zipkinUrls.load', this.loadFromStorage.bind(this)); 12 | this.pubsub.sub('zipkinUrls.add', this.addZipkinUrl.bind(this)); 13 | this.pubsub.sub('zipkinUrls.remove', this.removeZipkinUrl.bind(this)); 14 | } 15 | 16 | async loadFromStorage() { 17 | const zipkinUrls = await this.storage.get('zipkinUrls', []); 18 | 19 | await Promise.all( 20 | zipkinUrls 21 | .map(zipkinUrl => { 22 | const exists = this.zipkinUrls.find(z => z.url === zipkinUrl.url); 23 | if (!exists) { 24 | return this.addZipkinUrl(zipkinUrl.url, false); 25 | } 26 | 27 | return undefined; 28 | }) 29 | .filter(Boolean), 30 | ); 31 | 32 | this.publishZipkinUrlStatus(); 33 | } 34 | 35 | publishZipkinUrlStatus() { 36 | this.pubsub.pub('zipkinUrls.status', this.zipkinUrls); 37 | } 38 | 39 | setZipkinUIStatus(url, status, instrumented) { 40 | const zipkinUrl = this.zipkinUrls.find(e => e.url === url); 41 | if (zipkinUrl) { 42 | zipkinUrl.status = status; 43 | zipkinUrl.instrumented = instrumented; 44 | } 45 | this.publishZipkinUrlStatus(); 46 | } 47 | 48 | saveZipkinUrls() { 49 | return this.storage.set( 50 | 'zipkinUrls', 51 | this.zipkinUrls 52 | .map(url => new URL(url.url)) 53 | // Don't save the path part of the URL 54 | .map(url => ({ url: url.origin })), 55 | ); 56 | } 57 | 58 | async addZipkinUrl(inputUrl, saveToStorage = true) { 59 | // Fetch the endpoint to check if we get redirected 60 | const fetchUrl = await fetch(inputUrl); 61 | 62 | if (fetchUrl.body) { 63 | // Never actually download the body 64 | await fetchUrl.body.cancel(); 65 | } 66 | 67 | let url; 68 | if (fetchUrl.redirected && fetchUrl.url === `${inputUrl}/zipkin/`) { 69 | url = `${inputUrl}/zipkin`; 70 | } else { 71 | url = inputUrl; 72 | } 73 | 74 | this.zipkinUrls.push({ 75 | url, 76 | statusCheck: this.makeZipkinCheckInterval(url), 77 | }); 78 | this.publishZipkinUrlStatus(); 79 | if (saveToStorage) { 80 | this.saveZipkinUrls(); 81 | } 82 | } 83 | 84 | removeZipkinUrl(url) { 85 | const zipkinUrl = this.zipkinUrls.find(e => e.url === url); 86 | if (zipkinUrl) { 87 | this.clearInterval(zipkinUrl.statusCheck); 88 | this.zipkinUrls.splice(this.zipkinUrls.indexOf(zipkinUrl), 1); 89 | this.publishZipkinUrlStatus(); 90 | this.saveZipkinUrls(); 91 | } 92 | } 93 | 94 | makeZipkinCheckInterval(url) { 95 | const poll = async () => { 96 | try { 97 | const instrumented = await checkZipkinUI(url); 98 | 99 | this.setZipkinUIStatus(url, 'up', instrumented); 100 | } catch (err) { 101 | this.setZipkinUIStatus(url, err.message || 'down', []); 102 | } 103 | }; 104 | poll(); 105 | return this.setInterval(poll, 30000); 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /src/lib/addNetworkEvents.js: -------------------------------------------------------------------------------- 1 | export default function addNetworkEvents(network, pubsub) { 2 | network.onNavigated.addListener(() => { 3 | pubsub.pub('navigated'); 4 | }); 5 | // https://bugzilla.mozilla.org/show_bug.cgi?id=1311171 6 | if (network.onRequestFinished) { 7 | network.onRequestFinished.addListener(request => { 8 | pubsub.pub('requestFinished', { 9 | headers: request.request.headers, 10 | url: request.request.url, 11 | }); 12 | }); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/lib/attachBeforeSendHeadersListener.js: -------------------------------------------------------------------------------- 1 | import Random from 'random-js'; 2 | 3 | const random = new Random(); 4 | function generateZipkinTraceId() { 5 | return random.hex(16); 6 | } 7 | 8 | const filter = { 9 | urls: ['*://*/*'], 10 | }; 11 | 12 | export default function attachBeforeSendHeadersListener(webRequest) { 13 | webRequest.onBeforeSendHeaders.addListener( 14 | ({ requestHeaders = [] }) => { 15 | const traceId = generateZipkinTraceId(); 16 | const zipkinHeaders = { 17 | 'X-Zipkin-Extension': '1', 18 | // This flag means instrumentation shouldn't throw away this trace 19 | 'X-B3-Sampled': '1', 20 | // This flag means the collection tier shouldn't throw away this trace 21 | 'X-B3-Flags': '1', 22 | 'X-B3-TraceId': traceId, 23 | 'X-B3-SpanId': traceId, 24 | }; 25 | 26 | return { 27 | requestHeaders: [ 28 | ...requestHeaders, 29 | ...Object.entries(zipkinHeaders).map(([name, value]) => ({ 30 | name, 31 | value, 32 | })), 33 | ], 34 | }; 35 | }, 36 | filter, 37 | ['blocking', 'requestHeaders'], 38 | ); 39 | } 40 | -------------------------------------------------------------------------------- /src/lib/checkZipkinUI.js: -------------------------------------------------------------------------------- 1 | export default async function checkZipkinUI(url) { 2 | const fetchUrl = `${url}/config.json`; 3 | 4 | // Used to identity calls originating from within the plugin itself 5 | const res = await fetch(fetchUrl, { headers: { 'X-Zipkin-Extension': '1' } }); 6 | 7 | if (!res.ok) { 8 | throw new Error(`Invalid status: ${res.status}.`); 9 | } 10 | 11 | const data = await res.json(); 12 | 13 | return data.instrumented || '.*'; 14 | } 15 | -------------------------------------------------------------------------------- /src/lib/matchUrl.js: -------------------------------------------------------------------------------- 1 | const matcherCache = {}; 2 | function matches(url, matcher) { 3 | if (!matcherCache[matcher]) { 4 | matcherCache[matcher] = new RegExp(matcher); 5 | } 6 | return matcherCache[matcher].test(url); 7 | } 8 | 9 | module.exports = function matchUrl(requestUrl, zipkinUrls) { 10 | const res = zipkinUrls.find(url => matches(requestUrl, url.instrumented)); 11 | if (!res) { 12 | return null; 13 | } 14 | return res; 15 | }; 16 | -------------------------------------------------------------------------------- /src/lib/zipkinUI.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import PropTypes from 'prop-types'; 3 | import url from 'url'; 4 | 5 | const protocolRegexp = /https?:\/\//; 6 | 7 | export default class ZipkinUI extends Component { 8 | static propTypes = { 9 | pubsub: PropTypes.shape({ 10 | pub: PropTypes.func().isRequired, 11 | sub: PropTypes.func().isRequired, 12 | }).isRequired, 13 | darkTheme: PropTypes.bool(), 14 | }; 15 | 16 | static defaultProps = { 17 | darkTheme: false, 18 | }; 19 | 20 | constructor(props) { 21 | super(props); 22 | this.state = { 23 | zipkinUrl: '', 24 | zipkinUrls: [], 25 | }; 26 | 27 | this.handleSubmit = this.handleSubmit.bind(this); 28 | this.handleUrlChange = this.handleUrlChange.bind(this); 29 | this.handleZipkinStatuses = this.handleZipkinStatuses.bind(this); 30 | } 31 | 32 | componentDidMount() { 33 | this.props.pubsub.pub('zipkinUrls.load'); 34 | this.props.pubsub.sub('zipkinUrls.status', this.handleZipkinStatuses); 35 | } 36 | 37 | handleZipkinStatuses(statuses) { 38 | this.setState({ 39 | zipkinUrls: statuses, 40 | }); 41 | } 42 | 43 | handleSubmit(ev) { 44 | ev.preventDefault(); 45 | const { zipkinUrl } = this.state; 46 | this.setState({ 47 | zipkinUrl: '', 48 | }); 49 | 50 | try { 51 | if (!protocolRegexp.test(zipkinUrl)) { 52 | alert('The URL must start with http:// or https://'); 53 | } else { 54 | const parsed = url.parse(zipkinUrl); 55 | const rebuilt = url.format({ 56 | ...parsed, 57 | pathname: '', 58 | query: '', 59 | }); 60 | 61 | this.props.pubsub.pub('zipkinUrls.add', rebuilt); 62 | } 63 | } catch (err) { 64 | alert(`Couldn't parse url: ${err}`); 65 | } 66 | } 67 | 68 | handleUrlChange(ev) { 69 | this.setState({ 70 | zipkinUrl: ev.target.value, 71 | }); 72 | } 73 | 74 | handleRemoveUrl(removedUrl) { 75 | this.props.pubsub.pub('zipkinUrls.remove', removedUrl); 76 | } 77 | 78 | render() { 79 | const hasZipkinUrls = this.state.zipkinUrls.length > 0; 80 | const alignLeft = { textAlign: 'left', verticalAlign: 'top' }; 81 | const green = this.props.darkTheme ? '#00e600' : '#009900'; 82 | const red = this.props.darkTheme ? '#e60000' : '#990000'; 83 | 84 | return ( 85 |
86 |
87 |
88 | 97 | 98 |
99 |
100 | {hasZipkinUrls ? ( 101 | 102 | 103 | 104 | 105 | 106 | 107 | 109 | 110 | 111 | {this.state.zipkinUrls.map(zipkinUrl => { 112 | const status = 113 | zipkinUrl.status === 'up' 114 | ? '✓' 115 | : zipkinUrl.status || 'unknown status'; 116 | const color = zipkinUrl.status === 'up' ? green : red; 117 | return ( 118 | 119 | 120 | 121 | 122 | 129 | 130 | ); 131 | })} 132 | 133 |
URLStatusInstrumented sites 108 |
{zipkinUrl.url}{status}{zipkinUrl.instrumented} 123 | 128 |
134 | ) : ( 135 |
136 | You need to add the URL to a Zipkin UI in order to view traces. 137 |
138 | )} 139 |
140 | ); 141 | } 142 | } 143 | -------------------------------------------------------------------------------- /src/panel.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { render } from 'react-dom'; 3 | import ZipkinPanel from './lib/ZipkinPanel'; 4 | import PanelToExtensionPubsub from './lib/PanelToExtensionPubsub'; 5 | import PluginStorage from './lib/PluginStorage'; 6 | import { RemoteStorageServer } from './lib/RemoteStorage'; 7 | import addNetworkEvents from './lib/addNetworkEvents'; 8 | import { RemoteSetIntervalServer } from './lib/RemoteSetInterval'; 9 | 10 | const pubsub = new PanelToExtensionPubsub(); 11 | addNetworkEvents(browser.devtools.network, pubsub); 12 | 13 | const storage = new PluginStorage(browser.storage); 14 | // eslint-disable-next-line no-new 15 | new RemoteStorageServer(pubsub, storage); 16 | // eslint-disable-next-line no-new 17 | new RemoteSetIntervalServer(pubsub, window.setInterval, window.clearInterval); 18 | 19 | render( 20 | , 21 | document.getElementById('content'), 22 | ); 23 | -------------------------------------------------------------------------------- /test-server.js: -------------------------------------------------------------------------------- 1 | // This is a simple server that returns a JSON of all the 2 | // request headers that were sent. (Useful for seeing the 3 | // effects of the chrome extension) 4 | const express = require('express'); 5 | 6 | const app = express(); 7 | const port = 8080; 8 | 9 | app.set('json spaces', 2); 10 | 11 | app.get('/config.json', (req, res) => { 12 | res.json({ 13 | instrumented: '\\/\\/example\\.com\\/', 14 | }); 15 | }); 16 | app.get('*', (req, res) => { 17 | console.log('req', req.headers); 18 | res.header('Access-Control-Allow-Origin', '*'); 19 | res.header( 20 | 'Access-Control-Allow-Headers', 21 | 'Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With', 22 | ); 23 | res.header('Access-Control-Allow-Methods', 'GET, PUT, POST'); 24 | console.log('res', res.headers); 25 | res.json(req.headers); 26 | }); 27 | app.listen(port, () => { 28 | console.log(`zipkin-chrome-extension test server running on port ${port}`); 29 | }); 30 | -------------------------------------------------------------------------------- /test/matchUrl.test.js: -------------------------------------------------------------------------------- 1 | const matchUrl = require('../src/lib/matchUrl'); 2 | 3 | describe('urlMatcher', () => { 4 | it('should return null when no match is found', () => { 5 | expect(matchUrl('http://example.com/', [])).toBeNull(); 6 | }); 7 | 8 | it('should match a zipkin url', () => { 9 | const match = matchUrl('http://example.com/', [ 10 | { 11 | instrumented: 'notmatch', 12 | url: 'http://zipkin-nomatch.example.com', 13 | }, 14 | { 15 | instrumented: '.*', 16 | url: 'http://zipkin.example.com', 17 | }, 18 | ]); 19 | expect(match.url).toEqual('http://zipkin.example.com'); 20 | }); 21 | 22 | it('should return the first matching zipkin url', () => { 23 | const match = matchUrl('http://example.com/', [ 24 | { 25 | instrumented: 'notmatch', 26 | url: 'http://zipkin1.example.com', 27 | }, 28 | { 29 | instrumented: '.*', 30 | url: 'http://zipkin2.example.com', 31 | }, 32 | { 33 | instrumented: '.*', 34 | url: 'http://zipkin3.example.com', 35 | }, 36 | ]); 37 | expect(match.url).toEqual('http://zipkin2.example.com'); 38 | }); 39 | }); 40 | -------------------------------------------------------------------------------- /upload.js: -------------------------------------------------------------------------------- 1 | /* eslint "import/no-extraneous-dependencies": ["error", {"devDependencies": true}] */ 2 | 3 | // USAGE: 4 | // node upload.js upload 5 | // node upload.js publish 6 | 7 | const fs = require('fs'); 8 | const GoogleAuth = require('google-auth-library'); 9 | const fetch = require('node-fetch'); 10 | 11 | const command = process.argv[2]; 12 | 13 | const appId = 'jdpmaacocdhbmkppghmgnjmfikeeldfe'; 14 | 15 | const clientId = 16 | '1077732158179-kdth2msv27g08oair1pvo3apu3ievrsm.apps.googleusercontent.com'; 17 | const clientSecret = fs.readFileSync('client-secret.txt', 'utf-8').trim(); 18 | const refreshToken = fs.readFileSync('refresh-token.txt', 'utf-8').trim(); 19 | 20 | const auth = new GoogleAuth(); 21 | const OAuth2 = auth.OAuth2; 22 | const oauth2Client = new OAuth2( 23 | clientId, 24 | clientSecret, 25 | 'urn:ietf:wg:oauth:2.0:oob', 26 | ); 27 | const webstoreScope = 'https://www.googleapis.com/auth/chromewebstore'; 28 | const scopes = [webstoreScope]; 29 | oauth2Client.setCredentials({ 30 | refresh_token: refreshToken, 31 | }); 32 | oauth2Client.refreshAccessToken((err, tokens) => { 33 | if (err) { 34 | console.error('oh no!'); 35 | console.error(err); 36 | const url = oauth2Client.generateAuthUrl({ 37 | access_type: 'offline', 38 | scope: scopes, 39 | }); 40 | console.error('get a new token here', url); 41 | } else if (command === 'upload') { 42 | const data = fs.createReadStream('dist/zipkin-extension.zip'); 43 | // https://developer.chrome.com/webstore/using_webstore_api#uploadexisitng 44 | fetch( 45 | `https://www.googleapis.com/upload/chromewebstore/v1.1/items/${appId}`, 46 | { 47 | method: 'PUT', 48 | body: data, 49 | headers: { 50 | Authorization: `Bearer ${tokens.access_token}`, 51 | 'x-goog-api-version': '2', 52 | }, 53 | }, 54 | ) 55 | .then(res => res.text()) 56 | .then(console.log) 57 | .catch(console.error); 58 | } else if (command === 'publish') { 59 | fetch( 60 | `https://www.googleapis.com/chromewebstore/v1.1/items/${appId}/publish`, 61 | { 62 | method: 'POST', 63 | headers: { 64 | Authorization: `Bearer ${tokens.access_token}`, 65 | 'x-goog-api-version': '2', 66 | }, 67 | }, 68 | ) 69 | .then(res => res.text()) 70 | .then(console.log) 71 | .catch(console.error); 72 | } else { 73 | console.log(`Invalid command "${command}".`); 74 | } 75 | }); 76 | -------------------------------------------------------------------------------- /webpack.config.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | const webpack = require('webpack'); 3 | const ChromeDevPlugin = require('chrome-dev-webpack-plugin'); 4 | const CopyWebpackPlugin = require('copy-webpack-plugin'); 5 | const ZipPlugin = require('zip-webpack-plugin'); 6 | 7 | module.exports = { 8 | entry: { 9 | background: './src/background.js', 10 | devtools: './src/devtools.js', 11 | panel: './src/panel.js', 12 | }, 13 | output: { 14 | filename: '[name].bundle.js', 15 | path: path.join(__dirname, 'build'), 16 | }, 17 | context: __dirname, 18 | module: { 19 | loaders: [ 20 | { 21 | test: /\.js$/, 22 | loader: 'babel-loader', 23 | exclude: ['node_modules'], 24 | }, 25 | ], 26 | }, 27 | plugins: [ 28 | new ChromeDevPlugin(), 29 | new CopyWebpackPlugin([ 30 | { context: path.join(__dirname, 'src/html'), from: '*' }, 31 | { context: path.join(__dirname, 'src/img'), from: '*' }, 32 | { from: require.resolve('webextension-polyfill') }, 33 | ]), 34 | new ZipPlugin({ 35 | path: path.join(__dirname, 'dist'), 36 | filename: 'zipkin-extension.zip', 37 | }), 38 | new webpack.DefinePlugin({ 39 | 'process.env': { 40 | NODE_ENV: '"dev"', 41 | }, 42 | }), 43 | ], 44 | }; 45 | -------------------------------------------------------------------------------- /zipkin.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/openzipkin/zipkin-browser-extension/f02c385e1d239026d435ea18056ceba3c5e7e265/zipkin.png --------------------------------------------------------------------------------