├── .github └── workflows │ └── build_crx.yml ├── LICENSE ├── README.md ├── background.js ├── crypto.js ├── firebase-app.js ├── firebase-auth.js ├── firebase-firestore.js ├── img ├── icon128.png ├── icon16.png ├── icon32.png └── icon48.png ├── manifest.json ├── options.html ├── options.js ├── popup.css ├── popup.html ├── popup.js ├── serverside ├── README.md ├── firestore_security_rules └── index.js └── toolbox.js /.github/workflows/build_crx.yml: -------------------------------------------------------------------------------- 1 | # Build crx for Kiwi Browser Sync 2 | name: automatic build of crx 3 | 4 | # Controls when the action will run. Triggers the workflow on push or pull request events 5 | on: 6 | workflow_dispatch: 7 | push: 8 | paths-ignore: 9 | - '*.md' 10 | - '*.yml' 11 | branches: [ master ] 12 | pull_request: 13 | paths-ignore: 14 | - '*.md' 15 | - '*.yml' 16 | branches: [ master ] 17 | 18 | jobs: 19 | build: 20 | # The type of runner that the job will run on 21 | runs-on: ubuntu-latest 22 | 23 | steps: 24 | - name: Checking-out source-code in $GITHUB_WORKSPACE 25 | uses: actions/checkout@v2 26 | 27 | - uses: cardinalby/webext-buildtools-pack-extension-dir-action@v1 28 | with: 29 | extensionDir: '.' 30 | crxFilePath: './extension.zip' 31 | 32 | - uses: cardinalby/webext-buildtools-chrome-crx-action@v2 33 | with: 34 | zipFilePath: './extension.zip' 35 | crxFilePath: './extension.crx' 36 | 37 | - name: Creating release 38 | id: create_release 39 | uses: actions/create-release@v1 40 | env: 41 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 42 | with: 43 | tag_name: ${{ github.run_id }} 44 | release_name: Generation ${{ github.run_id }} 45 | draft: false 46 | prerelease: true 47 | body: | 48 | This release was automatically generated from GitHub ${{ github.ref }} in run ID ${{ github.run_id }}. 49 | 50 | - name: Uploading CRX into GitHub release 51 | uses: actions/upload-release-asset@v1 52 | env: 53 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 54 | with: 55 | upload_url: ${{ steps.create_release.outputs.upload_url }} 56 | asset_path: ./extension.crx 57 | asset_name: Kiwi-Sync-${{ github.run_id }}.crx 58 | asset_content_type: application/x-chrome-extension 59 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Kiwi Sync 2 | Open-source Chrome Extension for Bookmarks and Profile sync 3 | 4 | Copyright 2020 Geometry OU / Kiwi Browser 5 | 6 | Licensed under GPL 7 | 8 | ![cloud sync](https://cloud.google.com/images/firestore/sync-data-across-devices.png) 9 | 10 | Kiwi Sync will appear on the top right of your address bar. 11 | To invoke Kiwi Sync, press CTRL-Shift-F (on Windows), or CTRL-F (on MacOS) and Kiwi Sync will search accross all your bookmarks very, very, very fast (faster than Chrome). 12 | 13 | What's implemented: 14 | - A blazingly fast way to search local and remote bookmarks 15 | - Live synchronisation of bookmarks across multiple devices 16 | - Offline synchronisation (you can add bookmarks while offline, and come back few minutes or days later). 17 | - Strong cryptography 18 | - Cross-browser support 19 | - Keyboard shortcut 20 | - Keyboard navigation with arrows 21 | 22 | WARNING: THIS EXTENSION IS IN DEVELOPMENT: 23 | == 24 | This is an extension that will send your bookmarks to a private folder created specifically for you on a public server. 25 | 26 | The bookmarks are encrypted, and there is strong encryption (heh! there's a challenge for you to break it!). 27 | 28 | There are NO KNOWN WAYS to decrypt user data. 29 | However: 30 | This extension is in DEVELOPMENT and provided WITHOUT ANY GUARANTEE. It is NOT recommended to use it. 31 | The bookmarks you are syncing may be LEAKED. Do not sync secrets. 32 | Do not use it in a profile where your bookmarks are secret until it is thoroughly tested 33 | or if you are not ready to accept to lose your local bookmarks in case of a bug. 34 | 35 | What's missing: 36 | - [x] Mobile UI (to use inside Kiwi!) 37 | - [x] UI to add a new device 38 | - [ ] UI to remove a device 39 | - [ ] UI to delete data from the server 40 | - [ ] UI to choose the Firebase server where to sync to (for users who want to host their own instance) 41 | - [ ] A reverse proxy for Chinese users to be able to access Firestore from China 42 | 43 | Precepts: 44 | - Sync server *can* be compromised, and this should *not* impact user privacy. 45 | - The user should not have to trust the Sync server. 46 | - Users prefers to be anonymous (avoid Google SSO for example). 47 | 48 | The main concept: 49 | - Each user generates a 32 bytes user ID {userId} derived from a passphrase provided by the user. 50 | - Sync server allocates one folder to each user. 51 | - All devices belonging to {userId} can access /users/{userId} and be informed when changes are happening. 52 | 53 | Flow: 54 | - User enters a passphrase (e.g. 12 seed words), from this passphrase, using PBKDF2 (SHA-512, 100 000 iterations) is derived an AES-256 CBC secret key* {secretKey} and one username {userId} using window.crypto.subtle.deriveKey. 55 | - To access Google Cloud Firestore, device requests a database session token at https://us-central1-sync-internal.cloudfunctions.net/generateToken?uid={userId} 56 | - Device is assigned a folder /users/{userId}/bookmarks in Google Cloud Firestore. 57 | - Every time a bookmark is created, updated or removed on a device, the device publishes the change to /users/{userId}/bookmarks/{deviceId}|{bookmarkId} 58 | - Other devices listen to changes using onSnapshot 59 | 60 | 61 | *To confirm which mode of operation AES is the most appropriate 62 | 63 | Arnaud. 64 | -------------------------------------------------------------------------------- /background.js: -------------------------------------------------------------------------------- 1 | var firebaseConfig = { 2 | // This is a public API key to access Firebase 3 | apiKey: 'AIzaSyCxCyVS2aFQuwIo7WS-S3nY6veMnCwlzyM', 4 | 5 | authDomain: 'sync-internal.firebaseapp.com', 6 | databaseURL: 'https://sync-internal.firebaseio.com', 7 | projectId: 'sync-internal', 8 | storageBucket: 'sync-internal.appspot.com' 9 | }; 10 | async function updateRecordOnServer(i, record, commitInBatch) { 11 | record.device = localStorage.deviceId; 12 | var node = json_encode(record); 13 | console.log("node encoded -> "+node); 14 | var iv = crypto.getRandomValues(new Uint8Array(16)); 15 | var encryptedData = await encrypt(string_to_array(node), base64_string_to_array(localStorage.pkey), iv, 'AES-CBC'); 16 | encryptedData = array_to_base64_string(encryptedData); 17 | iv = array_to_base64_string(iv); 18 | if (commitInBatch) { 19 | if (batch && batch._mutations.length >= 400) { 20 | batch.commit(); 21 | batch = db.batch(); 22 | } else if (!batch) { 23 | batch = db.batch(); 24 | } 25 | batch.set(db.collection('users').doc(localStorage.uid).collection('bookmarks').doc(record.id), { 26 | 'data': encryptedData, 27 | 'iv': iv 28 | }); 29 | } else { 30 | db.collection('users').doc(localStorage.uid).collection('bookmarks').doc(record.id).set({ 31 | 'data': encryptedData, 32 | 'iv': iv 33 | }).then(function () { 34 | console.log(" ---- Bookmark set with ID: " + record.id); 35 | }) 36 | .catch(function (error) { 37 | console.error("Error on set bookmark with ID : " + record.id, error); 38 | }); 39 | } 40 | } 41 | 42 | async function deleteRecordOnServer(i, record) { 43 | db.collection('users').doc(localStorage.uid).collection('bookmarks').doc(record.node.id).delete() 44 | .then(function () { 45 | console.log(" ---- Deleted bookmark with ID: ", record.node.id); 46 | }) 47 | .catch(function (error) { 48 | console.error("Error deleting bookmark with ID: " + record.node.id, error); 49 | }); 50 | } 51 | 52 | async function pushLocalBookmarksToServer(items, localOnly) { 53 | if (batch && batch._mutations.length && !batch._committed) { 54 | batch.commit(); 55 | batch = db.batch(); 56 | } 57 | if (!createdRoots[localStorage.deviceId]) { 58 | createdRoots[localStorage.deviceId] = true; 59 | bookmarksToShowInTheUI.push({ 60 | 'id': localStorage.deviceId + '|0', 61 | 'icon': 'fas fa-mobile-android-alt', 62 | 'type': 'device', 63 | 'title': 'This device', 64 | 'parentId': null, 65 | 'device': localStorage.deviceId 66 | }); 67 | } 68 | for (var i = 0, l = items.length; i < l; i++) { 69 | var d = items[i]; 70 | if (d.parentId == 'root________') // Used in Firefox 71 | d.parentId = '0'; 72 | var isFolder = d.dateGroupModified || d.children || typeof d.url == 'undefined' || d.type == 'folder'; 73 | var obj = { 74 | 'dateAdded': d.dateAdded, 75 | 'id': localStorage.deviceId + '|' + d.id, 76 | 'index': d.index, 77 | 'parentId': localStorage.deviceId + '|' + d.parentId, 78 | 'title': d.title, 79 | 'url': d.url, 80 | 'device': localStorage.deviceId 81 | }; 82 | pushItemToUI(obj); 83 | if (!localOnly) { 84 | var alreadyPresent = bookmarksDownloadedFromServer.some(function (item) { 85 | return item.id == obj.id; 86 | }); 87 | if (!alreadyPresent) 88 | await updateRecordOnServer(obj.id, obj, commitInBatch = true); 89 | } 90 | if (isFolder && d.children) { 91 | await pushLocalBookmarksToServer(d.children, localOnly); 92 | } 93 | } 94 | if (batch && batch._mutations.length && !batch._committed) { 95 | batch.commit(); 96 | batch = db.batch(); 97 | } 98 | bookmarksToShowInTheUI.sort((a, b) => (a.title.toLowerCase() > b.title.toLowerCase()) ? 1 : -1) 99 | localStorage.remoteBookmarks = json_encode(bookmarksToShowInTheUI); 100 | } 101 | 102 | var pushItemToUI = function (node) { 103 | if (!createdRoots[node.id.split('|')[0]]) { 104 | createdRoots[node.id.split('|')[0]] = true; 105 | if (node.id.split('|')[0] == localStorage.deviceId) { 106 | bookmarksToShowInTheUI.push({ 107 | 'id': localStorage.deviceId + '|0', 108 | 'icon': 'fas fa-mobile-android-alt', 109 | 'type': 'device', 110 | 'title': 'This device', 111 | 'parentId': null, 112 | 'device': localStorage.deviceId 113 | }); 114 | } else { 115 | bookmarksToShowInTheUI.push({ 116 | 'id': node.id.split('|')[0] + '|0', 117 | 'icon': 'fas fa-mobile-android-alt', 118 | 'type': 'device', 119 | 'title': node.id.split('|')[0], 120 | 'parentId': null 121 | }); 122 | } 123 | } 124 | var alreadyPresent = bookmarksToShowInTheUI.some(function (item) { 125 | return item.id == node.id; 126 | }); 127 | if (!alreadyPresent) { 128 | bookmarksToShowInTheUI.push(node); 129 | } 130 | } 131 | var getItemById= (edited)=>{ 132 | var indexToEdit = bookmarksToShowInTheUI.map(function (item) { 133 | return item.id; 134 | }).indexOf(edited.id); 135 | bookmarksToShowInTheUI[indexToEdit].title=edited.title; 136 | bookmarksToShowInTheUI[indexToEdit].url=edited.url; 137 | return bookmarksToShowInTheUI[indexToEdit]; 138 | } 139 | var removeItemFromUI = function (node) { 140 | var indexToRemove = bookmarksToShowInTheUI.map(function (item) { 141 | return item.id; 142 | }).indexOf(node.id); 143 | bookmarksToShowInTheUI.splice(indexToRemove, 1); 144 | } 145 | 146 | var sortBookmarksInTheUI = function () { 147 | bookmarksToShowInTheUI.sort((a, b) => (a.title.toLowerCase() > b.title.toLowerCase()) ? 1 : -1) 148 | } 149 | 150 | // Initialize Firebase 151 | firebase.initializeApp(firebaseConfig); 152 | 153 | var db = firebase.firestore(); 154 | var bookmarksDownloadedFromServer = []; 155 | var bookmarksToShowInTheUI = []; 156 | var initialSyncDone = false; 157 | var createdRoots = []; 158 | var batch = null; 159 | 160 | console.log('Locally load bookmarks'); 161 | chrome.bookmarks.getTree(function (tree) { 162 | pushLocalBookmarksToServer(tree[0].children, localOnly = true); 163 | }); 164 | console.log('Local bookmarks loaded'); 165 | //Update bookmark on server on locally changed 166 | 167 | chrome.bookmarks.onChanged.addListener((i, record) => { 168 | record.id = localStorage.deviceId + '|' + i; 169 | var editedRecord = getItemById(record); 170 | sortBookmarksInTheUI(); 171 | updateRecordOnServer(i, editedRecord); 172 | localStorage.remoteBookmarks = json_encode(bookmarksToShowInTheUI); 173 | }); 174 | 175 | //Update bookamark on server on locally created 176 | chrome.bookmarks.onCreated.addListener((i, record) => { 177 | record.id = localStorage.deviceId + '|' + i; 178 | record.parentId=localStorage.deviceId + '|' + record.parentId; 179 | pushItemToUI(record); 180 | sortBookmarksInTheUI(); 181 | updateRecordOnServer(i, record); 182 | localStorage.remoteBookmarks = json_encode(bookmarksToShowInTheUI); 183 | }); 184 | 185 | //Remove bookmark from server on locally removed 186 | chrome.bookmarks.onRemoved.addListener((i, record) => { 187 | record.id = localStorage.deviceId + '|' + i; 188 | record.node.id = localStorage.deviceId + '|' + record.node.id; 189 | removeItemFromUI(record); 190 | sortBookmarksInTheUI(); 191 | deleteRecordOnServer(i, record); 192 | localStorage.remoteBookmarks = json_encode(bookmarksToShowInTheUI); 193 | }); 194 | 195 | firebase.auth().onAuthStateChanged(async function (user) { 196 | console.log('onAuthStateChanged'); 197 | if (user) { 198 | console.log('Logged-in under UID: ' + user.uid); 199 | localStorage.uid = user.uid; 200 | 201 | bookmarksDownloadedFromServer = []; 202 | bookmarksToShowInTheUI = []; 203 | createdRoots = []; 204 | 205 | 206 | 207 | 208 | console.log('onAuthStateChanged calling base64_string_to_array'); 209 | db.collection('users').doc(localStorage.uid).collection('bookmarks').onSnapshot(async function (querySnapshot) { 210 | console.log('Receiving query snapshot - ' + querySnapshot.docChanges().length); 211 | await Promise.all(querySnapshot.docChanges().map(async function (change) { 212 | var doc = change.doc; 213 | await decrypt(base64_string_to_array(doc.data().data), base64_string_to_array(localStorage.pkey), 214 | base64_string_to_array(doc.data().iv), 'AES-CBC').then(function (decryptedNode) { 215 | decryptedNode = JSON.parse(array_to_string(decryptedNode)); 216 | if (change.type == 'removed') { 217 | var indexToRemove = bookmarksDownloadedFromServer.map(function (item) { 218 | return item.id; 219 | }).indexOf(decryptedNode.id); 220 | bookmarksDownloadedFromServer.splice(indexToRemove, 1); 221 | indexToRemove = bookmarksToShowInTheUI.map(function (item) { 222 | return item.id; 223 | }).indexOf(decryptedNode.id); 224 | bookmarksToShowInTheUI.splice(indexToRemove, 1); 225 | return; 226 | } else if (change.type == 'added' || change.type == 'modified') { 227 | var alreadyPresent = bookmarksDownloadedFromServer.some(function (item) { 228 | return item.id == decryptedNode.id; 229 | }); 230 | if (alreadyPresent) { 231 | var indexToRemove = bookmarksDownloadedFromServer.map(function (item) { 232 | return item.id; 233 | }).indexOf(decryptedNode.id); 234 | bookmarksDownloadedFromServer.splice(indexToRemove, 1); 235 | indexToRemove = bookmarksToShowInTheUI.map(function (item) { 236 | return item.id; 237 | }).indexOf(decryptedNode.id); 238 | bookmarksToShowInTheUI.splice(indexToRemove, 1); 239 | } 240 | bookmarksDownloadedFromServer.push(decryptedNode); 241 | pushItemToUI(decryptedNode); 242 | } 243 | }); 244 | })); 245 | sortBookmarksInTheUI(); 246 | localStorage.remoteBookmarks = json_encode(bookmarksToShowInTheUI); 247 | console.log('Updated data from server, we have: ' + bookmarksDownloadedFromServer.length + ' records from the server and ' + bookmarksToShowInTheUI.length + ' in the UI'); 248 | if (!initialSyncDone) { 249 | chrome.bookmarks.getTree(function (tree) { 250 | pushLocalBookmarksToServer(tree[0].children, localOnly = false); 251 | }); 252 | console.log('Local bookmarks have been pushed to server as part of the initial sync'); 253 | initialSyncDone = true; 254 | } 255 | }); 256 | } else { 257 | // No user is signed in. 258 | } 259 | }); 260 | 261 | async function connect_to_firebase() { 262 | localStorage.uid = await derive_uid_from_passphrase(localStorage.passphrase); 263 | localStorage.pkey = await derive_aes_key_from_passphrase(localStorage.passphrase); 264 | 265 | try { 266 | fetch('https://us-central1-sync-internal.cloudfunctions.net/generateToken?uid=' + encodeURIComponent(localStorage.uid)) 267 | .then(function (response) { 268 | return response.text(); 269 | }).then(function (answer) { 270 | var token = answer; 271 | firebase.auth().signInWithCustomToken(token).catch(function (error) {}); 272 | }); 273 | } catch (err) { 274 | console.log('Cannot fetch database token'); 275 | } 276 | } 277 | 278 | async function main() { 279 | if (typeof localStorage.passphrase == 'undefined' || !localStorage.passphrase) { 280 | console.log('First initialization, we are generating a random passphrase'); 281 | localStorage.passphrase = array_to_base64_string(generate_passphrase()); 282 | } 283 | 284 | if (typeof localStorage.deviceId != 'undefined' && localStorage.deviceId && localStorage.deviceId != null) { 285 | console.log('Device ID identified: ' + localStorage.deviceId); 286 | await connect_to_firebase(); 287 | } else { 288 | var waitForDeviceId = setInterval(async function () { 289 | console.log('Waiting for device id'); 290 | if (typeof localStorage.deviceId != 'undefined' && localStorage.deviceId && localStorage.deviceId != null) { 291 | await connect_to_firebase(); 292 | clearInterval(waitForDeviceId); 293 | } 294 | }, 2000); 295 | } 296 | } 297 | 298 | //Message listener 299 | chrome.runtime.onMessage.addListener((request, sender, sendResponse) => { 300 | if (request.type == "showOptions") { //Check the request 301 | chrome.runtime.openOptionsPage(); //Open the settings page 302 | } 303 | if(request.type == "deleteDevice"){ 304 | console.log("Delete device : "+request.value); 305 | sendResponse({error: false}); 306 | } 307 | return true; 308 | 309 | }); 310 | main(); -------------------------------------------------------------------------------- /crypto.js: -------------------------------------------------------------------------------- 1 | // The flow for encryption is the following: 2 | // 3 | // Using a user-provided passphrase, we derive: 4 | // 1) Username 5 | // 2) Private KEY (to encrypt user data using AES) 6 | // 7 | // To derive the key, we use PBKDF2 with 100'000 iterations, and we have to provide one salt for generating the UID, and one salt for generating the private key 8 | // 9 | // These values have been generated with crypto.getRandomValues(new Uint8Array(64)) 10 | // You can change these default values to anything you want, as long as they are the same on all your devices 11 | // 12 | var cryptoSalts = { 13 | uid: new Uint8Array([24,206,116,1,83,177,137,240,230,23,3,115,219,61,204,42,4,221,44,25,37,160,227,35,162,58,120,149,8,58,242,25,181,94,46,255,2,225,80,143,158,88,144,191,216,184,65,46,86,233,148,52,99,215,133,222,195,228,44,91,156,107,212,165]), 14 | pkey: new Uint8Array([34,79,240,56,71,26,229,251,174,181,58,13,99,174,22,7,72,234,170,21,242,31,61,165,9,52,183,102,113,140,18,25,174,67,172,74,247,227,226,10,23,205,176,56,219,81,31,4,174,142,68,186,235,140,103,88,64,192,91,77,223,243,250,176]) 15 | }; 16 | 17 | var crypto = window.crypto || window.msCrypto; 18 | 19 | // Encrypt 20 | const encrypt = (data, key, iv, mode) => 21 | crypto.subtle.importKey('raw', key, { name: mode }, true, ['encrypt']) 22 | .then(bufKey => crypto.subtle.encrypt({ name: mode, iv }, bufKey, data)) 23 | 24 | // Decrypt 25 | const decrypt = (data, key, iv, mode) => 26 | crypto.subtle.importKey('raw', key, { name: mode }, true, ['decrypt']) 27 | .then(bufKey => crypto.subtle.decrypt({ name: mode, iv }, bufKey, data)) 28 | 29 | // PBKDF2 - Derive an encryption key from a password 30 | const pbkdf2 = (password, salt, iterations, hash, mode) => 31 | crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']) 32 | .then(baseKey => crypto.subtle.deriveKey({ name: 'PBKDF2', salt, iterations, hash }, baseKey, { 'name': mode, 'length': 256 }, true, ['encrypt', 'decrypt'])) 33 | .then(key => crypto.subtle.exportKey('raw', key)) 34 | 35 | function generate_passphrase() { 36 | return crypto.getRandomValues(new Uint8Array(64)); 37 | } 38 | 39 | async function derive_uid_from_passphrase(passphrase) { 40 | var uid = await pbkdf2(base64_string_to_array(passphrase), cryptoSalts.uid, iterations = 100000, hash = 'SHA-512', mode = 'AES-CBC'); 41 | 42 | // We store data in our folder, we cannot have a folder containing a slash so we swap it with a pipe instead 43 | return array_to_base64_string(uid).replace(/\//g, '|'); 44 | } 45 | 46 | async function derive_aes_key_from_passphrase(passphrase) { 47 | var pkey = await pbkdf2(base64_string_to_array(passphrase), cryptoSalts.pkey, iterations = 100000, hash = 'SHA-512', mode = 'AES-CBC'); 48 | 49 | return array_to_base64_string(pkey); 50 | } 51 | -------------------------------------------------------------------------------- /firebase-app.js: -------------------------------------------------------------------------------- 1 | !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).firebase=t()}(this,function(){"use strict";var i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)};var r=function(){return(r=Object.assign||function(e){for(var t,r=1,n=arguments.length;r"})):"Error",c=this.serviceName+": "+s+" ("+i+").",u=new h(i,c),l=0,p=Object.keys(o);l 2 | 3 | 4 | 5 | 6 | 7 | Sync - Settings 8 | 309 | 310 | 311 | 312 |
313 |
This is an Alert!
314 |
315 |
316 | 317 |
318 | 319 | Sync Setup 320 |

