├── .github ├── FUNDING.yml └── workflows │ └── node.js.yml ├── .gitignore ├── .gitlab-ci.yml ├── .npmrc ├── LICENSE ├── README.md ├── commitlint.config.js ├── index.js ├── lib ├── core.js ├── crypto.js ├── database.js ├── hyper-fts.js └── swarm.js ├── package.json ├── tests ├── data │ ├── email.eml │ └── test.doc ├── database.test.js ├── drive.test.js ├── helpers │ └── setup.js └── vars.json └── util ├── filedb.util.js ├── fixedChunker.js ├── requestChunker.js └── workerKeyPairs.js /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: [Telios-org] 4 | -------------------------------------------------------------------------------- /.github/workflows/node.js.yml: -------------------------------------------------------------------------------- 1 | 2 | name: Build Status 3 | 4 | on: push 5 | 6 | jobs: 7 | build: 8 | strategy: 9 | matrix: 10 | node-version: [16.x] 11 | os: [ubuntu-latest] 12 | runs-on: ${{ matrix.os }} 13 | steps: 14 | - uses: actions/checkout@v2 15 | - name: Use Node.js ${{ matrix.node-version }} 16 | uses: actions/setup-node@v1 17 | with: 18 | node-version: ${{ matrix.node-version }} 19 | - run: npm install 20 | - run: npm test 21 | publish: 22 | name: Publish Package 23 | needs: build 24 | runs-on: ubuntu-latest 25 | if: github.ref == 'refs/heads/master' 26 | steps: 27 | - uses: actions/checkout@v2 28 | - name: Use Node.js 16.x 29 | uses: actions/setup-node@v1 30 | with: 31 | node-version: 16.x 32 | - run: npm install 33 | - uses: JS-DevTools/npm-publish@v1 34 | with: 35 | token: ${{ secrets.NPM_TOKEN }} 36 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | 9 | # Diagnostic reports (https://nodejs.org/api/report.html) 10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 11 | 12 | # Runtime data 13 | pids 14 | *.pid 15 | *.seed 16 | *.pid.lock 17 | 18 | # Directory for instrumented libs generated by jscoverage/JSCover 19 | lib-cov 20 | 21 | # Coverage directory used by tools like istanbul 22 | coverage 23 | *.lcov 24 | 25 | # nyc test coverage 26 | .nyc_output 27 | 28 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 29 | .grunt 30 | 31 | # Bower dependency directory (https://bower.io/) 32 | bower_components 33 | 34 | # node-waf configuration 35 | .lock-wscript 36 | 37 | # Compiled binary addons (https://nodejs.org/api/addons.html) 38 | build/Release 39 | 40 | # Dependency directories 41 | node_modules/ 42 | jspm_packages/ 43 | 44 | # TypeScript v1 declaration files 45 | typings/ 46 | 47 | # TypeScript cache 48 | *.tsbuildinfo 49 | 50 | # Optional npm cache directory 51 | .npm 52 | 53 | # Optional eslint cache 54 | .eslintcache 55 | 56 | # Microbundle cache 57 | .rpt2_cache/ 58 | .rts2_cache_cjs/ 59 | .rts2_cache_es/ 60 | .rts2_cache_umd/ 61 | 62 | # Optional REPL history 63 | .node_repl_history 64 | 65 | # Output of 'npm pack' 66 | *.tgz 67 | *.zip 68 | 69 | # Yarn Integrity file 70 | .yarn-integrity 71 | 72 | # dotenv environment variables file 73 | .env 74 | .env.test 75 | 76 | # parcel-bundler cache (https://parceljs.org/) 77 | .cache 78 | 79 | # Next.js build output 80 | .next 81 | 82 | # Nuxt.js build / generate output 83 | .nuxt 84 | dist 85 | 86 | # Gatsby files 87 | .cache/ 88 | # Comment in the public line in if your project uses Gatsby and *not* Next.js 89 | # https://nextjs.org/blog/next-9-1#public-directory-support 90 | # public 91 | 92 | # vuepress build output 93 | .vuepress/dist 94 | 95 | # Serverless directories 96 | .serverless/ 97 | 98 | # FuseBox cache 99 | .fusebox/ 100 | 101 | # DynamoDB Local files 102 | .dynamodb/ 103 | 104 | # TernJS port file 105 | .tern-port 106 | 107 | # Drives 108 | drive/ 109 | core/ 110 | tests/storage 111 | tests/localDrive 112 | tests/drive* 113 | tests/peer* 114 | !tests/drive.* 115 | tests/peer-drive 116 | tests/data/meta/* 117 | tests/data/enc_meta.tmp.json 118 | tests/vars.tmp.json 119 | tests/data/encrypted_tmp.email 120 | .tmp 121 | .vscode 122 | package-lock.json 123 | yarn.lock 124 | .DS_Store 125 | scratch.js 126 | drive1* 127 | d1/**/** -------------------------------------------------------------------------------- /.gitlab-ci.yml: -------------------------------------------------------------------------------- 1 | stages: 2 | - build 3 | - test 4 | - publish 5 | - ci_status 6 | 7 | image: node:12.18.4 8 | 9 | workflow: 10 | rules: 11 | - if: $CI_COMMIT_BRANCH 12 | 13 | test: 14 | stage: test 15 | before_script: 16 | - | 17 | { 18 | echo "@${CI_PROJECT_ROOT_NAMESPACE}:registry=${CI_API_V4_URL}/packages/npm/" 19 | } | tee --append .npmrc 20 | - npm ci --cache .npm --prefer-offline 21 | script: 22 | - npm run test 23 | 24 | include: 25 | - project: telios2/telios-devops 26 | ref: master 27 | file: ".gitlab-ci.DiscordWebhook.yml" 28 | - project: telios2/telios-devops 29 | ref: master 30 | file: ".gitlab-ci.NPMPublish.yml" 31 | - template: Secret-Detection.gitlab-ci.yml 32 | - template: SAST.gitlab-ci.yml 33 | - template: License-Scanning.gitlab-ci.yml 34 | - template: Dependency-Scanning.gitlab-ci.yml 35 | 36 | publish:npm: 37 | stage: publish 38 | extends: .publish:npm 39 | -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | package-lock=false -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Nebula 2 | 3 | 4 | ![Build Status](https://github.com/Telios-org/nebula/actions/workflows/node.js.yml/badge.svg) 5 | 6 | Nebula drives are real-time distributed storage for files and key value databases built on top of [Hypercore Protocol](https://hypercore-protocol.org/). This project exists because the [Telios](https://telios.io) email client needed a way to distribute and store encrypted emails on user's local file systems over a peer-to-peer (P2P) network. A lot of inspiration was taken from [Hyperdrive](https://github.com/hypercore-protocol/hyperdrive), but Hyperdrive didn't have options for fine-grain access control, multiple writers, and the ability to delete files from disk once added to the drives. 7 | 8 | Nebula drives come with a handful of useful features like: 9 | - __Shareable over company firewalls and mobile networks__: The P2P network runs on [Hyperswarm](https://github.com/hyperswarm/hyperswarm) which has the ability to hole-punch through most company firewalls and mobile connections. 10 | - __Full Text Search__: Create encrypted full text search indexes on top of Hypercores. 11 | - __Access Control__: Control access to each file by sharing the file's hash and the drive's discovery key. 12 | - __Multiwriter__: Drives can have multiple peers with write access by exchanging eachother's keys. 13 | - __Collections__: Along with files, drives can create and share simple key value btree databases built on [Hyperbee](https://github.com/hypercore-protocol/hyperbee). Collections also have the option to be encrypted with a secret key. 14 | 15 | ### TODOs: 16 | - [x] Connect to drives behind corporate firewalls and mobile networks 17 | - [x] Create and share key value databases between peers 18 | - [x] Upgrade multiwriter to Hypercore v10 19 | - [x] Build full text search indexes from encrypted Hypercores 20 | - [x] Upgrade collections API with [Hyperbeedeebee](https://github.com/RangerMauve/hyperbeedeebee) 21 | - [ ] Upgrade access control to limit sharing by a peer's public key 22 | - [ ] Turn an existing directory into a drive and watch for changes 23 | 24 | ## Installation 25 | 26 | ```js 27 | npm i @telios/nebula 28 | ``` 29 | 30 | ## Usage 31 | 32 | ```js 33 | /****************************************************** 34 | * 35 | * Create a new drive and write encrypted files to it 36 | * 37 | ******************************************************/ 38 | 39 | const Drive = require('@telios/nebula') 40 | 41 | // Optionally pass in an encryption key to encrypt the drive's databases 42 | const encryptionKey = Buffer.alloc(32, 'hello world') 43 | 44 | const localDrive = new Drive(__dirname + "/drive", null, { 45 | keyPair, 46 | encryptionKey, 47 | swarmOpts: { 48 | server: true, 49 | client: true 50 | }, 51 | fullTextSearch: true 52 | }) 53 | 54 | await localDrive.ready() 55 | 56 | // Key to be shared with other devices or services that want to seed this drive 57 | const drivePubKey = localDrive.publicKey 58 | 59 | // Clone a remote drive 60 | const remoteDrive = new Drive(__dirname + "/drive_remote", drivePubKey, { 61 | keyPair, 62 | swarmOpts: { 63 | server: true, 64 | client: true 65 | } 66 | }) 67 | 68 | await remoteDrive.ready() 69 | 70 | localDrive.on('file-sync', file => { 71 | // Local drive has synced somefile.json from remote drive 72 | }) 73 | 74 | // Write a non-encrypted file to the drive 75 | await remoteDrive.writeFile('/dest/path/on/drive/somefile.json', readableStream) 76 | 77 | // Write anencrypted file to the drive 78 | await remoteDrive.writeFile('/dest/path/on/drive/someEncryptedFile.json', readableStream, { encrypted: true }) 79 | 80 | 81 | /****************************************************************** 82 | * 83 | * Create an encrypted and shared database with full text search 84 | * 85 | *****************************************************************/ 86 | 87 | const corpus = [ 88 | { 89 | title: 'Painting 1', 90 | text_body: "In your world you can create anything you desire." 91 | }, 92 | { 93 | title: 'Painting 2', 94 | text_body: "I thought today we would make a happy little stream that's just running through the woods here." 95 | }, 96 | { 97 | title: 'Painting 3', 98 | text_body: "See. We take the corner of the brush and let it play back-and-forth. No pressure. Just relax and watch it happen." 99 | }, 100 | { 101 | title: 'Painting 4', 102 | text_body: "Just go back and put one little more happy tree in there. Without washing the brush, I'm gonna go right into some Van Dyke Brown." 103 | }, 104 | { 105 | title: 'Painting 5', 106 | text_body: "Trees get lonely too, so we'll give him a little friend. If what you're doing doesn't make you happy - you're doing the wrong thing." 107 | }, 108 | { 109 | title: 'Painting 6', 110 | text_body: "Son of a gun. We're not trying to teach you a thing to copy. We're just here to teach you a technique, then let you loose into the world." 111 | } 112 | ] 113 | 114 | const collection = await drive.db.collection('BobRoss') 115 | 116 | for(const data of corpus) { 117 | await collection.insert({ title: data.title, text_body: data.text_body }) 118 | } 119 | 120 | // Build a search index from the title and text_body properties 121 | await collection.ftsIndex(['title', 'text_body']) 122 | 123 | // Query the index 124 | const query = await collection.search("happy tree", { limit: 10 }) 125 | ``` 126 | 127 | ## API / Examples 128 | 129 | #### `const drive = new Drive(storagePath, [key], [options])` 130 | 131 | Create a drive to be shared over the network which can be replicated and seeded by other peers. 132 | 133 | - `storagePath`: The directory where you want the drive to be created. 134 | - `key`: The public key of the remote drive you want to clone 135 | 136 | Options include: 137 | 138 | ```js 139 | { 140 | storage, // Override Hypercore's default random-access-file storage with a different random-access-storage module 141 | storageMaxBytes, // Maximum bytes the drive will store before turning off replication/file syncing 142 | encryptionKey, // optionally pass an encryption key to encrypt the drive's database 143 | keyPair: { // ed25519 keypair 144 | publicKey, 145 | secretKey 146 | }, 147 | syncFiles: true | false // Sync all files from peer drives 148 | joinSwarm: true | false // Optionally set whether or not to join hyperswarm when starting the drive. Defaults to true. 149 | swarmOpts: { // Set server to true to start this drive as a server and announce its public key to the network 150 | server: true | false, 151 | client: true | false 152 | }, 153 | checkNetworkStatus: true | false // Listen for when the drive's network status changes 154 | fulltextSearch: true | false // support full text search indexes 155 | blind: true // Initialize drive as a blind seeder. For example when you're seeding another encrypted drive and you don't have the encryption key 156 | broadcast: true // Tell other peers about this drive. Defaults to true. 157 | } 158 | ``` 159 | 160 | ```js 161 | const Drive = require('nebula-drive') 162 | 163 | // Create a new local drive. 164 | const localDrive = new Drive(__dirname + "/drive", null, { 165 | keyPair, 166 | swarmOpts: { 167 | server: true, 168 | client: true 169 | } 170 | }) 171 | 172 | await localDrive.ready() 173 | 174 | // Key to be shared with other devices or services that want to seed this drive 175 | const drivePubKey = localDrive.publicKey 176 | 177 | // Clone a remote drive 178 | const remoteDrive = new Drive(__dirname + "/drive_remote", drivePubKey, { 179 | keyPair, 180 | swarmOpts: { 181 | server: true, 182 | client: true 183 | } 184 | }) 185 | 186 | await remoteDrive.ready() 187 | ``` 188 | #### `drive.publicKey` 189 | 190 | The drive's `publicKey` should ONLY be given to remote peers you would like to replicate with. All peers with this key will have write access to your drive's metadata (peers this drive connects to and generic file data). The publicKey + the drive's encryption key will give peers full write access. 191 | 192 | #### `drive.peerWriterKey` 193 | 194 | The key of this drive's primary writer Hypercore. This key can be used for adding and removing this drive as a remote peer. 195 | 196 | #### `drive.peers` 197 | 198 | A Set containing the public keys of all connected peers. 199 | 200 | #### `drive.encryptionKey` 201 | 202 | The drive's symmetric key used for encrypting the writer hypercores. Share this key with trusted peers only and as they will have full write access. 203 | 204 | #### `await drive.ready()` 205 | 206 | Initialize the drive and all resources needed. 207 | 208 | #### `await drive.addPeer(peer)` 209 | 210 | Adds a remote drive as a new writer. After a peer has been added, the drive will automatically try to reconnect to this peer after every restart. Drives automatically add remote peers that initialized their drives with a public key so this rarely needs to be manually called. 211 | 212 | - `peer` 213 | - `blind`: true | false `drive.blind` 214 | - `publicKey`: The remote peer's public key `drive.publicKey` 215 | - `writer`: The remote peer's writer core public key `drive.peerWriter` 216 | - `meta`: The remote peer's meta core public key `drive.publicKey` 217 | 218 | Example Usage: 219 | 220 | ```js 221 | // Local drive on Device A 222 | const drive1 = new Drive(__dirname + "/drive", null, { 223 | keyPair, 224 | swarmOpts: { 225 | server: true, 226 | client: true 227 | } 228 | }) 229 | 230 | // Local drive on Device B 231 | const drive2 = new Drive(__dirname + "/drive", drive1.publicKey, { 232 | keyPair, 233 | swarmOpts: { 234 | server: true, 235 | client: true 236 | } 237 | }) 238 | 239 | // Writer and meta keys need to be exchanged between both devices for bi-directional writing. 240 | // Drive2 already includes drive1 as a peer because it was initialized with drive1's publicKey 241 | await drive1.addPeer({ 242 | blind: drive2.blind, 243 | publicKey: drive2.publickey, 244 | writer: drive2.peerWriter, 245 | meta: drive2.publicKey 246 | }) 247 | ``` 248 | 249 | #### `await drive.removePeer(peer)` 250 | 251 | Stop replicating with another drive peer. 252 | 253 | - `peer` 254 | - `blind`: true | false `drive.blind` 255 | - `publicKey`: The remote peer's public key `drive.publicKey` 256 | - `writer`: The remote peer's writer core public key `drive.peerWriter` 257 | - `meta`: The remote peer's meta core public key `drive.publicKey` 258 | 259 | ```js 260 | 261 | await drive1.removePeer({ 262 | blind: drive1.blind, 263 | publicKey: drive1.publickey, 264 | writer: drive1.peerWriter, 265 | meta: drive1.publicKey 266 | }) 267 | ``` 268 | 269 | #### `const file = await drive.writeFile(path, readableStream, [opts])` 270 | 271 | Write a file from a readable stream. When choosing to encrypt a file, the encryption key will be passed back in the response. Each file is encrypted with a unique key which should be stored separately. 272 | 273 | - `path`: Full path where the file resides on the local drive `dir/to/my/file.jpg` 274 | - `readableStream`: Any readableStream `fs.createReadableStream()` 275 | 276 | Options include: 277 | ```js 278 | // When encrypted is true a key and header value will be returned after the file has been written 279 | { 280 | encrypted: true 281 | } 282 | ``` 283 | 284 | #### `const stream = await drive.readFile(path)` 285 | 286 | Creates a readable stream of data from the requested file path. 287 | 288 | - `path`: Full path where the file resides on the local drive `dir/to/my/file.jpg` 289 | 290 | 295 | 296 | #### `const stream = await drive.fetchFileByDriveHash(discoveryKey, fileHash, [opts])` 297 | 298 | Drives with many files may not want to announce every file by it's hash due to network bandwidth limits. In this case, a drive has the option of sharing it's `discoveryKey` which peers can use to connect to the drive and then make a request file hash request. 299 | 300 | - `discoveryKey`: Remote drive's discovery key `drive.discoveryKey` which is used by peers to request resources from the drive. 301 | - `fileHash`: Hash of the file being requested on the remote drive. 302 | - `opts`: If a key and header are passed in then the return stream will be the deciphered data 303 | - `key`: Encryption key used for deciphering the encrypted stream. This key is returned from the `drive.writeFile` method. 304 | - `header`: Needed for validating the encrypted stream. This gets returned from `drive.writeFile()`. 305 | 306 | #### `const stream = drive.decryptFileStream(stream, key, header)` 307 | 308 | If `drive.fetchFileByDriveHash` is returning encrypted data, then `decryptFileStream` will transform that stream and return a new stream of deciphered data. 309 | 310 | - `stream`: Readable stream of encrypted data 311 | - `key`: Encryption key used for deciphering the encrypted stream. This key is returned from the `drive.writeFile` method. 312 | - `header`: Needed for validating the encrypted stream. This gets returned from `drive.writeFile()`. 313 | 314 | #### `await drive.fetchFileBatch(files, cb)` 315 | 316 | Fetching files as a batch automatically chunks parallel requests in a fixed batch size so a drive can request as many files as it needs without impacting performance. 317 | 318 | - `files`: Array of file objects with the following structure 319 | - `discovery_key`: Remote drive's discovery key `drive.discoveryKey` which is used by peers to request resources from the drive. 320 | - `hash`: Hash of the file being requested on the remote drive. 321 | - `key`: Encryption key used for deciphering the encrypted stream. This key is returned from the `drive.writeFile` method. 322 | - `header`: Needed for validating the encrypted stream. This gets returned from `drive.writeFile()`. 323 | - `cb`: Callback method that runs after every file stream has been initialized. Use this for handling what to do with the individual file streams. Note that this should return a promise. 324 | 325 | Example Usage: 326 | 327 | ```js 328 | 329 | await drive.fetchFileBatch(files, (stream, file) => { 330 | return new Promise((resolve, reject) => { 331 | const writeStream = fs.createWriteStream(`./${file.path}`) 332 | pump(stream, writeStream, (err) => { 333 | resolve() 334 | }) 335 | }) 336 | }) 337 | 338 | ``` 339 | 340 | #### `await drive.close()` 341 | 342 | Fully close the drive and all of it's resources. 343 | 344 | #### `await drive.stat()` 345 | 346 | Returns the drive's storage info 347 | 348 | ```js 349 | { 350 | file_bytes: 0, 351 | core_bytes: 0, 352 | total_bytes: 0 353 | } 354 | ``` 355 | 356 | #### `drive.on('message', (peerPubKey, socket) => {})` 357 | 358 | Emitted when the drive has recieved a message from a peer. 359 | 360 | - `peerPubKey`: Public key of the peer that sent the message 361 | - `socket`: The socket returned on this event can be used as a duplex stream for bi-directional communication with the connecting peer. `socket.write` `socket.on('data, data => {})` 362 | 363 | #### `drive.on('collection-update', (item) => {})` 364 | 365 | Emitted when a collection has received an update from a remote peer 366 | 367 | - `item` 368 | - `collection`: The collection that was updated 369 | - `value`: JSON value of the new update 370 | 371 | #### `drive.on('file-add', (file, enc) => {})` 372 | 373 | Emitted when a new file has been added to a local drive. 374 | 375 | - `file`: A file object 376 | - `path`: drive path the file was saved to 377 | - `hash`: Hash of the file 378 | - `enc`: Passes back properties needed to decrypt the file 379 | - `key`: Key needed to decrypt the file 380 | - `header`: Needed for validating the encrypted stream 381 | 382 | #### `drive.on('sync', () => {})` 383 | 384 | Emitted when the drive has synced remote data. 385 | 386 | #### `drive.on('file-sync', (file) => {})` 387 | 388 | Emitted when the drive has synced remote a remote file. 389 | 390 | #### `drive.on('file-unlink', (file) => {})` 391 | 392 | Emitted when a file has been deleted on the drive. 393 | 394 | #### `drive.on('fetch-error', (err) => {})` 395 | 396 | Emitted when there has been an error downloading from the remote drive. 397 | 398 | #### `drive.on('network-updated', (network) => {})` 399 | 400 | Emitted when either the internet connection or the drive's connection to Hyperswarm has changed. The drive option `checkNetworkStatus` must be set to true in order for these events to be emitted. 401 | 402 | Returns: 403 | - `network` 404 | - `internet`: true|false 405 | - `drive`: true|false 406 | 407 | #### `drive.on('peer-connected', (peer) => {})` 408 | 409 | Emitted when a remote peer connects and starts replicating. 410 | 411 | #### `drive.on('peer-disconnected', (peer) => {})` 412 | 413 | Emitted when a remote peer disconnects. 414 | 415 | ## Drive Database API 416 | Drive databases mimic the MongoDB API. Full API documentation can be found on [Hyperbeedeebee](https://github.com/RangerMauve/hyperbeedeebee) 417 | 418 | #### `const collection = await drive.db.collection(name)` 419 | 420 | Creates a new collection. Collections are automatically encrypted when a drive is instantiated with `encryptionKey` (`drive.encryptionKey`) 421 | 422 | #### `await collection.insert(doc)` 423 | 424 | Inserts a new document into the collection. 425 | 426 | Example: 427 | ```js 428 | const doc = await collection.insert({ name: 'alice', age: 37 }) 429 | 430 | // doc._id gets set to an ObjectId if you don't specify it 431 | ``` 432 | 433 | #### `await collection.find(query)` 434 | 435 | Search through all documents by query 436 | 437 | Example: 438 | ```js 439 | const docs = await collection.find({ name: 'alice' }) 440 | ``` 441 | 442 | #### `await collection.createIndex(fields, [opts])` 443 | 444 | Creates an index for a set of fields. This will speed up queries and is required for sorting by fields 445 | 446 | Example: 447 | ```js 448 | const docs = await collection.createIndex(['name','address']) 449 | ``` 450 | 451 | #### `await collection.ftsIndex([prop1, prop2, ...], docs)` 452 | 453 | Create a full text search index from a collection's properties 454 | 455 | ```js 456 | const docs = [] 457 | 458 | // Documents can only be added to search indexes after they've been inserted into a collection. 459 | const doc = await collection.insert(item) 460 | 461 | docs.push(doc) 462 | 463 | await collection.ftsIndex(['address', 'first_name', 'last_name'], docs) 464 | ``` 465 | 466 | #### `const results = await collection.search(query, [opts])` 467 | 468 | Query a searchable index 469 | 470 | Options include: 471 | ```js 472 | { 473 | limit: 10 474 | } 475 | ``` -------------------------------------------------------------------------------- /commitlint.config.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Telios-org/nebula/1994b5284a4492fe1e1f549cb76a6c5c47f459b7/commitlint.config.js -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs') 2 | const EventEmitter = require('events') 3 | const getDirName = require('path').dirname 4 | const path = require('path') 5 | const Database = require('./lib/database') 6 | const Hyperbee = require('hyperbee') 7 | const Hypercore = require('hypercore') 8 | const pump = require('pump') 9 | const Crypto = require('./lib/crypto') 10 | const Swarm = require('./lib/swarm') 11 | const stream = require('stream') 12 | const blake = require('blakejs') 13 | const Hyperswarm = require('hyperswarm') 14 | const DHT = require('@hyperswarm/dht') 15 | const MemoryStream = require('memorystream') 16 | const { v4: uuidv4 } = require('uuid') 17 | const FixedChunker = require('./util/fixedChunker.js') 18 | const RequestChunker = require('./util/requestChunker.js') 19 | const WorkerKeyPairs = require('./util/workerKeyPairs.js') 20 | const isOnline = require('is-online') 21 | const FileDB = require('./util/filedb.util') 22 | const BSON = require('bson') 23 | 24 | const HASH_OUTPUT_LENGTH = 32 // bytes 25 | const MAX_PLAINTEXT_BLOCK_SIZE = 65536 26 | const MAX_ENCRYPTED_BLOCK_SIZE = 65553 27 | const FILE_TIMEOUT = 2000 // How long to wait for the on data event when downloading a file from a remote drive. 28 | const FILE_RETRY_ATTEMPTS = 3 // Fail to fetch file after n attempts 29 | const FILE_BATCH_SIZE = 10 // How many parallel requests are made in each file request batch 30 | 31 | 32 | class Drive extends EventEmitter { 33 | constructor( 34 | drivePath, 35 | peerPubKey, // Key used to clone and seed drive. Should only be shared with trusted sources 36 | { 37 | storage, 38 | keyPair, // ed25519 keypair to listen on 39 | writable, 40 | swarmOpts, 41 | encryptionKey, 42 | fileTimeout, 43 | fileRetryAttempts, 44 | checkNetworkStatus, 45 | joinSwarm, 46 | fullTextSearch, // Initialize a corestore to support full text search indexes. 47 | blind, // Set to true if blind mirroring another drive (you don't have the encryption key) 48 | storageMaxBytes, // Max size this drive will store in bytes before turning off replication/file syncing 49 | syncFiles = true, 50 | includeFiles, 51 | broadcast = true // Tell the other peer drives about this drive 52 | } 53 | ) { 54 | super() 55 | 56 | this.storage = storage 57 | this.encryptionKey = encryptionKey 58 | this.database = null 59 | this.db = null; 60 | this.drivePath = drivePath 61 | this.swarmOpts = swarmOpts 62 | this.publicKey = null 63 | this.peerPubKey = peerPubKey 64 | this.peerWriterKey = null 65 | this.keyPair = keyPair ? keyPair : DHT.keyPair() 66 | this.writable = writable 67 | this.fullTextSearch = fullTextSearch 68 | this.fileTimeout = fileTimeout || FILE_TIMEOUT 69 | this.fileRetryAttempts = fileRetryAttempts-1 || FILE_RETRY_ATTEMPTS-1 70 | this.requestQueue = new RequestChunker(null, FILE_BATCH_SIZE) 71 | this.checkNetworkStatus = checkNetworkStatus 72 | this.joinSwarm = typeof joinSwarm === 'boolean' ? joinSwarm : true 73 | this.peers = new Set() 74 | this.network = { 75 | internet: false, 76 | drive: false 77 | } 78 | 79 | this.blind = blind ? blind : false 80 | this.storageMaxBytes = storageMaxBytes || false 81 | this.syncFiles = syncFiles 82 | this.includeFiles = includeFiles 83 | this.opened = false 84 | this.broadcast = broadcast 85 | 86 | // When using custom storage, transform drive path into beginning of the storage namespace 87 | this.storageName = drivePath.slice(drivePath.lastIndexOf('/') + 1, drivePath.length) 88 | 89 | this._localCore = null 90 | this._localHB = null // Optional datastore for storing encrypted data locally. This will not sync with peers or be replicated. 91 | this._swarm = null 92 | this._workerKeyPairs = new WorkerKeyPairs(FILE_BATCH_SIZE) 93 | this._collections = {} 94 | this._filesDir = path.join(drivePath, `./Files`) 95 | this._localDB = null // Local Key value datastore only 96 | this._lastSeq = null 97 | this._checkInternetInt = null 98 | this._checkInternetInProgress = false 99 | this._fileStatPath = this.drivePath + '/Files/file_stat.txt' 100 | this._stat = { 101 | file_bytes: 0, 102 | core_bytes: 0, 103 | total_bytes: 0 104 | } 105 | this._dbVersion = '2.0' 106 | 107 | this.indexCreated = false 108 | 109 | if (!fs.existsSync(drivePath)) { 110 | fs.mkdirSync(drivePath) 111 | } 112 | 113 | if (!fs.existsSync(this._filesDir)) { 114 | fs.mkdirSync(this._filesDir) 115 | } 116 | 117 | this.requestQueue.on('process-queue', async files => { 118 | this.requestQueue.reset() 119 | 120 | await this.fetchFileBatch(files, (stream, file) => { 121 | return new Promise((resolve, reject) => { 122 | fs.mkdirSync(getDirName(this._filesDir + file.path), { recursive: true }) 123 | 124 | const writeStream = fs.createWriteStream(this._filesDir + file.path) 125 | 126 | pump(stream, writeStream, (err) => { 127 | if (err) reject(err) 128 | 129 | setTimeout(async () => { 130 | if(this.opened) { 131 | this.emit('file-sync', file) 132 | const filePath = file.encrypted ? `/${file.uuid}` : file.path 133 | await this._localHB.put(filePath, {}) 134 | } 135 | }) 136 | 137 | resolve() 138 | }) 139 | }) 140 | }) 141 | }) 142 | 143 | // Periodically check this drive's connection to the internet. 144 | // When the internet is down, emit a network status updated event. 145 | if(this.checkNetworkStatus) { 146 | this._checkInternetInt = setInterval(async () => { 147 | if(!this._checkInternetInProgress) { 148 | this._checkInternetInProgress = true 149 | await this._checkInternet(); 150 | this._checkInternetInProgress = false 151 | } 152 | }, 1500) 153 | } 154 | } 155 | 156 | async ready() { 157 | const uncaughtCount = process.listenerCount('uncaughtException') 158 | 159 | if(uncaughtCount === 0) { 160 | process.on('uncaughtException', (err) => { 161 | if( 162 | err.message.indexOf('PEER_NOT_FOUND') === -1 && 163 | err.message.indexOf('PeerDiscovery') === -1 && 164 | err.message.indexOf('connection reset') === -1 && 165 | err.message.indexOf('Linearization') === -1 166 | ) { 167 | // uncaught error 168 | } 169 | }) 170 | } 171 | 172 | await this._bootstrap() 173 | 174 | const stat = this._localDB.get('stat') 175 | 176 | if(!stat) { 177 | await this.database._updateStatBytes(0) 178 | this._localDB.put('stat', { ...this._stat }) 179 | } else { 180 | this._stat = stat 181 | } 182 | 183 | this.publicKey = this.database.localMetaCore.key.toString('hex') 184 | 185 | if(!this.blind) { 186 | this.peerWriterKey = this.database.localInput.key.toString('hex') 187 | } 188 | 189 | if (this.peerPubKey) { 190 | this.discoveryKey = createTopicHash(this.peerPubKey).toString('hex') 191 | } else { 192 | this.discoveryKey = createTopicHash(this.publicKey).toString('hex') 193 | } 194 | 195 | if (this.keyPair && this.joinSwarm) { 196 | await this.connect() 197 | } 198 | 199 | // Data here can only be read by peer drives 200 | // that are sharing the same drive secret 201 | if(!this.blind) { 202 | this._collections.files = await this.database.collection('file') 203 | 204 | // This drastically speeds up queries and is necessary for sorting by fields 205 | this._collections.files.createIndex(['path']) 206 | } 207 | 208 | this.database.on('collection-update', async data => { 209 | if(!data) { 210 | this.emit('collection-update') 211 | } 212 | 213 | if( 214 | data.value.author === this.keyPair.publicKey.toString('hex') || 215 | data.value.peerPubKey === this.keyPair.publicKey.toString('hex') || 216 | data.value.peer === this.keyPair.publicKey.toString('hex') 217 | ) return 218 | 219 | if(data && data.collection === 'metadb' && !data.value.cores) { 220 | await this._update(data) 221 | } else { 222 | if(data.collection !== 'metadb') { 223 | // If this drive can't decipher the data inside the remote hypercore's then just listen for when those cores are updated. 224 | this.emit('collection-update', !this.blind ? data : null) 225 | } 226 | } 227 | }) 228 | 229 | this.opened = true 230 | } 231 | 232 | // Connect to the Hyperswarm network 233 | async connect() { 234 | if (this._swarm) { 235 | await this._swarm.close() 236 | } 237 | 238 | this._swarm = new Swarm({ 239 | keyPair: this.keyPair, 240 | blind: this.blind, 241 | workerKeyPairs: this._workerKeyPairs.keyPairs, 242 | topic: this.discoveryKey, 243 | publicKey: this.peerPubKey || this.publicKey, 244 | isServer: this.swarmOpts.server, 245 | isClient: this.swarmOpts.client, 246 | acl: this.swarmOpts.acl, 247 | }) 248 | 249 | this._swarm.on('peer-connected', async socket => { 250 | if(this.broadcast) { 251 | socket.write(JSON.stringify({ 252 | type: 'sync', 253 | meta: { 254 | __version: this._dbVersion, 255 | drivePubKey: this.peerPubKey || this.publicKey, 256 | peerPubKey: this.keyPair.publicKey.toString('hex'), 257 | blind: this.blind, 258 | writer: this.peerWriterKey, 259 | meta: this.publicKey 260 | } 261 | })) 262 | } 263 | }) 264 | 265 | if(this.checkNetworkStatus) { 266 | this._swarm.on('disconnected', () => { 267 | if(this.network.drive) { 268 | this.network.drive = false 269 | this.emit('network-updated', { drive: this.network.drive }) 270 | } 271 | }) 272 | 273 | this._swarm.on('connected', () => { 274 | if(!this.network.drive) { 275 | this.network.drive = true 276 | this.emit('network-updated', { drive: this.network.drive }) 277 | } 278 | }) 279 | } 280 | 281 | 282 | this._swarm.on('message', async (peerPubKey, data) => { 283 | const drivePubKey = this.peerPubKey || this.publicKey 284 | try { 285 | const msg = JSON.parse(data.toString()) 286 | if(msg && msg.type === 'sync') { 287 | this.emit('newMessage', msg) 288 | 289 | if(msg.meta.drivePubKey === drivePubKey) { 290 | await this.addPeer(msg.meta) 291 | } else { 292 | // ACCESS DENIED 293 | } 294 | } 295 | 296 | this.emit('message', peerPubKey, data) 297 | } catch(err) { 298 | console.log(err) 299 | } 300 | }) 301 | 302 | this._swarm.on('file-requested', socket => { 303 | socket.once('data', async data => { 304 | const fileHash = data.toString('utf-8') 305 | let file 306 | 307 | try { 308 | file = await this.metadb.findOne({ hash: fileHash }) 309 | } catch(err) { 310 | // Not Found 311 | } 312 | 313 | if (!file) { 314 | let err = new Error() 315 | err.message = 'Requested file was not found on drive' 316 | socket.destroy(err) 317 | } else { 318 | const readStream = fs.createReadStream(path.join(this.drivePath, `./Files${file.path}`)) 319 | 320 | pump(readStream, socket, (err) => { 321 | // handle done 322 | }) 323 | } 324 | }) 325 | 326 | socket.on('error', (err) => { 327 | // handle errors 328 | }) 329 | }) 330 | 331 | await this._swarm.ready() 332 | } 333 | 334 | async addPeer(peer) { 335 | try { 336 | const doc = await this.database.metadb.findOne({ peerPubKey: peer.peerPubKey }) 337 | } catch(err) { 338 | if(peer.__version === this._dbVersion) { 339 | await this.database.metadb.insert({ 340 | __version: this._dbVersion, 341 | blacklisted: false, 342 | peerPubKey: peer.peerPubKey, 343 | blind: peer.blind, 344 | cores: { 345 | writer: peer.writer, 346 | meta: peer.meta 347 | } 348 | }) 349 | 350 | await this.database.addRemotePeer(peer) 351 | } 352 | } 353 | } 354 | 355 | // Remove Peer 356 | async removePeer(peer) { 357 | await this.database.removeRemotePeer({ 358 | peerPubKey: peer.publicKey, 359 | blind: peer.blind, 360 | writer: peer.writer, 361 | meta: peer.meta 362 | }) 363 | 364 | await this.database.metadb.update({ peerPubKey: peer.publicKey }, { blacklisted: true }) 365 | } 366 | 367 | async writeFile(path, readStream, opts = {}) { 368 | let filePath = path 369 | let dest 370 | const uuid = uuidv4() 371 | 372 | if (filePath[0] === '/') { 373 | filePath = filePath.slice(1, filePath.length) 374 | } 375 | 376 | if (opts.encrypted) { 377 | dest = `${this._filesDir}/${uuid}` 378 | } else { 379 | fs.mkdirSync(getDirName(this._filesDir + path), { recursive: true }) 380 | dest = this._filesDir + path 381 | } 382 | 383 | return new Promise(async (resolve, reject) => { 384 | const pathSeg = filePath.split('/') 385 | let fullFile = pathSeg[pathSeg.length - 1] 386 | let fileName 387 | let fileExt 388 | 389 | if (fullFile.indexOf('.') > -1) { 390 | fileName = fullFile.split('.')[0] 391 | fileExt = fullFile.split('.')[1] 392 | } 393 | 394 | const writeStream = fs.createWriteStream(dest) 395 | 396 | if (opts.encrypted && !opts.skipEncryption) { 397 | const fixedChunker = new FixedChunker(readStream, MAX_PLAINTEXT_BLOCK_SIZE) 398 | const { key, header, file } = await Crypto.encryptStream(fixedChunker, writeStream) 399 | 400 | await this.database._updateStatBytes(file.size) 401 | 402 | await this.metadb.update( 403 | { 404 | path: `/${uuid}` 405 | }, 406 | { 407 | uuid, 408 | size: file.size, 409 | hash: file.hash, 410 | path: `/${uuid}`, 411 | peer: this.keyPair.publicKey.toString('hex'), 412 | discovery_key: this.discoveryKey, 413 | custom_data: opts.customData 414 | }, 415 | { 416 | upsert: true 417 | } 418 | ) 419 | 420 | const fileMeta = { 421 | uuid, 422 | name: fileName, 423 | size: file.size, 424 | mimetype: fileExt, 425 | encrypted: true, 426 | key: key.toString('hex'), 427 | header: header.toString('hex'), 428 | hash: file.hash, 429 | path: filePath, 430 | peer: this.keyPair.publicKey.toString('hex'), 431 | discovery_key: this.discoveryKey, 432 | custom_data: opts.customData 433 | } 434 | 435 | await this._collections.files.update( 436 | { 437 | path: filePath 438 | }, 439 | { 440 | ...fileMeta, 441 | updatedAt: new Date().toISOString() 442 | }, 443 | { 444 | upsert: true 445 | } 446 | ) 447 | 448 | this.emit('file-add', fileMeta) 449 | 450 | resolve({ 451 | key: key.toString('hex'), 452 | header: header.toString('hex'), 453 | ...fileMeta 454 | }) 455 | } else { 456 | let bytes = 0 457 | const hash = blake.blake2bInit(HASH_OUTPUT_LENGTH, null) 458 | const calcHash = new stream.Transform({ 459 | transform 460 | }) 461 | 462 | function transform(chunk, encoding, callback) { 463 | bytes += chunk.byteLength 464 | 465 | blake.blake2bUpdate(hash, chunk) 466 | callback(null, chunk) 467 | } 468 | 469 | pump(readStream, calcHash, writeStream, async () => { 470 | setTimeout(async () => { 471 | const _hash = Buffer.from(blake.blake2bFinal(hash)).toString('hex') 472 | 473 | if (bytes > 0) { 474 | await this.database._updateStatBytes(bytes) 475 | 476 | await this.metadb.update( 477 | { 478 | path 479 | }, 480 | { 481 | uuid, 482 | size: bytes, 483 | hash: _hash, 484 | path, 485 | peer: this.keyPair.publicKey.toString('hex'), 486 | discovery_key: this.discoveryKey, 487 | custom_data: opts.customData 488 | }, 489 | { 490 | upsert: true 491 | } 492 | ) 493 | 494 | const fileMeta = { 495 | uuid, 496 | name: fileName, 497 | size: bytes, 498 | mimetype: fileExt, 499 | hash: _hash, 500 | path: filePath, 501 | peer: this.keyPair.publicKey.toString('hex'), 502 | discovery_key: this.discoveryKey, 503 | custom_data: opts.customData 504 | } 505 | 506 | await this._collections.files.update( 507 | { 508 | path: filePath 509 | }, 510 | { 511 | ...fileMeta, 512 | updatedAt: new Date().toISOString() 513 | }, 514 | { 515 | upsert: true 516 | } 517 | ) 518 | 519 | this.emit('file-add', fileMeta) 520 | resolve(fileMeta) 521 | } else { 522 | reject('No bytes were written.') 523 | } 524 | }) 525 | }) 526 | } 527 | }) 528 | } 529 | 530 | async readFile(path) { 531 | let file 532 | let filePath = path 533 | 534 | if (filePath[0] === '/') { 535 | filePath = filePath.slice(1, filePath.length) 536 | } 537 | 538 | try { 539 | file = await this._collections.files.findOne({ path: filePath }) 540 | 541 | if(!fs.existsSync(`${this._filesDir}/${file.uuid}`)) { 542 | throw new Error('File does not exist.') 543 | } 544 | 545 | const stream = fs.createReadStream(`${this._filesDir}/${file.uuid}`) 546 | 547 | // If key then decipher file 548 | if (file.encrypted && file.key && file.header) { 549 | const fixedChunker = new FixedChunker(stream, MAX_ENCRYPTED_BLOCK_SIZE) 550 | return Crypto.decryptStream(fixedChunker, file.key, file.header) 551 | } else { 552 | return stream 553 | } 554 | } catch (err) { 555 | throw err 556 | } 557 | } 558 | 559 | decryptFileStream(stream, key, header) { 560 | const fixedChunker = new FixedChunker(stream, MAX_ENCRYPTED_BLOCK_SIZE) 561 | return Crypto.decryptStream(fixedChunker, key, header) 562 | } 563 | 564 | // TODO: Implement this 565 | fetchFileByHash(fileHash) { 566 | } 567 | 568 | async fetchFileByDriveHash(discoveryKey, fileHash, opts = {}) { 569 | const keyPair = opts.keyPair || this.keyPair 570 | const memStream = new MemoryStream() 571 | const topic = blake.blake2bHex(discoveryKey, null, HASH_OUTPUT_LENGTH) 572 | 573 | 574 | if (!fileHash || typeof fileHash !== 'string') { 575 | return reject('File hash is required before making a request.') 576 | } 577 | 578 | if (!discoveryKey || typeof discoveryKey !== 'string') { 579 | return reject('Discovery key cannot be null and must be a string.') 580 | } 581 | 582 | try { 583 | await this._initFileSwarm(memStream, topic, fileHash, 0, { keyPair }) 584 | } catch(e) { 585 | setTimeout(() => { 586 | memStream.destroy(e) 587 | }) 588 | return memStream 589 | } 590 | 591 | if (opts.key && opts.header) { 592 | return this.decryptFileStream(memStream, opts.key, opts.header) 593 | } 594 | 595 | return memStream 596 | } 597 | 598 | async fetchFileBatch(files, cb) { 599 | const batches = new RequestChunker(files, FILE_BATCH_SIZE) 600 | 601 | for (let batch of batches) { 602 | const requests = [] 603 | 604 | for (let file of batch) { 605 | if(typeof file.size === 'number') await this.database._updateStatBytes(file.size) 606 | const stat = this._localDB.get('stat') 607 | if(stat.total_bytes <= this.storageMaxBytes || !this.storageMaxBytes) { 608 | requests.push(new Promise(async (resolve, reject) => { 609 | if (file.discovery_key) { 610 | try { 611 | const keyPair = this._workerKeyPairs.getKeyPair() 612 | const stream = await this.fetchFileByDriveHash(file.discovery_key, file.hash, { key: file.key, header: file.header, keyPair }) 613 | 614 | await cb(stream, file) 615 | 616 | return resolve() 617 | } catch(err) { 618 | return reject(err) 619 | } 620 | } else { 621 | // TODO: Fetch files by hash 622 | return reject() 623 | } 624 | })) 625 | } 626 | } 627 | 628 | try { 629 | await Promise.all(requests) 630 | } catch(err) { 631 | // Could not download some files. Will try again. 632 | } 633 | 634 | this.requestQueue.queue = [] 635 | } 636 | } 637 | 638 | async _initFileSwarm(stream, topic, fileHash, attempts, { keyPair }) { 639 | return new Promise(async (resolve, reject) => { 640 | if(!this.opened) throw ('Drive is closed.') 641 | 642 | if (attempts > this.fileRetryAttempts) { 643 | const err = new Error('Unable to make a connection or receive data within the allotted time.') 644 | err.fileHash = fileHash 645 | this._workerKeyPairs.release(keyPair.publicKey.toString('hex')) 646 | stream.destroy(err) 647 | return reject(err) 648 | } 649 | 650 | const swarm = new Hyperswarm({ keyPair }) 651 | 652 | let connected = false 653 | let receivedData = false 654 | let streamError = false 655 | 656 | swarm.join(Buffer.from(topic, 'hex'), { server: false, client: true }) 657 | 658 | swarm.on('connection', async (socket, info) => { 659 | receivedData = false 660 | 661 | if (!connected) { 662 | connected = true 663 | 664 | // Tell the host drive which file we want 665 | socket.write(fileHash) 666 | 667 | socket.on('data', (data) => { 668 | resolve() 669 | stream.write(data) 670 | receivedData = true 671 | }) 672 | 673 | socket.once('end', () => { 674 | if (receivedData) { 675 | this._workerKeyPairs.release(keyPair.publicKey.toString('hex')) 676 | stream.end() 677 | swarm.destroy() 678 | } 679 | }) 680 | 681 | socket.once('error', (err) => { 682 | stream.destroy(err) 683 | streamError = true 684 | reject(err) 685 | }) 686 | } 687 | }) 688 | 689 | setTimeout(async () => { 690 | if (!connected || streamError || !receivedData) { 691 | attempts += 1 692 | 693 | await swarm.destroy() 694 | 695 | try { 696 | await this._initFileSwarm(stream, topic, fileHash, attempts, { keyPair }) 697 | resolve() 698 | } catch(e) { 699 | reject(e) 700 | } 701 | } 702 | }, this.fileTimeout) 703 | }) 704 | } 705 | 706 | async _checkInternet() { 707 | return new Promise((resolve, reject) => { 708 | isOnline().then((isOnline) => { 709 | if(!isOnline && this.network.internet) { 710 | this.network.internet = false 711 | this.emit('network-updated', { internet: this.network.internet }) 712 | } 713 | 714 | if(isOnline && !this.network.internet) { 715 | this.network.internet = true 716 | this.emit('network-updated', { internet: this.network.internet }) 717 | } 718 | 719 | resolve() 720 | }) 721 | }) 722 | } 723 | 724 | async unlink(filePath) { 725 | let fp = filePath 726 | 727 | if (fp[0] === '/') { 728 | fp = filePath.slice(1, fp.length) 729 | } 730 | 731 | try { 732 | const file = await this._collections.files.findOne({ path: fp }) 733 | 734 | if (!file) return 735 | 736 | fs.unlinkSync(path.join(this._filesDir, file.encrypted ? `/${file.uuid}` : file.path)) 737 | 738 | await this._collections.files.delete({ _id: file._id }) 739 | 740 | await this.database._updateStatBytes(-Math.abs(file.size)) 741 | 742 | await this.metadb.delete({ hash: file.hash }) 743 | 744 | this.emit('file-unlink', file) 745 | } catch (err) { 746 | throw err 747 | } 748 | } 749 | 750 | async destroyHyperfile(path) { 751 | const filePath = await this.bee.get(path) 752 | const file = await this.bee.get(filePath.value.hash) 753 | await this._clearStorage(file.value) 754 | } 755 | 756 | async _bootstrap() { 757 | this._localCore = new Hypercore(path.join(this.drivePath, `./LocalCore`)) 758 | await this._localCore.ready() 759 | this._localHB = new Hyperbee(this._localCore, { keyEncoding: 'utf8', valueEncoding: 'json' }) 760 | this._localDB = new FileDB(`${this.drivePath}/LocalDS`) 761 | 762 | this.database = new Database(this.storage || this.drivePath, { 763 | localDB: this._localDB, 764 | keyPair: this.keyPair, 765 | storageName: this.storageName, 766 | encryptionKey: this.encryptionKey, 767 | peerPubKey: this.peerPubKey, 768 | acl: this.swarmOpts && this.swarmOpts.acl ? this.swarmOpts.acl : null, 769 | joinSwarm: this.joinSwarm, 770 | fts: this.fullTextSearch, 771 | blind: this.blind, 772 | stat: this._stat, 773 | storageMaxBytes: this.storageMaxBytes, 774 | fileStatPath: this._fileStatPath, 775 | broadcast: this.broadcast, 776 | dbVersion: this._dbVersion 777 | }) 778 | 779 | this.database.on('disconnected', () => { 780 | if(this.network.drive) { 781 | this.network.drive = false 782 | this.emit('network-updated', { drive: this.network.drive }) 783 | } 784 | }) 785 | 786 | this.database.on('connected', () => { 787 | if(!this.network.drive) { 788 | this.network.drive = true 789 | this.emit('network-updated', { drive: this.network.drive }) 790 | } 791 | }) 792 | 793 | if(this.checkNetworkStatus) { 794 | this.database.on('disconnected', () => { 795 | if(this.network.drive) { 796 | this.network.drive = false 797 | this.emit('network-updated', { drive: this.network.drive }) 798 | } 799 | }) 800 | } 801 | 802 | this.database.on('remote-cores-downloaded', () => { 803 | this.emit('remote-cores-downloaded') 804 | }) 805 | 806 | this.database.on('peer-connected', (peer) => { 807 | if(!this.peers.has(peer.peerPubKey)) { 808 | this.emit('peer-connected', peer) 809 | this.peers.add(peer.peerPubKey) 810 | } 811 | }) 812 | 813 | this.database.on('peer-disconnected', (peer) => { 814 | if(this.peers.has(peer.peerPubKey)) { 815 | this.emit('peer-disconnected', peer) 816 | this.peers.delete(peer.peerPubKey) 817 | } 818 | }) 819 | 820 | 821 | await this.database.ready() 822 | this.db = this.database 823 | this.metadb = this.database.metadb 824 | } 825 | 826 | async _update(data) { 827 | this.emit('sync', data) 828 | 829 | const fileHash = await this._localHB.get(data.value.path) 830 | 831 | if ( 832 | data.type !== 'del' && 833 | data.value.peer !== this.keyPair.publicKey.toString('hex') && 834 | !fileHash 835 | ) { 836 | 837 | if (this.syncFiles && !this.includeFiles && data.value.hash || this.includeFiles && this.includeFiles.indexOf(data.value.path) > -1 && data.value.hash) { 838 | try { 839 | const stat = this._localDB.get('stat') 840 | if(stat.total_bytes <= this.storageMaxBytes || !this.storageMaxBytes) { 841 | this.requestQueue.addFile(data.value) 842 | } 843 | } catch (err) { 844 | throw err 845 | } 846 | } else { 847 | if(data.value.path) { 848 | const filePath = data.value.encrypted ? `/${data.value.uuid}` : data.value.path 849 | await this._localHB.put(filePath, {}) 850 | } 851 | } 852 | } 853 | 854 | if (data.type === 'del' && 855 | data.value.peer !== this.keyPair.publicKey.toString('hex')) { 856 | try { 857 | let filePath = path.join(this._filesDir, `${data.value.path}`) 858 | 859 | if (fs.existsSync(filePath)) { 860 | fs.unlinkSync(filePath) 861 | 862 | const _file = await this._localHB.get(data.value.path) 863 | 864 | if(_file) { 865 | await this._localHB.del(data.value.path) 866 | } 867 | 868 | await this.database._updateStatBytes(-Math.abs(data.value.size)) 869 | 870 | setTimeout(() => { 871 | this.emit('file-unlink', data.value) 872 | }) 873 | } 874 | } catch (err) { 875 | console.log(err) 876 | throw err 877 | } 878 | } 879 | } 880 | 881 | // Deprecated 882 | info() { 883 | const bytes = getTotalSize(this.drivePath) 884 | return { 885 | size: bytes 886 | } 887 | } 888 | 889 | async stat() { 890 | return this._localDB.get('stat') 891 | } 892 | 893 | /** 894 | * Close drive and disconnect from all Hyperswarm topics 895 | */ 896 | async close() { 897 | this.opened = false 898 | 899 | if(this.joinSwarm) { 900 | await this._swarm.close() 901 | } 902 | 903 | if(this._localCore) { 904 | await this._localCore.close() 905 | } 906 | 907 | await this.database.close() 908 | 909 | this.database = null 910 | 911 | clearInterval(this._checkInternetInt) 912 | 913 | this.network = { 914 | internet: false, 915 | drive: false 916 | } 917 | 918 | this.emit('network-updated', this.network) 919 | 920 | if(this.checkNetworkStatus) { 921 | clearInterval(this._checkInternetInt) 922 | 923 | this.network = { 924 | internet: false, 925 | drive: false 926 | } 927 | 928 | this.emit('network-updated', this.network) 929 | } 930 | 931 | if(this.joinSwarm) { 932 | this.removeAllListeners() 933 | this.requestQueue.removeAllListeners() 934 | this._swarm.removeAllListeners() 935 | } 936 | } 937 | } 938 | 939 | function createTopicHash(topic) { 940 | const crypto = require('crypto') 941 | 942 | return crypto.createHash('sha256') 943 | .update(topic) 944 | .digest() 945 | } 946 | 947 | async function auditFile(stream, remoteHash) { 948 | return new Promise((resolve, reject) => { 949 | let hash = blake.blake2bInit(HASH_OUTPUT_LENGTH, null) 950 | 951 | stream.on('error', err => reject(err)) 952 | stream.on('data', chunk => { 953 | blake.blake2bUpdate(hash, chunk) 954 | }) 955 | stream.on('end', () => { 956 | const localHash = Buffer.from(blake.blake2bFinal(hash)).toString('hex') 957 | 958 | if (localHash === remoteHash) 959 | return resolve() 960 | 961 | reject('Hashes do not match') 962 | }) 963 | }) 964 | } 965 | 966 | 967 | const getAllFiles = function (dirPath, arrayOfFiles) { 968 | files = fs.readdirSync(dirPath) 969 | 970 | arrayOfFiles = arrayOfFiles || [] 971 | 972 | files.forEach(function (file) { 973 | if (fs.statSync(dirPath + "/" + file).isDirectory()) { 974 | arrayOfFiles = getAllFiles(dirPath + "/" + file, arrayOfFiles) 975 | } else { 976 | arrayOfFiles.push(path.join(dirPath, file)) 977 | } 978 | }) 979 | 980 | return arrayOfFiles 981 | } 982 | 983 | const getTotalSize = function (directoryPath) { 984 | const arrayOfFiles = getAllFiles(directoryPath) 985 | 986 | let totalSize = 0 987 | 988 | arrayOfFiles.forEach(function (filePath) { 989 | totalSize += fs.statSync(filePath).size 990 | }) 991 | 992 | return totalSize 993 | } 994 | 995 | module.exports = Drive 996 | -------------------------------------------------------------------------------- /lib/core.js: -------------------------------------------------------------------------------- 1 | const hypercore = require('hypercore'); 2 | 3 | class Hypercore { 4 | constructor(storage, key, opts) { 5 | this.storage = storage 6 | this.opts = opts 7 | 8 | if(key && typeof key === 'object') { 9 | this.opts = key 10 | } 11 | 12 | return new hypercore(this.storage, key, opts) 13 | } 14 | } 15 | 16 | module.exports = Hypercore -------------------------------------------------------------------------------- /lib/crypto.js: -------------------------------------------------------------------------------- 1 | const sodium = require('sodium-native'); 2 | const stream = require('stream'); 3 | const pump = require('pump'); 4 | const blake = require('blakejs'); 5 | const bip39 = require('bip39'); 6 | 7 | exports.signSeedKeypair = (mnemonic) => { 8 | let pk = Buffer.alloc(sodium.crypto_sign_PUBLICKEYBYTES); 9 | let sk = Buffer.alloc(sodium.crypto_sign_SECRETKEYBYTES); 10 | let seed = Buffer.alloc(sodium.crypto_sign_SEEDBYTES); 11 | 12 | if (!mnemonic) { 13 | sodium.randombytes_buf(seed); 14 | mnemonic = bip39.entropyToMnemonic(seed.toString('hex')); 15 | } else { 16 | buf = Buffer.from(bip39.mnemonicToEntropy(mnemonic), 'hex'); 17 | seed.fill(buf); 18 | } 19 | 20 | sodium.crypto_sign_seed_keypair(pk, sk, seed); 21 | 22 | return { 23 | publicKey: pk.toString('hex'), 24 | privateKey: sk.toString('hex'), 25 | seedKey: seed.toString('hex'), 26 | mnemonic 27 | } 28 | } 29 | 30 | exports.boxSeedKeypair = (mnemonic) => { 31 | let pk = Buffer.alloc(sodium.crypto_box_PUBLICKEYBYTES); 32 | let sk = Buffer.alloc(sodium.crypto_box_SECRETKEYBYTES); 33 | let seed = Buffer.alloc(sodium.crypto_box_SEEDBYTES); 34 | 35 | if (!mnemonic) { 36 | sodium.randombytes_buf(seed); 37 | mnemonic = bip39.entropyToMnemonic(seed.toString('hex')); 38 | } else { 39 | buf = Buffer.from(bip39.mnemonicToEntropy(mnemonic), 'hex'); 40 | seed.fill(buf); 41 | } 42 | 43 | sodium.crypto_box_seed_keypair(pk, sk, seed); 44 | 45 | return { 46 | publicKey: pk.toString('hex'), 47 | privateKey: sk.toString('hex'), 48 | seedKey: seed.toString('hex'), 49 | mnemonic 50 | } 51 | } 52 | 53 | exports.boxKeypairFromStr = (str) => { 54 | let pk = Buffer.alloc(sodium.crypto_box_PUBLICKEYBYTES); 55 | let sk = Buffer.alloc(sodium.crypto_box_SECRETKEYBYTES); 56 | let seed = Buffer.alloc(sodium.crypto_box_SEEDBYTES); 57 | 58 | const buf = Buffer.from(blake.blake2sHex(str)); 59 | 60 | seed.fill(buf); 61 | 62 | sodium.crypto_box_seed_keypair(pk, sk, seed); 63 | 64 | return { 65 | publicKey: pk.toString('hex'), 66 | privateKey: sk.toString('hex') 67 | } 68 | } 69 | 70 | exports.verifySig = (sig, publicKey, msg) => { 71 | let m = Buffer.from(JSON.stringify(msg)); 72 | let signature = Buffer.alloc(sodium.crypto_sign_BYTES); 73 | let pk = Buffer.alloc(sodium.crypto_sign_PUBLICKEYBYTES); 74 | 75 | pk.fill(Buffer.from(publicKey, 'hex')); 76 | signature.fill(Buffer.from(sig, 'hex')); 77 | 78 | return sodium.crypto_sign_verify_detached(signature, m, pk); 79 | }; 80 | 81 | exports.generateSigKeypair = () => { 82 | let pk = Buffer.alloc(sodium.crypto_sign_PUBLICKEYBYTES); 83 | let sk = Buffer.alloc(sodium.crypto_sign_SECRETKEYBYTES); 84 | 85 | sodium.crypto_sign_keypair(pk, sk); 86 | 87 | return { 88 | publicKey: pk.toString('hex'), 89 | privateKey: sk.toString('hex') 90 | } 91 | } 92 | 93 | exports.generateBoxKeypair = () => { 94 | let pk = Buffer.alloc(sodium.crypto_box_PUBLICKEYBYTES); 95 | let sk = Buffer.alloc(sodium.crypto_box_SECRETKEYBYTES); 96 | 97 | sodium.crypto_box_keypair(pk, sk); 98 | 99 | return { 100 | publicKey: pk.toString('hex'), 101 | privateKey: sk.toString('hex') 102 | } 103 | } 104 | 105 | exports.encryptPubSecretBoxMessage = (msg, sbpkey, privKey) => { 106 | const m = Buffer.from(msg, 'utf-8'); 107 | const c = Buffer.alloc(m.length + sodium.crypto_box_MACBYTES); 108 | const n = Buffer.alloc(sodium.crypto_box_NONCEBYTES); 109 | const pk = Buffer.alloc(sodium.crypto_box_PUBLICKEYBYTES); 110 | const sk = Buffer.alloc(sodium.crypto_box_SECRETKEYBYTES); 111 | 112 | pk.fill(Buffer.from(sbpkey, 'hex')); 113 | sk.fill(Buffer.from(privKey, 'hex')); 114 | 115 | sodium.crypto_box_easy(c, m, n, pk, sk); 116 | 117 | return c.toString('hex'); 118 | } 119 | 120 | exports.decryptPubSecretBoxMessage = (msg, sbpkey, privKey) => { 121 | const c = Buffer.from(msg, 'hex'); 122 | const m = Buffer.alloc(c.length - sodium.crypto_box_MACBYTES); 123 | const n = Buffer.alloc(sodium.crypto_box_NONCEBYTES); 124 | const pk = Buffer.alloc(sodium.crypto_box_PUBLICKEYBYTES); 125 | const sk = Buffer.alloc(sodium.crypto_box_SECRETKEYBYTES); 126 | 127 | pk.fill(Buffer.from(sbpkey, 'hex')); 128 | sk.fill(Buffer.from(privKey, 'hex')); 129 | 130 | const bool = sodium.crypto_box_open_easy(m, c, n, pk, sk); 131 | 132 | if (!bool) throw new Error('Unable to decrypt message.'); 133 | 134 | return m.toString('utf-8'); 135 | } 136 | 137 | exports.signDetached = (msg, privKey) => { 138 | let sig = Buffer.alloc(sodium.crypto_sign_BYTES); 139 | let m = Buffer.from(JSON.stringify(msg)); 140 | let sk = Buffer.alloc(sodium.crypto_sign_SECRETKEYBYTES); 141 | 142 | sk.fill(Buffer.from(privKey, 'hex')); 143 | 144 | sodium.crypto_sign_detached(sig, m, sk); 145 | 146 | const signature = sig.toString('hex'); 147 | 148 | return signature; 149 | }; 150 | 151 | exports.encryptSealedBox = (msg, pubKey) => { 152 | let m = Buffer.from(msg, 'utf-8'); 153 | let c = Buffer.alloc(m.length + sodium.crypto_box_SEALBYTES); 154 | let pk = Buffer.from(pubKey, 'hex'); 155 | 156 | sodium.crypto_box_seal(c, m, pk); 157 | 158 | return c; 159 | } 160 | 161 | exports.decryptSealedBox = (msg, privKey, pubKey) => { 162 | let c = Buffer.from(msg, 'hex'); 163 | let m = Buffer.alloc(c.length - sodium.crypto_box_SEALBYTES); 164 | let sk = Buffer.from(privKey, 'hex'); 165 | let pk = Buffer.from(pubKey, 'hex'); 166 | 167 | var bool = sodium.crypto_box_seal_open(m, c, pk, sk); 168 | 169 | if (!bool) throw new Error('Unable to decrypt message.'); 170 | 171 | return m.toString('utf-8'); 172 | } 173 | 174 | exports.hash = (str, k) => { 175 | let out = Buffer.alloc(sodium.crypto_generichash_BYTES); 176 | let txt = Buffer.from(str); 177 | 178 | if(k) { 179 | k = Buffer.from(k, 'hex'); 180 | sodium.crypto_generichash(out, txt, k); 181 | } else { 182 | sodium.crypto_generichash(out, txt); 183 | } 184 | 185 | return out.toString('hex'); 186 | }; 187 | 188 | 189 | exports.hashPassword = str => { 190 | let out = Buffer.alloc(sodium.crypto_pwhash_STRBYTES); 191 | let passwd = Buffer.from(str, 'utf-8'); 192 | let opslimit = sodium.crypto_pwhash_OPSLIMIT_MODERATE; 193 | let memlimit = sodium.crypto_pwhash_MEMLIMIT_MODERATE; 194 | 195 | sodium.crypto_pwhash_str(out, passwd, opslimit, memlimit); 196 | 197 | return out; 198 | }; 199 | 200 | exports.generateMasterKey = () => { 201 | let key = Buffer.alloc(sodium.crypto_kdf_KEYBYTES); 202 | sodium.crypto_kdf_keygen(key); 203 | return key; 204 | }; 205 | 206 | exports.deriveKeyFromMaster = (masterKey, skId) => { 207 | let subkey = Buffer.alloc(sodium.crypto_kdf_BYTES_MAX); 208 | let subkeyId = skId; 209 | let ctx = Buffer.alloc(sodium.crypto_kdf_CONTEXTBYTES); 210 | let key = Buffer.from(masterKey, 'hex'); 211 | 212 | sodium.crypto_kdf_derive_from_key(subkey, subkeyId, ctx, key); 213 | 214 | return subkey; 215 | }; 216 | 217 | exports.randomBytes = data => { 218 | let buf = Buffer.alloc(sodium.randombytes_SEEDBYTES); 219 | let seed = Buffer.from(data, 'utf-8'); 220 | 221 | sodium.randombytes_buf_deterministic(buf, seed); 222 | 223 | return buf.toString('hex'); 224 | }; 225 | 226 | exports.generateAEDKey = () => { 227 | let k = Buffer.alloc(sodium.crypto_aead_xchacha20poly1305_ietf_KEYBYTES); 228 | sodium.crypto_aead_xchacha20poly1305_ietf_keygen(k); 229 | return k.toString('hex'); 230 | } 231 | 232 | exports.encryptAED = (msg, key) => { 233 | let m = Buffer.from(msg, 'utf-8'); 234 | let c = Buffer.alloc(m.length + sodium.crypto_aead_xchacha20poly1305_ietf_ABYTES); 235 | let nonce = Buffer.alloc(sodium.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES); 236 | let k = Buffer.from(key, 'hex'); 237 | 238 | sodium.randombytes_buf(nonce); 239 | 240 | sodium.crypto_aead_xchacha20poly1305_ietf_encrypt(c, m, null, null, nonce, k); 241 | 242 | let encrypted = Buffer.from([]); 243 | encrypted = Buffer.concat([nonce, c], sodium.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES + c.length); 244 | 245 | return encrypted; 246 | } 247 | 248 | exports.decryptAED = (c, key) => { 249 | // slice nonce out of the encrypted message 250 | nonce = c.slice(0, sodium.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES); 251 | let cipher = c.slice(sodium.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES, c.length); 252 | 253 | let m = Buffer.alloc(cipher.length - sodium.crypto_aead_xchacha20poly1305_ietf_ABYTES); 254 | let k = Buffer.from(key, 'hex'); 255 | 256 | sodium.crypto_aead_xchacha20poly1305_ietf_decrypt(m, null, cipher, null, nonce, k); 257 | 258 | return m.toString(); 259 | } 260 | 261 | exports.generateStreamKey = () => { 262 | let k = Buffer.alloc(sodium.crypto_secretstream_xchacha20poly1305_KEYBYTES); 263 | sodium.crypto_secretstream_xchacha20poly1305_keygen(k); 264 | return k; 265 | } 266 | 267 | exports.initStreamPushState = (k) => { 268 | let state = Buffer.alloc(sodium.crypto_secretstream_xchacha20poly1305_STATEBYTES); 269 | let header = Buffer.alloc(sodium.crypto_secretstream_xchacha20poly1305_HEADERBYTES); 270 | sodium.crypto_secretstream_xchacha20poly1305_init_push(state, header, k); 271 | 272 | return { state: state, header: header }; 273 | } 274 | 275 | exports.secretStreamPush = (chunk, state) => { 276 | let c = Buffer.alloc(chunk.length + sodium.crypto_secretstream_xchacha20poly1305_ABYTES); 277 | let tag = Buffer.alloc(sodium.crypto_secretstream_xchacha20poly1305_TAGBYTES); 278 | 279 | sodium.crypto_secretstream_xchacha20poly1305_push(state, c, chunk, null, tag); 280 | 281 | return c; 282 | } 283 | 284 | exports.initStreamPullState = (header, k) => { 285 | let state = Buffer.alloc(sodium.crypto_secretstream_xchacha20poly1305_STATEBYTES); 286 | sodium.crypto_secretstream_xchacha20poly1305_init_pull(state, header, k); 287 | return state; 288 | } 289 | 290 | exports.secretStreamPull = (chunk, state) => { 291 | let m = Buffer.alloc(chunk.length - sodium.crypto_secretstream_xchacha20poly1305_ABYTES); 292 | let tag = Buffer.alloc(sodium.crypto_secretstream_xchacha20poly1305_TAGBYTES); 293 | 294 | sodium.crypto_secretstream_xchacha20poly1305_pull(state, m, tag, chunk, null); 295 | 296 | return m; 297 | } 298 | 299 | exports.encryptStream = async (readStream, writeStream) => { 300 | const OUTPUT_LENGTH = 32 // bytes 301 | const hash = blake.blake2bInit(OUTPUT_LENGTH, null); 302 | const key = _generateStreamKey(); 303 | 304 | let bytes = 0; 305 | let { state, header } = _initStreamPushState(key); 306 | 307 | return new Promise((resolve, reject) => { 308 | const encrypt = _encrypt(header, state); 309 | 310 | pump(readStream, encrypt, writeStream, (err) => { 311 | if(err) return reject(err); 312 | const file = { 313 | hash: Buffer.from(blake.blake2bFinal(hash)).toString('hex'), 314 | size: bytes 315 | } 316 | resolve({ key, header, file }); 317 | }) 318 | }); 319 | 320 | function _encrypt(header, state) { 321 | let message = Buffer.from([]); 322 | 323 | return new stream.Transform({ 324 | transform 325 | }); 326 | 327 | 328 | function transform(chunk, encoding, callback) { 329 | message = _secretStreamPush(chunk, state); 330 | bytes += message.byteLength; 331 | blake.blake2bUpdate(hash, message); 332 | callback(null, message); 333 | } 334 | } 335 | 336 | function _generateStreamKey() { 337 | let k = Buffer.alloc(sodium.crypto_secretstream_xchacha20poly1305_KEYBYTES); 338 | sodium.crypto_secretstream_xchacha20poly1305_keygen(k); 339 | return k; 340 | } 341 | 342 | function _initStreamPushState(k) { 343 | let state = Buffer.alloc(sodium.crypto_secretstream_xchacha20poly1305_STATEBYTES); 344 | let header = Buffer.alloc(sodium.crypto_secretstream_xchacha20poly1305_HEADERBYTES); 345 | sodium.crypto_secretstream_xchacha20poly1305_init_push(state, header, k); 346 | 347 | return { state: state, header: header }; 348 | } 349 | 350 | function _secretStreamPush(chunk, state) { 351 | let c = Buffer.alloc(chunk.length + sodium.crypto_secretstream_xchacha20poly1305_ABYTES); 352 | let tag = Buffer.alloc(sodium.crypto_secretstream_xchacha20poly1305_TAGBYTES); 353 | 354 | sodium.crypto_secretstream_xchacha20poly1305_push(state, c, chunk, null, tag); 355 | 356 | return c; 357 | } 358 | } 359 | 360 | exports.decryptStream = (readStream, key, header) => { 361 | if(!Buffer.isBuffer(key) && typeof key === 'string') { 362 | key = Buffer.from(key, 'hex'); 363 | } 364 | 365 | if(!Buffer.isBuffer(header) && typeof header === 'string') { 366 | header = Buffer.from(header, 'hex'); 367 | } 368 | 369 | const decrypt = _decrypt(key, header); 370 | 371 | pump(readStream, decrypt, (err) => { 372 | if(err) return err; 373 | }); 374 | 375 | return decrypt; 376 | 377 | 378 | function _decrypt(k, h) { 379 | let message = Buffer.from([]); 380 | let state = _initStreamPullState(h, k); 381 | 382 | return new stream.Transform({ 383 | writableObjectMode: true, 384 | transform 385 | }); 386 | 387 | function transform(chunk, encoding, callback) { 388 | try { 389 | message = _secretStreamPull(chunk, state); 390 | callback(null, message); 391 | } catch(err) { 392 | callback(err, null); 393 | } 394 | } 395 | } 396 | 397 | function _initStreamPullState(header, k) { 398 | let state = Buffer.alloc(sodium.crypto_secretstream_xchacha20poly1305_STATEBYTES); 399 | sodium.crypto_secretstream_xchacha20poly1305_init_pull(state, header, k); 400 | return state; 401 | } 402 | 403 | function _secretStreamPull(chunk, state) { 404 | try { 405 | let m = Buffer.alloc(chunk.length - sodium.crypto_secretstream_xchacha20poly1305_ABYTES); 406 | let tag = Buffer.alloc(sodium.crypto_secretstream_xchacha20poly1305_TAGBYTES); 407 | 408 | sodium.crypto_secretstream_xchacha20poly1305_pull(state, m, tag, chunk, null); 409 | 410 | return m; 411 | } catch(err) { 412 | throw err; 413 | } 414 | } 415 | } 416 | -------------------------------------------------------------------------------- /lib/database.js: -------------------------------------------------------------------------------- 1 | const { rmdir } = require('fs').promises 2 | const Hypercore = require('hypercore') 3 | const EventEmitter = require('events') 4 | const Autobase = require('autobase') 5 | const Autodeebee = require('hyperbeedeebee/autodeebee') 6 | const Hyperswarm = require('hyperswarm') 7 | const HyperFTS = require('./hyper-fts') 8 | const { DB } = require('hyperbeedeebee') 9 | const BSON = require('bson') 10 | const debounce = require('debounce') 11 | 12 | class Database extends EventEmitter { 13 | constructor(storage, opts = {}) { 14 | super() 15 | 16 | const key = opts.peerPubKey ? opts.peerPubKey : null 17 | 18 | this.storageName = opts.storageName 19 | this.opts = opts 20 | this.keyPair = opts.keyPair 21 | this.autobee = null 22 | this.bee = null 23 | this.metaAutobee = null 24 | this.metadb = null 25 | this.acl = opts.acl 26 | this.peerPubKey = key 27 | this.encryptionKey = opts.encryptionKey 28 | this.storage = typeof storage === 'string' ? `${storage}/Database` : storage 29 | this.storageIsString = typeof storage === 'string' ? true : false 30 | this.joinSwarm = typeof opts.joinSwarm === 'boolean' ? opts.joinSwarm : true 31 | this.storageMaxBytes = opts.storageMaxBytes 32 | this.stat = opts.stat 33 | this.localDB = opts.localDB 34 | this.fileStatPath = opts.fileStatPath 35 | this.blind = opts.blind 36 | this.syncingCoreCount = 0 37 | this.broadcast = opts.broadcast 38 | this._inputs = new Map() 39 | this._dbVersion = opts.dbVersion 40 | this.localInput = { 41 | key: Buffer.alloc(32) 42 | } 43 | 44 | this._statTimeout = null 45 | 46 | // Init local Autobase 47 | if(!this.blind) { 48 | this.localInput = new Hypercore( 49 | this.storageIsString ? `${this.storage}/local-writer` : this.storage, 50 | null, 51 | { 52 | encryptionKey: this.encryptionKey 53 | } 54 | ) 55 | 56 | this.localOutput = new Hypercore( 57 | this.storageIsString ? `${this.storage}/local-index` : this.storage, 58 | null, 59 | { 60 | encryptionKey: this.encryptionKey 61 | } 62 | ) 63 | 64 | const base1 = new Autobase({ 65 | inputs: [this.localInput], 66 | localOutput: this.localOutput, 67 | localInput: this.localInput 68 | }) 69 | 70 | this.autobee = new Autodeebee(base1) 71 | } 72 | 73 | // Init Meta Autobase 74 | if(this.peerPubKey) { 75 | this.remoteMetaCore = new Hypercore(this.storageIsString ? `${this.storage}/meta-remote` : this.storage, this.peerPubKey) 76 | } 77 | 78 | this.localMetaCore = new Hypercore(this.storageIsString ? `${this.storage}/meta-local` : this.storage) 79 | this.metaIndex = new Hypercore(this.storageIsString ? `${this.storage}/meta-index` : this.storage) 80 | 81 | const base2 = new Autobase({ 82 | inputs: [this.localMetaCore], 83 | localOutput: this.metaIndex, 84 | localInput: this.localMetaCore 85 | }) 86 | 87 | try { 88 | this.metaAutobee = new Autodeebee(base2) 89 | } catch(e) { 90 | 91 | } 92 | 93 | if(this.peerPubKey) { 94 | this.addInput(this.remoteMetaCore, 'meta') 95 | } 96 | 97 | this.collections = {} 98 | this.connections = [] 99 | this.coresLocal = new Map() 100 | this.coresRemote = new Map() 101 | 102 | // Init local search index 103 | if(opts.fts) { 104 | this.fts = new HyperFTS(this.storageIsString ? `${this.storage}/fts` : this.storage, this.encryptionKey) 105 | } 106 | } 107 | 108 | async ready() { 109 | if(this.localDB) { 110 | this.lastWriterSeq = this.localDB.get('lastWSeq') 111 | } 112 | 113 | this.connections = [] // reset connections 114 | 115 | if(this.opts.fts && !this.blind) { 116 | await this.fts.ready() 117 | } 118 | 119 | if(!this.blind) { 120 | this.autobeeVersion = this.autobee.version() 121 | await this.autobee.ready() 122 | 123 | await this._joinSwarm(this.localInput, { server: true, client: true }) 124 | 125 | if(!this.bee) { 126 | this.bee = new DB(this.autobee) 127 | } 128 | } 129 | 130 | this.metaAutobeeVersion = this.metaAutobee.version() 131 | await this.metaAutobee.ready() 132 | 133 | await this._joinSwarm(this.localMetaCore, { server: true, client: true }) 134 | 135 | if(!this.metadb) { 136 | this.mdb = new DB(this.metaAutobee) 137 | 138 | this.metadb = await this.mdb.collection('metadb') 139 | } 140 | 141 | if(this.peerPubKey) { 142 | try { 143 | this._handleCoreSyncStatus(1) 144 | 145 | let remoteMetaDidSync = false 146 | 147 | this.remoteMetaCore.on('append', debounce(async () => { 148 | if(!remoteMetaDidSync) { 149 | this._handleCoreSyncStatus(-1) 150 | remoteMetaDidSync = true 151 | } 152 | await this._getDiff(this.metaAutobee, this.metaAutobeeVersion) 153 | if(this.storageMaxBytes) await this._updateStatBytes() 154 | this.metaAutobeeVersion = this.metaAutobee.version() 155 | }, 500)) 156 | 157 | await this._joinSwarm(this.remoteMetaCore, { server: true, client: true }) 158 | 159 | // Download blocks from remote peer 160 | this.remoteMetaCore.download({ start: 0, end: -1 }) 161 | } catch(err) { 162 | // No results 163 | } 164 | } 165 | 166 | if(this.broadcast) { 167 | const peerInfo = { 168 | __version: this._dbVersion, 169 | blacklisted: false, 170 | peerPubKey: this.keyPair.publicKey.toString('hex'), 171 | blind: this.blind, 172 | cores : { 173 | writer: !this.blind ? this.localInput.key.toString('hex') : null, 174 | meta: this.localMetaCore.key.toString('hex') 175 | } 176 | } 177 | 178 | try { 179 | const doc = await this.metadb.findOne({ peerPubKey: this.keyPair.publicKey.toString('hex')}) 180 | } catch(err) { 181 | await this.metadb.insert(peerInfo) 182 | } 183 | } 184 | 185 | try { 186 | const docs = await this.metadb.find() 187 | 188 | for await(const doc of docs) { 189 | if(doc.cores && !doc.blacklisted && doc.__version === this._dbVersion) { 190 | const peer = { 191 | blind: doc.blind, 192 | peerPubKey: doc.peerPubKey, 193 | ...doc.cores 194 | } 195 | await this.addRemotePeer(peer) 196 | } 197 | } 198 | } catch(err) { 199 | console.log(err) 200 | } 201 | 202 | this.opened = true 203 | } 204 | 205 | async addRemotePeer(peer) { 206 | if(!this._inputs.get(peer.writer) && 207 | !this._inputs.get(peer.meta) && 208 | peer.peerPubKey !== this.keyPair.publicKey.toString('hex')) { 209 | 210 | if(peer.meta && !peer.writer) { 211 | this._handleCoreSyncStatus(1) 212 | } else { 213 | this._handleCoreSyncStatus(2) 214 | } 215 | 216 | if(peer.writer) { 217 | let peerWriterDidSync = false 218 | const peerWriter = new Hypercore( 219 | this.storageIsString ? `${this.storage}/peers/${peer.writer}` : this.storage, 220 | peer.writer, 221 | { 222 | encryptionKey: this.encryptionKey 223 | } 224 | ) 225 | 226 | if(!this.blind) { 227 | await this.addInput(peerWriter, 'autobee') 228 | } 229 | 230 | peerWriter.update().then(() => { 231 | peerWriter.on('append', debounce(async () => { 232 | if(!peerWriterDidSync) this._handleCoreSyncStatus(-1) 233 | 234 | peerWriterDidSync = true 235 | 236 | if(!this.blind) { 237 | this._getDiff(this.autobee, this.autobeeVersion, 'autob', peerWriter.length) 238 | } else { 239 | this.emit('collection-update') 240 | } 241 | 242 | if(this.storageMaxBytes) this._updateStatBytes() 243 | }, 500)) 244 | }) 245 | 246 | await this._joinSwarm(peerWriter, { server: true, client: true, peer }) 247 | this._inputs.set(peer.writer, peerWriter) 248 | 249 | // Download blocks from remote peer 250 | peerWriter.download({ start: 0, end: -1 }) 251 | } 252 | 253 | if(peer.meta) { 254 | let peerMetaDidSync = false 255 | const peerMeta = new Hypercore( 256 | this.storageIsString ? `${this.storage}/peers/${peer.meta}` : this.storage, 257 | peer.meta 258 | ) 259 | 260 | await this.addInput(peerMeta, 'meta') 261 | 262 | peerMeta.on('append', debounce(async () => { 263 | if(!peerMetaDidSync) this._handleCoreSyncStatus(-1) 264 | 265 | peerMetaDidSync = true 266 | 267 | await this._getDiff(this.metaAutobee, this.metaAutobeeVersion, 'meta') 268 | if(this.storageMaxBytes) this._updateStatBytes() 269 | this.metaAutobeeVersion = this.metaAutobee.version() 270 | }, 500)) 271 | 272 | await this._joinSwarm(peerMeta, { server: true, client: true, peer }) 273 | this._inputs.set(peer.meta, peerMeta) 274 | // Download blocks from remote peer 275 | peerMeta.download({ start: 0, end: -1 }) 276 | } 277 | } 278 | } 279 | 280 | async removeRemotePeer(peer) { 281 | try { 282 | if(peer.peerPubKey !== this.keyPair.publicKey.toString('hex')) { 283 | 284 | if(!this.blind && !peer.blind) { 285 | const core = this._inputs.get(peer.writer) 286 | 287 | if(core) { 288 | await this.autobee.removeInput(core) 289 | await core.close() 290 | 291 | // Remove Hypercores from disk 292 | await rmdir(`${this.storage}/peers/${peer.writer}`, { 293 | recursive: true, 294 | force: true, 295 | }) 296 | } 297 | } 298 | 299 | const metaCore = this._inputs.get(peer.meta) 300 | 301 | if(metaCore) { 302 | await this.metaAutobee.removeInput(metaCore) 303 | await metaCore.close() 304 | 305 | // Remove Hypercores from disk 306 | await rmdir(`${this.storage}/peers/${peer.meta}`, { 307 | recursive: true, 308 | force: true, 309 | }) 310 | } 311 | } 312 | } catch(e) {} 313 | } 314 | 315 | async addInput(core, type) { 316 | if(!type) return 317 | 318 | if(!core.key) { 319 | await core.ready() 320 | } 321 | 322 | if(type === 'autobee') { 323 | await this.autobee.addInput(core) 324 | } 325 | 326 | if(type === 'meta') { 327 | await this.metaAutobee.addInput(core) 328 | } 329 | } 330 | 331 | async collection(name) { 332 | const _collection = await this.bee.collection(name) 333 | const self = this 334 | const collection = new Proxy(_collection, { 335 | get (target, prop) { 336 | if(prop === 'insert') { 337 | return async (doc, opts) => { 338 | const _doc = {...doc, author: self.keyPair.publicKey.toString('hex') } 339 | return await _collection.insert(_doc) 340 | } 341 | } 342 | 343 | if(prop === 'update') { 344 | return async (query, data, opts) => { 345 | let _data = {...data } 346 | _data = {..._data, author: self.keyPair.publicKey.toString('hex') } 347 | return await _collection.update(query, _data, opts) 348 | } 349 | } 350 | 351 | if(prop === 'remove') { 352 | return async (query) => { 353 | if(self.fts) { 354 | await self.fts.deIndex({ db:_collection, name, query }) 355 | } 356 | await _collection.delete(query) 357 | } 358 | } 359 | return _collection[prop] 360 | } 361 | }) 362 | 363 | collection.ftsIndex = async (props, docs) => { 364 | if(!this.opts.fts) throw('Full text search is currently disabled because the option was set to false') 365 | await this.fts.index({ name, props, docs }) 366 | } 367 | 368 | collection.search = async (query, opts) => { 369 | if(!this.opts.fts) throw('Full text search is currently disabled because the option was set to false') 370 | 371 | return this.fts.search({ db:collection, name, query, opts }) 372 | } 373 | 374 | this.collections[name] = collection 375 | return collection 376 | } 377 | 378 | // TODO: Figure out how to multiplex these connections 379 | async _joinSwarm(core, { server, client, peer }) { 380 | 381 | if(!this.storageMaxBytes || this.stat.total_bytes < this.storageMaxBytes) { 382 | const swarm = new Hyperswarm() 383 | 384 | try { 385 | await core.ready() 386 | } catch(err) { 387 | console.log(err) 388 | } 389 | 390 | if(this.joinSwarm) { 391 | let connected = false 392 | try { 393 | swarm.on('connection', async (socket, info) => { 394 | connected = true 395 | 396 | socket.on('error', err => {}) 397 | 398 | if(peer && peer.peerPubKey) { 399 | this.emit('peer-connected', peer) 400 | 401 | socket.on('close', () => { 402 | this.emit('peer-disconnected', peer) 403 | }) 404 | } 405 | 406 | socket.pipe(core.replicate(info.client)).pipe(socket) 407 | }) 408 | 409 | const topic = core.discoveryKey; 410 | const discovery = swarm.join(topic, { server, client }) 411 | 412 | this.connections.push(swarm) 413 | 414 | if(server) { 415 | discovery.flushed().then(() => { 416 | this.emit('connected') 417 | }) 418 | } 419 | 420 | swarm.flush().then(() => { 421 | this.emit('connected') 422 | }) 423 | 424 | // Refresh if no connection has been made within 10s 425 | const refreshInt = setInterval(() => { 426 | if(!connected) { 427 | discovery.refresh({ client, server }) 428 | } else { 429 | clearInterval(refreshInt) 430 | } 431 | }, 10000) 432 | } catch(e) { 433 | this.emit('disconnected') 434 | } 435 | } 436 | } 437 | } 438 | 439 | async _leaveSwarm() { 440 | for await(const conn of this.connections) { 441 | await conn.destroy() 442 | } 443 | } 444 | 445 | async _updateStatBytes(fileBytes) { 446 | return new Promise(async (resolve, reject) => { 447 | let totalBytes = 0 448 | 449 | if(this._statTimeout && !fileBytes) { 450 | return resolve(this.stat.total_bytes) 451 | } 452 | 453 | this._statTimeout = setTimeout(() => { 454 | clearTimeout(this._statTimeout) 455 | this._statTimeout = null 456 | }, 200) 457 | 458 | totalBytes += this.metaIndex.byteLength 459 | totalBytes += this.localMetaCore.byteLength 460 | 461 | if(!this.blind) { 462 | totalBytes += this.localInput.byteLength 463 | totalBytes += this.localOutput.byteLength 464 | } 465 | 466 | if(this._inputs.size) { 467 | for (const [key, value] of this._inputs.entries()) { 468 | const core = this._inputs.get(key) 469 | totalBytes += core.byteLength 470 | } 471 | } 472 | 473 | this.stat.core_bytes = totalBytes 474 | 475 | if(fileBytes) { 476 | this.stat.file_bytes += fileBytes 477 | this.stat.total_bytes = totalBytes + this.stat.file_bytes 478 | } 479 | 480 | this.localDB.put('stat', { ...this.stat }) 481 | 482 | if(this.storageMaxBytes && this.stat.total_bytes >= this.storageMaxBytes) { 483 | // Shut down replication 484 | await this._leaveSwarm() 485 | } 486 | 487 | return resolve(totalBytes) 488 | }) 489 | } 490 | 491 | async close() { 492 | if(this.opts.fts) { 493 | await this.fts.close() 494 | } 495 | 496 | if(this.autobee) { 497 | await this.autobee.close() 498 | } 499 | 500 | await this.metaAutobee.close() 501 | 502 | for await(const conn of this.connections) { 503 | await conn.destroy() 504 | } 505 | 506 | 507 | if(this.remoteMetaCore) { 508 | for (const session of this.remoteMetaCore.sessions) { 509 | if(session) { 510 | await session.close() 511 | } 512 | } 513 | } 514 | 515 | if(this.metaIndex) { 516 | for (const session of this.metaIndex.sessions) { 517 | if(session) { 518 | await session.close() 519 | } 520 | } 521 | } 522 | 523 | if(this.localOutput) { 524 | for (const session of this.localOutput.sessions) { 525 | if(session) { 526 | await session.close() 527 | } 528 | } 529 | } 530 | 531 | // Only way found to force-close autobase and prevent file lock errors when 532 | // trying to re-instantiate 533 | try { 534 | await this.remoteMetaCore.sessions[0].close() 535 | while(this.remoteMetaCore.sessions[0].opened) { 536 | await this.remoteMetaCore.sessions[0].close() 537 | } 538 | } catch(e) {} 539 | 540 | try { 541 | await this.metaIndex.sessions[0].close() 542 | while(this.metaIndex.sessions[0].opened) { 543 | await this.metaIndex.sessions[0].close() 544 | } 545 | } catch(e) {} 546 | 547 | try { 548 | await this.localOutput.sessions[0].close() 549 | while(this.localOutput.sessions[0].opened) { 550 | await this.localOutput.sessions[0].close() 551 | } 552 | } catch(e) {} 553 | 554 | if(this._inputs.size) { 555 | for await(const [key, value] of this._inputs.entries()) { 556 | const core = this._inputs.get(key) 557 | 558 | if(core && core.opened) { 559 | await core.close() 560 | } 561 | 562 | try { 563 | await core.sessions[0].close() 564 | 565 | while(core.sessions[0].opened) { 566 | await core.sessions[0].close() 567 | } 568 | } catch(e) { 569 | 570 | } 571 | } 572 | } 573 | 574 | 575 | this.metadb = null 576 | this.mdb = null 577 | this.bee = null 578 | this._inputs = new Map() 579 | 580 | this._inputs = [] 581 | 582 | this.collections = {} 583 | this.connections = [] 584 | this.coresLocal = new Map() 585 | this.coresRemote = new Map() 586 | this.recordsSet = new Set() 587 | this.removeAllListeners() 588 | this.opened = false 589 | } 590 | 591 | async _getDiff(bee, version, type, length) { 592 | let diffStream = bee.createDiffStream(version) 593 | let lastSeq = 0 594 | 595 | for await(const data of diffStream) { 596 | let node 597 | // New Record 598 | if(data && data.left && data.left.key.toString().indexOf('\x00doc') > -1 && !data.right) { 599 | node = await this._buildNode(data.left, 'create') 600 | } 601 | 602 | // Recored Updated 603 | if(data && data.left && data.left.key.toString().indexOf('\x00doc') > -1 && data.right && data.right.key.toString().indexOf('\x00doc') > -1) { 604 | node = await this._buildNode(data.left, 'update') 605 | } 606 | 607 | // Deleted Record 608 | if(data && !data.left && data.right && data.right.key.toString().indexOf('\x00doc') > -1) { 609 | node = await this._buildNode(data.right, 'del') 610 | } 611 | 612 | if(data && data.right && data.right.key.toString().indexOf('\x00doc') > -1 || data && data.left && data.left.key.toString().indexOf('\x00doc') > -1) { 613 | if(type === 'autob') { 614 | lastSeq = node.seq 615 | this.autobeeVersion = bee.version() 616 | } 617 | } 618 | 619 | if(node && node.collection === 'metadb' || 620 | node && node.collection !== 'metadb' && !this.lastWriterSeq || 621 | node && node.collection !== 'metadb' && this.lastWriterSeq && this.lastWriterSeq < node.seq 622 | ) { 623 | this.emit('collection-update', node) 624 | } 625 | } 626 | 627 | if(this.localDB) { 628 | this.localDB.put('lastWSeq', lastSeq) 629 | } 630 | 631 | diffStream = null 632 | } 633 | 634 | async _buildNode(data, event) { 635 | const _data = BSON.deserialize(data.value) 636 | const collection = data.key.toString().split('\x00doc')[0] 637 | let node = { collection, type: event, value: _data, seq: data.seq } 638 | 639 | if(collection === 'metadb' && _data.cores && _data.__version === this._dbVersion) { 640 | const peer = { 641 | blind: _data.blind, 642 | peerPubKey: _data.peerPubKey, 643 | ..._data.cores 644 | } 645 | 646 | if(_data.blacklisted) { 647 | await this.removeRemotePeer(peer) 648 | } else { 649 | const peerInfo = { 650 | __version: this._dbVersion, 651 | blacklisted: false, 652 | peerPubKey: peer.peerPubKey, 653 | blind: peer.blind, 654 | cores : { 655 | writer: _data.cores.writer, 656 | meta: _data.cores.meta 657 | } 658 | } 659 | 660 | await this.metadb.update({peerPubKey: peer.peerPubKey}, peerInfo, { upsert: true }) 661 | 662 | await this.addRemotePeer(peer) 663 | } 664 | } 665 | 666 | return node 667 | } 668 | 669 | _handleCoreSyncStatus(count) { 670 | this.syncingCoreCount += count 671 | if(this.syncingCoreCount === 0) { 672 | this.emit('remote-cores-downloaded') 673 | } 674 | } 675 | } 676 | 677 | module.exports = Database -------------------------------------------------------------------------------- /lib/hyper-fts.js: -------------------------------------------------------------------------------- 1 | const natural = require('natural') 2 | const Corestore = require('corestore') 3 | const Hyperbee = require('hyperbee') 4 | const tokenizer = new natural.AggressiveTokenizer() 5 | const pump = require('pump') 6 | const concat = require('concat-stream') 7 | const BSON = require('bson') 8 | const { ObjectID } = BSON 9 | 10 | /** 11 | * This implementation of full text search on hypercore was refactored from 12 | * Paul Frazee's Hyper search experiment (https://github.com/pfrazee/hyper-search-experiments) 13 | */ 14 | 15 | class HyperFTS { 16 | constructor(storage, encryptionKey) { 17 | this.store = new Corestore(storage) 18 | this.encryptionKey = encryptionKey 19 | this.indexes = new Map() 20 | this.indexInProgress = false 21 | this.deIndexInProgress = false 22 | this.indexQueue = [] 23 | this.deIndexQueue = [] 24 | this.stopwords = [ 25 | "the", 26 | "a", 27 | "an", 28 | "and", 29 | "as", 30 | "i", 31 | "if", 32 | "it", 33 | "its", 34 | "it's" 35 | ] 36 | } 37 | 38 | async ready() { 39 | await this.store.ready() 40 | } 41 | 42 | async index({ name, props, docs }) { 43 | if(this.indexInProgress) { 44 | this.indexQueue.push({ name, props, docs }) 45 | return 46 | } 47 | 48 | this.indexInProgress = true 49 | 50 | const bee = this._getDB(name) 51 | const promises = [] 52 | 53 | await bee.put('idxProps', props) 54 | 55 | if (!bee.tx) bee.tx = bee.batch() 56 | const tx = bee.tx 57 | 58 | for(const doc of docs) { 59 | let text = '' 60 | 61 | for(const prop of props) { 62 | if(doc[prop]) text += doc[prop] 63 | } 64 | 65 | const id = ObjectID(doc._id).toHexString() 66 | 67 | if(!text) { 68 | throw 'Property to index cannot be null' 69 | } 70 | 71 | const tokens = this._toTokens(text) 72 | 73 | for (let token of tokens) { 74 | promises.push(tx.put(`idx:${token}:${id}`, {})) 75 | } 76 | } 77 | 78 | await Promise.all(promises) 79 | await tx.flush() 80 | 81 | this.indexInProgress = false 82 | 83 | if(this.indexQueue.length > 0) { 84 | const indexQueue = [...this.indexQueue] 85 | this.indexQueue = [] 86 | for(const item of indexQueue) { 87 | await this.index(item) 88 | } 89 | } 90 | } 91 | 92 | async deIndex({ db, name, query }) { 93 | if(this.deIndexInProgress) { 94 | this.deIndexQueue.push({ db, name, query }) 95 | return 96 | } 97 | 98 | this.deIndexInProgress = true 99 | 100 | const bee = this._getDB(name) 101 | const props = await bee.get('idxProps') 102 | 103 | if(!props) return 104 | 105 | const batch = await bee.batch() 106 | const doc = await db.findOne(query) 107 | let text = '' 108 | let _id = doc._id 109 | 110 | if(typeof _id !== 'string') _id = doc._id.toHexString() 111 | 112 | for(const prop of props.value) { 113 | if(doc[prop]) text += doc[prop] 114 | } 115 | 116 | const tokens = this._toTokens(text) 117 | 118 | for (let token of tokens) { 119 | await batch.del(`idx:${token}:${_id}`) 120 | } 121 | 122 | await batch.flush() 123 | 124 | this.deIndexInProgress = false 125 | 126 | if(this.deIndexQueue.length > 0) { 127 | const deIndexQueue = [...this.deIndexQueue] 128 | this.deIndexQueue = [] 129 | for(const item of deIndexQueue) { 130 | await this.deIndex(item) 131 | } 132 | } 133 | } 134 | 135 | async search({ db, name, query, opts }) { 136 | const bee = this._getDB(name) 137 | const queryTokens = this._toTokens(query) 138 | const listsPromises = [] 139 | const limit = opts && opts.limit || 10 140 | 141 | for (let qt of queryTokens) { 142 | listsPromises.push(bee.list({gt: `idx:${qt}:\x00`, lt: `idx:${qt}:\xff`})) 143 | } 144 | 145 | const listsResults = await Promise.all(listsPromises) 146 | const docIdHits = {} 147 | 148 | for (let listResults of listsResults) { 149 | for (let item of listResults) { 150 | const docId = item.key.split(':')[2] 151 | if(docIdHits[docId] === undefined) { 152 | docIdHits[docId] = 0 153 | } else { 154 | docIdHits[docId] += 1 155 | } 156 | } 157 | } 158 | 159 | const docIdsSorted = Object.keys(docIdHits).sort((a, b) => docIdHits[b] - docIdHits[a]) 160 | 161 | let results = await db.find({ _id: { $in: docIdsSorted.slice(0, limit) } }) 162 | 163 | return results.map(result => { 164 | let hits = docIdHits[result._id] 165 | 166 | for(const prop in result) { 167 | query = query.toLowerCase() 168 | if(typeof result[prop] === 'string') { 169 | hits += natural.JaroWinklerDistance(result[prop], query) 170 | } 171 | } 172 | 173 | return { 174 | ...result, 175 | hits 176 | } 177 | }) 178 | .sort((a,b) => b.hits - a.hits) 179 | } 180 | 181 | async close() { 182 | await this.store.close() 183 | } 184 | 185 | _getDB(name) { 186 | const core = this.store.get({ name, encryptionKey: this.encryptionKey }) 187 | 188 | let bee = new Hyperbee(core, { 189 | keyEncoding: 'utf-8', 190 | valueEncoding: 'json' 191 | }) 192 | 193 | bee.list = async (opts) => { 194 | let stream = await bee.createReadStream(opts) 195 | return new Promise((resolve, reject) => { 196 | pump( 197 | stream, 198 | concat(resolve), 199 | err => { 200 | if (err) reject(err) 201 | } 202 | ) 203 | }) 204 | } 205 | 206 | this.indexes.set(name, bee) 207 | 208 | return bee 209 | } 210 | 211 | _toTokens (str) { 212 | let arr = Array.isArray(str) ? str : tokenizer.tokenize(str) 213 | return [...new Set(arr.map(token => token.toLowerCase()))].map(token => natural.Metaphone.process(token)) 214 | } 215 | } 216 | 217 | module.exports = HyperFTS -------------------------------------------------------------------------------- /lib/swarm.js: -------------------------------------------------------------------------------- 1 | const EventEmitter = require('events') 2 | const Hyperswarm = require('hyperswarm') 3 | const blake = require('blakejs') 4 | 5 | class Swarm extends EventEmitter { 6 | constructor({ acl, keyPair, workerKeyPairs, publicKey, topic, ephemeral, isServer, isClient, blind }) { 7 | super() 8 | 9 | this.fileSwarm = new Hyperswarm({ // Networking for streaming file data 10 | firewall(remotePublicKey) { 11 | if (workerKeyPairs[remotePublicKey.toString('hex')]) { 12 | return true; 13 | } 14 | return false; 15 | } 16 | }) 17 | this.keyPair = keyPair 18 | this.blind = blind 19 | this.publicKey = publicKey 20 | this.topic = blake.blake2bHex(publicKey, null, 32) 21 | this.fileTopic = blake.blake2bHex(topic, null, 32) 22 | this.ephemeral = ephemeral 23 | this.closing = false 24 | this.fileDiscovery = null 25 | this.serverDiscovery = null 26 | this.isServer = isServer 27 | this.isClient = isClient 28 | 29 | 30 | this.server = new Hyperswarm({ 31 | keyPair, 32 | firewall(remotePublicKey) { 33 | // validate if you want a connection from remotePublicKey 34 | if (acl && acl.length) { 35 | return acl.indexOf(remotePublicKey.toString('hex')) === -1; 36 | } 37 | 38 | return false; 39 | } 40 | }) 41 | } 42 | 43 | async ready() { 44 | this.fileSwarm.on('connection', async (socket, info) => { 45 | this.emit('file-requested', socket) 46 | 47 | socket.on('error', (err) => {}) 48 | }) 49 | 50 | 51 | this.server.on('connection', (socket, info) => { 52 | const peerPubKey = socket.remotePublicKey.toString('hex') 53 | this.emit('peer-connected', socket) 54 | 55 | socket.on('error', (err) => {}) 56 | 57 | socket.on('data', data => { 58 | this.emit('message', peerPubKey, data) 59 | }) 60 | }) 61 | 62 | try { 63 | const serverDiscoveryTopic = blake.blake2bHex(this.topic, null, 32) 64 | this.serverDiscovery = this.server.join(Buffer.from(serverDiscoveryTopic, 'hex'), { server: true, client: true }) 65 | await this.serverDiscovery.flushed() 66 | await this.server.listen() 67 | } catch(e) { 68 | this.emit('disconnected') 69 | } 70 | 71 | try { 72 | this.fileDiscovery = this.fileSwarm.join(Buffer.from(this.fileTopic, 'hex'), { server: true, client: false }) 73 | this.fileDiscovery.flushed().then(() => { 74 | this.emit('connected') 75 | }) 76 | } catch(e) { 77 | this.emit('disconnected') 78 | } 79 | } 80 | 81 | connect(publicKey) { 82 | const noiseSocket = this.node.connect(Buffer.from(publicKey, 'hex')) 83 | 84 | noiseSocket.on('error', (err) => {}) 85 | 86 | noiseSocket.on('open', function () { 87 | // noiseSocket fully open with the other peer 88 | this.emit('onPeerConnected', noiseSocket) 89 | }); 90 | } 91 | 92 | async close() { 93 | const promises = [] 94 | 95 | if(this.fileDiscovery) 96 | promises.push(this.fileDiscovery.destroy()) 97 | 98 | if(this.server) { 99 | promises.push(this.serverDiscovery.destroy()) 100 | promises.push(this.server.leave(this.keyPair.publicKey)) 101 | } 102 | 103 | try { 104 | await Promise.all(promises) 105 | 106 | this.removeAllListeners() 107 | this.fileSwarm.removeAllListeners() 108 | } catch (err) { 109 | throw err 110 | } 111 | } 112 | } 113 | 114 | module.exports = Swarm 115 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@telios/nebula", 3 | "version": "4.0.11", 4 | "description": "Real-time distributed file and data storage.", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "cross-env NODE_ENV=test_sdk tape tests/*.test.js | tap-spec", 8 | "semantic-release": "semantic-release", 9 | "commit": "cz", 10 | "debug": "cross-env NODE_ENV=test_sdk tape tests/drive.test.js | tap-spec --nolazy --debug-brk=5858" 11 | }, 12 | "repository": { 13 | "type": "git", 14 | "url": "https://github.com/Telios-org/nebula.git" 15 | }, 16 | "author": "Hexadecibal", 17 | "license": "AGPL-3.0", 18 | "bugs": { 19 | "url": "https://github.com/Telios-org/nebula/issues" 20 | }, 21 | "homepage": "https://github.com/Telios-org/nebula", 22 | "dependencies": { 23 | "autobase": "https://github.com/hypercore-protocol/autobase", 24 | "bip39": "^3.0.4", 25 | "blakejs": "^1.1.0", 26 | "codecs": "^2.2.0", 27 | "concat-stream": "^2.0.0", 28 | "corestore": "^6.2.0", 29 | "dat-encoding": "^5.0.1", 30 | "data-store": "^4.0.3", 31 | "debounce": "^1.2.1", 32 | "graceful-fs": "^4.2.9", 33 | "hyperbee": "^2.1.2", 34 | "hyperbeedeebee": "git+https://github.com/Telios-org/hyperdeebee.git", 35 | "hypercore": "^10.4.1", 36 | "hyperswarm": "^4.3.5", 37 | "is-online": "^9.0.1", 38 | "memorystream": "^0.3.1", 39 | "natural": "^5.1.11", 40 | "pump": "^3.0.0", 41 | "random-access-memory": "^6.0.0", 42 | "sodium-native": "^3.4.1", 43 | "stopwords": "^0.0.9", 44 | "uuid": "^8.2.0" 45 | }, 46 | "devDependencies": { 47 | "@commitlint/cli": "^12.0.1", 48 | "@commitlint/config-conventional": "^12.0.1", 49 | "@semantic-release/git": "^9.0.0", 50 | "@semantic-release/gitlab": "^6.0.9", 51 | "@semantic-release/npm": "^7.1.0", 52 | "cross-env": "^7.0.3", 53 | "cz-conventional-changelog": "^3.0.1", 54 | "del": "^6.0.0", 55 | "husky": "^6.0.0", 56 | "npm-force-resolutions": "^0.0.10", 57 | "semantic-release": "^17.4.2", 58 | "tap-spec": "^2.2.2", 59 | "tape": "^5.2.2", 60 | "tape-promise": "^4.0.0" 61 | }, 62 | "directories": { 63 | "lib": "lib", 64 | "test": "tests" 65 | }, 66 | "keywords": [ 67 | "telios", 68 | "decentralized", 69 | "distributed", 70 | "file", 71 | "sharing", 72 | "drive", 73 | "storage", 74 | "p2p", 75 | "peer-to-peer", 76 | "hypercore", 77 | "hypercore-protocol", 78 | "hyperdrive", 79 | "hyperswarm" 80 | ], 81 | "husky": { 82 | "hooks": { 83 | "prepare-commit-msg": "exec < /dev/tty && git cz --hook || true" 84 | } 85 | }, 86 | "config": { 87 | "commitizen": { 88 | "path": "./node_modules/cz-conventional-changelog" 89 | } 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /tests/data/test.doc: -------------------------------------------------------------------------------- 1 | this is a test document -------------------------------------------------------------------------------- /tests/database.test.js: -------------------------------------------------------------------------------- 1 | const tape = require('tape') 2 | const _test = require('tape-promise').default 3 | const test = _test(tape) 4 | const Database = require('../lib/database') 5 | const ram = require('random-access-memory') 6 | const DHT = require('@hyperswarm/dht') 7 | const { v4: uuidv4 } = require('uuid') 8 | 9 | test('Database - Create new db', async t => { 10 | t.plan(1) 11 | 12 | const keyPair = DHT.keyPair() 13 | const encryptionKey = Buffer.alloc(32, 'hello world') 14 | 15 | try { 16 | const database = new Database(ram, { 17 | keyPair, 18 | encryptionKey 19 | }) 20 | 21 | await database.ready() 22 | 23 | t.ok(database.localMetaCore.key.toString('hex')) 24 | } catch (err) { 25 | console.log('ERROR: ', err) 26 | t.error(err) 27 | } 28 | }) 29 | 30 | test('Database - Test put/get', async t => { 31 | t.plan(3) 32 | 33 | const keyPair = DHT.keyPair() 34 | const encryptionKey = Buffer.alloc(32, 'hello world') 35 | 36 | try { 37 | const database = new Database(ram, { 38 | keyPair, 39 | encryptionKey, 40 | fts: true 41 | }) 42 | 43 | await database.ready() 44 | 45 | const collection = await database.collection('foobar') 46 | 47 | await collection.insert({ foo: "bar" }) 48 | await collection.insert({ foo: "biz" }) 49 | await collection.insert({ foo: "baz" }) 50 | 51 | const docs = await collection.find() 52 | 53 | t.equals(docs[0].foo, 'bar') 54 | 55 | let doc = await collection.findOne({ 56 | foo: 'biz' 57 | }) 58 | 59 | t.equals(doc.foo, 'biz') 60 | 61 | await collection.update({_id: docs[0]._id }, { hello: "baz" }) 62 | 63 | doc = await collection.findOne({ 64 | foo: 'baz' 65 | }) 66 | 67 | t.equals(doc.foo, 'baz') 68 | } catch (err) { 69 | t.error(err) 70 | } 71 | }) 72 | 73 | test('Database - Full text search', async t => { 74 | t.plan(3) 75 | 76 | const corpus = [ 77 | { 78 | title: 'Painting 1', 79 | text_body: "In your world you can create anything you desire." 80 | }, 81 | { 82 | title: 'Painting 2', 83 | text_body: "I thought today we would make a happy little stream that's just running through the woods here." 84 | }, 85 | { 86 | title: 'Painting 3', 87 | text_body: "See. We take the corner of the brush and let it play back-and-forth. No pressure. Just relax and watch it happen." 88 | }, 89 | { 90 | title: 'Painting 4', 91 | text_body: "Just go back and put one little more happy tree in there. Without washing the brush, I'm gonna go right into some Van Dyke Brown." 92 | }, 93 | { 94 | title: 'Painting 5', 95 | text_body: "Trees get lonely too, so we'll give him a little friend. If what you're doing doesn't make you happy - you're doing the wrong thing." 96 | }, 97 | { 98 | title: 'Painting 6', 99 | text_body: "Son of a gun. We're not trying to teach you a thing to copy. We're just here to teach you a technique, then let you loose into the world." 100 | }, 101 | { 102 | title: 'Painting 1', 103 | text_body: "In your world you can create anything you desire." 104 | }, 105 | { 106 | title: 'Painting 2', 107 | text_body: "I thought today we would make a happy little stream that's just running through the woods here." 108 | }, 109 | { 110 | title: 'Painting 3', 111 | text_body: "See. We take the corner of the brush and let it play back-and-forth. No pressure. Just relax and watch it happen." 112 | }, 113 | { 114 | title: 'Painting 4', 115 | text_body: "Just go back and put one little more happy tree in there. Without washing the brush, I'm gonna go right into some Van Dyke Brown." 116 | }, 117 | { 118 | title: 'Painting 5', 119 | text_body: "Trees get lonely too, so we'll give him a little friend. If what you're doing doesn't make you happy - you're doing the wrong thing." 120 | }, 121 | { 122 | title: 'Painting 6', 123 | text_body: "Son of a gun. We're not trying to teach you a thing to copy. We're just here to teach you a technique, then let you loose into the world." 124 | } 125 | ] 126 | 127 | const keyPair = DHT.keyPair() 128 | const encryptionKey = Buffer.alloc(32, 'hello world') 129 | 130 | try { 131 | const database = new Database(ram, { 132 | keyPair, 133 | encryptionKey, 134 | fts: true 135 | }) 136 | 137 | await database.ready() 138 | 139 | const collection = await database.collection('BobRoss') 140 | const inserted = [] 141 | 142 | for(const data of corpus) { 143 | const doc = await collection.insert({ title: data.title, text_body: data.text_body }) 144 | inserted.push(doc) 145 | collection.ftsIndex(['text_body', 'title'], [doc]) 146 | } 147 | 148 | setTimeout(async() => { 149 | await collection.delete({ title: 'Painting 2' }) 150 | 151 | const q1 = await collection.search("happy tree") 152 | 153 | t.equals(q1.length, 5) 154 | 155 | const q2 = await collection.search("happy tree", { limit: 1 }) 156 | 157 | t.equals(q2.length, 1) 158 | 159 | const q3 = await collection.search("noresults") 160 | 161 | t.equals(q3.length, 0) 162 | }) 163 | } catch (err) { 164 | t.error(err) 165 | } 166 | }) 167 | 168 | test('Database - Remove item from hyperbee', async t => { 169 | t.plan(1) 170 | 171 | const keyPair = DHT.keyPair() 172 | const encryptionKey = Buffer.alloc(32, 'hello world') 173 | 174 | try { 175 | const database = new Database(ram, { 176 | keyPair, 177 | encryptionKey 178 | }) 179 | 180 | await database.ready() 181 | 182 | const collection = await database.collection('foobar') 183 | const doc = await collection.insert({ foo: 'bar' }) 184 | await collection.delete({ _id: doc._id }) 185 | 186 | const item = await collection.find({ _id: doc._id }) 187 | 188 | t.equals(0, item.length) 189 | } catch (err) { 190 | t.error(err) 191 | } 192 | }) -------------------------------------------------------------------------------- /tests/drive.test.js: -------------------------------------------------------------------------------- 1 | const tape = require('tape') 2 | const _test = require('tape-promise').default 3 | const test = _test(tape) 4 | const fs = require('fs') 5 | const path = require('path') 6 | const del = require('del') 7 | const Drive = require('..') 8 | const DHT = require('@hyperswarm/dht') 9 | const ram = require('random-access-memory') 10 | const BSON = require('bson') 11 | 12 | const keyPair = DHT.keyPair() 13 | const keyPair2 = DHT.keyPair() 14 | const keyPair3 = DHT.keyPair() 15 | const keyPair4 = DHT.keyPair() 16 | 17 | let drive 18 | let drive2 19 | let drive3 20 | let drive4 21 | let drive5 22 | let drive6 23 | 24 | let hyperFiles = [] 25 | 26 | const encryptionKey = Buffer.alloc(32, 'hello world') 27 | 28 | test('Drive - Create', async t => { 29 | t.plan(9) 30 | 31 | let networkCount = 0 32 | 33 | await cleanup() 34 | 35 | await peerCleanup() 36 | 37 | drive = new Drive(__dirname + '/drive', null, { 38 | keyPair, 39 | encryptionKey, 40 | checkNetworkStatus: true, 41 | fullTextSearch: false, 42 | swarmOpts: { 43 | server: true, 44 | client: true 45 | } 46 | }) 47 | 48 | drive.on('network-updated', async data => { 49 | networkCount += 1 50 | 51 | t.ok(data) 52 | 53 | if(networkCount == 2) { 54 | await drive.close() 55 | 56 | } 57 | }) 58 | 59 | await drive.ready() 60 | 61 | t.ok(drive.publicKey, `Drive has public key ${drive.publicKey}`) 62 | t.ok(drive.keyPair, `Drive has peer keypair`) 63 | t.ok(drive.db, `Drive has Database`) 64 | t.ok(drive.drivePath, `Drive has path ${drive.drivePath}`) 65 | t.equals(true, drive.opened, `Drive is open`) 66 | }) 67 | 68 | test('Drive - Upload Local Encrypted File', async t => { 69 | t.plan(28) 70 | 71 | try { 72 | 73 | drive = new Drive(__dirname + '/drive', null, { 74 | keyPair, 75 | encryptionKey, 76 | checkNetworkStatus: true, 77 | fullTextSearch: true, 78 | swarmOpts: { 79 | server: true, 80 | client: true 81 | } 82 | }) 83 | 84 | await drive.ready() 85 | 86 | const readStream = fs.createReadStream(path.join(__dirname, '/data/email.eml')) 87 | const file = await drive.writeFile('/email/rawEmailEncrypted.eml', readStream, { encrypted: true, customData: { foo: 'bar' } }) 88 | 89 | hyperFiles.push(file) 90 | 91 | t.ok(file.key, `File was encrypted with key`) 92 | t.ok(file.header, `File was encrypted with header`) 93 | t.ok(file.hash, `Hash of file was returned ${file.hash}`) 94 | t.ok(file.size, `Size of file in bytes was returned ${file.size}`) 95 | t.equals(file.custom_data.foo, 'bar', `File has custom data`) 96 | 97 | for (let i = 0; i < 20; i++) { 98 | const readStream = fs.createReadStream(path.join(__dirname, '/data/email.eml')) 99 | const file = await drive.writeFile(`/email/rawEmailEncrypted${i}.eml`, readStream, { encrypted: true, customData: { foo: 'bar' } }) 100 | t.ok(file) 101 | } 102 | 103 | const stat = await drive.stat() 104 | 105 | t.ok(stat.file_bytes) 106 | t.ok(stat.core_bytes) 107 | t.ok(stat.total_bytes) 108 | } catch (e) { 109 | t.error(e) 110 | } 111 | }) 112 | 113 | test('Drive - Read Local Encrypted File', async t => { 114 | t.plan(2) 115 | 116 | const origFile = fs.readFileSync(path.join(__dirname, '/data/email.eml'), { encoding: 'utf-8' }) 117 | const stream = await drive.readFile('/email/rawEmailEncrypted.eml') 118 | let decrypted = '' 119 | 120 | stream.on('data', chunk => { 121 | decrypted += chunk.toString('utf-8') 122 | }) 123 | 124 | stream.on('end', () => { 125 | t.ok(decrypted.length, 'Returned encrypted data') 126 | t.equals(origFile.length, decrypted.length, 'Decrypted file matches original') 127 | }) 128 | }) 129 | 130 | test('Drive - Create Seed Peer', async t => { 131 | t.plan(22) 132 | 133 | drive2 = new Drive(__dirname + '/drive2', drive.publicKey, { 134 | keyPair: keyPair2, 135 | encryptionKey: drive.encryptionKey, 136 | swarmOpts: { 137 | server: true, 138 | client: true 139 | } 140 | }) 141 | 142 | await drive2.ready() 143 | 144 | drive2.on('file-sync', async (file) => { 145 | t.ok(file.uuid, `File has synced from remote peer`) 146 | }) 147 | 148 | const readStream = fs.createReadStream(path.join(__dirname, '/data/test.doc')) 149 | const file = await drive.writeFile('/email/test.doc', readStream) 150 | 151 | hyperFiles.push(file) 152 | }) 153 | 154 | test('Drive - Add/remove docs from synced drives', async t => { 155 | t.plan(3) 156 | 157 | try { 158 | const encKey = Buffer.alloc(32, 'hello world') 159 | 160 | const peer1 = new Drive(__dirname + '/peer1', null, { 161 | keyPair: DHT.keyPair(), 162 | checkNetworkStatus: true, 163 | fullTextSearch: true, 164 | broadcast: true, 165 | encryptionKey: encKey, 166 | swarmOpts: { 167 | server: true, 168 | client: true 169 | } 170 | }) 171 | 172 | await peer1.ready() 173 | 174 | const peer2 = new Drive(__dirname + '/peer2', peer1.publicKey, { 175 | keyPair: DHT.keyPair(), 176 | checkNetworkStatus: true, 177 | fullTextSearch: true, 178 | broadcast: true, 179 | encryptionKey: encKey, 180 | swarmOpts: { 181 | server: true, 182 | client: true 183 | } 184 | }) 185 | 186 | await peer2.ready() 187 | 188 | const collection1 = await peer1.db.collection('example') 189 | await collection1.createIndex(['foo2']) 190 | 191 | const collection2 = await peer2.db.collection('example') 192 | await collection2.createIndex(['foo2']) 193 | 194 | peer2.on('collection-update', async data => { 195 | if(data.collection !== 'metadb' && data.type === 'del') { 196 | const docs = await collection2.find({ foo2: 'bar2' }) 197 | t.equals(0, docs.length, 'Peer2 returns 0 results') 198 | } 199 | 200 | 201 | if(data.collection !== 'metadb' && data.type !== 'del') { 202 | await collection2.delete({ foo2: 'bar2' }) 203 | t.ok(true, 'Peer2 deleted synced document from peer1') 204 | } 205 | }) 206 | 207 | peer1.on('collection-update', async data => { 208 | if(data.collection !== 'metadb' && data.type === 'del') { 209 | const docs = await collection1.find({ foo2: 'bar2' }) 210 | t.equals(0, docs.length, 'Peer1 returns 0 results') 211 | } 212 | }) 213 | 214 | await collection1.insert({ foo0: 'bar0' }) 215 | await collection1.insert({ foo1: 'bar1' }) 216 | const doc = await collection1.insert({ foo2: 'bar2' }) 217 | await collection1.ftsIndex(['foo2'], [doc]) 218 | 219 | t.teardown(async () => { 220 | try { 221 | await closeCores([peer1, peer2]) 222 | await peerCleanup() 223 | } catch(err) { 224 | console.log(err) 225 | } 226 | }) 227 | } catch(err) { 228 | console.log(err) 229 | } 230 | }) 231 | 232 | test('Drive - Sync Remote Database Updates from blind peer', async t => { 233 | t.plan(1) 234 | 235 | try { 236 | const encKey = Buffer.alloc(32, 'hello world') 237 | const p1KP = DHT.keyPair() 238 | let peer1 = new Drive(__dirname + '/peer1', null, { 239 | keyPair: p1KP, 240 | checkNetworkStatus: true, 241 | fullTextSearch: true, 242 | broadcast: true, 243 | encryptionKey: encKey, 244 | swarmOpts: { 245 | server: true, 246 | client: true 247 | } 248 | }) 249 | 250 | await peer1.ready() 251 | 252 | // BLIND PEER DOES NOT HAVE ENCRYPTION KEY 253 | const peer2 = new Drive(__dirname + '/peer2', peer1.publicKey, { 254 | keyPair: DHT.keyPair(), 255 | blind: true, 256 | syncFiles: false, 257 | broadcast: true, 258 | includeFiles: ['/test.doc'], 259 | swarmOpts: { 260 | server: true, 261 | client: true 262 | } 263 | }) 264 | 265 | await peer2.ready() 266 | 267 | // Sync remote updates from offline peer1 via blind peer2 268 | const peer3 = new Drive(__dirname + '/peer3', peer1.publicKey, { 269 | keyPair: DHT.keyPair(), 270 | encryptionKey: encKey, 271 | broadcast: true, 272 | swarmOpts: { 273 | server: true, 274 | client: true 275 | } 276 | }) 277 | 278 | await peer1.close() 279 | await peer3.ready() 280 | 281 | const collection2 = await peer3.db.collection('example') 282 | await collection2.insert({ hello: 'world' }) 283 | 284 | setTimeout(async () => { 285 | await peer3.close() 286 | 287 | peer1 = new Drive(__dirname + '/peer1', null, { 288 | keyPair: p1KP, 289 | checkNetworkStatus: true, 290 | fullTextSearch: true, 291 | broadcast: true, 292 | encryptionKey: encKey, 293 | swarmOpts: { 294 | server: true, 295 | client: true 296 | } 297 | }) 298 | 299 | peer1.on('collection-update', async data => { 300 | if(data.value.hello) { 301 | const col = await peer1.db.collection('example') 302 | const docs = await col.find(data.value) 303 | t.equals(docs[0].hello, 'world', 'peer 1 retrieved update from peer3') 304 | } 305 | }) 306 | 307 | await peer1.ready() 308 | }, 3000) 309 | 310 | t.teardown(async () => { 311 | try { 312 | await closeCores([peer1, peer2]) 313 | await peerCleanup() 314 | } catch(err) { 315 | console.log(err) 316 | } 317 | }) 318 | } catch(err) { 319 | console.log(err) 320 | } 321 | }) 322 | 323 | test('Drive - Sync Remote Database Updates', async t => { 324 | t.plan(4) 325 | 326 | try { 327 | const encKey = Buffer.alloc(32, 'hello world') 328 | 329 | const peer1 = new Drive(__dirname + '/peer1', null, { 330 | keyPair: DHT.keyPair(), 331 | encryptionKey: encKey, 332 | broadcast: true, 333 | swarmOpts: { 334 | server: true, 335 | client: true 336 | } 337 | }) 338 | 339 | await peer1.ready() 340 | 341 | const peer2 = new Drive(__dirname + '/peer2', peer1.publicKey, { 342 | keyPair: DHT.keyPair(), 343 | encryptionKey: encKey, 344 | broadcast: true, 345 | swarmOpts: { 346 | server: true, 347 | client: true 348 | } 349 | }) 350 | 351 | await peer2.ready() 352 | 353 | const peer3 = new Drive(__dirname + '/peer3', peer1.publicKey, { 354 | keyPair: DHT.keyPair(), 355 | encryptionKey: encKey, 356 | broadcast: true, 357 | swarmOpts: { 358 | server: true, 359 | client: true 360 | } 361 | }) 362 | 363 | peer1.on('collection-update', async data => { 364 | if(data.value.hello) { 365 | t.ok(data.value.hello, 'peer 1 has value hello') 366 | } 367 | }) 368 | 369 | peer2.on('collection-update', data => { 370 | if(data.value.foo) { 371 | t.ok(data.value.foo, 'peer 2 has value foo') 372 | } 373 | 374 | if(data.value.hello) { 375 | t.ok(data.value.hello, 'peer 2 has value hello') 376 | } 377 | }) 378 | 379 | peer3.on('collection-update', async data => { 380 | if(data.value.foo) { 381 | t.ok(data.value.foo, 'peer 3 has value foo') 382 | } 383 | }) 384 | 385 | await peer3.ready() 386 | 387 | setTimeout(async () => { 388 | const collection1 = await peer1.db.collection('example') 389 | await collection1.insert({ foo: 'bar' }) 390 | 391 | const collection3 = await peer3.db.collection('example') 392 | await collection3.insert({ hello: 'world' }) 393 | }, 5000) 394 | 395 | t.teardown(async () => { 396 | try { 397 | await closeCores([peer1, peer2, peer3]) 398 | await peerCleanup() 399 | } catch(err) { 400 | t.fail(err) 401 | } 402 | }) 403 | } catch(err) { 404 | t.fail(err) 405 | } 406 | }) 407 | 408 | // test('Drive - Remove remote peer', async t => { 409 | // t.plan(1) 410 | // try { 411 | // const encKey = Buffer.alloc(32, 'hello world') 412 | 413 | // const peer1 = new Drive(__dirname + '/peer1', null, { 414 | // keyPair: DHT.keyPair(), 415 | // encryptionKey: encKey, 416 | // broadcast: true, 417 | // swarmOpts: { 418 | // server: true, 419 | // client: true 420 | // } 421 | // }) 422 | 423 | // peer1.on('collection-update', async data => { 424 | // if(data.value.baz) { 425 | // t.fail('Should not sync data from removed peer!') 426 | // } 427 | // }) 428 | // await peer1.ready() 429 | // const p2Kp = DHT.keyPair() 430 | // let peer2 = new Drive(__dirname + '/peer2', peer1.publicKey, { 431 | // keyPair: p2Kp, 432 | // encryptionKey: encKey, 433 | // broadcast: true, 434 | // swarmOpts: { 435 | // server: true, 436 | // client: true 437 | // } 438 | // }) 439 | 440 | // await peer2.ready() 441 | 442 | // const collection2 = await peer2.db.collection('example') 443 | 444 | // const peer3 = new Drive(__dirname + '/peer3', peer1.publicKey, { 445 | // keyPair: DHT.keyPair(), 446 | // encryptionKey: encKey, 447 | // broadcast: true, 448 | // swarmOpts: { 449 | // server: true, 450 | // client: true 451 | // } 452 | // }) 453 | 454 | // peer3.on('collection-update', async data => { 455 | // if(data.value.baz) { 456 | // t.fail('Should not sync data from removed peer!') 457 | // } 458 | // }) 459 | // await peer3.ready() 460 | 461 | // const peer4 = new Drive(__dirname + '/peer4', peer1.publicKey, { 462 | // keyPair: DHT.keyPair(), 463 | // encryptionKey: encKey, 464 | // broadcast: true, 465 | // swarmOpts: { 466 | // server: true, 467 | // client: true 468 | // } 469 | // }) 470 | 471 | // peer4.on('collection-update', async data => { 472 | // if(data.value.baz) { 473 | // t.fail('Should not sync data from removed peer!') 474 | // } 475 | // }) 476 | 477 | // await peer4.ready() 478 | 479 | // pause(2000) 480 | 481 | // await peer1.removePeer({ 482 | // blind: peer2.blind, 483 | // publicKey: peer2.keyPair.publicKey.toString('hex'), 484 | // writer: peer2.peerWriterKey, 485 | // meta: peer2.publicKey 486 | // }) 487 | 488 | // setTimeout(async () => { 489 | // await collection2.insert({ baz: 'foo' }) 490 | // t.ok(true) 491 | // }, 10000) 492 | 493 | // t.teardown(async () => { 494 | // try { 495 | // await closeCores([peer1, peer2, peer3, peer4]) 496 | // await peerCleanup() 497 | // } catch(err) { 498 | // console.log(err) 499 | // } 500 | // }) 501 | // } catch(err) { 502 | // console.log(err) 503 | // } 504 | // }) 505 | 506 | test('Drive - Create Seed Peer with Max Storage of 12mb', async t => { 507 | t.plan(4) 508 | 509 | drive6 = new Drive(__dirname + '/drive6', drive.publicKey, { 510 | keyPair: DHT.keyPair(), 511 | encryptionKey: drive.encryptionKey, 512 | storageMaxBytes: 1000 * 1000 * 12, // max size = 12mb 513 | swarmOpts: { 514 | server: true, 515 | client: true 516 | } 517 | }) 518 | 519 | await drive6.ready() 520 | 521 | drive6.on('file-sync', async (file) => { 522 | t.ok(file.uuid, `File has synced from remote peer`) 523 | }) 524 | }) 525 | 526 | // test('Drive - Fetch Files from Remote Drive', async t => { 527 | // t.plan(4) 528 | 529 | // drive3 = new Drive(__dirname + '/drive3', null, { 530 | // keyPair: keyPair3, 531 | // fileRetryAttempts: 10, 532 | // swarmOpts: { 533 | // server: true, 534 | // client: true 535 | // } 536 | // }) 537 | 538 | // await drive3.ready() 539 | 540 | // await drive3.fetchFileBatch(hyperFiles, (stream, file) => { 541 | // return new Promise((resolve, reject) => { 542 | // let content = '' 543 | 544 | // stream.on('data', chunk => { 545 | // content += chunk.toString() 546 | // }) 547 | 548 | // stream.once('end', () => { 549 | // t.ok(file.hash, `File has hash ${file.hash}`) 550 | // t.ok(content.length, `File downloaded from remote peer`) 551 | // resolve() 552 | // }) 553 | // }) 554 | // }) 555 | // }) 556 | 557 | // test('Drive - Fail to Fetch Files from Remote Drive', async t => { 558 | // t.plan(2) 559 | 560 | // drive4 = new Drive(__dirname + '/drive4', null, { 561 | // keyPair: keyPair3, 562 | // swarmOpts: { 563 | // server: true, 564 | // client: true 565 | // } 566 | // }) 567 | // drive5 = new Drive(__dirname + '/drive5', null, { 568 | // keyPair: keyPair4, 569 | // swarmOpts: { 570 | // server: true, 571 | // client: true 572 | // } 573 | // }) 574 | 575 | 576 | // await drive4.ready() 577 | // await drive5.ready() 578 | 579 | // const readStream = fs.createReadStream(path.join(__dirname, '/data/email.eml')) 580 | // const file = await drive4.writeFile('/email/rawEmailEncrypted2.eml', readStream, { encrypted: true }) 581 | // console.log('drive 4 write file') 582 | // await drive4.unlink(file.path) 583 | // console.log('drive 4 unlink file') 584 | // await drive5.fetchFileBatch([file], (stream, file) => { 585 | // return new Promise((resolve, reject) => { 586 | // let content = '' 587 | 588 | // stream.on('data', chunk => { 589 | // console.log('got data') 590 | // content += chunk.toString() 591 | // }) 592 | 593 | // stream.on('error', (err) => { 594 | // console.log('stream error!') 595 | // t.ok(err.message, `Error has message: ${err.message}`) 596 | // t.equals(file.hash, err.fileHash, `Failed file hash matches the has in the request`) 597 | // resolve() 598 | // }) 599 | // }) 600 | // }) 601 | // }) 602 | 603 | // test('Drive - Unlink Local File', async t => { 604 | // t.plan(3) 605 | 606 | // const drive2 = new Drive(__dirname + '/drive2', drive.publicKey, { 607 | // keyPair: keyPair2, 608 | // encryptionKey: drive.encryptionKey, 609 | // swarmOpts: { 610 | // server: true, 611 | // client: true 612 | // } 613 | // }) 614 | 615 | // await drive2.ready() 616 | 617 | // const drive1Size = drive.info().size 618 | // const drive2Size = drive2.info().size 619 | 620 | 621 | 622 | // drive.on('file-unlink', file => { 623 | // t.ok(drive1Size > drive.info().size, `Drive1 size before: ${drive1Size} > size after: ${drive.info().size}`) 624 | // }) 625 | 626 | // drive2.on('file-unlink', file => { 627 | // t.ok(drive2Size > drive2.info().size, `Drive2 size before: ${drive2Size} > size after: ${drive2.info().size}`) 628 | // }) 629 | 630 | // await drive.unlink('/email/rawEmailEncrypted.eml') 631 | // }) 632 | 633 | test('Drive - Receive messages', async t => { 634 | t.plan(1) 635 | 636 | drive.on('message', (publicKey, data) => { 637 | const msg = JSON.parse(data.toString()) 638 | t.ok(msg, 'Drive can receive messages.') 639 | }) 640 | 641 | const node = new DHT() 642 | const noiseSocket = node.connect(keyPair.publicKey) 643 | 644 | noiseSocket.on('open', function () { 645 | noiseSocket.end(JSON.stringify({ 646 | type: 'newMail', 647 | meta: 'meta mail message' 648 | })) 649 | }) 650 | }) 651 | 652 | test('Drive - Close drives', async t => { 653 | t.plan(1) 654 | 655 | const promises = [] 656 | 657 | promises.push(drive.close()) 658 | promises.push(drive2.close()) 659 | promises.push(drive6.close()) 660 | 661 | try { 662 | await Promise.all(promises) 663 | await cleanup() 664 | t.ok(1) 665 | } catch(err) { 666 | t.fail(err) 667 | } 668 | }) 669 | 670 | test.onFinish(async () => { 671 | process.exit(0) 672 | }) 673 | 674 | 675 | async function cleanup() { 676 | if (fs.existsSync(path.join(__dirname, '/drive'))) { 677 | await del([ 678 | path.join(__dirname, '/drive') 679 | ]) 680 | } 681 | 682 | if (fs.existsSync(path.join(__dirname, '/drive2'))) { 683 | await del([ 684 | path.join(__dirname, '/drive2') 685 | ]) 686 | } 687 | 688 | if (fs.existsSync(path.join(__dirname, '/drive3'))) { 689 | await del([ 690 | path.join(__dirname, '/drive3') 691 | ]) 692 | } 693 | 694 | if (fs.existsSync(path.join(__dirname, '/drive4'))) { 695 | await del([ 696 | path.join(__dirname, '/drive4') 697 | ]) 698 | } 699 | 700 | if (fs.existsSync(path.join(__dirname, '/drive5'))) { 701 | await del([ 702 | path.join(__dirname, '/drive5') 703 | ]) 704 | } 705 | 706 | if (fs.existsSync(path.join(__dirname, '/drive6'))) { 707 | await del([ 708 | path.join(__dirname, '/drive6') 709 | ]) 710 | } 711 | } 712 | 713 | async function peerCleanup() { 714 | if (fs.existsSync(path.join(__dirname, '/peer1'))) { 715 | await del([ 716 | path.join(__dirname, '/peer1') 717 | ]) 718 | } 719 | 720 | if (fs.existsSync(path.join(__dirname, '/peer2'))) { 721 | await del([ 722 | path.join(__dirname, '/peer2') 723 | ]) 724 | } 725 | 726 | if (fs.existsSync(path.join(__dirname, '/peer3'))) { 727 | await del([ 728 | path.join(__dirname, '/peer3') 729 | ]) 730 | } 731 | 732 | if (fs.existsSync(path.join(__dirname, '/peer4'))) { 733 | await del([ 734 | path.join(__dirname, '/peer4') 735 | ]) 736 | } 737 | } 738 | 739 | async function closeCores(cores) { 740 | const promises = [] 741 | 742 | for(const core of cores) { 743 | promises.push(new Promise((resolve, reject) => { 744 | setTimeout(async () => { 745 | try { 746 | await core.close() 747 | resolve() 748 | } catch(err) { 749 | console.log(err) 750 | reject(err) 751 | } 752 | }) 753 | })) 754 | } 755 | 756 | return Promise.all(promises) 757 | } 758 | 759 | async function pause(ms) { 760 | return new Promise((res, rej) => { 761 | setTimeout(() => { 762 | res() 763 | }, ms) 764 | }) 765 | } -------------------------------------------------------------------------------- /tests/helpers/setup.js: -------------------------------------------------------------------------------- 1 | const fs = require("fs"); 2 | const path = require("path"); 3 | const { Drive, Account } = require("../../"); 4 | const del = require("del"); 5 | 6 | module.exports.init = async () => { 7 | await cleanup(); 8 | }; 9 | 10 | async function cleanup() { 11 | if (fs.existsSync(path.join(__dirname, "../localDrive"))) { 12 | await del([path.join(__dirname, "../localDrive")]); 13 | } 14 | 15 | if (fs.existsSync(path.join(__dirname, "../drive1"))) { 16 | await del([path.join(__dirname, "../drive1")]); 17 | } 18 | 19 | if (fs.existsSync(path.join(__dirname, "../drive2"))) { 20 | await del([path.join(__dirname, "../drive2")]); 21 | } 22 | 23 | if (fs.existsSync(path.join(__dirname, "../drive"))) { 24 | await del([path.join(__dirname, "../drive")]); 25 | } 26 | 27 | if (fs.existsSync(path.join(__dirname, "../peer-drive"))) { 28 | await del([path.join(__dirname, "../peer-drive")]); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /tests/vars.json: -------------------------------------------------------------------------------- 1 | { 2 | "ALICE_SB_PUB_KEY": "", 3 | "ALICE_SB_PRIV_KEY": "", 4 | "ALICE_SIG_PUB_KEY": "", 5 | "ALICE_SIG_PRIV_KEY": "", 6 | "ALICE_PEER_PUB_KEY": "", 7 | "ALICE_DRIVE_KEY": "", 8 | "ALICE_DIFF_KEY": "", 9 | "ALICE_PEER_SECRET_KEY": "", 10 | "ALICE_RECOVERY": "alice@mail.com", 11 | "ALICE_MAILBOX": "alice@telios.io", 12 | "ALICE_ACCOUNT_SIG": "", 13 | "ALICE_ACCOUNT_SERVER_SIG": "", 14 | "ALICE_DEVICE_1_ID": "", 15 | "ALICE_DEVICE_1_CORE_NAME": "Alice", 16 | "ALICE_DEVICE_1_KEY": "", 17 | "BOB_SB_PUB_KEY": "", 18 | "BOB_SB_PRIV_KEY": "", 19 | "BOB_SIG_PUB_KEY": "", 20 | "BOB_SIG_PRIV_KEY": "", 21 | "TEST_EMAIL_ENCRYPTED_META": "", 22 | "TEST_EMAIL": { 23 | "to": [{ 24 | "name": "Alice Tester", 25 | "address": "alice@telios.io" 26 | }], 27 | "from": [{ 28 | "name": "Bob Tester", 29 | "address": "bob@telios.io" 30 | }], 31 | "subject": "Hello Alice", 32 | "text_body": "You're my favorite test person ever", 33 | "html_body": "

