├── .editorconfig ├── .github └── workflows │ ├── build.yml │ ├── codeql.yml │ └── lint.yml ├── .gitignore ├── .gitmodules ├── .pre-commit-config.yaml ├── .prettierignore ├── LICENSE ├── Makefile ├── README.md ├── package-lock.json ├── package.json ├── src ├── background │ ├── client.ts │ ├── heartbeat.ts │ ├── helpers.ts │ └── main.ts ├── config.ts ├── consent │ ├── index.html │ ├── main.ts │ └── style.css ├── manifest.json ├── popup │ ├── index.html │ ├── main.ts │ └── style.css ├── settings │ ├── index.html │ ├── main.ts │ └── style.css ├── storage.ts └── vite-env.d.ts ├── tsconfig.json └── vite.config.ts /.editorconfig: -------------------------------------------------------------------------------- 1 | # Unix-style newlines with a newline ending every file 2 | [*] 3 | indent_style = space 4 | indent_size = 4 5 | end_of_line = lf 6 | trim_trailing_whitespace = true 7 | charset = utf-8 8 | 9 | # 2 spaces for JS, HTML and CSS/SASS 10 | [*.{ts,js,html,yml,css,scss,sass,less}] 11 | indent_size = 2 12 | 13 | # 4 spaces for markdown 14 | [*.md] 15 | indent_size = 4 16 | trim_trailing_whitespace = false 17 | 18 | # Hard TAB for Makefile 19 | [Makefile] 20 | indent_style = tab 21 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | 3 | on: 4 | push: 5 | branches: [master] 6 | pull_request: 7 | branches: [master] 8 | 9 | jobs: 10 | build: 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - name: Checkout 15 | uses: actions/checkout@v4 16 | with: 17 | submodules: recursive 18 | 19 | - name: Use Node.js 23.x 20 | uses: actions/setup-node@v4 21 | with: 22 | node-version: 23.x 23 | cache: npm 24 | 25 | - name: Build Firefox 26 | run: make build-firefox 27 | - name: Upload artifact 28 | uses: actions/upload-artifact@v4 29 | with: 30 | name: firefox 31 | path: artifacts/firefox.zip 32 | - name: Check reproducibility from src-zip 33 | run: make test-reproducibility-firefox 34 | 35 | - name: Build Chrome 36 | run: make build-chrome 37 | - name: Upload artifact 38 | uses: actions/upload-artifact@v4 39 | with: 40 | name: chrome 41 | path: artifacts/chrome.zip 42 | - name: Check reproducibility from src-zip 43 | run: make test-reproducibility-chrome 44 | 45 | typecheck: 46 | runs-on: ubuntu-latest 47 | 48 | steps: 49 | - name: Checkout 50 | uses: actions/checkout@v4 51 | with: 52 | submodules: recursive 53 | 54 | - name: Use Node.js 23.x 55 | uses: actions/setup-node@v4 56 | with: 57 | node-version: 23.x 58 | cache: npm 59 | 60 | - name: Install dependencies 61 | run: make install 62 | 63 | - name: Typecheck TypeScript 64 | run: make compile 65 | -------------------------------------------------------------------------------- /.github/workflows/codeql.yml: -------------------------------------------------------------------------------- 1 | name: CodeQL 2 | 3 | on: 4 | push: 5 | branches: [master] 6 | pull_request: 7 | branches: [master] 8 | schedule: 9 | - cron: 25 4 * * 3 10 | 11 | jobs: 12 | analyze: 13 | name: Analyze 14 | runs-on: ubuntu-latest 15 | permissions: 16 | actions: read 17 | contents: read 18 | security-events: write 19 | 20 | strategy: 21 | fail-fast: false 22 | matrix: 23 | language: [javascript] 24 | 25 | steps: 26 | - name: Checkout 27 | uses: actions/checkout@v4 28 | with: 29 | submodules: recursive 30 | 31 | - name: Initialize CodeQL 32 | uses: github/codeql-action/init@v3 33 | with: 34 | languages: ${{ matrix.language }} 35 | queries: security-and-quality 36 | 37 | - name: Autobuild 38 | uses: github/codeql-action/autobuild@v3 39 | 40 | - name: Perform CodeQL Analysis 41 | uses: github/codeql-action/analyze@v3 42 | with: 43 | category: /language:${{ matrix.language }} 44 | -------------------------------------------------------------------------------- /.github/workflows/lint.yml: -------------------------------------------------------------------------------- 1 | name: Lint 2 | 3 | on: 4 | push: 5 | branches: [master] 6 | pull_request: 7 | branches: [master] 8 | 9 | jobs: 10 | lint: 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - name: Checkout 15 | uses: actions/checkout@v4 16 | with: 17 | submodules: recursive 18 | 19 | - name: Use Node.js 23.x 20 | uses: actions/setup-node@v4 21 | with: 22 | node-version: 23.x 23 | cache: npm 24 | 25 | - name: Install dependencies 26 | run: npm ci 27 | 28 | - name: Run Prettier 29 | run: npx prettier --check . 30 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | build 3 | artifacts 4 | .DS_Store 5 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "media"] 2 | path = media 3 | url = https://github.com/ActivityWatch/media.git 4 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | repos: 2 | - repo: local 3 | hooks: 4 | - id: make-format 5 | name: Format code 6 | entry: make format 7 | language: system 8 | pass_filenames: false 9 | - id: make-compile 10 | name: TypeScript compile check 11 | entry: make compile 12 | language: system 13 | pass_filenames: false 14 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | media -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: build install clean 2 | 3 | install: 4 | npm ci 5 | 6 | compile: 7 | npx tsc --noEmit 8 | 9 | clean: 10 | rm -rf node_modules build 11 | 12 | format: 13 | npx prettier --write . 14 | 15 | #--------- 16 | ## Building 17 | 18 | dev: 19 | NODE_ENV=development npx vite build --mode development --watch 20 | 21 | # This is what Google wants us to upload when we release a new version to the Addon "store" 22 | build-chrome: install update-chrome zip-build-chrome 23 | 24 | update-chrome: 25 | VITE_TARGET_BROWSER=chrome npx vite build 26 | 27 | # This is what Mozilla wants us to upload when we release a new version to the Addon "store" 28 | build-firefox: install update-firefox zip-build-firefox 29 | 30 | update-firefox: 31 | VITE_TARGET_BROWSER=firefox npx vite build 32 | 33 | #--------- 34 | ## Zipping 35 | 36 | # To build a zip archive for uploading to the Chrome Web Store or Mozilla Addons 37 | zip-build-chrome: 38 | mkdir -p artifacts && cd build && zip -FS ../artifacts/chrome.zip -r * 39 | 40 | zip-build-firefox: 41 | mkdir -p artifacts && cd build && zip -FS ../artifacts/firefox.zip -r * 42 | 43 | # To build a source archive, wanted by Mozilla reviewers. Include media subdir. 44 | # NOTE: we include the .git in the media archive so that it lines up with the output 45 | # of vite 46 | zip-src: 47 | (rm -rfv build && mkdir -p artifacts build) 48 | # archive the main repo 49 | git archive --prefix=aw-watcher-web/ -o build/aw-watcher-web.zip HEAD 50 | # archive the media subrepo 51 | (cd media/ && git archive --prefix=aw-watcher-web/media/ --add-file=.git -o ../build/media.zip HEAD) 52 | # extract the archives into a single directory 53 | (cd build && unzip -q aw-watcher-web.zip) 54 | (cd build && unzip -q media.zip) 55 | # zip the whole thing 56 | (cd build && zip -r ../artifacts/src.zip aw-watcher-web) 57 | # clean up 58 | (cd build && rm -r aw-watcher-web media.zip aw-watcher-web.zip) 59 | 60 | #--------- 61 | ## Reproducibility 62 | 63 | test-reproducibility-setup: 64 | mkdir -p artifacts build 65 | (cd build && rm -rf aw-watcher-web && unzip -q ../artifacts/src.zip) 66 | 67 | # Tests whether the zipped src reliably builds the same as the archive 68 | test-reproducibility-chrome: zip-src build-chrome test-reproducibility-setup 69 | @echo "Building from src-zip..." 70 | @(cd build/aw-watcher-web && make build-chrome && cp artifacts/chrome.zip ../../artifacts/reproducibility-chrome.zip) 71 | @rm -r build/aw-watcher-web 72 | @echo "Checking..." 73 | @test "$$(wc -c artifacts/chrome.zip | awk '{print $$1}')" = \ 74 | "$$(wc -c artifacts/reproducibility-chrome.zip | awk '{print $$1}')" \ 75 | || (echo "❌ Build artifacts are not the same size" && exit 1) 76 | @echo "✅ Build artifacts are the same size" 77 | 78 | # Tests whether the zipped src reliably builds the same as the archive 79 | test-reproducibility-firefox: zip-src build-firefox test-reproducibility-setup 80 | @echo "Building from src-zip..." 81 | @(cd build/aw-watcher-web && make build-firefox && cp artifacts/firefox.zip ../../artifacts/reproducibility-firefox.zip) 82 | @rm -r build/aw-watcher-web 83 | @echo "Checking..." 84 | @test "$$(wc -c artifacts/firefox.zip | awk '{print $$1}')" = \ 85 | "$$(wc -c artifacts/reproducibility-firefox.zip | awk '{print $$1}')" \ 86 | || (echo "❌ Build artifacts are not the same size" && exit 1) 87 | @echo "✅ Build artifacts are the same size" 88 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # aw-watcher-web 2 | 3 | [![Chrome Web Store](https://img.shields.io/chrome-web-store/v/nglaklhklhcoonedhgnpgddginnjdadi.svg)][chrome] 4 | [![Mozilla Add-on](https://img.shields.io/amo/v/aw-watcher-web.svg)][firefox] 5 | 6 | A cross-browser WebExtension that serves as a web browser watcher for [ActivityWatch][activitywatch]. 7 | 8 | ## Installation 9 | 10 | ### Official Releases 11 | 12 | Install from official stores: 13 | 14 | - [Chrome Web Store][chrome] 15 | - [Firefox Add-ons][firefox] 16 | 17 | ### Development Build 18 | 19 | Download the latest development build from our [GitHub Actions][gh-actions]: 20 | 21 | 1. Click on the latest successful workflow run 22 | 2. Scroll down to "Artifacts" 23 | 3. Download either `firefox.zip` or `chrome.zip` 24 | 25 | > [!NOTE] 26 | > 27 | > - GitHub login is required to download artifacts 28 | > - These builds are unsigned and require developer mode/settings 29 | 30 | ### Firefox Enterprise Policy 31 | 32 | > [!NOTE] 33 | > Due to Mozilla Add-on Policy, this is not possible with the Mozilla-hosted versions of the extension. You will need to fork the extension and change a hardcoded value to make this work. 34 | 35 | Due to the above issue, a privacy notice must be displayed to comply with the Mozilla Add-on Policy. This can be pre-accepted by setting the following Firefox Enterprise Policy ([More about Firefox Policies][mozilla-policy]): 36 | 37 | ```json 38 | { 39 | "policies": { 40 | "3rdparty": { 41 | "Extensions": { 42 | "{ef87d84c-2127-493f-b952-5b4e744245bc}": { 43 | "consentOfflineDataCollection": true 44 | } 45 | } 46 | } 47 | } 48 | } 49 | ``` 50 | 51 | ## Building from Source 52 | 53 | ### Prerequisites 54 | 55 | - Node.js (23 or higher) 56 | - Git 57 | - Make 58 | 59 | ### Build Steps 60 | 61 | 1. Clone the repository with submodules: 62 | 63 | ```sh 64 | git clone --recurse-submodules https://github.com/ActivityWatch/aw-watcher-web.git 65 | cd aw-watcher-web 66 | ``` 67 | 68 | 2. Install dependencies: 69 | 70 | ```sh 71 | make install 72 | ``` 73 | 74 | 3. Build the extension: 75 | 76 | ```sh 77 | # For Firefox: 78 | make build-firefox 79 | 80 | # For Chrome: 81 | make build-chrome 82 | ``` 83 | 84 | This will create zip files in the `artifacts` directory: 85 | 86 | - `artifacts/firefox.zip` for Firefox 87 | - `artifacts/chrome.zip` for Chrome 88 | 89 | ### Installing the Development Build 90 | 91 | #### Chrome 92 | 93 | 1. Extract `artifacts/chrome.zip` to a folder 94 | 2. Go to `chrome://extensions` 95 | 3. Enable "Developer mode" 96 | 4. Click "Load unpacked" and select the extracted folder 97 | 98 | #### Firefox 99 | 100 | 1. Go to `about:addons` 101 | 2. Click the gear icon (⚙️) and select "Install Add-on From File..." 102 | 3. Navigate to and select the `artifacts/firefox.zip` file 103 | 104 | > [!NOTE] 105 | > For Firefox, installing unsigned extensions requires Firefox Developer Edition or Nightly. 106 | > In Firefox Developer Edition, you need to set `xpinstall.signatures.required` to `false` in `about:config`. 107 | 108 | [activitywatch]: https://github.com/ActivityWatch/activitywatch 109 | [firefox]: https://addons.mozilla.org/en-US/firefox/addon/aw-watcher-web/ 110 | [chrome]: https://chromewebstore.google.com/detail/activitywatch-web-watcher/nglaklhklhcoonedhgnpgddginnjdadi 111 | [mozilla-policy]: https://mozilla.github.io/policy-templates/ 112 | [gh-actions]: https://github.com/ActivityWatch/aw-watcher-web/actions/workflows/build.yml?query=branch%3Amaster+is%3Asuccess 113 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "type": "module", 3 | "name": "aw-watcher-web", 4 | "license": "MPL-2.0", 5 | "bugs": { 6 | "url": "https://github.com/ActivityWatch/aw-watcher-web/issues" 7 | }, 8 | "repository": { 9 | "type": "git", 10 | "url": "git+https://github.com/ActivityWatch/aw-watcher-web.git" 11 | }, 12 | "dependencies": { 13 | "aw-client": "^0.4.1", 14 | "deep-equal": "^2.2.3", 15 | "p-retry": "^6.2.1", 16 | "webextension-polyfill": "^0.12.0" 17 | }, 18 | "devDependencies": { 19 | "@types/deep-equal": "^1.0.4", 20 | "@types/webextension-polyfill": "^0.12.1", 21 | "prettier": "^3.4.2", 22 | "typescript": "^5.7.3", 23 | "vite": "^6.0.11", 24 | "vite-plugin-web-extension": "^4.4.3" 25 | }, 26 | "prettier": { 27 | "semi": false, 28 | "singleQuote": true 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/background/client.ts: -------------------------------------------------------------------------------- 1 | import config from '../config' 2 | 3 | import { AWClient, IEvent } from 'aw-client' 4 | import retry from 'p-retry' 5 | import { emitNotification, getBrowser, logHttpError } from './helpers' 6 | import { getHostname, getSyncStatus, setSyncStatus } from '../storage' 7 | 8 | export const getClient = () => 9 | new AWClient('aw-client-web', { testing: config.isDevelopment }) 10 | 11 | // TODO: We might want to get the hostname somehow, maybe like this: 12 | // https://stackoverflow.com/questions/28223087/how-can-i-allow-firefox-or-chrome-to-read-a-pcs-hostname-or-other-assignable 13 | export function ensureBucket( 14 | client: AWClient, 15 | bucketId: string, 16 | hostname: string, 17 | ) { 18 | return retry( 19 | () => 20 | client 21 | .ensureBucket(bucketId, 'web.tab.current', hostname) 22 | .catch((err) => { 23 | console.error('Failed to create bucket, retrying...') 24 | logHttpError(err) 25 | return Promise.reject(err) 26 | }), 27 | { forever: true, minTimeout: 500 }, 28 | ) 29 | } 30 | 31 | export async function detectHostname(client: AWClient) { 32 | console.debug('Attempting to detect hostname from server...') 33 | return retry( 34 | () => { 35 | console.debug('Making request to server for hostname...') 36 | return client.getInfo() 37 | }, 38 | { 39 | retries: 3, 40 | onFailedAttempt: (error) => { 41 | console.warn( 42 | `Failed to detect hostname (attempt ${error.attemptNumber}/${error.retriesLeft + error.attemptNumber}):`, 43 | error.message, 44 | ) 45 | }, 46 | }, 47 | ) 48 | .then((info) => { 49 | console.info('Successfully detected hostname:', info.hostname) 50 | return info.hostname 51 | }) 52 | .catch((err) => { 53 | console.error('All attempts to detect hostname failed:', err) 54 | return undefined 55 | }) 56 | } 57 | 58 | export async function sendHeartbeat( 59 | client: AWClient, 60 | bucketId: string, 61 | timestamp: Date, 62 | data: IEvent['data'], 63 | pulsetime: number, 64 | ) { 65 | const hostname = (await getHostname()) ?? 'unknown' 66 | const syncStatus = await getSyncStatus() 67 | return retry( 68 | () => 69 | client.heartbeat(bucketId, pulsetime, { 70 | data, 71 | duration: 0, 72 | timestamp, 73 | }), 74 | { 75 | retries: 3, 76 | onFailedAttempt: () => 77 | ensureBucket(client, bucketId, hostname).then(() => {}), 78 | }, 79 | ) 80 | .then(() => { 81 | if (syncStatus.success === false) { 82 | emitNotification( 83 | 'Now connected again', 84 | 'Connection to ActivityWatch server established again', 85 | ) 86 | } 87 | setSyncStatus(true) 88 | }) 89 | .catch((err) => { 90 | if (syncStatus.success) { 91 | emitNotification( 92 | 'Unable to send event to server', 93 | 'Please ensure that ActivityWatch is running', 94 | ) 95 | } 96 | setSyncStatus(false) 97 | return logHttpError(err) 98 | }) 99 | } 100 | 101 | export const getBucketId = async (): Promise => { 102 | const browser = await getBrowser() 103 | const hostname = await getHostname() 104 | if (hostname !== undefined) { 105 | return `aw-watcher-web-${browser}_${hostname}` 106 | } else { 107 | return `aw-watcher-web-${browser}` 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /src/background/heartbeat.ts: -------------------------------------------------------------------------------- 1 | import browser from 'webextension-polyfill' 2 | import { getActiveWindowTab, getTab, getTabs } from './helpers' 3 | import config from '../config' 4 | import { AWClient, IEvent } from 'aw-client' 5 | import { getBucketId, sendHeartbeat } from './client' 6 | import { getEnabled, getHeartbeatData, setHeartbeatData } from '../storage' 7 | import deepEqual from 'deep-equal' 8 | 9 | async function heartbeat( 10 | client: AWClient, 11 | tab: browser.Tabs.Tab | undefined, 12 | tabCount: number, 13 | ) { 14 | const enabled = await getEnabled() 15 | if (!enabled) { 16 | console.warn('Ignoring heartbeat because client has not been enabled') 17 | return 18 | } 19 | 20 | if (!tab) { 21 | console.warn('Ignoring heartbeat because no active tab was found') 22 | return 23 | } 24 | 25 | if (!tab.url || !tab.title) { 26 | console.warn('Ignoring heartbeat because tab is missing URL or title') 27 | return 28 | } 29 | 30 | const now = new Date() 31 | const data: IEvent['data'] = { 32 | url: tab.url, 33 | title: tab.title, 34 | audible: tab.audible ?? false, 35 | incognito: tab.incognito, 36 | tabCount: tabCount, 37 | } 38 | const previousData = await getHeartbeatData() 39 | if (previousData && !deepEqual(previousData, data)) { 40 | console.debug('Sending heartbeat for previous data', previousData) 41 | await sendHeartbeat( 42 | client, 43 | await getBucketId(), 44 | new Date(now.getTime() - 1), 45 | previousData, 46 | config.heartbeat.intervalInSeconds + 20, 47 | ) 48 | } 49 | console.debug('Sending heartbeat', data) 50 | await sendHeartbeat( 51 | client, 52 | await getBucketId(), 53 | now, 54 | data, 55 | config.heartbeat.intervalInSeconds + 20, 56 | ) 57 | await setHeartbeatData(data) 58 | } 59 | 60 | export const sendInitialHeartbeat = async (client: AWClient) => { 61 | const activeWindowTab = await getActiveWindowTab() 62 | const tabs = await getTabs() 63 | console.debug('Sending initial heartbeat', activeWindowTab) 64 | await heartbeat(client, activeWindowTab, tabs.length) 65 | } 66 | 67 | export const heartbeatAlarmListener = 68 | (client: AWClient) => async (alarm: browser.Alarms.Alarm) => { 69 | if (alarm.name !== config.heartbeat.alarmName) return 70 | const activeWindowTab = await getActiveWindowTab() 71 | if (!activeWindowTab) return 72 | const tabs = await getTabs() 73 | console.debug('Sending heartbeat for alarm', activeWindowTab) 74 | await heartbeat(client, activeWindowTab, tabs.length) 75 | } 76 | 77 | export const tabActivatedListener = 78 | (client: AWClient) => 79 | async (activeInfo: browser.Tabs.OnActivatedActiveInfoType) => { 80 | const tab = await getTab(activeInfo.tabId) 81 | const tabs = await getTabs() 82 | console.debug('Sending heartbeat for tab activation', tab) 83 | await heartbeat(client, tab, tabs.length) 84 | } 85 | -------------------------------------------------------------------------------- /src/background/helpers.ts: -------------------------------------------------------------------------------- 1 | import browser from 'webextension-polyfill' 2 | import { FetchError } from 'aw-client' 3 | import { getBrowserName, setBrowserName } from '../storage' 4 | 5 | export const getTab = (id: number) => browser.tabs.get(id) 6 | export const getTabs = (query: browser.Tabs.QueryQueryInfoType = {}) => 7 | browser.tabs.query(query) 8 | 9 | export const getActiveWindowTab = async (): Promise< 10 | browser.Tabs.Tab | undefined 11 | > => { 12 | const tabs = await getTabs({ 13 | active: true, 14 | currentWindow: true, 15 | }) 16 | 17 | if (tabs.length > 0) { 18 | return tabs[0] 19 | } 20 | 21 | console.debug('No active tab found in current window') 22 | 23 | const allTabs = await getTabs({ 24 | active: true, 25 | }) 26 | 27 | if (allTabs.length > 0) { 28 | return allTabs[0] 29 | } 30 | 31 | console.debug('No active tab found in any window') 32 | 33 | return undefined 34 | } 35 | 36 | export function emitNotification(title: string, message: string) { 37 | browser.notifications.create({ 38 | type: 'basic', 39 | iconUrl: browser.runtime.getURL('logo-128.png'), 40 | title, 41 | message, 42 | }) 43 | } 44 | 45 | export const getBrowser = async (): Promise => { 46 | const storedName = await getBrowserName() 47 | if (storedName) { 48 | return storedName 49 | } 50 | 51 | const browserName = detectBrowser() 52 | 53 | await setBrowserName(browserName) 54 | return browserName 55 | } 56 | 57 | // FIXME: Detect Vivaldi? It seems to be intentionally impossible 58 | export const detectBrowser = () => { 59 | if ((navigator as any).brave?.isBrave()) { 60 | return 'brave' 61 | } else if ( 62 | navigator.userAgent.includes('Opera') || 63 | navigator.userAgent.includes('OPR') 64 | ) { 65 | return 'opera' 66 | } else if (navigator.userAgent.includes('Firefox')) { 67 | return 'firefox' 68 | } else if (navigator.userAgent.includes('Chrome')) { 69 | return 'chrome' 70 | } else if (navigator.userAgent.includes('Safari')) { 71 | return 'safari' 72 | } else { 73 | return 'unknown' 74 | } 75 | } 76 | 77 | export async function logHttpError(error: T) { 78 | if (error instanceof FetchError) { 79 | return error.response 80 | .json() 81 | .then((data) => 82 | console.error( 83 | `Status code: ${error.response.status}, response: ${data.message}`, 84 | ), 85 | ) 86 | .catch(() => console.error(`Status code: ${error.response.status}`)) 87 | } else { 88 | console.error('Unexpected error', error) 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /src/background/main.ts: -------------------------------------------------------------------------------- 1 | import browser from 'webextension-polyfill' 2 | import config from '../config' 3 | import { 4 | heartbeatAlarmListener, 5 | sendInitialHeartbeat, 6 | tabActivatedListener, 7 | } from './heartbeat' 8 | import { getClient, detectHostname } from './client' 9 | import { 10 | getConsentStatus, 11 | getHostname, 12 | setBaseUrl, 13 | setConsentStatus, 14 | setEnabled, 15 | setHostname, 16 | waitForEnabled, 17 | } from '../storage' 18 | 19 | async function getIsConsentRequired() { 20 | if (!config.requireConsent) return false 21 | return browser.storage.managed 22 | .get('consentOfflineDataCollection') 23 | .then((consentOfflineDataCollection) => !consentOfflineDataCollection) 24 | .catch(() => true) 25 | } 26 | 27 | async function autodetectHostname() { 28 | const hostname = await getHostname() 29 | if (hostname === undefined) { 30 | const detectedHostname = await detectHostname(client) 31 | if (detectedHostname !== undefined) { 32 | setHostname(detectedHostname) 33 | } 34 | } 35 | } 36 | 37 | /** Init */ 38 | console.info('Starting...') 39 | 40 | console.debug('Creating client') 41 | const client = getClient() 42 | 43 | browser.runtime.onInstalled.addListener(async () => { 44 | const { consent } = await getConsentStatus() 45 | const isConsentRequired = await getIsConsentRequired() 46 | if (!isConsentRequired || consent) { 47 | if (!isConsentRequired) console.info('Consent is not required') 48 | else if (consent) console.info('Consent required but already accepted') 49 | console.debug('Enabling the extension') 50 | await setEnabled(true) 51 | } else { 52 | console.info('Consent is required...opening consent tab') 53 | await setConsentStatus({ consent, required: true }) 54 | await browser.tabs.create({ 55 | active: true, 56 | url: browser.runtime.getURL('src/consent/index.html'), 57 | }) 58 | } 59 | 60 | await autodetectHostname() 61 | }) 62 | 63 | console.debug('Creating alarms and tab listeners') 64 | browser.alarms.create(config.heartbeat.alarmName, { 65 | periodInMinutes: Math.floor(config.heartbeat.intervalInSeconds / 60), 66 | }) 67 | browser.alarms.onAlarm.addListener(heartbeatAlarmListener(client)) 68 | browser.tabs.onActivated.addListener(tabActivatedListener(client)) 69 | 70 | console.debug('Setting base url') 71 | setBaseUrl(client.baseURL) 72 | .then(() => 73 | console.debug('Waiting for enable before sending initial heartbeat'), 74 | ) 75 | .then(waitForEnabled) 76 | .then(() => sendInitialHeartbeat(client)) 77 | .then(() => console.info('Started successfully')) 78 | 79 | /** 80 | * Keep the service worker alive to prevent Chrome's 5-minute inactivity termination 81 | * This is a workaround for Chrome's behavior of terminating inactive service workers 82 | * https://stackoverflow.com/questions/66618136 83 | */ 84 | if (import.meta.env.VITE_TARGET_BROWSER === 'chrome') { 85 | function setupKeepAlive(): void { 86 | console.debug( 87 | 'Setting up keep-alive ping to prevent service worker termination', 88 | ) 89 | 90 | setInterval( 91 | () => { 92 | console.debug('Keep-alive ping') 93 | // Force some minimal activity 94 | browser.alarms 95 | .get(config.heartbeat.alarmName) 96 | .then(() => console.debug('Keep-alive ping completed')) 97 | .catch((err) => console.error('Keep-alive ping failed:', err)) 98 | }, 99 | 4 * 60 * 1000, 100 | ) // 4 minutes (less than Chrome's ~5 minute timeout) 101 | } 102 | 103 | // Start the keep-alive mechanism 104 | setupKeepAlive() 105 | } 106 | -------------------------------------------------------------------------------- /src/config.ts: -------------------------------------------------------------------------------- 1 | const config = { 2 | isDevelopment: import.meta.env.DEV, 3 | requireConsent: import.meta.env.VITE_TARGET_BROWSER === 'firefox', 4 | heartbeat: { 5 | alarmName: 'heartbeat', 6 | intervalInSeconds: 60, 7 | }, 8 | } 9 | 10 | export default config 11 | -------------------------------------------------------------------------------- /src/consent/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ActivityWatch Consent Dialog 5 | 6 | 7 | 8 | 9 | 10 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /src/consent/main.ts: -------------------------------------------------------------------------------- 1 | import browser from 'webextension-polyfill' 2 | import { setConsentStatus, setEnabled } from '../storage' 3 | 4 | const consentRefused = document.getElementById('consent-refused')! 5 | consentRefused.addEventListener('click', () => { 6 | browser.management.uninstallSelf() 7 | window.close() 8 | }) 9 | 10 | const consentGiven = document.getElementById('consent-given')! 11 | consentGiven.addEventListener('click', async () => { 12 | await setConsentStatus({ consent: true, required: true }) 13 | await setEnabled(true) 14 | window.close() 15 | }) 16 | -------------------------------------------------------------------------------- /src/consent/style.css: -------------------------------------------------------------------------------- 1 | body { 2 | font-family: 'Segoe UI', 'Lucida Grande', Tahoma, sans-serif; 3 | font-size: 100%; 4 | display: flex; 5 | justify-content: center; 6 | } 7 | 8 | .consent { 9 | width: 400px; 10 | } 11 | 12 | hr { 13 | border: 1px solid #ddd; 14 | } 15 | 16 | h1, 17 | h3 { 18 | margin: 0; 19 | } 20 | 21 | button { 22 | cursor: pointer; 23 | font-size: 100%; 24 | } 25 | 26 | .button { 27 | display: inline-block; 28 | color: #333333; 29 | padding: 0.5em; 30 | border-radius: 0.2em; 31 | background-color: #eee; 32 | border: 1px solid #ddd; 33 | } 34 | 35 | .accept { 36 | color: #fff; 37 | background-color: #007ef8; 38 | border: 1px solid #0073e6; 39 | } 40 | 41 | .action-container { 42 | display: flex; 43 | gap: 0.5em; 44 | } 45 | -------------------------------------------------------------------------------- /src/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "{{chrome}}.manifest_version": 3, 3 | "{{firefox}}.manifest_version": 2, 4 | 5 | "name": "ActivityWatch Web Watcher", 6 | "description": "Log the current tab and your browser activity with ActivityWatch.", 7 | "version": "0.5.3", 8 | "icons": { 9 | "128": "logo-128.png" 10 | }, 11 | 12 | "{{chrome}}.action": { 13 | "default_icon": { "128": "logo-128.png" }, 14 | "default_popup": "src/popup/index.html" 15 | }, 16 | "{{firefox}}.browser_action": { 17 | "default_icon": "logo-128.png", 18 | "default_popup": "src/popup/index.html" 19 | }, 20 | 21 | "background": { 22 | "{{chrome}}.service_worker": "src/background/main.ts", 23 | "{{firefox}}.scripts": ["src/background/main.ts"], 24 | "{{firefox}}.persistent": true 25 | }, 26 | 27 | "options_ui": { 28 | "page": "src/settings/index.html" 29 | }, 30 | 31 | "{{firefox}}.permissions": [ 32 | "tabs", 33 | "alarms", 34 | "notifications", 35 | "activeTab", 36 | "storage", 37 | "http://127.0.0.1:5600/api/*", 38 | "http://127.0.0.1:5666/api/*" 39 | ], 40 | "{{chrome}}.permissions": [ 41 | "tabs", 42 | "alarms", 43 | "notifications", 44 | "activeTab", 45 | "storage" 46 | ], 47 | "{{chrome}}.host_permissions": [""], 48 | 49 | "{{firefox}}.browser_specific_settings": { 50 | "gecko": { 51 | "id": "{ef87d84c-2127-493f-b952-5b4e744245bc}" 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/popup/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ActivityWatch Popup 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 |
17 | 18 |
19 | 20 |
21 | 22 | 23 | Open web UI 24 | 25 | 26 | 27 | 28 | Visit forum 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 |
37 | 38 | 39 | 40 | 41 | 44 | 49 | 50 | 51 | 52 | 53 | 56 | 57 | 58 | 59 | 60 | 63 | 64 | 65 | 66 | 67 | 72 | 73 | 74 | 75 | 76 | 81 | 82 |
Enabled: 42 | 43 | 45 | 48 |
Connected: 54 | 55 |
Last sync: 61 | 62 |
Browser: 68 | 69 | 70 | 71 |
Hostname: 77 | 78 | 79 | 80 |
83 | 84 |
85 | 86 | 87 |

