├── .eslintrc.js ├── .github ├── ISSUE_TEMPLATE.md └── PULL_REQUEST_TEMPLATE.md ├── .gitignore ├── .npmrc ├── .prettierrc.json ├── LICENSE ├── README.md ├── docs ├── code-of-conduct.md ├── contributing.md └── screenshot.png ├── package-lock.json ├── package.json ├── public ├── index.html ├── index.js └── style.css └── server ├── crx.js ├── generated └── crx3.js ├── index.js ├── routes ├── extension.js ├── policy.js ├── status.js ├── updates.js └── upload │ ├── directory.js │ └── zip.js ├── state.js └── utils.js /.eslintrc.js: -------------------------------------------------------------------------------- 1 | /* eslint-env node */ 2 | module.exports = { 3 | extends: ["prettier", "eslint:recommended", "plugin:import/recommended"], 4 | plugins: ["prettier"], 5 | rules: { 6 | "prettier/prettier": ["error"], 7 | "no-var": ["error"], 8 | "no-unused-vars": [ 9 | "warn", 10 | { 11 | argsIgnorePattern: "^_", 12 | varsIgnorePattern: "^_" 13 | } 14 | ] 15 | }, 16 | env: { 17 | node: true, 18 | web: true 19 | }, 20 | overrides: [], 21 | parserOptions: { 22 | ecmaVersion: "latest", 23 | sourceType: "module" 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ## Expected Behavior 2 | 3 | 4 | ## Actual Behavior 5 | 6 | 7 | ## Steps to Reproduce the Problem 8 | 9 | 1. 10 | 1. 11 | 1. 12 | 13 | ## Specifications 14 | 15 | - Version: 16 | - Platform: -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | Fixes # 2 | 3 | > It's a good idea to open an issue first for discussion. 4 | 5 | - [ ] Appropriate changes to documentation are included in the PR 6 | - [ ] Tool has been tested locally following changes 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | tmp 2 | node_modules 3 | .DS_STORE 4 | key.pem 5 | -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | engine-strict=true -------------------------------------------------------------------------------- /.prettierrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "printWidth": 80, 3 | "tabWidth": 2, 4 | "semi": true, 5 | "trailingComma": "none", 6 | "bracketSpacing": true, 7 | "arrowParens": "always" 8 | } 9 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Extension Update Testing Tool 2 | 3 | The Extension Update Testing Tool is a local extension update server that can be used for testing updates to Chrome Extensions during local development, including permission grants. 4 | 5 | ![Screenshot of Extension Update Testing Tool](/docs/screenshot.png) 6 | 7 | ## Use Cases 8 | 9 | This tool serves a number of use cases: 10 | 11 | - Testing what permission warnings are generated for specific changes in the manifest.json file. 12 | - Seeing the update flow, including how an extension is disabled until a user grants additional permissions. 13 | - Testing migration logic between versions (this is possible by simply reloading an extension, but using the update logic is closer to what happens when updating from the Chrome Web Store). 14 | 15 | It is particularly useful for (but not limited to) migrations to Manifest V3, since this often involves changes to the permissions an extension requests. 16 | 17 | ## Getting Started 18 | 19 | 1. Install Node.js and NPM: https://nodejs.org/ 20 | 1. Clone this repository. 21 | 1. Run `npm install` in the root of the repository. 22 | 23 | ## How to use 24 | 25 | 1. Run `npm start`. 26 | 1. Open the local server at http://localhost:8080. 27 | 1. Drag an unpacked extension (folder or .zip file) to the page. 28 | 1. Follow the instructions to install the extension. 29 | 1. Drag an updated extension to the page, making sure to update the version field in the manifest.json file. 30 | 1. Click "Update" at chrome://extensions to see the extension update. 31 | 32 | ## Advanced Configuration 33 | 34 | You can configure the port of the local server using the `PORT` environment variable, e.g: 35 | 36 | ``` 37 | PORT=4000 npm start 38 | ``` 39 | 40 | You can also use `WRITE_KEY` to write a private key locally and have a consistent extension ID across restarts, e.g: 41 | 42 | ``` 43 | WRITE_KEY=1 npm start 44 | ``` 45 | 46 | ## FAQ 47 | 48 | ### Why do I see "Package is invalid: 'CRX_REQUIRED_PROOF_MISSING'."? 49 | 50 | This happens if you try to use the policy install methods but haven't set the required policy keys. If you've already set these, you may need to click "Reload policies" at chrome://policy. 51 | 52 | ## Acknowledgements 53 | 54 | This project was inspired by many great community projects, including https://github.com/thom4parisot/crx. 55 | 56 | ## Contributing 57 | 58 | Contributions are welcome. See [How to Contribute](docs/contributing.md) for more information on how to get involved. 59 | -------------------------------------------------------------------------------- /docs/code-of-conduct.md: -------------------------------------------------------------------------------- 1 | # Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, gender identity and expression, level of 9 | experience, education, socio-economic status, nationality, personal appearance, 10 | race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or reject 41 | comments, commits, code, wiki edits, issues, and other contributions that are 42 | not aligned to this Code of Conduct, or to ban temporarily or permanently any 43 | contributor for other behaviors that they deem inappropriate, threatening, 44 | offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | This Code of Conduct also applies outside the project spaces when the Project 56 | Steward has a reasonable belief that an individual's behavior may have a 57 | negative impact on the project or its community. 58 | 59 | ## Conflict Resolution 60 | 61 | We do not believe that all conflict is bad; healthy debate and disagreement 62 | often yield positive results. However, it is never okay to be disrespectful or 63 | to engage in behavior that violates the project’s code of conduct. 64 | 65 | If you see someone violating the code of conduct, you are encouraged to address 66 | the behavior directly with those involved. Many issues can be resolved quickly 67 | and easily, and this gives people more control over the outcome of their 68 | dispute. If you are unable to resolve the matter for any reason, or if the 69 | behavior is threatening or harassing, report it. We are dedicated to providing 70 | an environment where participants feel welcome and safe. 71 | 72 | Reports should be directed to *[PROJECT STEWARD NAME(s) AND EMAIL(s)]*, the 73 | Project Steward(s) for *[PROJECT NAME]*. It is the Project Steward’s duty to 74 | receive and address reported violations of the code of conduct. They will then 75 | work with a committee consisting of representatives from the Open Source 76 | Programs Office and the Google Open Source Strategy team. If for any reason you 77 | are uncomfortable reaching out to the Project Steward, please email 78 | opensource@google.com. 79 | 80 | We will investigate every complaint, but you may not receive a direct response. 81 | We will use our discretion in determining when and how to follow up on reported 82 | incidents, which may range from not taking action to permanent expulsion from 83 | the project and project-sponsored spaces. We will notify the accused of the 84 | report and provide them an opportunity to discuss it before any action is taken. 85 | The identity of the reporter will be omitted from the details of the report 86 | supplied to the accused. In potentially harmful situations, such as ongoing 87 | harassment or threats to anyone's safety, we may take action without notice. 88 | 89 | ## Attribution 90 | 91 | This Code of Conduct is adapted from the Contributor Covenant, version 1.4, 92 | available at 93 | https://www.contributor-covenant.org/version/1/4/code-of-conduct/ 94 | -------------------------------------------------------------------------------- /docs/contributing.md: -------------------------------------------------------------------------------- 1 | # How to Contribute 2 | 3 | We would love to accept your patches and contributions to this project. 4 | 5 | ## Before you begin 6 | 7 | ### Sign our Contributor License Agreement 8 | 9 | Contributions to this project must be accompanied by a 10 | [Contributor License Agreement](https://cla.developers.google.com/about) (CLA). 11 | You (or your employer) retain the copyright to your contribution; this simply 12 | gives us permission to use and redistribute your contributions as part of the 13 | project. 14 | 15 | If you or your current employer have already signed the Google CLA (even if it 16 | was for a different project), you probably don't need to do it again. 17 | 18 | Visit to see your current agreements or to 19 | sign a new one. 20 | 21 | ### Review our Community Guidelines 22 | 23 | This project follows [Google's Open Source Community 24 | Guidelines](https://opensource.google/conduct/). 25 | 26 | ## Contribution process 27 | 28 | ### Code Reviews 29 | 30 | All submissions, including submissions by project members, require review. We 31 | use [GitHub pull requests](https://docs.github.com/articles/about-pull-requests) 32 | for this purpose. 33 | -------------------------------------------------------------------------------- /docs/screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GoogleChromeLabs/extension-update-testing-tool/71750fb68edaa98e2c34123bce2300ae9097e4eb/docs/screenshot.png -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "extension-update-server", 3 | "version": "0.0.1", 4 | "scripts": { 5 | "start": "node server/index.js" 6 | }, 7 | "engines" : { 8 | "node" : ">=14.0.0" 9 | }, 10 | "dependencies": { 11 | "adm-zip": "^0.5.10", 12 | "body-parser": "^1.20.2", 13 | "express": "^4.21.0", 14 | "multer": "^1.4.5-lts.1", 15 | "pbf": "^3.2.1", 16 | "uuid": "^9.0.0" 17 | }, 18 | "devDependencies": { 19 | "eslint": "^8.41.0", 20 | "eslint-config-prettier": "8.6.0", 21 | "eslint-plugin-import": "2.27.5", 22 | "eslint-plugin-prettier": "4.2.1", 23 | "prettier": "^2.8.8" 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 14 | 15 | 16 | 17 | 18 | Extension Update Server 19 | 20 | 21 | 22 |
23 |
24 | 28 |

Upload an extension to get started.

29 | 30 |
31 |
32 |

How to install:

33 |
34 | Install via Policy (macOS) 35 |
    36 |
  1. Download and open the policy file: policy.mobileconfig
  2. 37 |
  3. Install the policy at System Settings > General > Device Management from the menu bar
  4. 38 |
  5. Reload policies in Chrome at chrome://policy
  6. 39 |
  7. Install the extension:
  8. 40 |
41 | 42 |
43 |
44 | Install via Policy (Windows) 45 |

Note: The following commands may overwrite existing policies.

46 |
    47 |
  1. Open Command Prompt as an administrator.
  2. 48 |
  3. Run the following command: reg add HKLM\SOFTWARE\Policies\Google\Chrome\ExtensionInstallAllowlist /v 1 /t REG_SZ /d /f
  4. 49 |
  5. Run the following command: reg add HKLM\SOFTWARE\Policies\Google\Chrome\ExtensionInstallSources /v 1 /t REG_SZ /d /* /f
  6. 50 |
  7. Reload policies in Chrome at chrome://policy
  8. 51 |
  9. Install the extension:
  10. 52 |
53 | 54 |

Hint: You can use the following commands to remove these policies:

55 |

reg delete HKLM\SOFTWARE\Policies\Google\Chrome\ExtensionInstallAllowlist /f

56 |

reg delete HKLM\SOFTWARE\Policies\Google\Chrome\ExtensionInstallSources /f

57 |
58 |
59 | Install manually 60 |

Linux: This is supported in all versions of Chrome.

61 |

Mac and Windows: This method is only supported in Chromium.

62 |
    63 |
  1. Download the extension: Download
  2. 64 |
  3. Drag and drop the file on to the chrome://extensions page.
  4. 65 |
66 |
67 |

Hint: To update the extension, simply enable Developer Mode at chrome://extensions and press "Update" after dragging a new extension here. You must increase the version number for Chrome to update the extension.

68 |
69 |
70 | 71 | 72 | 73 | -------------------------------------------------------------------------------- /public/index.js: -------------------------------------------------------------------------------- 1 | // Copyright 2023 Google LLC 2 | 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | const STATUS_ELEMENT = document.getElementById("status"); 16 | const UPLOAD_ELEMENT = document.getElementById("upload"); 17 | const FILE_INPUT = UPLOAD_ELEMENT.querySelector("input"); 18 | const DOWNLOAD_BUTTON = document.getElementById("download"); 19 | const INSTRUCTIONS_SECTION = document.getElementById("instructions"); 20 | const WINDOWS_POLICY_ID = document.getElementById("windows-policy-id"); 21 | const WINDOWS_POLICY_HOST = document.getElementById("windows-policy-host"); 22 | 23 | let uploaded = false; 24 | 25 | async function onDrop(event) { 26 | if (!event.dataTransfer?.items) return; 27 | 28 | event.preventDefault(); 29 | 30 | const items = event.dataTransfer.items; 31 | 32 | if (items.length > 1) { 33 | STATUS_ELEMENT.innerText = "Error: Drop an extension folder or zip."; 34 | return; 35 | } 36 | 37 | const handle = await items[0].getAsFileSystemHandle(); 38 | 39 | if (handle.kind === "file" && handle.name.endsWith(".zip")) { 40 | // Assume we've been given a valid zip file... 41 | const file = await handle.getFile(); 42 | 43 | STATUS_ELEMENT.innerText = "Uploading..."; 44 | 45 | fetch("/upload/zip", { 46 | method: "POST", 47 | body: await file.arrayBuffer(), 48 | headers: { 49 | "Content-Type": "application/zip" 50 | } 51 | }).then(onUploadFinished); 52 | 53 | return; 54 | } 55 | 56 | if (handle.kind === "directory") { 57 | // Assume we've been given an extension directory 58 | STATUS_ELEMENT.innerText = "Uploading..."; 59 | 60 | fetch("/upload/directory", { 61 | method: "POST", 62 | body: await buildFormDataFromDirectory(handle) 63 | }).then(onUploadFinished); 64 | return; 65 | } 66 | 67 | STATUS_ELEMENT.innerText = "Error: Drop an extension folder or zip."; 68 | } 69 | 70 | async function buildFormDataFromDirectory(directory) { 71 | const formData = new FormData(); 72 | await addFiles(formData, "", directory); 73 | return formData; 74 | } 75 | 76 | async function addFiles(formData, currentPath, directory) { 77 | for await (const entry of directory.values()) { 78 | switch (entry.kind) { 79 | case "file": 80 | const fileToAdd = await entry.getFile(); 81 | formData.append( 82 | "files", 83 | new Blob([await fileToAdd.arrayBuffer()]), 84 | `${currentPath}/${fileToAdd.name}` 85 | ); 86 | break; 87 | case "directory": 88 | const directoryToAdd = entry; 89 | await addFiles( 90 | formData, 91 | `${currentPath}/${directoryToAdd.name}`, 92 | directoryToAdd 93 | ); 94 | break; 95 | } 96 | } 97 | } 98 | 99 | async function onUploadFinished(response) { 100 | const data = await response.json(); 101 | 102 | if (data.success) { 103 | showDownloadInstructions(data.id, data.name, data.version); 104 | } else { 105 | STATUS_ELEMENT.innerText = data.message; 106 | } 107 | } 108 | 109 | function showDownloadInstructions(id, name, version) { 110 | STATUS_ELEMENT.innerText = `Serving "${name}" version ${version}...`; 111 | INSTRUCTIONS_SECTION.removeAttribute("data-disabled"); 112 | 113 | WINDOWS_POLICY_ID.innerText = id; 114 | WINDOWS_POLICY_HOST.innerText = window.location.origin; 115 | } 116 | 117 | async function onDownload(event) { 118 | event.preventDefault(); 119 | 120 | const handle = await showSaveFilePicker({ 121 | suggestedName: "extension.crx", 122 | types: [ 123 | { 124 | description: "Chrome Extension", 125 | accept: { "application/x-chrome-extension": [".crx"] } 126 | } 127 | ] 128 | }); 129 | 130 | const response = await fetch("/extension.crx"); 131 | const data = await response.blob(); 132 | 133 | const writableStream = await handle.createWritable(); 134 | await writableStream.write(data); 135 | await writableStream.close(); 136 | } 137 | 138 | UPLOAD_ELEMENT.addEventListener("dragover", (e) => e.preventDefault()); 139 | UPLOAD_ELEMENT.addEventListener("drop", onDrop); 140 | 141 | FILE_INPUT.addEventListener("change", async (e) => { 142 | if ( 143 | FILE_INPUT.files.length === 1 && 144 | FILE_INPUT.files[0].name.endsWith(".zip") 145 | ) { 146 | STATUS_ELEMENT.innerText = "Uploading..."; 147 | 148 | fetch("/upload/zip", { 149 | method: "POST", 150 | body: await FILE_INPUT.files[0].arrayBuffer(), 151 | headers: { 152 | "Content-Type": "application/zip" 153 | } 154 | }).then(onUploadFinished); 155 | } else { 156 | STATUS_ELEMENT.innerText = "Please select a .zip file."; 157 | } 158 | }); 159 | 160 | DOWNLOAD_BUTTON.addEventListener("click", onDownload); 161 | 162 | fetch("/status") 163 | .then((response) => response.json()) 164 | .then((response) => { 165 | // If the user has already uploaded an extension 166 | if (response.serving) { 167 | showDownloadInstructions(response.id, response.name, response.version); 168 | } else { 169 | STATUS_ELEMENT.innerText = "Upload an extension to get started."; 170 | INSTRUCTIONS_SECTION.setAttribute("data-disabled", true); 171 | } 172 | }); 173 | -------------------------------------------------------------------------------- /public/style.css: -------------------------------------------------------------------------------- 1 | /* Copyright 2023 Google LLC 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | https://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. */ 14 | 15 | .container { 16 | font-family: Arial; 17 | min-height: 100vh; 18 | display: flex; 19 | align-items: center; 20 | justify-content: center; 21 | flex-direction: column; 22 | user-select: none; 23 | font-size: 15px; 24 | } 25 | 26 | section#instructions { 27 | width: 500px; 28 | } 29 | 30 | section#instructions[data-disabled] { 31 | opacity: 0.4; 32 | pointer-events: none; 33 | } 34 | 35 | details { 36 | margin-top: 10px; 37 | border: 1px solid #aaaaaa; 38 | border-radius: 11px; 39 | padding: 10px 13px; 40 | background: white; 41 | user-select: text; 42 | } 43 | 44 | details summary { 45 | user-select: none; 46 | } 47 | 48 | details[open] summary { 49 | margin-bottom: 15px; 50 | } 51 | 52 | details p { 53 | margin: 5px 0; 54 | } 55 | 56 | details code { 57 | display: block; 58 | overflow: scroll; 59 | background: #323232; 60 | color: white; 61 | padding: 6px 12px; 62 | white-space: nowrap; 63 | border-radius: 3px; 64 | margin: 6px 0px; 65 | user-select: all; 66 | } 67 | 68 | #upload { 69 | width: 500px; 70 | height: 300px; 71 | border: 4px dashed grey; 72 | border-radius: 10px; 73 | display: flex; 74 | align-items: center; 75 | justify-content: center; 76 | } 77 | 78 | #upload:hover { 79 | background: #fafafa; 80 | } 81 | 82 | #upload input { 83 | display: none; 84 | } 85 | 86 | button { 87 | margin-top: 5px; 88 | width: calc(100% - 40px); 89 | margin: 0 20px 10px 20px; 90 | padding: 10px 5px; 91 | background-color: #3f51b5; 92 | border-radius: 5px; 93 | border: none; 94 | color: white; 95 | } 96 | 97 | section#uploader p { 98 | opacity: 0.8; 99 | margin-top: 20px; 100 | } 101 | -------------------------------------------------------------------------------- /server/crx.js: -------------------------------------------------------------------------------- 1 | // Copyright 2023 Google LLC 2 | 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | /** 16 | * Utility file that contains helpers for creating .crx files from an unpacked 17 | * extension directory. This uses only the built in Node crypto module. 18 | */ 19 | 20 | const AdmZip = require("adm-zip"); 21 | const Pbf = require("pbf"); 22 | const crypto = require("crypto"); 23 | const { promisify } = require("util"); 24 | const { writeFile, stat, readFile } = require("fs/promises"); 25 | 26 | const { CrxFileHeader, SignedData } = require("./generated/crx3"); 27 | 28 | const SHOULD_WRITE_KEY = process.env.WRITE_KEY === "1"; 29 | let keyPair; 30 | 31 | /** 32 | * Creates a signed .crx file from the unpacked extension directory passed in 33 | * as unpackedFolder. If this function has been called previously, the existing 34 | * keyPair used in memory is used which ensures a stable extension ID across 35 | * versions. Otherwise, a new 2048-bit RSA key is generated. 36 | * 37 | * @param unpackedFolder Location of unpacked extension. 38 | */ 39 | module.exports.createCrx = async function (unpackedFolder) { 40 | if (!keyPair) { 41 | keyPair = await generateKey(); 42 | } 43 | 44 | // Pack extension as .zip and get as buffer 45 | const zip = new AdmZip(); 46 | await zip.addLocalFolderPromise(unpackedFolder); 47 | const zipBuffer = await zip.toBufferPromise(); 48 | 49 | // Get signed header data using key and zip data 50 | const headerData = headerDataForExtension(keyPair, zipBuffer); 51 | 52 | return { 53 | id: getExtensionIdAsString( 54 | keyPair.publicKey.export({ 55 | type: "spki", 56 | format: "der" 57 | }) 58 | ), 59 | packed: Buffer.concat([ 60 | // Magic bytes 61 | Buffer.from("Cr24", "utf8"), 62 | // Version identifier (v3) 63 | new Uint8Array([3, 0, 0, 0]), 64 | // Length of header data 65 | UInt32Le(4, headerData.length), 66 | // Header data 67 | headerData, 68 | // Archive contents 69 | zipBuffer 70 | ]) 71 | }; 72 | }; 73 | 74 | /** 75 | * Gets a SignedData Protocol Buffer containing a given extension ID. This is 76 | * signed as part of the overall crx file header. 77 | * 78 | * @param id Extension ID. 79 | */ 80 | function signedDataForExtensionId(id) { 81 | const pbf = new Pbf(); 82 | SignedData.write({ crx_id: id }, pbf); 83 | return pbf.finish(); 84 | } 85 | 86 | /** 87 | * Gets a CrxFileHeader Protocol Buffer, including signed data for both the 88 | * header and contents. This is directly prepended to the contents of the 89 | * extension archive as part of building a crx file. 90 | * 91 | * @param publicKey Public key associated with privateKey. 92 | * @param privateKey Key to sign header with. 93 | * @param signedData Data to sign in header. 94 | * @param zipBuffer Contents to sign. 95 | */ 96 | function fileHeader(publicKey, privateKey, signedData, zipBuffer) { 97 | const pbf = new Pbf(); 98 | 99 | CrxFileHeader.write( 100 | { 101 | sha256_with_rsa: [ 102 | { 103 | public_key: publicKey, 104 | signature: Buffer.from( 105 | getSignature(privateKey, signedData, zipBuffer), 106 | "binary" 107 | ) 108 | } 109 | ], 110 | signed_header_data: signedData 111 | }, 112 | pbf 113 | ); 114 | 115 | return pbf.finish(); 116 | } 117 | 118 | /** 119 | * Creates a Buffer containg the header data to be prepended to the extension 120 | * archive as part of building a crx file. This is a wrapper around fileHeader 121 | * that takes more readily available data. 122 | * 123 | * @param keyPair Key to sign header with. 124 | * @param zipBuffer Contents to sign. 125 | */ 126 | function headerDataForExtension(keyPair, zipBuffer) { 127 | const publicKey = keyPair.publicKey.export({ 128 | type: "spki", 129 | format: "der" 130 | }); 131 | 132 | const extensionId = getExtensionId(publicKey); 133 | const signedData = signedDataForExtensionId(extensionId); 134 | 135 | const header = fileHeader( 136 | publicKey, 137 | keyPair.privateKey, 138 | signedData, 139 | zipBuffer 140 | ); 141 | 142 | return header; 143 | } 144 | 145 | /** 146 | * Creates a new Buffer of size `size` and stores the value `value`, as an 147 | * unsigned 32-bit int in little-endian. 148 | * 149 | * @param size Size of buffer in bytes. 150 | * @param value Value to store in buffer. 151 | */ 152 | function UInt32Le(size, value) { 153 | const buffer = Buffer.alloc(size); 154 | buffer.writeUInt32LE(value, 0); 155 | return buffer; 156 | } 157 | 158 | /** 159 | * Gets an extension ID as a SHA-256 hash of the public key from the keypair 160 | * used to sign the extension. See `getExtensionIdAsString` to convert this to 161 | * a human-readable string. 162 | * 163 | * @param publicKey Public key associated with keypair used to sign extension. 164 | */ 165 | function getExtensionId(publicKey) { 166 | return crypto.createHash("sha256").update(publicKey).digest().subarray(0, 16); 167 | } 168 | 169 | // prettier-ignore 170 | const BASE16_NORMAL_ALPHABET = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]; 171 | 172 | // prettier-ignore 173 | const BASE16_CRX_ALPHABET = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p"]; 174 | 175 | /** 176 | * Gets a human-readable string associated with the extension ID. This is a 177 | * base16 encoding of the data but using a a-p alphabet instead of the usual 178 | * 0-9a-f. 179 | * 180 | * @param publicKey Public key associated with keypair used to sign extension. 181 | */ 182 | function getExtensionIdAsString(publicKey) { 183 | return getExtensionId(publicKey) 184 | .toString("hex") 185 | .split("") 186 | .map((c) => BASE16_CRX_ALPHABET[BASE16_NORMAL_ALPHABET.indexOf(c)]) 187 | .join(""); 188 | } 189 | 190 | /** 191 | * Gets a signature to include in a crx file header based on the signed header 192 | * data and contents of the archived extension. 193 | * 194 | * @param privateKey Private key used to sign extension. 195 | * @param headerData Header data to sign. 196 | * @param zipBuffer Contents to sign. 197 | * @returns 198 | */ 199 | function getSignature(privateKey, headerData, zipBuffer) { 200 | const hash = crypto.createSign("sha256"); 201 | 202 | hash.update(Buffer.from("CRX3 SignedData\x00", "utf8")); 203 | hash.update(UInt32Le(4, headerData.length)); 204 | hash.update(headerData); 205 | hash.update(zipBuffer); 206 | 207 | return hash.sign(privateKey); 208 | } 209 | 210 | /** 211 | * Generates a new 2048-bit RSA keypair which can be used to sign extensions. 212 | */ 213 | async function generateKey() { 214 | if (SHOULD_WRITE_KEY) { 215 | if ( 216 | await stat("key.pem") 217 | .then((s) => s.isFile()) 218 | .catch(() => false) 219 | ) { 220 | const privateKeyData = await readFile("key.pem"); 221 | const privateKey = crypto.createPrivateKey(privateKeyData); 222 | 223 | return { 224 | publicKey: crypto.createPublicKey(privateKey), 225 | privateKey 226 | }; 227 | } 228 | } 229 | 230 | const generateKeyPair = promisify(crypto.generateKeyPair); 231 | const { publicKey, privateKey } = await generateKeyPair("rsa", { 232 | modulusLength: 2048 233 | }); 234 | 235 | if (SHOULD_WRITE_KEY) { 236 | await writeFile( 237 | "key.pem", 238 | privateKey.export({ type: "pkcs8", format: "pem" }) 239 | ); 240 | } 241 | 242 | return { publicKey, privateKey }; 243 | } 244 | -------------------------------------------------------------------------------- /server/generated/crx3.js: -------------------------------------------------------------------------------- 1 | 'use strict'; // code generated by pbf v3.2.1 2 | 3 | // CrxFileHeader ======================================== 4 | 5 | var CrxFileHeader = exports.CrxFileHeader = {}; 6 | 7 | CrxFileHeader.read = function (pbf, end) { 8 | return pbf.readFields(CrxFileHeader._readField, {sha256_with_rsa: [], sha256_with_ecdsa: [], verified_contents: null, signed_header_data: null}, end); 9 | }; 10 | CrxFileHeader._readField = function (tag, obj, pbf) { 11 | if (tag === 2) obj.sha256_with_rsa.push(AsymmetricKeyProof.read(pbf, pbf.readVarint() + pbf.pos)); 12 | else if (tag === 3) obj.sha256_with_ecdsa.push(AsymmetricKeyProof.read(pbf, pbf.readVarint() + pbf.pos)); 13 | else if (tag === 4) obj.verified_contents = pbf.readBytes(); 14 | else if (tag === 10000) obj.signed_header_data = pbf.readBytes(); 15 | }; 16 | CrxFileHeader.write = function (obj, pbf) { 17 | if (obj.sha256_with_rsa) for (var i = 0; i < obj.sha256_with_rsa.length; i++) pbf.writeMessage(2, AsymmetricKeyProof.write, obj.sha256_with_rsa[i]); 18 | if (obj.sha256_with_ecdsa) for (i = 0; i < obj.sha256_with_ecdsa.length; i++) pbf.writeMessage(3, AsymmetricKeyProof.write, obj.sha256_with_ecdsa[i]); 19 | if (obj.verified_contents) pbf.writeBytesField(4, obj.verified_contents); 20 | if (obj.signed_header_data) pbf.writeBytesField(10000, obj.signed_header_data); 21 | }; 22 | 23 | // AsymmetricKeyProof ======================================== 24 | 25 | var AsymmetricKeyProof = exports.AsymmetricKeyProof = {}; 26 | 27 | AsymmetricKeyProof.read = function (pbf, end) { 28 | return pbf.readFields(AsymmetricKeyProof._readField, {public_key: null, signature: null}, end); 29 | }; 30 | AsymmetricKeyProof._readField = function (tag, obj, pbf) { 31 | if (tag === 1) obj.public_key = pbf.readBytes(); 32 | else if (tag === 2) obj.signature = pbf.readBytes(); 33 | }; 34 | AsymmetricKeyProof.write = function (obj, pbf) { 35 | if (obj.public_key) pbf.writeBytesField(1, obj.public_key); 36 | if (obj.signature) pbf.writeBytesField(2, obj.signature); 37 | }; 38 | 39 | // SignedData ======================================== 40 | 41 | var SignedData = exports.SignedData = {}; 42 | 43 | SignedData.read = function (pbf, end) { 44 | return pbf.readFields(SignedData._readField, {crx_id: null}, end); 45 | }; 46 | SignedData._readField = function (tag, obj, pbf) { 47 | if (tag === 1) obj.crx_id = pbf.readBytes(); 48 | }; 49 | SignedData.write = function (obj, pbf) { 50 | if (obj.crx_id) pbf.writeBytesField(1, obj.crx_id); 51 | }; 52 | -------------------------------------------------------------------------------- /server/index.js: -------------------------------------------------------------------------------- 1 | // Copyright 2023 Google LLC 2 | 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | const state = require("./state"); 16 | const utils = require("./utils"); 17 | 18 | const bodyParser = require("body-parser"); 19 | const express = require("express"); 20 | 21 | const app = express(); 22 | 23 | // Serve public directory on root (HTML, JS files etc.) 24 | app.use("/", express.static("public")); 25 | 26 | // Handle zip based uploads automatically 27 | app.use( 28 | bodyParser.raw({ type: "application/zip", limit: Number.POSITIVE_INFINITY }) 29 | ); 30 | 31 | app.get("/status", require("./routes/status")); 32 | 33 | app.post( 34 | "/upload/directory", 35 | require("./utils").setupTmpDirectory, 36 | require("./routes/upload/directory") 37 | ); 38 | 39 | app.post( 40 | "/upload/zip", 41 | require("./utils").setupTmpDirectory, 42 | require("./routes/upload/zip") 43 | ); 44 | 45 | app.get( 46 | "/extension.crx", 47 | utils.requireExtensionMiddleware, 48 | require("./routes/extension") 49 | ); 50 | 51 | app.get( 52 | "/updates.xml", 53 | utils.requireExtensionMiddleware, 54 | require("./routes/updates") 55 | ); 56 | 57 | app.get( 58 | "/policy.mobileconfig", 59 | utils.requireExtensionMiddleware, 60 | require("./routes/policy") 61 | ); 62 | 63 | app.listen(state.PORT); 64 | console.log(`Listening at http://localhost:${state.PORT}...`); 65 | -------------------------------------------------------------------------------- /server/routes/extension.js: -------------------------------------------------------------------------------- 1 | // Copyright 2023 Google LLC 2 | 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | const path = require("path"); 16 | 17 | module.exports = (_, res) => { 18 | res.setHeader("Content-Type", "application/x-chrome-extension"); 19 | res.sendFile(path.resolve("tmp/extension.crx")); 20 | }; 21 | -------------------------------------------------------------------------------- /server/routes/policy.js: -------------------------------------------------------------------------------- 1 | // Copyright 2023 Google LLC 2 | 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | const uuid = require("uuid"); 16 | const state = require("../state"); 17 | 18 | module.exports = (_, res) => { 19 | res.setHeader("Content-Disposition", "attachment"); 20 | res.setHeader("Content-Type", "application/xml"); 21 | res.send(generateMobileConfig(state.getExtension().id)); 22 | }; 23 | 24 | function generateMobileConfig(extensionId) { 25 | const rootPayloadUuid = uuid.v4(); 26 | const chromePayloadUuid = uuid.v4(); 27 | 28 | return ` 29 | 30 | 31 | 32 | PayloadContent 33 | 34 | 35 | PayloadContent 36 | 37 | com.google.Chrome 38 | 39 | Forced 40 | 41 | 42 | mcx_preference_settings 43 | 44 | ExtensionInstallAllowlist 45 | 46 | ${extensionId} 47 | 48 | ExtensionInstallSources 49 | 50 | http://localhost:${state.PORT}/* 51 | 52 | 53 | 54 | 55 | 56 | 57 | PayloadEnabled 58 | 59 | PayloadIdentifier 60 | ${chromePayloadUuid} 61 | PayloadType 62 | com.apple.ManagedClient.preferences 63 | PayloadUUID 64 | ${chromePayloadUuid} 65 | PayloadVersion 66 | 1 67 | 68 | 69 | PayloadDescription 70 | Config generated by the extension-update-server tool 71 | PayloadDisplayName 72 | Extension Update Server 73 | PayloadIdentifier 74 | extensionupdateserver 75 | PayloadOrganization 76 | 77 | PayloadRemovalDisallowed 78 | 79 | PayloadScope 80 | System 81 | PayloadType 82 | Configuration 83 | PayloadUUID 84 | ${rootPayloadUuid} 85 | PayloadVersion 86 | 1 87 | 88 | `; 89 | } 90 | -------------------------------------------------------------------------------- /server/routes/status.js: -------------------------------------------------------------------------------- 1 | // Copyright 2023 Google LLC 2 | 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | const state = require("../state"); 16 | 17 | module.exports = (_, res) => { 18 | const extension = state.getExtension(); 19 | 20 | res.setHeader("Content-Type", "application/json"); 21 | res.send( 22 | JSON.stringify( 23 | extension 24 | ? { 25 | serving: true, 26 | id: extension.id, 27 | name: extension.name, 28 | version: extension.version 29 | } 30 | : { serving: false } 31 | ) 32 | ); 33 | }; 34 | -------------------------------------------------------------------------------- /server/routes/updates.js: -------------------------------------------------------------------------------- 1 | // Copyright 2023 Google LLC 2 | 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | const state = require("../state"); 16 | 17 | module.exports = (req, res) => { 18 | res.setHeader("Content-Type", "application/xml"); 19 | 20 | const { id, version } = state.getExtension(); 21 | 22 | // prettier-ignore 23 | res.send(` 24 | 25 | 26 | 27 | 28 | 29 | 30 | `.trim()); 31 | }; 32 | -------------------------------------------------------------------------------- /server/routes/upload/directory.js: -------------------------------------------------------------------------------- 1 | // Copyright 2023 Google LLC 2 | 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | const { mkdir } = require("fs/promises"); 16 | const path = require("path"); 17 | 18 | const utils = require("../../utils"); 19 | 20 | const multer = require("multer"); 21 | 22 | const upload = multer({ 23 | storage: multer.diskStorage({ 24 | destination: "tmp/unpacked", 25 | filename: async (_, file, cb) => { 26 | const filePath = path.resolve( 27 | "tmp/unpacked", 28 | file.originalname.replace(/^\//, "") 29 | ); 30 | await mkdir(path.dirname(filePath), { recursive: true }); 31 | cb(null, file.originalname); 32 | } 33 | }), 34 | preservePath: true 35 | }); 36 | 37 | module.exports = utils.makeUploadHandler((req, res) => { 38 | return new Promise((resolve, reject) => { 39 | upload.array("files")(req, res, (err) => { 40 | if (err) { 41 | reject(new Error("Unable to upload files")); 42 | } 43 | 44 | resolve(); 45 | }); 46 | }); 47 | }); 48 | -------------------------------------------------------------------------------- /server/routes/upload/zip.js: -------------------------------------------------------------------------------- 1 | // Copyright 2023 Google LLC 2 | 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | const { mkdir, writeFile } = require("fs/promises"); 16 | 17 | const AdmZip = require("adm-zip"); 18 | 19 | const utils = require("../../utils"); 20 | 21 | module.exports = utils.makeUploadHandler(async (req) => { 22 | // Download the file 23 | await writeFile("tmp/extension.zip", new Uint8Array(req.body)); 24 | 25 | // Extract the extension 26 | const zip = new AdmZip("tmp/extension.zip"); 27 | 28 | await mkdir("tmp/unpacked", { recursive: true }); 29 | 30 | await new Promise((resolve, reject) => 31 | zip.extractAllToAsync("tmp/unpacked", true, false, (err) => { 32 | if (err) reject(err); 33 | resolve(undefined); 34 | }) 35 | ); 36 | }); 37 | -------------------------------------------------------------------------------- /server/state.js: -------------------------------------------------------------------------------- 1 | // Copyright 2023 Google LLC 2 | 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | let _lastExtensionId; 16 | let _lastExtensionName; 17 | let _lastExtensionVersion; 18 | 19 | module.exports.PORT = process.env.PORT ? parseInt(process.env.PORT) : 8080; 20 | 21 | /** 22 | * Saves information about the last uploaded extension in memory. This is used 23 | * when building policy files, update XML files etc. 24 | * 25 | * @param {*} id ID of the extension. 26 | * @param {*} version Value of the version field in the extension manifest. 27 | */ 28 | module.exports.setExtension = function (id, name, version) { 29 | _lastExtensionId = id; 30 | _lastExtensionName = name; 31 | _lastExtensionVersion = version; 32 | }; 33 | 34 | /** 35 | * Gets information about the last uploaded extension in memory. 36 | */ 37 | module.exports.getExtension = function () { 38 | if (!_lastExtensionId || !_lastExtensionName || !_lastExtensionVersion) 39 | return undefined; 40 | 41 | return { 42 | id: _lastExtensionId, 43 | name: _lastExtensionName, 44 | version: _lastExtensionVersion 45 | }; 46 | }; 47 | -------------------------------------------------------------------------------- /server/utils.js: -------------------------------------------------------------------------------- 1 | // Copyright 2023 Google LLC 2 | 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | const { readFile, writeFile, rm, mkdir } = require("fs/promises"); 16 | 17 | const crx = require("./crx"); 18 | const state = require("./state"); 19 | 20 | /** 21 | * Express middleware function that clears the tmp directory ready to handle 22 | * a new upload. This should be used before any request handling that involves 23 | * uploading a new extension version. 24 | */ 25 | module.exports.setupTmpDirectory = async function (req, res, next) { 26 | await rm("tmp", { recursive: true, force: true }); 27 | await mkdir("tmp/unpacked", { recursive: true }); 28 | next(); 29 | }; 30 | 31 | /** 32 | * Creates a request handler which processes the extension in tmp/unpacked and 33 | * generates a new crx file based on it. The unpack parameter can be used to 34 | * run steps beforehand, such as saving file data from the request to disk or 35 | * extracting a zip file. 36 | * 37 | * @param unpack Function to run to upload and unpack request data. 38 | * @returns An express request handler. 39 | */ 40 | module.exports.makeUploadHandler = function (unpack) { 41 | return async (req, res) => { 42 | // Handle any custom unpacking steps first (e.g zip extraction) 43 | if (unpack) { 44 | await unpack(req, res); 45 | } 46 | 47 | let manifestBuffer; 48 | 49 | try { 50 | // Read manifest.json from disk 51 | manifestBuffer = await readFile("tmp/unpacked/manifest.json"); 52 | } catch (e) { 53 | return respondWithError(res, e, "Unable to open manifest.json"); 54 | } 55 | 56 | let manifest; 57 | 58 | try { 59 | manifest = JSON.parse(manifestBuffer.toString("utf-8")); 60 | } catch (e) { 61 | return respondWithError(res, e, "Unable to parse manifest.json"); 62 | } 63 | 64 | if (manifest.version === state.getExtension()?.version) { 65 | return respondWithError( 66 | res, 67 | undefined, 68 | "Please increase the version field in the manifest." 69 | ); 70 | } 71 | 72 | manifest.update_url = `http://${req.hostname}:${state.PORT}/updates.xml`; 73 | 74 | try { 75 | await writeFile("tmp/unpacked/manifest.json", JSON.stringify(manifest)); 76 | } catch (e) { 77 | return respondWithError(res, e, "Unable to write updated manifest.json"); 78 | } 79 | 80 | if (!manifest.name || !manifest.version) { 81 | return respondWithError( 82 | res, 83 | undefined, 84 | "Manifest is missing name or version." 85 | ); 86 | } 87 | 88 | let id, packed; 89 | 90 | try { 91 | const result = await crx.createCrx("tmp/unpacked"); 92 | id = result.id; 93 | packed = result.packed; 94 | } catch (e) { 95 | return respondWithError(res, e, "Unable to generated signed crx."); 96 | } 97 | 98 | try { 99 | await writeFile("tmp/extension.crx", packed); 100 | } catch (e) { 101 | return respondWithError(res, e, "Unable to write crx to disk."); 102 | } 103 | 104 | state.setExtension(id, manifest.name, manifest.version); 105 | 106 | res.setHeader("Content-Type", "application/json"); 107 | res.send( 108 | JSON.stringify({ 109 | success: true, 110 | id, 111 | name: manifest.name, 112 | version: manifest.version 113 | }) 114 | ); 115 | }; 116 | }; 117 | 118 | function respondWithError(res, error, message) { 119 | if (error) { 120 | console.error("Error uploading new extension:", error); 121 | } 122 | 123 | res.setHeader("Content-Type", "application/json"); 124 | res.send(JSON.stringify({ success: false, message })); 125 | } 126 | 127 | /** 128 | * Express middleware which causes a 404 error if a route is called but the 129 | * user has not yet uploaded an extension. This can be used in place of 130 | * explicitly checking that an extension has been uploaded in any route that 131 | * requires this to have been done. 132 | */ 133 | module.exports.requireExtensionMiddleware = async function (req, res, next) { 134 | if (!state.getExtension()) { 135 | res.status(404); 136 | res.send("No extension found."); 137 | return; 138 | } 139 | 140 | next(); 141 | }; 142 | --------------------------------------------------------------------------------