To enable Sync on this device pick a name

321 |
322 |
323 | 324 | 326 |
327 |
328 |

To sync between devices enter the same key on all the devices

329 |
330 |
331 | 332 | 347 | 348 |
349 |
350 | 351 | 352 | 353 |
354 |
355 | Your Devices 356 |

From below manage your devices, you will not lose the bookmarks on device you delete

357 |
358 |
359 |
360 | 361 |
362 |
363 |
364 |
365 |
366 | 367 | 368 | 369 | -------------------------------------------------------------------------------- /options.js: -------------------------------------------------------------------------------- 1 | //Custom Toast class for notification 2 | function Notif(option) { 3 | //Configuration 4 | var el = this; 5 | el.self = document.querySelector('.toast-message'); 6 | el.message = document.querySelector('.message'); 7 | el.top = option.topPos; 8 | el.classNames = option.classNames; 9 | el.autoClose = (typeof option.autoClose === "boolean") ? option.autoClose : false; 10 | el.autoCloseTimeout = (option.autoClose && typeof option.autoCloseTimeout === "number") ? option.autoCloseTimeout : 3000; 11 | //Methods 12 | el.reset = function () { 13 | (el.message).innerHTML = ""; 14 | el.self.classList.remove(el.classNames); 15 | } 16 | el.showN = function (msg, type) { 17 | el.reset(); 18 | el.message.innerHTML = msg; 19 | el.self.style.top = el.top; 20 | el.self.classList.add(type); 21 | 22 | if (el.autoClose) { 23 | setTimeout(function () { 24 | el.hideN(); 25 | }, el.autoCloseTimeout); 26 | } 27 | } 28 | el.hideN = function () { 29 | el.self.style.top = '-100%'; 30 | el.reset(); 31 | }; 32 | } 33 | //Initialize a Toast message object 34 | var notification = new Notif({ 35 | topPos: '200px', 36 | classNames: 'success', 37 | autoClose: true, 38 | autoCloseTimeout: 2000 39 | }); 40 | var deleteIcon=''; 41 | //Get top folders - Devices folder 42 | function orphans() { 43 | return data.filter(function(item) { 44 | return item.parentId === null; 45 | }); 46 | } 47 | //Get bookmarks 48 | var data ={}; 49 | if (typeof localStorage.remoteBookmarks != 'undefined') 50 | data = JSON.parse(localStorage.remoteBookmarks); 51 | //Initialize and show devices on option page 52 | const devices_list= document.getElementById("devices-list"); 53 | var devices=orphans();//Folders without parent are basically the devices folders 54 | var str='
    '; 55 | 56 | devices.forEach(element => { 57 | str+='
  • '+element.id.split('|')[0]+'

    '+deleteIcon+'
  • '; 58 | }); 59 | str+="