88 | If you find any bugs with this watcher, please report them 89 | here. 94 |

95 |
96 | 97 | 98 | 99 | -------------------------------------------------------------------------------- /src/popup/main.ts: -------------------------------------------------------------------------------- 1 | import browser from 'webextension-polyfill' 2 | import config from '../config' 3 | import { 4 | getBaseUrl, 5 | getConsentStatus, 6 | getEnabled, 7 | getSyncStatus, 8 | setEnabled, 9 | watchSyncDate, 10 | watchSyncSuccess, 11 | getBrowserName, 12 | getHostname, 13 | } from '../storage' 14 | 15 | function setConnected(connected: boolean | undefined) { 16 | const connectedColor = connected ? '#00AA00' : '#FF0000' 17 | const connectedCharacter = connected ? '✔' : '✖' 18 | const connectedIcon = document.getElementById('status-connected-icon')! 19 | if (!connectedIcon) throw Error('Connected icon is not defined') 20 | connectedIcon.innerHTML = connectedCharacter 21 | connectedIcon.style.setProperty('color', connectedColor) 22 | } 23 | 24 | function setSyncDate(date: string | undefined) { 25 | const lastSyncString = date ? new Date(date).toLocaleString() : 'never' 26 | const statusLastSync = document.getElementById('status-last-sync') 27 | if (!statusLastSync) throw Error('Status last sync is not defined') 28 | statusLastSync.innerHTML = lastSyncString 29 | } 30 | 31 | async function renderStatus() { 32 | const baseUrl = await getBaseUrl() 33 | const enabled = await getEnabled() 34 | const syncStatus = await getSyncStatus() 35 | const consentStatus = await getConsentStatus() 36 | const browserName = await getBrowserName() 37 | const hostname = await getHostname() 38 | 39 | // Enabled checkbox 40 | const enabledCheckbox = document.getElementById('status-enabled-checkbox') 41 | if (!(enabledCheckbox instanceof HTMLInputElement)) 42 | throw Error('Enable checkbox is not an input') 43 | enabledCheckbox.checked = enabled 44 | 45 | // Consent Button 46 | const showConsentBtn = document.getElementById('status-consent-btn') 47 | if (!(showConsentBtn instanceof HTMLButtonElement)) 48 | throw Error('Show consent button is not a button') 49 | 50 | if (!consentStatus.required || consentStatus.consent) { 51 | enabledCheckbox.removeAttribute('disabled') 52 | showConsentBtn.style.setProperty('display', 'none') 53 | } else { 54 | enabledCheckbox.setAttribute('disabled', '') 55 | showConsentBtn.style.setProperty('display', 'inline-block') 56 | } 57 | 58 | // Connected 59 | setConnected(syncStatus.success) 60 | watchSyncSuccess(setConnected) 61 | 62 | // Last sync 63 | setSyncDate(syncStatus.date) 64 | watchSyncDate(setSyncDate) 65 | 66 | // Testing 67 | if (config.isDevelopment) { 68 | const element = document.getElementById('testing-notice')! 69 | element.innerHTML = 'Extension is running in testing mode' 70 | element.style.setProperty('color', '#F60') 71 | element.style.setProperty('font-size', '1.2em') 72 | } 73 | 74 | // Set webUI button link 75 | const webuiLink = document.getElementById('webui-link') 76 | if (!(webuiLink instanceof HTMLAnchorElement)) 77 | throw Error('Web UI link is not an anchor') 78 | webuiLink.href = baseUrl ?? '#' 79 | 80 | // Browser name 81 | const browserNameElement = document.getElementById('status-browser') 82 | if (!(browserNameElement instanceof HTMLElement)) 83 | throw Error('Browser name element is not defined') 84 | browserNameElement.innerText = browserName ?? 'unknown' 85 | 86 | // Hostname 87 | const hostnameElement = document.getElementById('status-hostname') 88 | if (!(hostnameElement instanceof HTMLElement)) 89 | throw Error('Hostname element is not defined') 90 | hostnameElement.innerText = hostname ?? 'unknown' 91 | } 92 | 93 | function domListeners() { 94 | const enabledCheckbox = document.getElementById('status-enabled-checkbox') 95 | if (!(enabledCheckbox instanceof HTMLInputElement)) 96 | throw Error('Enable checkbox is not an input') 97 | enabledCheckbox.addEventListener('change', async () => { 98 | const enabled = enabledCheckbox.checked 99 | setEnabled(enabled) 100 | }) 101 | 102 | const consentButton = document.getElementById('status-consent-btn')! 103 | consentButton.addEventListener('click', () => { 104 | browser.tabs.create({ 105 | active: true, 106 | url: browser.runtime.getURL('src/consent/index.html'), 107 | }) 108 | }) 109 | 110 | const settingsButton = document.getElementById('settings-btn') 111 | if (!(settingsButton instanceof HTMLAnchorElement)) 112 | throw Error('Settings button is not a link') 113 | settingsButton.addEventListener('click', () => { 114 | browser.runtime.openOptionsPage() 115 | }) 116 | } 117 | 118 | renderStatus() 119 | domListeners() 120 | -------------------------------------------------------------------------------- /src/popup/style.css: -------------------------------------------------------------------------------- 1 | body { 2 | font-family: 'Segoe UI', 'Lucida Grande', Tahoma, sans-serif; 3 | font-size: 100%; 4 | width: 25em; 5 | } 6 | 7 | hr { 8 | border: 1px solid #ddd; 9 | } 10 | 11 | a { 12 | text-decoration: none; 13 | } 14 | 15 | button { 16 | cursor: pointer; 17 | } 18 | 19 | .button { 20 | display: inline-block; 21 | color: #333333; 22 | padding: 0.5em; 23 | margin: 0.5em 0 0.5em 0.5em; 24 | border-radius: 0.2em; 25 | background-color: #eee; 26 | border: 1px solid #ddd; 27 | } 28 | 29 | #status-consent-btn { 30 | display: none; 31 | } 32 | 33 | form { 34 | margin: 0 0.5em; 35 | } 36 | 37 | label { 38 | font-weight: bold; 39 | } 40 | -------------------------------------------------------------------------------- /src/settings/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | ActivityWatch settings 6 | 7 | 8 | 9 | 10 |
11 |
12 | 15 | 16 | 29 | 30 | 37 |
38 | 39 |
40 | 43 | 44 | 51 |
52 | 53 |
54 | 55 |
56 |
57 | 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /src/settings/main.ts: -------------------------------------------------------------------------------- 1 | import browser from 'webextension-polyfill' 2 | import { 3 | getBrowserName, 4 | setBrowserName, 5 | getHostname, 6 | setHostname, 7 | } from '../storage' 8 | import { detectBrowser } from '../background/helpers' 9 | 10 | async function reloadExtension(): Promise { 11 | browser.runtime.reload() 12 | 13 | // Close the settings popup on Chromium based browsers 14 | if (detectBrowser() !== 'firefox') { 15 | window.close() 16 | } 17 | } 18 | 19 | async function saveOptions(e: SubmitEvent): Promise { 20 | e.preventDefault() 21 | 22 | const browserSelect = document.querySelector('#browser') 23 | const customBrowserInput = 24 | document.querySelector('#customBrowser') 25 | if (!browserSelect) return 26 | 27 | let selectedBrowser = browserSelect.value 28 | if (selectedBrowser === 'other' && customBrowserInput?.value) { 29 | selectedBrowser = customBrowserInput.value.toLowerCase() 30 | } 31 | 32 | const hostnameInput = document.querySelector('#hostname') 33 | if (!hostnameInput) return 34 | 35 | const hostname = hostnameInput.value 36 | 37 | const form = e.target as HTMLFormElement 38 | const button = form.querySelector('button') 39 | if (!button) return 40 | 41 | button.textContent = 'Saving...' 42 | button.classList.remove('accept') 43 | 44 | try { 45 | await setBrowserName(selectedBrowser) 46 | await setHostname(hostname) 47 | await reloadExtension() 48 | button.textContent = 'Save' 49 | button.classList.add('accept') 50 | } catch (error) { 51 | console.error('Failed to save options:', error) 52 | button.textContent = 'Error' 53 | button.classList.add('error') 54 | } 55 | } 56 | 57 | function toggleCustomBrowserInput(): void { 58 | const browserSelect = document.querySelector('#browser') 59 | const customInput = document.querySelector('#customBrowser') 60 | 61 | if (browserSelect && customInput) { 62 | const isOther = browserSelect.value === 'other' 63 | customInput.style.display = isOther ? 'block' : 'none' 64 | customInput.required = isOther 65 | } 66 | } 67 | 68 | async function restoreOptions(): Promise { 69 | try { 70 | const browserName = await getBrowserName() 71 | const browserSelect = document.querySelector('#browser') 72 | const customInput = 73 | document.querySelector('#customBrowser') 74 | 75 | if (!browserSelect || !customInput || !browserName) return 76 | 77 | const standardBrowsers = Array.from(browserSelect.options).map( 78 | (opt) => opt.value, 79 | ) 80 | if (!standardBrowsers.includes(browserName)) { 81 | browserSelect.value = 'other' 82 | customInput.style.display = 'block' 83 | customInput.value = browserName 84 | customInput.required = true 85 | } else { 86 | browserSelect.value = browserName 87 | customInput.style.display = 'none' 88 | customInput.required = false 89 | } 90 | 91 | const hostname = await getHostname() 92 | const hostnameInput = document.querySelector('#hostname') 93 | if (!hostnameInput) return 94 | 95 | if (hostname !== undefined) { 96 | hostnameInput.value = hostname 97 | } 98 | } catch (error) { 99 | console.error('Failed to restore options:', error) 100 | } 101 | } 102 | 103 | document.addEventListener('DOMContentLoaded', () => { 104 | restoreOptions() 105 | toggleCustomBrowserInput() 106 | }) 107 | 108 | document 109 | .querySelector('#browser') 110 | ?.addEventListener('change', toggleCustomBrowserInput) 111 | const form = document.querySelector('form') 112 | if (form) { 113 | form.addEventListener('submit', (e: Event) => { 114 | e.preventDefault() 115 | saveOptions(e as SubmitEvent) 116 | }) 117 | } 118 | -------------------------------------------------------------------------------- /src/settings/style.css: -------------------------------------------------------------------------------- 1 | body { 2 | font-family: 'Segoe UI', 'Lucida Grande', Tahoma, sans-serif; 3 | } 4 | 5 | form div { 6 | display: flex; 7 | gap: 10px; 8 | align-items: center; 9 | margin: 0.5em; 10 | } 11 | 12 | input:invalid { 13 | border-color: red; 14 | } 15 | 16 | #customBrowser { 17 | display: none; 18 | } 19 | -------------------------------------------------------------------------------- /src/storage.ts: -------------------------------------------------------------------------------- 1 | import { IEvent } from 'aw-client' 2 | import browser from 'webextension-polyfill' 3 | 4 | function watchKey(key: string, cb: (value: T) => void | Promise) { 5 | const listener = ( 6 | changes: browser.Storage.StorageAreaOnChangedChangesType, 7 | ) => { 8 | if (!(key in changes)) return 9 | cb(changes[key].newValue as T) 10 | } 11 | browser.storage.local.onChanged.addListener(listener) 12 | return () => browser.storage.local.onChanged.removeListener(listener) 13 | } 14 | 15 | async function waitForKey(key: string, desiredValue: T) { 16 | const value = await browser.storage.local.get(key).then((_) => _[key]) 17 | if (value === desiredValue) return 18 | return new Promise((resolve) => { 19 | const unsubscribe = watchKey(key, (value) => { 20 | if (value !== desiredValue) return 21 | resolve() 22 | unsubscribe() 23 | }) 24 | }) 25 | } 26 | 27 | type SyncStatus = { success?: boolean; date?: string } 28 | export const getSyncStatus = (): Promise => 29 | browser.storage.local 30 | .get(['lastSyncSuccess', 'lastSync']) 31 | .then(({ lastSyncSuccess, lastSync }) => ({ 32 | success: 33 | lastSyncSuccess === undefined 34 | ? lastSyncSuccess 35 | : Boolean(lastSyncSuccess), 36 | date: lastSync === undefined ? lastSync : String(lastSync), 37 | })) 38 | export const setSyncStatus = (lastSyncSuccess: boolean) => 39 | browser.storage.local.set({ 40 | lastSyncSuccess, 41 | lastSync: new Date().toISOString(), 42 | }) 43 | export const watchSyncSuccess = ( 44 | cb: (success: boolean | undefined) => void | Promise, 45 | ) => watchKey('lastSyncSuccess', cb) 46 | export const watchSyncDate = ( 47 | cb: (date: string | undefined) => void | Promise, 48 | ) => watchKey('lastSync', cb) 49 | 50 | type ConsentStatus = { consent?: boolean; required?: boolean } 51 | export const getConsentStatus = async (): Promise => 52 | browser.storage.local 53 | .get(['consentRequired', 'consent']) 54 | .then(({ consent, consentRequired }) => ({ 55 | consent: typeof consent === 'boolean' ? consent : undefined, 56 | required: 57 | typeof consentRequired === 'boolean' ? consentRequired : undefined, 58 | })) 59 | export const setConsentStatus = async (status: ConsentStatus): Promise => 60 | browser.storage.local.set({ 61 | consentRequired: status.required, 62 | consent: status.consent, 63 | }) 64 | 65 | type Enabled = boolean 66 | export const waitForEnabled = () => waitForKey('enabled', true) 67 | export const getEnabled = (): Promise => 68 | browser.storage.local.get('enabled').then((_) => Boolean(_.enabled)) 69 | export const setEnabled = (enabled: Enabled) => 70 | browser.storage.local.set({ enabled }) 71 | 72 | type BaseUrl = string 73 | export const getBaseUrl = (): Promise => 74 | browser.storage.local 75 | .get('baseUrl') 76 | .then((_) => _.baseUrl as string | undefined) 77 | export const setBaseUrl = (baseUrl: BaseUrl) => 78 | browser.storage.local.set({ baseUrl }) 79 | 80 | type HeartbeatData = IEvent['data'] 81 | export const getHeartbeatData = (): Promise => 82 | browser.storage.local 83 | .get('heartbeatData') 84 | .then((_) => _.heartbeatData as HeartbeatData | undefined) 85 | export const setHeartbeatData = (heartbeatData: HeartbeatData) => 86 | browser.storage.local.set({ heartbeatData }) 87 | 88 | type BrowserName = string 89 | type StorageData = { [key: string]: any } 90 | export const getBrowserName = (): Promise => 91 | browser.storage.local 92 | .get('browserName') 93 | .then((data: StorageData) => data.browserName as string | undefined) 94 | export const setBrowserName = (browserName: BrowserName) => 95 | browser.storage.local.set({ browserName }) 96 | 97 | type Hostname = string 98 | export const getHostname = (): Promise => 99 | browser.storage.local 100 | .get('hostname') 101 | .then((data: StorageData) => data.hostname as string | undefined) 102 | export const setHostname = (hostname: Hostname) => 103 | browser.storage.local.set({ hostname }) 104 | -------------------------------------------------------------------------------- /src/vite-env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ESNext", 4 | "useDefineForClassFields": true, 5 | "module": "ESNext", 6 | "lib": ["ESNext", "DOM"], 7 | "moduleResolution": "Node", 8 | "strict": true, 9 | "resolveJsonModule": true, 10 | "isolatedModules": true, 11 | "esModuleInterop": true, 12 | "noEmit": true, 13 | "noUnusedLocals": true, 14 | "noUnusedParameters": true, 15 | "noImplicitReturns": true, 16 | "skipLibCheck": true 17 | }, 18 | "include": ["src"] 19 | } 20 | -------------------------------------------------------------------------------- /vite.config.ts: -------------------------------------------------------------------------------- 1 | import { defineConfig } from 'vite' 2 | import webExtension, { readJsonFile } from 'vite-plugin-web-extension' 3 | 4 | function generateManifest() { 5 | const manifest = readJsonFile('src/manifest.json') 6 | const pkg = readJsonFile('package.json') 7 | return { 8 | name: pkg.name, 9 | description: pkg.description, 10 | version: pkg.version, 11 | ...manifest, 12 | } 13 | } 14 | 15 | export default defineConfig({ 16 | build: { 17 | minify: false, 18 | outDir: 'build', 19 | }, 20 | plugins: [ 21 | webExtension({ 22 | manifest: generateManifest, 23 | additionalInputs: ['src/consent/index.html', 'src/consent/main.ts'], 24 | browser: process.env.VITE_TARGET_BROWSER, 25 | }), 26 | ], 27 | }) 28 | --------------------------------------------------------------------------------