You're my favorite test person ever

", 34 | "attachments": [ 35 | { 36 | "filename": "test.pdf", 37 | "fileblob": "--base64-data--", 38 | "mimetype": "application/pdf" 39 | }, 40 | { 41 | "filename": "test.txt", 42 | "fileblob": "--base64-data--", 43 | "mimetype": "text/plain" 44 | } 45 | ] 46 | } 47 | } -------------------------------------------------------------------------------- /util/filedb.util.js: -------------------------------------------------------------------------------- 1 | // const store = require('data-store')({ path: process.cwd() + `${storageDir}/data.db` }) 2 | const fs = require('graceful-fs') 3 | 4 | class FileDB { 5 | constructor(storageDir) { 6 | this.storageDir = storageDir 7 | this.dbPath = `${storageDir}/data.db` 8 | this.store = require('data-store')({ path: this.dbPath }) 9 | } 10 | 11 | get(key) { 12 | return this.store.get(key) 13 | } 14 | 15 | put(key, value) { 16 | this.store.set(key, value) 17 | } 18 | 19 | del(key) { 20 | this.store.del(key) 21 | } 22 | } 23 | 24 | module.exports = FileDB -------------------------------------------------------------------------------- /util/fixedChunker.js: -------------------------------------------------------------------------------- 1 | const MemoryStream = require('memorystream'); 2 | const EventEmitter = require('events'); 3 | 4 | class Chunker extends EventEmitter { 5 | constructor(readStream, maxBlockSize) { 6 | super(); 7 | 8 | this.chunkSize = maxBlockSize; 9 | this.chunkStream = readStream; 10 | this.stream = new MemoryStream(); 11 | this.buffer = Buffer.from([]); 12 | 13 | this.openStream(); 14 | 15 | return this.stream; 16 | } 17 | 18 | resetBuffer() { 19 | this.buffer = Buffer.from([]); 20 | } 21 | 22 | processBuffer() { 23 | if(this.buffer.length === this.chunkSize) { 24 | this.stream.write(this.buffer); 25 | this.resetBuffer(); 26 | } 27 | } 28 | 29 | openStream() { 30 | this.chunkStream.on('error', (err) => { 31 | this.stream.destroy(err); 32 | }); 33 | 34 | this.chunkStream.on('data', chunk => { 35 | this.processData(chunk); 36 | }); 37 | 38 | this.chunkStream.on('end', () => { 39 | this.stream.end(this.buffer); 40 | this.resetBuffer(); 41 | }); 42 | } 43 | 44 | processData(data) { 45 | const chunks = this.reduce(data); 46 | 47 | chunks.forEach((chunk) => { 48 | this.stream.write(chunk); 49 | }); 50 | } 51 | 52 | reduce(data) { 53 | const chunks = []; 54 | 55 | if(this.buffer.length) { 56 | const intoBuffer = data.slice(0, this.chunkSize - this.buffer.length); 57 | this.buffer = Buffer.concat([this.buffer, intoBuffer]); 58 | 59 | data = data.slice(intoBuffer.length); 60 | 61 | this.processBuffer(); 62 | } 63 | 64 | while (data.length > this.chunkSize) { 65 | const chunk = data.slice(0, this.chunkSize); 66 | data = data.slice(this.chunkSize); 67 | 68 | chunks.push(chunk); 69 | } 70 | 71 | if (data.length + this.buffer.length <= this.chunkSize) { 72 | this.buffer = Buffer.concat([this.buffer, data]); 73 | this.processBuffer(); 74 | } 75 | 76 | return chunks; 77 | } 78 | } 79 | 80 | module.exports = Chunker; -------------------------------------------------------------------------------- /util/requestChunker.js: -------------------------------------------------------------------------------- 1 | const EventEmitter = require('events'); 2 | 3 | class RequestChunker extends EventEmitter { 4 | constructor(files, batchSize) { 5 | super(); 6 | 7 | this.BATCH_SIZE = batchSize || 5; 8 | this.files = files; 9 | this.queue = []; 10 | this.resetTimeout = 2000; 11 | this.timer = this.resetTimeout; 12 | this.interval = null; 13 | 14 | if(files) { 15 | return this.chunkFileRequests(files); 16 | } 17 | } 18 | 19 | chunkFileRequests(files) { 20 | const size = this.BATCH_SIZE; 21 | const chunked = []; 22 | 23 | for (let i = 0; i < files.length; i += size) { 24 | chunked.push(files.slice(i, i + size)); 25 | } 26 | 27 | return chunked; 28 | } 29 | 30 | addFile(file) { 31 | let exists = false; 32 | 33 | if(!this.interval) { 34 | this.startTimer(); 35 | } 36 | 37 | for(let i = 0; i < this.queue.length; i += 1) { 38 | if(this.queue[i].hash === file.hash) { 39 | exists = true; 40 | this.queue.splice(i, 1); 41 | } 42 | } 43 | 44 | if(!exists) { 45 | this.queue.push(file); 46 | } 47 | 48 | this.timer = this.resetTimeout; 49 | } 50 | 51 | processQueue() { 52 | this.emit('process-queue', this.queue); 53 | } 54 | 55 | startTimer() { 56 | this.interval = setInterval(() => { 57 | if(this.timer > 0) { 58 | this.timer -= 100; 59 | } 60 | 61 | if(this.timer === 0) { 62 | this.clearTimer(); 63 | this.processQueue(); 64 | } 65 | }, 100); 66 | } 67 | 68 | clearTimer() { 69 | clearInterval(this.interval); 70 | this.interval = null; 71 | this.timer = this.resetTimeout; 72 | } 73 | 74 | reset() { 75 | this.queue = []; 76 | } 77 | } 78 | 79 | module.exports = RequestChunker; -------------------------------------------------------------------------------- /util/workerKeyPairs.js: -------------------------------------------------------------------------------- 1 | const DHT = require('@hyperswarm/dht'); 2 | 3 | class WorkerKeyPairs { 4 | constructor(count) { 5 | this.keyPairs = {}; 6 | 7 | for(let i = 0; i < count; i += 1) { 8 | const keyPair = DHT.keyPair(); 9 | this.keyPairs[keyPair.publicKey.toString('hex')] = { active: false, ...keyPair }; 10 | } 11 | } 12 | 13 | getKeyPair() { 14 | for(let key in this.keyPairs) { 15 | 16 | if(!this.keyPairs[key].active) { 17 | this.keyPairs[key].active = true; 18 | return this.keyPairs[key]; 19 | } 20 | } 21 | 22 | return null; 23 | } 24 | 25 | release(key) { 26 | if(this.keyPairs[key]) { 27 | this.keyPairs[key].active = false; 28 | } 29 | } 30 | } 31 | 32 | module.exports = WorkerKeyPairs; --------------------------------------------------------------------------------