"; 60 | devices_list.innerHTML=str; 61 | const removeButtons=document.getElementsByClassName("removeItemBtn"); 62 | Array.prototype.forEach.call(removeButtons, function(el, i){ 63 | el.onclick=()=>{ 64 | var device=el.parentNode.querySelector('p').innerHTML; 65 | chrome.runtime.sendMessage({type:"deleteDevice",value:device},function(response) { 66 | console.log(response); 67 | if(!response.error){ 68 | notification.showN('Delete is not possible yet !', 'danger'); 69 | } 70 | }); 71 | 72 | } 73 | }); 74 | //Get input elements 75 | const input_synckey = document.getElementById("sync-key"); 76 | const input_devicename = document.getElementById("device-name"); 77 | //Get sync key 78 | var passphrase = localStorage.passphrase; 79 | //Get device name (id) 80 | var deviceId = localStorage.deviceId; 81 | 82 | if (typeof localStorage.deviceId == 'undefined') { 83 | deviceId = "Device-" + Math.random(); 84 | }else{ 85 | 86 | input_devicename.disabled=true; 87 | } 88 | 89 | 90 | 91 | 92 | //Function to paste from clipboard 93 | async function pasteFromClip () { 94 | const text = await navigator.clipboard.readText(); 95 | input_synckey.value = text; 96 | notification.showN('Sync key has been pasted from clipboard !', 'success'); 97 | } 98 | // Function to copy to clipboard 99 | function copyToClip(str) { 100 | const el = document.createElement('textarea'); 101 | el.value = str; 102 | el.setAttribute('readonly', ''); 103 | el.style.position = 'absolute'; 104 | el.style.left = '-9999px'; 105 | document.body.appendChild(el); 106 | const selected = 107 | document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false; 108 | el.select(); 109 | document.execCommand('copy'); 110 | el.parentNode.removeChild(el); 111 | if (selected) { 112 | document.getSelection().removeAllRanges(); 113 | document.getSelection().addRange(selected); 114 | } 115 | notification.showN('Your key has been copied to clipboard !', 'success'); 116 | } 117 | 118 | // set-up values and initialize listeners 119 | input_devicename.value = deviceId; 120 | 121 | input_synckey.value = passphrase; 122 | 123 | document.getElementById("copy-key").addEventListener('click', () => { 124 | copyToClip(passphrase); 125 | }); 126 | document.getElementById("save").addEventListener('click', () => { 127 | save_settings(); 128 | }); 129 | document.getElementById("paste-key").addEventListener('click', () => { 130 | pasteFromClip(); 131 | }); 132 | 133 | 134 | //Function to save settings( to localstorage) 135 | function save_settings() { 136 | let key =input_synckey.value.trim(); 137 | if (key.length == 0 || !window.atob(input_synckey.value)) { 138 | notification.showN('Sync key not valid', 'danger'); 139 | return; 140 | } 141 | //Remove white spaces at start/end 142 | let id = input_devicename.value.trim(); 143 | if (id.length==0) {//Check if device name is not empty 144 | notification.showN('Invalid device name', 'danger'); 145 | return; 146 | } 147 | localStorage.passphrase = input_synckey.value; 148 | localStorage.deviceId = input_devicename.value; 149 | notification.showN('Settings saved correctly!', 'success'); 150 | } -------------------------------------------------------------------------------- /popup.css: -------------------------------------------------------------------------------- 1 | *{ 2 | box-sizing: border-box; 3 | border-spacing: 0; 4 | outline: none; 5 | } 6 | body { 7 | min-width: 300px; 8 | width: 300px; 9 | font-size: 13px; 10 | color: #222; 11 | } 12 | .fld-icon{ 13 | height: 1rem; 14 | margin-right: 5px; 15 | } 16 | .fld-label,.item-label{ 17 | display: flex; 18 | align-items: center; 19 | color: #111; 20 | text-decoration: none; 21 | width: 100%; 22 | padding: .5rem; 23 | border: 1px solid #222; 24 | border-radius: .3rem; 25 | } 26 | .item-label{ 27 | display: block; 28 | overflow-wrap: break-word; 29 | } 30 | 31 | 32 | .search:not(focus) { 33 | padding: 5px; 34 | border-radius: 5px; 35 | -moz-border-radius: 5px; 36 | -webkit-border-radius: 5px; 37 | border: 2px solid #F2F3F5; 38 | background-color: #F2F3F5; 39 | font-size: 14px; 40 | outline: none; 41 | } 42 | 43 | .search:focus { 44 | padding: 5px; 45 | border-radius: 5px; 46 | -moz-border-radius: 5px; 47 | -webkit-border-radius: 5px; 48 | border: 2px solid #F2F3F5; 49 | background-color: #FFF; 50 | font-size: 14px; 51 | outline: none; 52 | } 53 | 54 | ul { 55 | list-style:none; 56 | padding-left: 1.75em; 57 | } 58 | 59 | .top-right { 60 | font-size:small; 61 | position:fixed; 62 | right:1em; 63 | top:1em; 64 | } 65 | 66 | 67 | li { 68 | padding: 3px; 69 | } 70 | li { 71 | background: white; 72 | list-style-type:none; 73 | border-radius: .3rem; 74 | user-select: none; 75 | margin:0; 76 | position:relative 77 | } 78 | li::before, li::after { 79 | content:''; 80 | left:-20px; 81 | position:absolute; 82 | right:auto; 83 | } 84 | li::before { 85 | border-left:1px solid #999; 86 | height:100%; 87 | top:0; 88 | width:1px; 89 | } 90 | li::after { 91 | border-top:1px solid #999; 92 | height:20px; 93 | top:20px; 94 | width:23px; 95 | } 96 | 97 | li:last-child::before { 98 | height:21px; 99 | } 100 | 101 | .selected>a { 102 | background: #dddddd; 103 | } 104 | 105 | 106 | .source { 107 | color: #bbb; 108 | } 109 | -------------------------------------------------------------------------------- /popup.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |   9 |
10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /popup.js: -------------------------------------------------------------------------------- 1 | /* data is in flat array format like this: 2 | [ 3 | { 4 | id: 'abc', 5 | name: 'ABCDE', 6 | parent: null 7 | }, 8 | { 9 | id: 'def', 10 | name: 'DEFGH', 11 | parent: 'abc' 12 | } 13 | ] 14 | */ 15 | 16 | console.log('Initializing popup'); 17 | var selected = 0; 18 | var data = []; 19 | 20 | //Event listener for button to open settings page 21 | let btt = document.querySelector("#settings-icon"); 22 | btt.addEventListener("click", () => { 23 | chrome.runtime.sendMessage({type:"showOptions"}); 24 | }); 25 | 26 | 27 | function currently_selected_elem(){ 28 | return document.querySelector('li.selected'); 29 | } 30 | //Get top folders - Devices folder 31 | function orphans() { 32 | return data.filter(function(item) { 33 | return item.parentId === null; 34 | }); 35 | } 36 | 37 | function getItemsByText(query) { 38 | var queryx = query.split(' '); 39 | return data.filter(function(item) { 40 | const src = item.title.toString().toLowerCase(); 41 | for (var i = 0; i < queryx.length; i++) { 42 | if (!src.includes(queryx[i].toString().toLowerCase())) { 43 | return false; 44 | } 45 | } 46 | return true; 47 | }); 48 | } 49 | 50 | function hasChildren(parentId) { 51 | return data.some(function(item) { 52 | return item.parentId === parentId; 53 | }); 54 | } 55 | 56 | function getChildren(parentId) { 57 | return data.filter(function(item) { 58 | return item.parentId === parentId; 59 | }); 60 | } 61 | const folderIcon = ''; 62 | function generateListItem(query, item) { 63 | const li = document.createElement('li'); 64 | li.id = 'item-' + item.id; 65 | li.tabIndex = 0; 66 | const a = document.createElement('a'); 67 | 68 | itemlabeltext = document.createTextNode(item.title); 69 | sanitizedtext = itemlabeltext.nodeValue; 70 | if (query && query.length > 0) { 71 | var queryx = query.split(' '); 72 | for (var i = 0; i < queryx.length; i++) 73 | queryx[i] = queryx[i].replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); 74 | var reg = new RegExp(queryx.join('|'), 'gi'); 75 | sanitizedtext = sanitizedtext.replace(reg, '$&'); 76 | } 77 | if (item.device && item.device != localStorage.deviceId && document.getElementById('searchField').value) 78 | sanitizedtext += ' ' + item.device + ''; 79 | 80 | if (item.url) {//Check if it's a bookmark (Check Two) 81 | const itemlink = document.createElement('a'); 82 | itemlink.classList="item-label"; 83 | itemlink.href = item.url; 84 | itemlink.target = '_blank'; 85 | itemlink.innerHTML = ' ' + sanitizedtext; 86 | li.appendChild(itemlink); 87 | } else { 88 | a.href = '#'; 89 | a.tabIndex = -1; 90 | a.classList.add('fld-label'); 91 | a.addEventListener('click', expand); 92 | let empty = (hasChildren(item.id))? "" : " (empty)"; 93 | a.innerHTML = folderIcon+sanitizedtext+empty; 94 | li.appendChild(a); 95 | } 96 | 97 | return li; 98 | } 99 | 100 | function expand(event) { 101 | console.time('expand'); 102 | event.preventDefault(); 103 | event.stopPropagation(); 104 | const et = event.target, 105 | parent = et.parentElement, 106 | id = parent.id.replace('item-', ''), 107 | kids = getChildren(id), 108 | items = kids.map(generateListItem.bind(null, '')), 109 | ul = document.createElement('ul'); 110 | var hasSelected = false; 111 | items.some(function(li) { 112 | if (!hasSelected) { 113 | if (currently_selected_elem()) { 114 | var curNode = currently_selected_elem(); 115 | curNode.classList.remove('selected'); 116 | } 117 | li.classList.add('selected'); 118 | hasSelected = true; 119 | } 120 | ul.appendChild(li); 121 | }); 122 | parent.appendChild(ul); 123 | et.classList.remove('plus'); 124 | et.classList.add('minus'); 125 | et.removeEventListener('click', expand); 126 | et.addEventListener('click', collapse); 127 | console.timeEnd('expand'); 128 | } 129 | 130 | function collapse(event) { 131 | console.time('collapse'); 132 | event.preventDefault(); 133 | event.stopPropagation(); 134 | const et = event.target, 135 | parent = et.parentElement, 136 | ul = parent.querySelector('ul'); 137 | parent.removeChild(ul); 138 | et.classList.remove('minus'); 139 | et.classList.add('plus'); 140 | et.removeEventListener('click', collapse); 141 | et.addEventListener('click', expand); 142 | if (currently_selected_elem()) { 143 | var curNode = currently_selected_elem(); 144 | curNode.classList.remove('selected'); 145 | } 146 | et.parentNode.classList.add('selected'); 147 | console.timeEnd('collapse'); 148 | } 149 | 150 | function addRemotebookmarks() { 151 | const root = document.getElementById('root'), 152 | orphansArray = orphans(); 153 | console.log(orphansArray); 154 | root.innerHTML = ''; 155 | if (orphansArray.length) { 156 | const items = orphansArray.map(generateListItem.bind(null, '')), 157 | ul = document.createElement('ul'); 158 | ul.id = 'rootList'; 159 | items.some(function(li) { 160 | ul.appendChild(li); 161 | }); 162 | root.appendChild(ul); 163 | } 164 | } 165 | 166 | function searchItem(query) { 167 | if (!query) { 168 | addRemotebookmarks(); 169 | return; 170 | } 171 | const root = document.getElementById('root'); 172 | resultsArray = getItemsByText(query); 173 | root.innerHTML = ''; 174 | if (resultsArray.length) { 175 | const items = resultsArray.map(generateListItem.bind(null, query)), 176 | ul = document.createElement('ul'); 177 | ul.id = 'rootList'; 178 | var hasSelected = false; 179 | var nresults = 0; 180 | // We use some as an alternative to forEach and use return as an early-break 181 | items.some(function(li) { 182 | if (!hasSelected) { 183 | if (currently_selected_elem()) { 184 | var curNode = currently_selected_elem(); 185 | curNode.classList.remove('selected'); 186 | } 187 | li.classList.add('selected'); 188 | hasSelected = true; 189 | } 190 | ul.appendChild(li); 191 | if (nresults++ > 100) 192 | return true; 193 | }); 194 | root.appendChild(ul); 195 | } 196 | } 197 | 198 | function process_key(e) 199 | { 200 | var list = document.getElementById('rootList'); 201 | if (!list) 202 | return false; 203 | var first = list.firstChild; 204 | if (!first) 205 | return false; 206 | var maininput = document.getElementById('searchField'); 207 | console.log('Pressed: ' + e.keyCode); 208 | if (e.keyCode == 38) { // up 209 | e.preventDefault(); 210 | if (currently_selected_elem()) { 211 | var curNode = currently_selected_elem(); 212 | if (currently_selected_elem().previousSibling) 213 | currently_selected_elem().previousSibling.classList.add('selected'); 214 | else if (currently_selected_elem() && currently_selected_elem().parentNode.tagName == 'UL' && currently_selected_elem().parentNode.parentNode.tagName == 'LI') 215 | currently_selected_elem().parentNode.parentNode.classList.add('selected'); 216 | else 217 | maininput.focus(); 218 | curNode.classList.remove('selected'); 219 | } 220 | return true; 221 | } 222 | else if (e.keyCode == 40) { // down 223 | e.preventDefault(); 224 | if (currently_selected_elem()) { 225 | var curNode = currently_selected_elem(); 226 | if (currently_selected_elem().nextSibling) 227 | currently_selected_elem().nextSibling.classList.add('selected'); 228 | curNode.classList.remove('selected'); 229 | } else { 230 | first.classList.add('selected'); 231 | } 232 | return true; 233 | } 234 | else if (e.keyCode == 13) { // enter 235 | e.preventDefault(); 236 | if (currently_selected_elem()) { 237 | document.querySelector('li.selected a').click(); 238 | } 239 | return true; 240 | } 241 | else if (e.keyCode == 39) { // right 242 | e.preventDefault(); 243 | if (currently_selected_elem() && document.querySelector('li.selected a') && document.querySelector('li.selected a').classList.contains('plus')) { 244 | document.querySelector('li.selected a').click(); 245 | } else if (currently_selected_elem() && document.querySelector('li.selected a') && document.querySelector('li.selected a').classList.contains('minus')) { 246 | var curNode = currently_selected_elem(); 247 | document.querySelector('li.selected ul>li').classList.add('selected'); 248 | curNode.classList.remove('selected'); 249 | } 250 | return true; 251 | } 252 | else if (e.keyCode == 37) { // left 253 | e.preventDefault(); 254 | if (currently_selected_elem() && document.querySelector('li.selected a') && document.querySelector('li.selected a').classList.contains('minus')) { 255 | document.querySelector('li.selected a').click(); 256 | } 257 | else if (currently_selected_elem() && currently_selected_elem().parentNode.tagName == 'UL' && currently_selected_elem().parentNode.parentNode.tagName == 'LI' 258 | && currently_selected_elem().parentNode.parentNode.firstChild.classList.contains('minus')) { 259 | currently_selected_elem().parentNode.parentNode.firstChild.click(); 260 | } 261 | return true; 262 | } 263 | return false; 264 | } 265 | 266 | console.log('Loading popup'); 267 | 268 | if (typeof localStorage.remoteBookmarks != 'undefined') 269 | data = JSON.parse(localStorage.remoteBookmarks); 270 | addRemotebookmarks(); 271 | 272 | document.getElementById('root').addEventListener('keydown', function (e) { 273 | process_key(e); 274 | }); 275 | 276 | document.getElementById('searchField').addEventListener('keyup', function (e) { 277 | if (!process_key(e)) 278 | searchItem(document.getElementById('searchField').value); 279 | }); 280 | 281 | document.getElementById('searchField').addEventListener('keydown', function (e) { 282 | if (currently_selected_elem() && (e.keyCode == 37 || e.keyCode == 38 || e.keyCode == 39 || e.keyCode == 40)) { // ignore up and down keys 283 | e.preventDefault(); 284 | return false; 285 | } 286 | }); 287 | 288 | 289 | -------------------------------------------------------------------------------- /serverside/README.md: -------------------------------------------------------------------------------- 1 | This function is a node.js Google Cloud Function deployed to serve the generateToken endpoint. 2 | 3 | It takes an UID in input (which is randomly generated by the client) and gives access to this folder for this UID 4 | -------------------------------------------------------------------------------- /serverside/firestore_security_rules: -------------------------------------------------------------------------------- 1 | service cloud.firestore { 2 | match /databases/{database}/documents { 3 | match /users/{userId} { 4 | allow create, read, update, list, write, delete: if request.auth.uid == userId; 5 | } 6 | match /users/{userId}/{document=**} { 7 | allow create, read, update, list, write, delete: if request.auth.uid == userId; 8 | } 9 | match /{document=**} { 10 | allow read, write: if false; 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /serverside/index.js: -------------------------------------------------------------------------------- 1 | const request = require('request'); 2 | const admin = require('firebase-admin'); 3 | admin.initializeApp(); 4 | 5 | const functions = require('firebase-functions'); 6 | 7 | exports.generateToken = functions.https.onRequest(async (req, res) => { 8 | var uid = req.query.uid || req.body.uid; 9 | res.set('Content-Type', 'application/json'); 10 | res.set('Access-Control-Allow-Origin', '*'); 11 | await admin.auth().createCustomToken(uid) 12 | .then(function(customToken) { 13 | 14 | // var text = '[Login] A new database access token has been assigned to: ' + uid; 15 | 16 | res.status(200).send(customToken); 17 | }) 18 | .catch(function(error) { 19 | console.log('Error creating custom token:', error); 20 | res.status(500).send("Error creating token"); 21 | }); 22 | }); 23 | -------------------------------------------------------------------------------- /toolbox.js: -------------------------------------------------------------------------------- 1 | // Here we could use JSON.stringify, but there is an issue: 2 | // https://bugs.chromium.org/p/v8/issues/detail?id=855 3 | // So we wrap the function in case we'll need workaround later 4 | function json_encode(obj) { 5 | return JSON.stringify(obj); 6 | } 7 | 8 | function array_to_string(buffer) { 9 | return new TextDecoder("utf-8").decode(buffer); 10 | } 11 | 12 | function string_to_array(str) { 13 | return new TextEncoder("utf-8").encode(str); 14 | } 15 | 16 | function array_to_base64_string(buffer) { 17 | var binary = ''; 18 | var bytes = new Uint8Array(buffer); 19 | var len = bytes.byteLength; 20 | for (var i = 0; i < len; i++) { 21 | binary += String.fromCharCode(bytes[i]); 22 | } 23 | return window.btoa(binary); 24 | } 25 | 26 | function base64_string_to_array(base64) { 27 | var binary_string = window.atob(base64); 28 | var len = binary_string.length; 29 | var bytes = new Uint8Array(len); 30 | for (var i = 0; i < len; i++) { 31 | bytes[i] = binary_string.charCodeAt(i); 32 | } 33 | return bytes.buffer; 34 | } 35 | --------------------------------------------------------------------------------